Skip to content

Commit 1a5c176

Browse files
committed
fix(opencode): simplify answers and decode titled multi-selects
1 parent 1acc933 commit 1a5c176

6 files changed

Lines changed: 151 additions & 94 deletions

File tree

‎apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1506,6 +1506,25 @@ describe("AcpAdapterV2", () => {
15061506
answers: { q0: "green" },
15071507
result: { action: "accept", content: { q0_custom: "green" } },
15081508
},
1509+
{
1510+
scenario: "OpenCode multi-select keeps values and custom text",
1511+
settings: OPENCODE_SETTINGS,
1512+
schema: {
1513+
...openCodeSchema,
1514+
properties: {
1515+
q0: {
1516+
type: "array",
1517+
title: "Color preference",
1518+
description: "Which color do you prefer?",
1519+
items: { anyOf: openCodeSchema.properties.q0.oneOf },
1520+
},
1521+
q0_custom: { type: "string", description: "Add your own answer" },
1522+
},
1523+
},
1524+
questions: openCodeQuestions.map((question) => ({ ...question, multiSelect: true })),
1525+
answers: { q0: ["blue", "green"] },
1526+
result: { action: "accept", content: { q0: ["blue"], q0_custom: "green" } },
1527+
},
15091528
{
15101529
scenario: "OpenCode cancels without accepting answers",
15111530
settings: OPENCODE_SETTINGS,

‎packages/effect-acp/scripts/generate.ts‎

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,37 @@ function isJsonArray(value: Schema.Json | undefined): value is ReadonlyArray<Sch
166166
return Array.isArray(value);
167167
}
168168

169+
// Keywords whose values are literal JSON data, not schemas.
170+
const DATA_KEYWORDS = new Set(["const", "default", "enum", "examples"]);
171+
172+
// Applies `transform` to every subschema of a schema object. `properties` maps names to
173+
// schemas, so its keys stay property names: ACP has properties named `anyOf`, `oneOf`, and
174+
// `type` that must not be read as keywords. Literal data values are left untouched.
175+
function mapSubschemas(
176+
value: { readonly [key: string]: Schema.Json },
177+
transform: (schema: Schema.Json) => Schema.Json,
178+
): Record<string, Schema.Json> {
179+
return Object.fromEntries(
180+
Object.entries(value).map(([key, child]) => {
181+
if (DATA_KEYWORDS.has(key)) return [key, child];
182+
if (
183+
key === "properties" &&
184+
child !== null &&
185+
typeof child === "object" &&
186+
!isJsonArray(child)
187+
) {
188+
return [
189+
key,
190+
Object.fromEntries(
191+
Object.entries(child).map(([name, schema]) => [name, transform(schema)]),
192+
),
193+
];
194+
}
195+
return [key, isJsonArray(child) ? child.map(transform) : transform(child)];
196+
}),
197+
);
198+
}
199+
169200
function normalizeSchemaKeywords(value: Schema.Json): Schema.Json {
170201
if (isJsonArray(value)) {
171202
return value.map(normalizeSchemaKeywords);
@@ -174,11 +205,7 @@ function normalizeSchemaKeywords(value: Schema.Json): Schema.Json {
174205
return value;
175206
}
176207

177-
const normalizedEntries = Object.entries(value).map(([key, child]) => [
178-
key,
179-
normalizeSchemaKeywords(child),
180-
]);
181-
const normalizedObject = Object.fromEntries(normalizedEntries) as Record<string, Schema.Json>;
208+
const normalizedObject = mapSubschemas(value, normalizeSchemaKeywords);
182209
// ACP's forward-compatible variants exclude known discriminator values.
183210
// The Effect generator does not support `not`; express this exact exclusion
184211
// as a string pattern while preserving validation of the known variants.
@@ -316,9 +343,7 @@ function flattenCompositions(
316343
): Schema.Json {
317344
if (isJsonArray(value)) return value.map((child) => flattenCompositions(child, definitions));
318345
if (value === null || typeof value !== "object") return value;
319-
const normalized = Object.fromEntries(
320-
Object.entries(value).map(([key, child]) => [key, flattenCompositions(child, definitions)]),
321-
);
346+
const normalized = mapSubschemas(value, (child) => flattenCompositions(child, definitions));
322347
const { allOf, anyOf, ...base } = normalized;
323348
const merge = (left: Schema.Json, right: Schema.Json): Schema.Json => {
324349
if (

‎packages/effect-acp/src/_generated/schema-v1.gen.ts‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -946,8 +946,25 @@ export const EnumOption = Schema.Struct({
946946
identifier: "EnumOption",
947947
});
948948

949-
export type TitledMultiSelectItems = never;
950-
export const TitledMultiSelectItems = Schema.Never.annotate({
949+
export type TitledMultiSelectItems = {
950+
readonly anyOf: ReadonlyArray<EnumOption>;
951+
readonly _meta?: { readonly [x: string]: Schema.Json } | null;
952+
} & { readonly [x: string]: Schema.Json };
953+
export const TitledMultiSelectItems = Schema.StructWithRest(
954+
Schema.Struct({
955+
anyOf: Schema.Array(EnumOption).annotate({ description: "Titled enum options." }),
956+
_meta: Schema.optionalKey(
957+
Schema.Union([
958+
Schema.Record(Schema.String, Schema.Json.annotate({ expected: "JSON value" })).annotate({
959+
description:
960+
"The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nOptional. Omitted and `null` are equivalent and mean no metadata.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)",
961+
}),
962+
Schema.Null,
963+
]),
964+
),
965+
}),
966+
[Schema.Record(Schema.String, Schema.Json.annotate({ expected: "JSON value" }))],
967+
).annotate({
951968
description: "Items definition for titled multi-select enum properties.",
952969
identifier: "TitledMultiSelectItems",
953970
});

‎packages/effect-acp/src/_generated/schema.gen.ts‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1128,8 +1128,27 @@ export const EnumOption = Schema.Struct({
11281128
identifier: "EnumOption",
11291129
});
11301130

1131-
export type TitledMultiSelectItems = never;
1132-
export const TitledMultiSelectItems = Schema.Never.annotate({
1131+
export type TitledMultiSelectItems = {
1132+
readonly anyOf: ReadonlyArray<EnumOption>;
1133+
readonly _meta?: { readonly [x: string]: Schema.Json } | null;
1134+
} & { readonly [x: string]: Schema.Json };
1135+
export const TitledMultiSelectItems = Schema.StructWithRest(
1136+
Schema.Struct({
1137+
anyOf: Schema.Array(EnumOption)
1138+
.annotate({ description: "Titled enum options. Must contain at least one option." })
1139+
.check(Schema.isMinLength(1).annotate({ expected: "a value with a length of at least 1" })),
1140+
_meta: Schema.optionalKey(
1141+
Schema.Union([
1142+
Schema.Record(Schema.String, Schema.Json.annotate({ expected: "JSON value" })).annotate({
1143+
description:
1144+
"The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nOptional. Omitted and `null` are equivalent and mean no metadata.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/draft/extensibility)",
1145+
}),
1146+
Schema.Null,
1147+
]),
1148+
),
1149+
}),
1150+
[Schema.Record(Schema.String, Schema.Json.annotate({ expected: "JSON value" }))],
1151+
).annotate({
11331152
description: "Items definition for titled multi-select enum properties.",
11341153
identifier: "TitledMultiSelectItems",
11351154
});

‎packages/provider-acp-registry/src/server/opencodeAcp.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,19 @@ describe("OpenCode ACP question form", () => {
5555
request({ q0: colorQuestion, q0_custom: colorCompanion }),
5656
);
5757

58+
for (const value of ["", " "]) {
59+
const blankChoice = extractOpenCodeElicitationForm(
60+
request({
61+
q0: { ...colorQuestion, oneOf: [{ const: value, title: "Blank" }] },
62+
q0_custom: colorCompanion,
63+
}),
64+
);
65+
expect(blankChoice?.respond({ q0: value })).toEqual({
66+
action: "accept",
67+
content: { q0: value },
68+
});
69+
}
70+
5871
expect(form?.respond({ q0: "blue" })).toEqual({
5972
action: "accept",
6073
content: { q0: "blue" },
@@ -88,6 +101,10 @@ describe("OpenCode ACP question form", () => {
88101
request({ q0: colorQuestion, q0_custom: colorCompanion }),
89102
);
90103

104+
expect(form?.respond({ q0: "Red" })).toEqual({
105+
action: "accept",
106+
content: { q0_custom: "Red" },
107+
});
91108
expect(form?.respond({ q0: "green" })).toEqual({
92109
action: "accept",
93110
content: { q0_custom: "green" },

‎packages/provider-acp-registry/src/server/opencodeAcp.ts‎

Lines changed: 42 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,6 @@ const isCustomCompanion = Schema.is(
4545
const questionId = /^q\d+$/;
4646
const companionSuffix = "_custom";
4747

48-
type Choice = { label: string; description: string; value: string };
49-
5048
// Intake appends file references to a user's answer; keep them with the custom text.
5149
const splitAttachments = (value: string) => {
5250
const marker = value.indexOf("\n\n");
@@ -59,8 +57,7 @@ const splitAttachments = (value: string) => {
5957
type Option = OrchestrationV2UserInputQuestion["options"][number];
6058

6159
const findChoice = (options: ReadonlyArray<Option>, value: string) =>
62-
options.find((option) => (option.value ?? option.label) === value) ??
63-
options.find((option) => option.label === value);
60+
options.find((option) => option.value === value);
6461

6562
const optionValue = (option: Option) => option.value ?? option.label;
6663

@@ -85,47 +82,33 @@ export const extractOpenCodeElicitationForm: NonNullable<
8582
const companion = properties[`${id}${companionSuffix}`];
8683
const hasCompanion = companion !== undefined;
8784
if (hasCompanion && !isCustomCompanion(companion)) return undefined;
88-
let header: string;
89-
let description: string | undefined;
90-
let options: Array<Choice>;
91-
let multiSelect = false;
92-
if (isChoiceQuestion(field)) {
93-
header = field.title;
94-
description = field.description?.trim();
95-
options = field.oneOf.map((option) => ({
96-
label: option.title,
97-
description: option.description?.trim() || option.title,
98-
value: option.const,
99-
}));
100-
} else if (isMultiChoiceQuestion(field)) {
101-
header = field.title;
102-
description = field.description?.trim();
103-
multiSelect = true;
104-
options = field.items.anyOf.map((option) => ({
105-
label: option.title,
106-
description: option.description?.trim() || option.title,
107-
value: option.const,
108-
}));
109-
} else if (isTextQuestion(field)) {
110-
// A choice field we do not fully understand must fall back instead of losing its options.
85+
const fieldChoices = isChoiceQuestion(field)
86+
? field.oneOf
87+
: isMultiChoiceQuestion(field)
88+
? field.items.anyOf
89+
: undefined;
90+
if (fieldChoices === undefined) {
91+
if (!isTextQuestion(field)) return undefined;
92+
// Unsupported choice schemas belong to the generic mapping.
11193
if ("enum" in field || "oneOf" in field || "anyOf" in field || "items" in field) {
11294
return undefined;
11395
}
114-
header = field.title;
115-
description = field.description?.trim();
116-
options = [];
117-
} else {
118-
return undefined;
11996
}
97+
if (!isTextQuestion(field) && !isMultiChoiceQuestion(field)) return undefined;
98+
const options = (fieldChoices ?? []).map((option) => ({
99+
label: option.title,
100+
description: option.description?.trim() || option.title,
101+
value: option.const,
102+
}));
120103
if (options.length > 0) choices += 1;
121104
if (hasCompanion) withCompanion.add(id);
122105
recognized += hasCompanion ? 2 : 1;
123106
questions.push({
124107
id,
125-
header,
126-
question: description || header,
108+
header: field.title,
109+
question: field.description?.trim() || field.title,
127110
options,
128-
...(multiSelect ? { multiSelect: true } : {}),
111+
...(field.type === "array" ? { multiSelect: true } : {}),
129112
allowCustomAnswer: hasCompanion || options.length === 0,
130113
});
131114
}
@@ -144,60 +127,37 @@ export const extractOpenCodeElicitationForm: NonNullable<
144127
: Predicate.isString(answer)
145128
? [answer]
146129
: [];
147-
if (values.length === 0 || values.some((value) => value.trim().length === 0)) {
130+
if (values.length === 0 || (question.multiSelect !== true && values.length > 1)) {
148131
return { action: "cancel" };
149132
}
150133
const companion = withCompanion.has(question.id);
151-
if (question.multiSelect === true) {
152-
const selected: Array<string> = [];
153-
const custom: Array<string> = [];
154-
for (const value of values) {
155-
const exact = findChoice(question.options, value);
156-
if (exact !== undefined) {
157-
selected.push(optionValue(exact));
158-
continue;
159-
}
160-
const split = splitAttachments(value);
161-
const attached =
162-
split === undefined ? undefined : findChoice(question.options, split.prefix);
163-
if (attached !== undefined && split !== undefined) {
164-
selected.push(optionValue(attached));
165-
custom.push(`${attached.label}${split.suffix}`);
166-
continue;
167-
}
168-
if (!companion) return { action: "cancel" };
134+
const selected: Array<string> = [];
135+
const custom: Array<string> = [];
136+
for (const value of values) {
137+
const exact = findChoice(question.options, value);
138+
if (exact !== undefined) {
139+
selected.push(optionValue(exact));
140+
continue;
141+
}
142+
if (value.trim().length === 0) return { action: "cancel" };
143+
const split = splitAttachments(value);
144+
const attached =
145+
split === undefined ? undefined : findChoice(question.options, split.prefix);
146+
if (companion && attached !== undefined && split !== undefined) {
147+
selected.push(optionValue(attached));
148+
custom.push(`${attached.label}${split.suffix}`);
149+
} else if (companion) {
169150
custom.push(value);
151+
} else if (question.options.length === 0) {
152+
selected.push(value);
153+
} else {
154+
return { action: "cancel" };
170155
}
171-
if (selected.length > 0) content[question.id] = selected;
172-
if (custom.length > 0) content[`${question.id}${companionSuffix}`] = custom.join("\n");
173-
continue;
174-
}
175-
if (values.length > 1) return { action: "cancel" };
176-
const value = values[0];
177-
if (value === undefined) return { action: "cancel" };
178-
const exact = findChoice(question.options, value);
179-
if (exact !== undefined) {
180-
content[question.id] = optionValue(exact);
181-
continue;
182-
}
183-
const split = splitAttachments(value);
184-
const attached =
185-
split === undefined ? undefined : findChoice(question.options, split.prefix);
186-
if (attached !== undefined && split !== undefined) {
187-
if (!companion) return { action: "cancel" };
188-
content[question.id] = optionValue(attached);
189-
content[`${question.id}${companionSuffix}`] = `${attached.label}${split.suffix}`;
190-
continue;
191-
}
192-
if (companion) {
193-
content[`${question.id}${companionSuffix}`] = value;
194-
continue;
195156
}
196-
if (question.options.length === 0) {
197-
content[question.id] = value;
198-
continue;
157+
if (selected.length > 0) {
158+
content[question.id] = question.multiSelect === true ? selected : selected[0]!;
199159
}
200-
return { action: "cancel" };
160+
if (custom.length > 0) content[`${question.id}${companionSuffix}`] = custom.join("\n");
201161
}
202162
return { action: "accept", content };
203163
},

0 commit comments

Comments
 (0)