The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 02:00 UTC
fix(acp): preserve native form questions and typed answers (#19659)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Yash Singh <saiansh2525@gmail.com> Co-authored-by: Honey Paptan <hpaptan@gmail.com>
Wout Stiens committed
Nov 7, 2026 at 12:42 UTC
f016a16b390f0a0237f71c691596fbd7bce43bc7
20 files changed
+1005
-89
apps/server/scripts/acp-mock-agent.ts
+19
-9
@@ -11,7 +11,7 @@ import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
11
12
import * as EffectAcpAgent from "effect-acp/agent";
13
import * as AcpError from "effect-acp/errors";
14
-import type * as AcpSchema from "effect-acp/schema";
14
+import * as AcpSchema from "effect-acp/schema";
15
import type * as AcpCompat from "effect-acp/compat";
16
17
import { beginAcpMockPrompt } from "./acpMockCancellationState.ts";
@@ -36,6 +36,12 @@ const emitBackgroundToolDuringAnswer =
36
process.env.T3_ACP_EMIT_BACKGROUND_TOOL_DURING_ANSWER === "1";
37
const emitMcpToolApprovalElicitation =
38
process.env.T3_ACP_EMIT_MCP_TOOL_APPROVAL_ELICITATION === "1";
39
+const emitElicitation = process.env.T3_ACP_EMIT_ELICITATION === "1";
40
+const elicitationSchema = process.env.T3_ACP_ELICITATION_SCHEMA;
41
+const decodeElicitationSchema = Schema.decodeUnknownSync(
42
+ Schema.fromJsonString(AcpSchema.ElicitationSchema),
43
+);
44
+const elicitationResponseLogPath = process.env.T3_ACP_ELICITATION_RESPONSE_LOG_PATH;
45
const grokKillTaskShape = process.env.T3_ACP_GROK_KILL_TASK_SHAPE;
46
const emitGrokBackgroundTaskPoll = process.env.T3_ACP_GROK_BACKGROUND_TASK_COMPLETION === "poll";
47
const emitForeignSessionUpdates = process.env.T3_ACP_EMIT_FOREIGN_SESSION_UPDATES === "1";
@@ -1541,21 +1547,25 @@ const program = Effect.gen(function* () {
1547
return yield* finishPrompt(requestedSessionId, "end_turn");
1548
}
1549
1544
- if (emitMcpToolApprovalElicitation) {
1545
- yield* agent.client.elicit({
1550
+ if (emitElicitation || emitMcpToolApprovalElicitation) {
1551
+ const response = yield* agent.client.elicit({
1552
sessionId: requestedSessionId,
1553
message: "Approve this request?",
1554
mode: "form",
1549
- requestedSchema: {
1550
- type: "object",
1551
- properties: {
1552
- approved: { type: "boolean", title: "Approved" },
1553
- },
1554
- },
1555
+ requestedSchema: elicitationSchema
1556
+ ? decodeElicitationSchema(elicitationSchema)
1557
+ : {
1558
+ type: "object",
1559
+ properties: {
1560
+ approved: { type: "boolean", title: "Approved" },
1561
+ },
1562
+ },
1563
...(emitMcpToolApprovalElicitation
1564
? { _meta: { codex_approval_kind: "mcp_tool_call" } }
1565
: {}),
1566
});
1567
+ if (elicitationResponseLogPath)
1568
+ NodeFS.appendFileSync(elicitationResponseLogPath, `${encodeJson(response)}\n`, "utf8");
1569
return yield* finishPrompt(requestedSessionId, "end_turn");
1570
}
1571
apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
+351
@@ -27,6 +27,7 @@ import {
27
ThreadId,
28
type OrchestrationV2ProviderThread,
29
type OrchestrationV2TurnItem,
30
+ type OrchestrationV2UserInputQuestion,
31
type ProviderOptionDescriptor,
32
type ProviderUserInputAnswers,
33
} from "@t3tools/contracts";
@@ -759,6 +760,100 @@ function assertReinjectedInstructions(
760
assert.include(text, `<user_request>\n${request}\n</user_request>`);
761
}
762
763
+const runFormElicitation = (input: {
764
+ readonly name: string;
765
+ readonly requestedSchema: unknown;
766
+ readonly answer: (
767
+ questions: ReadonlyArray<OrchestrationV2UserInputQuestion>,
768
+ ) => ProviderUserInputAnswers | undefined;
769
+}) =>
770
+ Effect.gen(function* () {
771
+ const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
772
+ const fileSystem = yield* FileSystem.FileSystem;
773
+ const path = yield* Path.Path;
774
+ const mockAgentPath = yield* path.fromFileUrl(
775
+ new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
776
+ );
777
+ const directory = yield* fileSystem.makeTempDirectoryScoped({
778
+ prefix: "t3-acp-form-elicitation-",
779
+ });
780
+ const responseLog = path.join(directory, "responses.jsonl");
781
+ const instanceId = ProviderInstanceId.make(`acp-test-form-${input.name}`);
782
+ const adapter = yield* makeAcpAdapterV2({
783
+ instanceId,
784
+ flavor: {
785
+ driver: ACP_TEST_DRIVER,
786
+ capabilities: AcpProviderCapabilitiesV2,
787
+ makeRuntime: makeMockRuntime({
788
+ childProcessSpawner,
789
+ mockAgentPath,
790
+ environment: {
791
+ T3_ACP_EMIT_ELICITATION: "1",
792
+ T3_ACP_ELICITATION_SCHEMA: JSON.stringify(input.requestedSchema),
793
+ T3_ACP_ELICITATION_RESPONSE_LOG_PATH: responseLog,
794
+ },
795
+ }),
796
+ },
797
+ selfInvocation: yield* resolveSelfInvocation(),
798
+ });
799
+ const threadId = ThreadId.make(`thread-acp-form-${input.name}`);
800
+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
801
+ runtimeMode: "approval-required",
802
+ interactionMode: "default",
803
+ cwd: process.cwd(),
804
+ });
805
+ const modelSelection = { instanceId, model: "default" } as const;
806
+ const runtime = yield* adapter.openSession({
807
+ threadId,
808
+ providerSessionId: ProviderSessionId.make(`provider-session-acp-form-${input.name}`),
809
+ modelSelection,
810
+ runtimePolicy,
811
+ });
812
+ const providerThread = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy });
813
+ yield* runtime.startTurn(
814
+ makeTurnInput({
815
+ threadId,
816
+ providerThread,
817
+ instanceId,
818
+ runtimePolicy,
819
+ now: yield* DateTime.now,
820
+ }),
821
+ );
822
+ const first = Option.getOrThrow(
823
+ yield* runtime.events.pipe(
824
+ Stream.filter(
825
+ (event) =>
826
+ event.type === "turn.terminal" ||
827
+ (event.type === "turn_item.updated" && event.turnItem.type === "user_input_request"),
828
+ ),
829
+ Stream.runHead,
830
+ ),
831
+ );
832
+ let questions: ReadonlyArray<OrchestrationV2UserInputQuestion> | undefined;
833
+ if (first.type === "turn_item.updated" && first.turnItem.type === "user_input_request") {
834
+ questions = first.turnItem.questions;
835
+ const answers = input.answer(questions);
836
+ yield* runtime.respondToRuntimeRequest({
837
+ requestId: first.turnItem.requestId,
838
+ ...(answers === undefined ? {} : { answers }),
839
+ });
840
+ yield* runtime.events.pipe(
841
+ Stream.filter((event) => event.type === "turn.terminal"),
842
+ Stream.runHead,
843
+ );
844
+ }
845
+ const responses = (yield* fileSystem.readFileString(responseLog))
846
+ .split("\n")
847
+ .filter((line) => line.length > 0)
848
+ .map((line) => Option.getOrThrow(decodeUnknownJson(line)));
849
+ assert.lengthOf(responses, 1);
850
+ return { questions, response: responses[0] };
851
+ });
852
+
853
+/** Submits like the web and mobile clients: an option's `value`, else its label. */
854
+const optionValues = (question: OrchestrationV2UserInputQuestion | undefined) =>
855
+ question?.options.map((option) => option.value ?? option.label);
856
+
857
describe("AcpAdapterV2", () => {
858
it.live("reports per-turn usage unavailable on a continuation turn that never prompts", () =>
859
Effect.gen(function* () {
@@ -6161,6 +6256,262 @@ describe("AcpAdapterV2", () => {
6256
}).pipe(Effect.provide(layerTest), Effect.scoped),
6257
);
6258
6259
+ it.live("asks form fields with their fixed choices and answers in the declared types", () =>
6260
+ Effect.gen(function* () {
6261
+ const { questions, response } = yield* runFormElicitation({
6262
+ name: "typed",
6263
+ requestedSchema: {
6264
+ type: "object",
6265
+ properties: {
6266
+ color: { type: "string", title: "Color", enum: ["red", "green"] },
6267
+ size: {
6268
+ type: "string",
6269
+ oneOf: [
6270
+ { const: "m", title: "Medium" },
6271
+ { const: "l", title: "Large" },
6272
+ ],
6273
+ },
6274
+ tags: { type: "array", items: { type: "string", enum: ["a", "b", "c"] } },
6275
+ areas: {
6276
+ type: "array",
6277
+ items: {
6278
+ anyOf: [
6279
+ { const: "api", title: "API", description: "Server routes" },
6280
+ { const: "ui", title: "Interface" },
6281
+ ],
6282
+ },
6283
+ },
6284
+ confirm: { type: "boolean" },
6285
+ count: { type: "integer" },
6286
+ ratio: { type: "number" },
6287
+ limit: { type: "integer" },
6288
+ note: { type: "string", enum: null },
6289
+ },
6290
+ required: ["color", "tags", "confirm", "count"],
6291
+ },
6292
+ answer: (asked) => {
6293
+ const byId = new Map(asked.map((question) => [question.id, question]));
6294
+ return {
6295
+ color: optionValues(byId.get("color"))?.[1],
6296
+ size: optionValues(byId.get("size"))?.[1],
6297
+ tags: ["c", "a", "unknown", "a"],
6298
+ areas: optionValues(byId.get("areas"))?.toReversed(),
6299
+ confirm: optionValues(byId.get("confirm"))?.[1],
6300
+ count: "3",
6301
+ ratio: " 0.5 ",
6302
+ // Not an integer: omitted, since the field is optional.
6303
+ limit: "3.7",
6304
+ note: "hi",
6305
+ extra: "not in the form",
6306
+ };
6307
+ },
6308
+ });
6309
+ assert.deepStrictEqual(
6310
+ questions?.map((question) => ({
6311
+ id: question.id,
6312
+ labels: question.options.map((option) => option.label),
6313
+ values: optionValues(question),
6314
+ multiSelect: question.multiSelect,
6315
+ allowCustomAnswer: question.allowCustomAnswer,
6316
+ })),
6317
+ [
6318
+ {
6319
+ id: "color",
6320
+ labels: ["red", "green"],
6321
+ values: ["red", "green"],
6322
+ multiSelect: undefined,
6323
+ allowCustomAnswer: false,
6324
+ },
6325
+ {
6326
+ id: "size",
6327
+ labels: ["Medium", "Large"],
6328
+ values: ["m", "l"],
6329
+ multiSelect: undefined,
6330
+ allowCustomAnswer: false,
6331
+ },
6332
+ {
6333
+ id: "tags",
6334
+ labels: ["a", "b", "c"],
6335
+ values: ["a", "b", "c"],
6336
+ multiSelect: true,
6337
+ allowCustomAnswer: false,
6338
+ },
6339
+ {
6340
+ id: "areas",
6341
+ labels: ["API", "Interface"],
6342
+ values: ["api", "ui"],
6343
+ multiSelect: true,
6344
+ allowCustomAnswer: false,
6345
+ },
6346
+ {
6347
+ id: "confirm",
6348
+ labels: ["true", "false"],
6349
+ values: ["true", "false"],
6350
+ multiSelect: undefined,
6351
+ allowCustomAnswer: false,
6352
+ },
6353
+ ...["count", "ratio", "limit", "note"].map((id) => ({
6354
+ id,
6355
+ labels: [],
6356
+ values: [],
6357
+ multiSelect: undefined,
6358
+ allowCustomAnswer: undefined,
6359
+ })),
6360
+ ],
6361
+ );
6362
+ assert.deepStrictEqual(response, {
6363
+ action: "accept",
6364
+ content: {
6365
+ color: "green",
6366
+ size: "l",
6367
+ tags: ["c", "a"],
6368
+ areas: ["ui", "api"],
6369
+ confirm: false,
6370
+ count: 3,
6371
+ ratio: 0.5,
6372
+ note: "hi",
6373
+ },
6374
+ });
6375
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
6376
+ );
6377
+
6378
+ it.live("keeps explicit empty selections and checks selection counts", () =>
6379
+ Effect.gen(function* () {
6380
+ const items = { type: "string", enum: ["a", "b", "c"] };
6381
+ const requestedSchema = {
6382
+ type: "object",
6383
+ properties: {
6384
+ none: { type: "array", items, default: [] },
6385
+ all: { type: "array", items, maxItems: 3 },
6386
+ optionalNone: { type: "array", items },
6387
+ some: { type: "array", items, minItems: 1 },
6388
+ tooMany: { type: "array", items, maxItems: 1 },
6389
+ single: { type: "array", items },
6390
+ unknownOnly: { type: "array", items },
6391
+ omitted: { type: "array", items },
6392
+ },
6393
+ required: ["none", "all", "some"],
6394
+ };
6395
+ const accepted = yield* runFormElicitation({
6396
+ name: "selection-counts",
6397
+ requestedSchema,
6398
+ answer: () => ({
6399
+ none: [],
6400
+ all: ["a", "b", "c"],
6401
+ optionalNone: [],
6402
+ some: ["b"],
6403
+ // Optional and not valid selections, so they are left out.
6404
+ tooMany: ["a", "b"],
6405
+ single: "a",
6406
+ unknownOnly: ["z"],
6407
+ }),
6408
+ });
6409
+ assert.deepStrictEqual(accepted.response, {
6410
+ action: "accept",
6411
+ content: { none: [], all: ["a", "b", "c"], optionalNone: [], some: ["b"] },
6412
+ });
6413
+ const belowMinimum = yield* runFormElicitation({
6414
+ name: "selection-below-minimum",
6415
+ requestedSchema,
6416
+ answer: () => ({ none: [], all: ["a"], some: [] }),
6417
+ });
6418
+ assert.deepStrictEqual(belowMinimum.response, { action: "cancel" });
6419
+ const requiredOmitted = yield* runFormElicitation({
6420
+ name: "selection-required-omitted",
6421
+ requestedSchema,
6422
+ answer: () => ({ all: ["a"], some: ["a"] }),
6423
+ });
6424
+ assert.deepStrictEqual(requiredOmitted.response, { action: "cancel" });
6425
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
6426
+ );
6427
+
6428
+ it.live("answers a field named __proto__ like any other field", () =>
6429
+ Effect.gen(function* () {
6430
+ const { questions, response } = yield* runFormElicitation({
6431
+ name: "proto-field",
6432
+ requestedSchema: {
6433
+ type: "object",
6434
+ properties: {
6435
+ ["__proto__"]: { type: "string", enum: ["a", "b"] },
6436
+ name: { type: "string" },
6437
+ },
6438
+ required: ["__proto__", "name"],
6439
+ },
6440
+ answer: () => ({ ["__proto__"]: "b", name: "hi" }),
6441
+ });
6442
+ assert.deepStrictEqual(
6443
+ questions?.map((question) => question.id),
6444
+ ["__proto__", "name"],
6445
+ );
6446
+ assert.deepStrictEqual(response, {
6447
+ action: "accept",
6448
+ content: { ["__proto__"]: "b", name: "hi" },
6449
+ });
6450
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
6451
+ );
6452
+
6453
+ it.live("declines a form whose selection counts the client cannot answer, without asking", () =>
6454
+ Effect.gen(function* () {
6455
+ const items = { type: "string", enum: ["a", "b"] };
6456
+ for (const [name, bounds] of [
6457
+ ["min-above-max", { minItems: 2, maxItems: 1 }],
6458
+ ["min-above-options", { minItems: 3 }],
6459
+ ["empty-only", { maxItems: 0 }],
6460
+ ] as const) {
6461
+ const { questions, response } = yield* runFormElicitation({
6462
+ name,
6463
+ requestedSchema: {
6464
+ type: "object",
6465
+ properties: { tags: { type: "array", items, ...bounds } },
6466
+ },
6467
+ answer: () => assert.fail("an impossible form must not reach the user"),
6468
+ });
6469
+ assert.isUndefined(questions);
6470
+ assert.deepStrictEqual(response, { action: "decline" });
6471
+ }
6472
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
6473
+ );
6474
+
6475
+ it.live("cancels a form whose required answer does not fit, or that is dismissed", () =>
6476
+ Effect.gen(function* () {
6477
+ const requestedSchema = {
6478
+ type: "object",
6479
+ properties: { count: { type: "integer" }, note: { type: "string" } },
6480
+ required: ["count"],
6481
+ };
6482
+ const invalid = yield* runFormElicitation({
6483
+ name: "invalid-required",
6484
+ requestedSchema,
6485
+ answer: () => ({ count: "two", note: "hi" }),
6486
+ });
6487
+ assert.deepStrictEqual(invalid.response, { action: "cancel" });
6488
+ const dismissed = yield* runFormElicitation({
6489
+ name: "dismissed",
6490
+ requestedSchema,
6491
+ answer: () => undefined,
6492
+ });
6493
+ assert.deepStrictEqual(dismissed.response, { action: "cancel" });
6494
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
6495
+ );
6496
+
6497
+ it.live("declines a form with a field it cannot ask for, without asking", () =>
6498
+ Effect.gen(function* () {
6499
+ const { questions, response } = yield* runFormElicitation({
6500
+ name: "unsupported",
6501
+ requestedSchema: {
6502
+ type: "object",
6503
+ properties: {
6504
+ color: { type: "string", enum: ["red"] },
6505
+ files: { type: "array", items: { type: "_upload" } },
6506
+ },
6507
+ },
6508
+ answer: () => assert.fail("an unsupported form must not reach the user"),
6509
+ });
6510
+ assert.isUndefined(questions);
6511
+ assert.deepStrictEqual(response, { action: "decline" });
6512
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
6513
+ );
6514
+
6515
it.live("auto-approves tagged MCP elicitations under full-access policy", () =>
6516
Effect.gen(function* () {
6517
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
apps/server/src/orchestration-v2/testkit/fixtures/acp_titled_multiselect/input.ts
new
+21
@@ -0,0 +1,21 @@
1
+import type { OrchestratorFixtureInput } from "../shared.ts";
2
+
3
+export const ACP_TITLED_MULTISELECT_PROMPT =
4
+ "Ask which areas this fixture should cover, allowing several. After receiving the answer, respond exactly: titled multi-select fixture complete";
5
+
6
+/**
7
+ * An ACP form elicitation whose multi-select lists titled `anyOf` options.
8
+ * The client submits option values, including one the form never offered.
9
+ */
10
+export function acpTitledMultiSelectInput(): OrchestratorFixtureInput {
11
+ return {
12
+ interactionMode: "plan",
13
+ steps: [
14
+ { type: "message", text: ACP_TITLED_MULTISELECT_PROMPT },
15
+ {
16
+ type: "answer_next_user_input_request",
17
+ answers: { fixture_areas: ["ui", "unknown", "schemas"] },
18
+ },
19
+ ],
20
+ };
21
+}
apps/server/src/orchestration-v2/testkit/fixtures/acp_titled_multiselect/output.ts
new
+46
@@ -0,0 +1,46 @@
1
+import { assert } from "@effect/vitest";
2
+import type { ProviderReplayTranscript } from "@t3tools/contracts";
3
+
4
+import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts";
5
+import {
6
+ assertAllRuntimeRequestsResolved,
7
+ assertAssistantTextIncludes,
8
+ assertBaseProjection,
9
+ assertRuntimeRequestKinds,
10
+ assertSemanticProjectionIntegrity,
11
+ assertTurnItemTypes,
12
+ assertUserMessagesInclude,
13
+ projectionFor,
14
+} from "../shared.ts";
15
+import { ACP_TITLED_MULTISELECT_PROMPT } from "./input.ts";
16
+
17
+/** The transcript's expected `elicitation/create` response pins the typed answer. */
18
+export function assertAcpTitledMultiSelectOutput(
19
+ result: OrchestratorV2ScenarioResult,
20
+ transcript: ProviderReplayTranscript,
21
+) {
22
+ assertBaseProjection({ result, transcript, runCount: 1, runStatuses: ["completed"] });
23
+ const projection = projectionFor(result, transcript.scenario);
24
+ assertSemanticProjectionIntegrity(projection);
25
+ assertRuntimeRequestKinds(projection, ["user_input"]);
26
+ assertAllRuntimeRequestsResolved(projection);
27
+ assertTurnItemTypes(projection, ["user_message", "user_input_request", "assistant_message"]);
28
+ assertUserMessagesInclude(projection, [ACP_TITLED_MULTISELECT_PROMPT]);
29
+ assertAssistantTextIncludes(projection, "titled multi-select fixture complete");
30
+
31
+ const requestItem = projection.turnItems.find((item) => item.type === "user_input_request");
32
+ assert.deepStrictEqual(requestItem?.type === "user_input_request" && requestItem.questions, [
33
+ {
34
+ id: "fixture_areas",
35
+ header: "Areas",
36
+ question: "Which areas should this fixture cover?",
37
+ options: [
38
+ { label: "Strict schemas", description: "Typed wire shapes", value: "schemas" },
39
+ { label: "UI flexibility", description: "UI flexibility", value: "ui" },
40
+ { label: "Docs", description: "Docs", value: "docs" },
41
+ ],
42
+ allowCustomAnswer: false,
43
+ multiSelect: true,
44
+ },
45
+ ]);
46
+}
apps/server/src/orchestration-v2/testkit/fixtures/acp_titled_multiselect/registry_transcript.ndjson
new
+11
@@ -0,0 +1,11 @@
1
+{"type":"transcript_start","provider":"acpRegistry","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"acp_titled_multiselect","metadata":{"generatedBy":"protocol-semantic-fixture","nativeSessionId":"registry-replay-session-1"}}
2
+{"type":"expect_outbound","label":"initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":2,"info":"<any>","capabilities":"<any>","clientCapabilities":"<any>","clientInfo":"<any>"}}}
3
+{"type":"emit_inbound","label":"initialized","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":true},"promptCapabilities":{"audio":false,"embeddedContext":true,"image":false}},"authMethods":[{"id":"replay","name":"Replay"}],"agentInfo":{"name":"generic-acp-replay","version":"1"}}}}
4
+{"type":"expect_outbound","label":"session.new","frame":{"kind":"request","method":"session/new","params":{"cwd":"<workspace>","mcpServers":"<any>"}}}
5
+{"type":"emit_inbound","label":"session.created","frame":{"kind":"response","method":"session/new","result":{"sessionId":"registry-replay-session-1"}}}
6
+{"type":"expect_outbound","label":"session.prompt","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"registry-replay-session-1","prompt":[{"type":"text","text":"<t3_code_instructions>\n<any>\n</t3_code_instructions>\n\n<user_request>\nAsk which areas this fixture should cover, allowing several. After receiving the answer, respond exactly: titled multi-select fixture complete\n</user_request>"}]}}}
7
+{"type":"emit_inbound","label":"elicitation.request","frame":{"kind":"request","method":"elicitation/create","params":{"sessionId":"registry-replay-session-1","mode":"form","message":"Choose the fixture areas.","requestedSchema":{"type":"object","title":"Fixture areas","properties":{"fixture_areas":{"type":"array","title":"Areas","description":"Which areas should this fixture cover?","minItems":1,"items":{"anyOf":[{"const":"schemas","title":"Strict schemas","description":"Typed wire shapes"},{"const":"ui","title":"UI flexibility"},{"const":"docs","title":"Docs"}]}}},"required":["fixture_areas"]}}}}
8
+{"type":"expect_outbound","label":"elicitation.response","frame":{"kind":"response","method":"elicitation/create","result":{"action":"accept","content":{"fixture_areas":["ui","schemas"]}}}}
9
+{"type":"emit_inbound","label":"assistant.final","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"registry-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"titled multi-select fixture complete"}}}}}
10
+{"type":"emit_inbound","label":"prompt.completed","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"end_turn"}}}
11
+{"type":"runtime_exit","status":"success"}
apps/server/src/orchestration-v2/testkit/fixtures/index.ts
+18
@@ -138,6 +138,8 @@ import {
138
} from "./plan_questions/codex_output.ts";
139
import { assertOpenCodePlanQuestionsOutput } from "./plan_questions/opencode_output.ts";
140
import { planQuestionsInput } from "./plan_questions/input.ts";
141
+import { acpTitledMultiSelectInput } from "./acp_titled_multiselect/input.ts";
142
+import { assertAcpTitledMultiSelectOutput } from "./acp_titled_multiselect/output.ts";
143
import { assertProposedPlanOutput } from "./proposed_plan/codex_output.ts";
144
import { assertProposedPlanCursorOutput } from "./proposed_plan/cursor_output.ts";
145
import { proposedPlanInput } from "./proposed_plan/input.ts";
@@ -788,6 +790,22 @@ export const ORCHESTRATOR_REPLAY_FIXTURES: ReadonlyArray<OrchestratorReplayFixtu
790
},
791
],
792
},
793
+ {
794
+ name: "acp_titled_multiselect",
795
+ buildInput: acpTitledMultiSelectInput,
796
+ providers: [
797
+ {
798
+ driver: ProviderDriverKind.make("acpRegistry"),
799
+ transcriptFile: new URL(
800
+ "./acp_titled_multiselect/registry_transcript.ndjson",
801
+ import.meta.url,
802
+ ),
803
+ modelSelection: ACP_REGISTRY_MODEL_SELECTION,
804
+ runtimePolicyOverride: READ_ONLY_NEVER_POLICY,
805
+ assertOutput: assertAcpTitledMultiSelectOutput,
806
+ },
807
+ ],
808
+ },
809
{
810
name: "simple",
811
buildInput: simpleInput,
apps/server/src/provider/Drivers/AntigravityDriver.test.ts
+48
-1
@@ -4,6 +4,8 @@ import { expect, it } from "@effect/vitest";
4
import {
5
ANTIGRAVITY_DEFAULT_MODEL,
6
ProviderInstanceId,
7
+ ProviderSessionId,
8
+ ThreadId,
9
type AntigravitySettings,
10
} from "@t3tools/contracts";
11
import * as HostProcess from "@t3tools/shared/HostProcess";
@@ -28,6 +30,7 @@ import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEve
30
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
31
import * as ModelManifest from "../ModelManifest.ts";
32
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
33
+import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
34
import { AntigravityDriver } from "./AntigravityDriver.ts";
35
import * as ProviderHostLive from "../ProviderHostLive.ts";
36
import * as ServerSecretStore from "../../auth/ServerSecretStore.ts";
@@ -276,7 +279,7 @@ const layerTest = ProviderHostLive.layer.pipe(
279
280
it.layer(layerTest)("AntigravityDriver", (it) => {
281
it.effect.skipIf(windowsHost)(
279
- "refreshes through the selected executable and personal Google ACP",
282
+ "refreshes the selected executable and limits form capabilities to chat",
283
() =>
284
Effect.gen(function* () {
285
const h = yield* makeHarness();
@@ -336,6 +339,50 @@ it.layer(layerTest)("AntigravityDriver", (it) => {
339
.map((request) => request.params?.mcpServers),
340
).toEqual([[], []]);
341
yield* h.assertClosed;
342
+ yield* h.instance.textGeneration
343
+ .generateThreadTitle({
344
+ cwd: h.profileDirectory,
345
+ message: "Name this thread",
346
+ modelSelection: { instanceId: h.instance.instanceId, model: "gemini-test-low" },
347
+ })
348
+ .pipe(Effect.ignore);
349
+ const workspace = yield* h.fs.makeTempDirectoryScoped({ prefix: "t3-ag-chat-" });
350
+ const threadId = ThreadId.make("thread-antigravity-capabilities");
351
+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
352
+ runtimeMode: "approval-required",
353
+ interactionMode: "default",
354
+ cwd: workspace,
355
+ });
356
+ const modelSelection = { instanceId: h.instance.instanceId, model: "gemini-test-low" };
357
+ const session = yield* h.instance.orchestrationAdapter.openSession({
358
+ threadId,
359
+ providerSessionId: ProviderSessionId.make("provider-session-antigravity-capabilities"),
360
+ modelSelection,
361
+ runtimePolicy,
362
+ });
363
+ yield* session.ensureThread({ threadId, modelSelection, runtimePolicy });
364
+
365
+ const helper = {
366
+ fs: { readTextFile: false, writeTextFile: false },
367
+ terminal: false,
368
+ session: { notices: {} },
369
+ };
370
+ expect(
371
+ (yield* h.readRequests)
372
+ .filter((request) => request.method === "initialize")
373
+ .map((request) => request.params?.clientCapabilities),
374
+ ).toEqual([
375
+ // Two model refreshes, then thread title generation.
376
+ helper,
377
+ helper,
378
+ helper,
379
+ {
380
+ fs: { readTextFile: true, writeTextFile: false },
381
+ terminal: false,
382
+ session: { notices: {} },
383
+ elicitation: { form: {} },
384
+ },
385
+ ]);
386
}).pipe(Effect.scoped),
387
);
388
apps/server/src/provider/acp/AntigravityAcpSupport.ts
+2
@@ -43,6 +43,7 @@ export interface AntigravityAcpRuntimeInput extends Omit<
43
readonly onAuthorizationUrl?: (url: string) => Effect.Effect<void, EffectAcpErrors.AcpError>;
44
/** Serve `fs/read_text_file` for runtimes whose native reader is not qualified. */
45
readonly clientFileReads?: boolean;
46
+ readonly clientCapabilities?: AcpSessionRuntime.AcpSessionRuntimeOptions["clientCapabilities"];
47
/** The installed version, known before `initialize`; it picks the file reader and client name. */
48
readonly runtimeVersion?: string | null;
49
/** Conversational sessions only; helpers and probes leave the system prompt untouched. */
@@ -136,6 +137,7 @@ export const makeAntigravityAcpRuntime = Effect.fn("makeAntigravityAcpRuntime")(
137
sessionMeta: (initializeResult) =>
138
antigravitySessionMeta(initializeResult, input.sessionSystemPromptAppend),
139
clientCapabilities: {
140
+ ...input.clientCapabilities,
141
// Advertising writes swaps the agent's diff edits for whole-file client_edit_file.
142
fs: {
143
readTextFile:
packages/client-runtime/src/state/pendingUserInput.test.ts
+27
@@ -178,3 +178,30 @@ describe("buildPendingUserInputAnswers", () => {
178
});
179
});
180
});
181
+
182
+it.each([
183
+ ["single-select", singleSelectQuestion, ["Orchestration-first"], '"Orchestration-first"'],
184
+ [
185
+ "multi-select",
186
+ {
187
+ ...singleSelectQuestion,
188
+ multiSelect: true,
189
+ options: [{ label: "Server" }, { label: "Web" }],
190
+ },
191
+ ["Server", "Web"],
192
+ '["Server","Web"]',
193
+ ],
194
+])("sends a %s answer to a question with the id __proto__", (_kind, question, selected, json) => {
195
+ const answers = buildPendingUserInputAnswers(
196
+ [
197
+ { ...question, id: "__proto__" },
198
+ { ...singleSelectQuestion, id: "name" },
199
+ ],
200
+ {
201
+ ["__proto__"]: { selectedOptionValues: selected },
202
+ name: { selectedOptionValues: ["Orchestration-first"] },
203
+ },
204
+ );
205
+
206
+ expect(JSON.stringify(answers)).toBe(`{"__proto__":${json},"name":"Orchestration-first"}`);
207
+});
packages/client-runtime/src/state/pendingUserInput.ts
+3
-3
@@ -162,15 +162,15 @@ export function buildPendingUserInputAnswers(
162
questions: ReadonlyArray<PendingUserInputQuestion>,
163
draftAnswers: Record<string, PendingUserInputDraftAnswer>,
164
): Record<string, PendingUserInputAnswer> | null {
165
- const answers: Record<string, PendingUserInputAnswer> = {};
165
+ const entries: Array<[string, PendingUserInputAnswer]> = [];
166
167
for (const question of questions) {
168
const answer = resolvePendingUserInputAnswer(question, draftAnswers[question.id]);
169
if (answer === null) {
170
return null;
171
}
172
- answers[question.id] = answer;
172
+ entries.push([question.id, answer]);
173
}
174
175
- return answers;
175
+ return Object.fromEntries(entries);
176
}
packages/client-runtime/src/state/threadRequests.test.ts
+14
@@ -235,6 +235,20 @@ describe("initial user input drafts", () => {
235
customAnswer: " Proposed commit\n\n",
236
});
237
});
238
+
239
+ it("seeds a question with the id __proto__ as its own draft", () => {
240
+ const seeded = seedUserInputDraftAnswers(
241
+ [
242
+ { id: "__proto__", initialAnswer: "Proposed" },
243
+ { id: "name", initialAnswer: "Control" },
244
+ ],
245
+ {},
246
+ );
247
+
248
+ expect(JSON.stringify(seeded)).toBe(
249
+ '{"__proto__":{"customAnswer":"Proposed"},"name":{"customAnswer":"Control"}}',
250
+ );
251
+ });
252
});
253
const projection: OrchestrationV2ThreadProjection = {
254
...v2Projection,
packages/client-runtime/src/state/threadRequests.ts
+9
-12
@@ -99,18 +99,15 @@ export function seedUserInputDraftAnswers<Draft extends { readonly customAnswer?
99
>,
100
drafts: Record<string, Draft>,
101
): Record<string, Draft | { customAnswer: string }> {
102
- let seeded: Record<string, Draft | { customAnswer: string }> = drafts;
103
- for (const question of questions) {
104
- if (
105
- question.initialAnswer === undefined ||
106
- question.allowCustomAnswer === false ||
107
- seeded[question.id] !== undefined
108
- )
109
- continue;
110
- if (seeded === drafts) seeded = { ...drafts };
111
- seeded[question.id] = { customAnswer: question.initialAnswer };
112
- }
113
- return seeded;
102
+ // Entries, not assignment, so an id such as `__proto__` becomes an own draft.
103
+ const seeds = questions.flatMap((question) =>
104
+ question.initialAnswer === undefined ||
105
+ question.allowCustomAnswer === false ||
106
+ Object.hasOwn(drafts, question.id)
107
+ ? []
108
+ : [[question.id, { customAnswer: question.initialAnswer }] as const],
109
+ );
110
+ return seeds.length === 0 ? drafts : { ...drafts, ...Object.fromEntries(seeds) };
111
}
112
113
/** Keys a user-input draft by thread so a thread's resolved requests can be pruned together. */
packages/effect-acp/scripts/generate.ts
+33
-8
@@ -166,6 +166,37 @@ function isJsonArray(value: Schema.Json | undefined): value is ReadonlyArray<Sch
166
return Array.isArray(value);
167
}
168
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
+
200
function normalizeSchemaKeywords(value: Schema.Json): Schema.Json {
201
if (isJsonArray(value)) {
202
return value.map(normalizeSchemaKeywords);
@@ -174,11 +205,7 @@ function normalizeSchemaKeywords(value: Schema.Json): Schema.Json {
205
return value;
206
}
207
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);
209
// ACP's forward-compatible variants exclude known discriminator values.
210
// The Effect generator does not support `not`; express this exact exclusion
211
// as a string pattern while preserving validation of the known variants.
@@ -316,9 +343,7 @@ function flattenCompositions(
343
): Schema.Json {
344
if (isJsonArray(value)) return value.map((child) => flattenCompositions(child, definitions));
345
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));
347
const { allOf, anyOf, ...base } = normalized;
348
const merge = (left: Schema.Json, right: Schema.Json): Schema.Json => {
349
if (
packages/effect-acp/src/_generated/schema-v1.gen.ts
+16
-2
@@ -946,8 +946,22 @@ export const EnumOption = Schema.Struct({
946
identifier: "EnumOption",
947
});
948
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
+};
953
+export const TitledMultiSelectItems = Schema.Struct({
954
+ anyOf: Schema.Array(EnumOption).annotate({ description: "Titled enum options." }),
955
+ _meta: Schema.optionalKey(
956
+ Schema.Union([
957
+ Schema.Record(Schema.String, Schema.Json.annotate({ expected: "JSON value" })).annotate({
958
+ description:
959
+ "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)",
960
+ }),
961
+ Schema.Null,
962
+ ]),
963
+ ),
964
+}).annotate({
965
description: "Items definition for titled multi-select enum properties.",
966
identifier: "TitledMultiSelectItems",
967
});
packages/effect-acp/src/_generated/schema.gen.ts
+18
-2
@@ -1128,8 +1128,24 @@ export const EnumOption = Schema.Struct({
1128
identifier: "EnumOption",
1129
});
1130
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
+};
1135
+export const TitledMultiSelectItems = Schema.Struct({
1136
+ anyOf: Schema.Array(EnumOption)
1137
+ .annotate({ description: "Titled enum options. Must contain at least one option." })
1138
+ .check(Schema.isMinLength(1).annotate({ expected: "a value with a length of at least 1" })),
1139
+ _meta: Schema.optionalKey(
1140
+ Schema.Union([
1141
+ Schema.Record(Schema.String, Schema.Json.annotate({ expected: "JSON value" })).annotate({
1142
+ description:
1143
+ "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)",
1144
+ }),
1145
+ Schema.Null,
1146
+ ]),
1147
+ ),
1148
+}).annotate({
1149
description: "Items definition for titled multi-select enum properties.",
1150
identifier: "TitledMultiSelectItems",
1151
});
packages/effect-acp/src/client.test.ts
+54
@@ -49,6 +49,7 @@ const PermissionRequest = jsonRpcRequest(
49
"session/request_permission",
50
AcpSchema.RequestPermissionRequest,
51
);
52
+const ElicitationResponse = jsonRpcResponse(AcpSchema.CreateElicitationResponse);
53
const PermissionResponse = jsonRpcResponse(AcpSchema.RequestPermissionResponse);
54
const ErrorResponse = Schema.Struct({ id: Schema.String, error: Schema.Unknown });
55
const DieResponse = Schema.Struct({
@@ -1295,6 +1296,59 @@ it.layer(NodeServices.layer)("effect-acp client", (it) => {
1296
}),
1297
);
1298
1299
+ it.effect("hands titled multi-select elicitation fields to the handler", () =>
1300
+ Effect.gen(function* () {
1301
+ const { stdio, input, output } = yield* makeInMemoryStdio();
1302
+ const scope = yield* Scope.make();
1303
+ const acp = yield* AcpClient.make(stdio).pipe(Effect.provideService(Scope.Scope, scope));
1304
+ const received = yield* Deferred.make<AcpSchema.CreateElicitationRequest>();
1305
+ yield* acp.handleElicitation((request) =>
1306
+ Deferred.succeed(received, request).pipe(
1307
+ Effect.as({ action: "accept" as const, content: { areas: ["ui"] } }),
1308
+ ),
1309
+ );
1310
+ const requestedSchema = {
1311
+ type: "object",
1312
+ properties: {
1313
+ areas: {
1314
+ type: "array",
1315
+ title: "Areas",
1316
+ items: {
1317
+ anyOf: [
1318
+ { const: "api", title: "API", description: "Server routes" },
1319
+ { const: "ui", title: "Interface" },
1320
+ ],
1321
+ },
1322
+ },
1323
+ },
1324
+ required: ["areas"],
1325
+ };
1326
+
1327
+ yield* Queue.offer(
1328
+ input,
1329
+ yield* encodeJsonl(jsonRpcRequest("elicitation/create", Schema.Unknown), {
1330
+ jsonrpc: "2.0",
1331
+ id: "elicitation",
1332
+ method: "elicitation/create",
1333
+ params: {
1334
+ sessionId: "session-1",
1335
+ mode: "form",
1336
+ message: "Pick areas",
1337
+ requestedSchema,
1338
+ },
1339
+ headers: [],
1340
+ }),
1341
+ );
1342
+ const response = yield* Queue.take(output).pipe(
1343
+ Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(ElicitationResponse))),
1344
+ );
1345
+ assert.deepEqual(response.result, { action: "accept", content: { areas: ["ui"] } });
1346
+ const request = yield* Deferred.await(received);
1347
+ assert.deepEqual("requestedSchema" in request && request.requestedSchema, requestedSchema);
1348
+ yield* Scope.close(scope, Exit.void);
1349
+ }),
1350
+ );
1351
+
1352
it.effect(
1353
"routes a standard prompt response after Grok extension notifications in the same batch",
1354
() =>
packages/effect-acp/src/schema.test.ts
+21
@@ -13,6 +13,27 @@ describe("pinned ACP wire schemas", () => {
13
expect(accepts({ type: "future_content", payload: { value: 1 } })).toBe(true);
14
});
15
16
+ it("decodes titled multi-select form fields in v1 and v2", () => {
17
+ const titled = (anyOf: ReadonlyArray<unknown>) => ({
18
+ sessionId: "session-1",
19
+ mode: "form",
20
+ message: "Pick areas",
21
+ requestedSchema: {
22
+ type: "object",
23
+ properties: { areas: { type: "array", minItems: 1, items: { anyOf } } },
24
+ required: ["areas"],
25
+ },
26
+ });
27
+ const form = titled([
28
+ { const: "api", title: "API", description: "Server routes" },
29
+ { const: "ui", title: "Interface" },
30
+ ]);
31
+ for (const request of [V1.CreateElicitationRequest, V2.CreateElicitationRequest]) {
32
+ expect(Schema.decodeUnknownSync(request)(form)).toEqual(form);
33
+ expect(Schema.is(request)(titled([{ const: "api" }]))).toBe(false);
34
+ }
35
+ });
36
+
37
it("keeps v1 command inputs compatible with native agents", () => {
38
const command = { name: "plan", description: "Make a plan", input: { hint: "Task" } };
39
const isAvailableCommand = Schema.is(V1.AvailableCommand);
packages/provider-acp/src/server/adapter.ts
+24
-52
@@ -99,6 +99,7 @@ import {
99
makeAcpClientPolicyGrants,
100
unknownRecord,
101
} from "./clientPolicy.ts";
102
+import { parseElicitationForm } from "./elicitationForm.ts";
103
import {
104
makeAcpClientTerminals,
105
resolveEmbeddedTerminalContent,
@@ -1321,22 +1322,6 @@ function selectAutoApprovedPermissionOption(
1322
);
1323
}
1324
1324
-function elicitationContent(
1325
- answers: ProviderUserInputAnswers,
1326
- allowedKeys: ReadonlySet<string>,
1327
-): Record<string, EffectAcpSchema.ElicitationContentValue> {
1328
- const content: Record<string, EffectAcpSchema.ElicitationContentValue> = {};
1329
- for (const [key, value] of Object.entries(answers)) {
1330
- if (!allowedKeys.has(key)) continue;
1331
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
1332
- content[key] = value;
1333
- } else if (Array.isArray(value)) {
1334
- content[key] = value.filter((entry): entry is string => typeof entry === "string");
1335
- }
1336
- }
1337
- return content;
1338
-}
1339
-
1325
interface ActiveTextSegment {
1326
readonly nativeItemId: string;
1327
readonly startedAt: DateTime.Utc;
@@ -6754,36 +6739,30 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
6739
if (params.mode !== "form" || !("requestedSchema" in params)) {
6740
return { action: "decline" } as const;
6741
}
6757
- const requestedSchema = unknownRecord(params.requestedSchema);
6758
- const properties = unknownRecord(requestedSchema?.properties) ?? {};
6742
const nativeForm = flavor.extractElicitationForm?.(params);
6743
+ const parsedForm =
6744
+ nativeForm === undefined
6745
+ ? parseElicitationForm(params.requestedSchema, params.message)
6746
+ : undefined;
6747
+ const form =
6748
+ nativeForm ??
6749
+ (parsedForm === undefined
6750
+ ? undefined
6751
+ : {
6752
+ questions: parsedForm.questions,
6753
+ respond: (
6754
+ answers: ProviderUserInputAnswers,
6755
+ ): EffectAcpSchema.CreateElicitationResponse => {
6756
+ const content = parsedForm.content(answers);
6757
+ return content === undefined
6758
+ ? { action: "cancel" }
6759
+ : { action: "accept", content };
6760
+ },
6761
+ });
6762
+ if (form === undefined) return { action: "decline" } as const;
6763
const elicitationScopeId =
6764
"sessionId" in params ? params.sessionId : `request:${params.requestId}`;
6762
- const questions =
6763
- nativeForm?.questions ??
6764
- Object.entries(properties).map(
6765
- ([id, property], index): OrchestrationV2UserInputQuestion => {
6766
- const record = unknownRecord(property);
6767
- const enumValues = Array.isArray(record?.enum)
6768
- ? record.enum.filter((value): value is string => typeof value === "string")
6769
- : [];
6770
- const options =
6771
- enumValues.length > 0
6772
- ? enumValues.map((value) => ({ label: value, description: value }))
6773
- : record?.type === "boolean"
6774
- ? [
6775
- { label: "true", description: "Yes" },
6776
- { label: "false", description: "No" },
6777
- ]
6778
- : [];
6779
- return {
6780
- id,
6781
- header: nonEmptyText(record?.title, `Question ${index + 1}`),
6782
- question: nonEmptyText(record?.description, params.message),
6783
- options,
6784
- };
6785
- },
6786
- );
6765
+
6766
const userInput = yield* requestUserInputWithAdmission(
6767
handlerGeneration,
6768
Effect.gen(function* () {
@@ -6795,7 +6774,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
6774
return {
6775
nativeItemId: nativeRequestId,
6776
nativeRequestId,
6798
- questions,
6777
+ questions: form.questions,
6778
};
6779
}),
6780
transportRequestId,
@@ -6803,14 +6782,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
6782
const response =
6783
userInput.answers === null
6784
? ({ action: "cancel" } as const)
6806
- : (nativeForm?.respond(userInput.answers) ??
6807
- ({
6808
- action: "accept",
6809
- content: elicitationContent(
6810
- userInput.answers,
6811
- new Set(Object.keys(properties)),
6812
- ),
6813
- } as const));
6785
+ : form.respond(userInput.answers);
6786
yield* userInput.acknowledgeNativeResponse;
6787
return response;
6788
}).pipe(holdingAgentRequest(handlerGeneration)),
packages/provider-acp/src/server/elicitationForm.test.ts
new
+47
@@ -0,0 +1,47 @@
1
+import { assert, describe, it } from "@effect/vitest";
2
+
3
+import { parseElicitationForm } from "./elicitationForm.ts";
4
+
5
+describe("parseElicitationForm", () => {
6
+ for (const type of ["string", "array"] as const) {
7
+ it.each([
8
+ { values: [" padded ", "", "plain"], labels: ["padded", '""', "plain"] },
9
+ { values: [" a", "a", "b"], labels: ['" a"', '"a"', "b"] },
10
+ { values: [" a", "a", '"a"'], labels: ['" a"', '"a"', '"\\"a\\""'] },
11
+ ])(
12
+ `preserves ${type} enum values with distinct readable labels: $values`,
13
+ ({ values, labels }) => {
14
+ const form = parseElicitationForm(
15
+ {
16
+ type: "object",
17
+ properties: {
18
+ answer:
19
+ type === "array"
20
+ ? { type, items: { type: "string", enum: values } }
21
+ : { type, enum: values },
22
+ },
23
+ required: ["answer"],
24
+ },
25
+ "Choose",
26
+ );
27
+ assert(form !== undefined);
28
+ const question = form.questions[0];
29
+ assert(question !== undefined);
30
+ assert.deepStrictEqual(
31
+ question.options.map((option) => option.label),
32
+ labels,
33
+ );
34
+ assert.deepStrictEqual(
35
+ question.options.map((option) => option.value),
36
+ values,
37
+ );
38
+ assert.strictEqual(question.allowCustomAnswer, false);
39
+ assert.strictEqual(question.multiSelect, type === "array" ? true : undefined);
40
+ for (const value of values) {
41
+ const answer = type === "array" ? [value] : value;
42
+ assert.deepStrictEqual(form.content({ answer }), { answer });
43
+ }
44
+ },
45
+ );
46
+ }
47
+});
packages/provider-acp/src/server/elicitationForm.ts
new
+223
@@ -0,0 +1,223 @@
1
+import type {
2
+ OrchestrationV2UserInputQuestion,
3
+ ProviderUserInputAnswers,
4
+} from "@t3tools/contracts";
5
+import type * as EffectAcpSchema from "effect-acp/compat";
6
+
7
+import { unknownRecord } from "./clientPolicy.ts";
8
+
9
+type Field =
10
+ | { readonly kind: "text" }
11
+ | { readonly kind: "number"; readonly integer: boolean }
12
+ | { readonly kind: "boolean" }
13
+ | { readonly kind: "choice"; readonly values: ReadonlySet<string> }
14
+ | {
15
+ readonly kind: "multiChoice";
16
+ readonly values: ReadonlySet<string>;
17
+ readonly minItems: number;
18
+ readonly maxItems: number;
19
+ };
20
+
21
+type Option = OrchestrationV2UserInputQuestion["options"][number];
22
+
23
+export interface ElicitationForm {
24
+ readonly questions: ReadonlyArray<OrchestrationV2UserInputQuestion>;
25
+ /**
26
+ * Types answers as the schema declares them. Unknown keys and options are
27
+ * dropped, as is an answer that does not fit its field. Returns undefined
28
+ * when a required field is left without a valid answer.
29
+ */
30
+ readonly content: (
31
+ answers: ProviderUserInputAnswers,
32
+ ) => Record<string, EffectAcpSchema.ElicitationContentValue> | undefined;
33
+}
34
+
35
+function text(value: unknown): string | undefined {
36
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
37
+}
38
+
39
+/** All of `entries` as options, or undefined when any entry cannot be one. */
40
+function choiceOptions(
41
+ entries: unknown,
42
+ toOption: (entry: unknown) => Option | undefined,
43
+): Option[] | undefined {
44
+ if (!Array.isArray(entries) || entries.length === 0) return undefined;
45
+ const options = entries.map(toOption);
46
+ return options.every((option) => option !== undefined) ? options : undefined;
47
+}
48
+
49
+function enumOptions(entries: unknown): Option[] | undefined {
50
+ if (
51
+ !Array.isArray(entries) ||
52
+ entries.length === 0 ||
53
+ !entries.every((value): value is string => typeof value === "string")
54
+ )
55
+ return undefined;
56
+ const counts = new Map<string, number>();
57
+ for (const value of entries) counts.set(value.trim(), (counts.get(value.trim()) ?? 0) + 1);
58
+ const options = entries.map((value) => {
59
+ const plain = value.trim();
60
+ const label = plain !== "" && counts.get(plain) === 1 ? plain : JSON.stringify(value);
61
+ return { label, description: label, value };
62
+ });
63
+ // A quoted fallback can collide with a literal label; quote every value in that case.
64
+ return new Set(options.map((option) => option.label)).size === options.length
65
+ ? options
66
+ : options.map((option) => {
67
+ const label = JSON.stringify(option.value);
68
+ return { ...option, label, description: label };
69
+ });
70
+}
71
+
72
+/** Titled entries (`oneOf` on strings, `anyOf` on array items) carry a title for their `const`. */
73
+function titledOption(entry: unknown): Option | undefined {
74
+ const option = unknownRecord(entry);
75
+ const label = text(option?.title) ?? text(option?.const);
76
+ return typeof option?.const === "string" && label !== undefined
77
+ ? { label, description: text(option.description) ?? label, value: option.const }
78
+ : undefined;
79
+}
80
+
81
+function parseField(
82
+ property: Readonly<Record<string, unknown>>,
83
+): { readonly field: Field; readonly options: Option[] } | undefined {
84
+ switch (property.type) {
85
+ case "string": {
86
+ // ACP treats a null `enum` or `oneOf` like an omitted one.
87
+ if ((property.enum ?? property.oneOf ?? undefined) === undefined) {
88
+ return { field: { kind: "text" }, options: [] };
89
+ }
90
+ const options = Array.isArray(property.oneOf)
91
+ ? choiceOptions(property.oneOf, titledOption)
92
+ : enumOptions(property.enum);
93
+ return options === undefined
94
+ ? undefined
95
+ : {
96
+ field: { kind: "choice", values: new Set(options.map(optionValue)) },
97
+ options,
98
+ };
99
+ }
100
+ case "array": {
101
+ // String items list plain values in `enum`; titled items list `{ const, title }` in `anyOf`.
102
+ const items = unknownRecord(property.items);
103
+ const options =
104
+ items?.type === "string"
105
+ ? enumOptions(items.enum)
106
+ : items !== undefined && items.type === undefined
107
+ ? choiceOptions(items.anyOf, titledOption)
108
+ : undefined;
109
+ if (options === undefined) return undefined;
110
+ // The schema decode already limits counts to non-negative integers.
111
+ const values = new Set(options.map(optionValue));
112
+ const minItems = typeof property.minItems === "number" ? property.minItems : 0;
113
+ const maxItems = typeof property.maxItems === "number" ? property.maxItems : Infinity;
114
+ // Clients require a selection, so empty-only questions cannot be answered.
115
+ if (maxItems === 0 || minItems > maxItems || minItems > values.size) return undefined;
116
+ return { field: { kind: "multiChoice", values, minItems, maxItems }, options };
117
+ }
118
+ case "boolean":
119
+ return {
120
+ field: { kind: "boolean" },
121
+ options: [
122
+ { label: "true", description: "Yes", value: "true" },
123
+ { label: "false", description: "No", value: "false" },
124
+ ],
125
+ };
126
+ case "number":
127
+ case "integer":
128
+ return { field: { kind: "number", integer: property.type === "integer" }, options: [] };
129
+ default:
130
+ return undefined;
131
+ }
132
+}
133
+
134
+function optionValue(option: Option): string {
135
+ return option.value ?? option.label;
136
+}
137
+
138
+function typedAnswer(
139
+ field: Field,
140
+ answer: unknown,
141
+): EffectAcpSchema.ElicitationContentValue | undefined {
142
+ switch (field.kind) {
143
+ case "text":
144
+ return typeof answer === "string" ? answer : undefined;
145
+ case "boolean":
146
+ if (typeof answer === "boolean") return answer;
147
+ return answer === "true" ? true : answer === "false" ? false : undefined;
148
+ case "number": {
149
+ const parsed =
150
+ typeof answer === "number"
151
+ ? answer
152
+ : typeof answer === "string" && answer.trim().length > 0
153
+ ? Number(answer.trim())
154
+ : Number.NaN;
155
+ if (!Number.isFinite(parsed)) return undefined;
156
+ return field.integer && !Number.isInteger(parsed) ? undefined : parsed;
157
+ }
158
+ case "choice":
159
+ return typeof answer === "string" && field.values.has(answer) ? answer : undefined;
160
+ case "multiChoice": {
161
+ if (!Array.isArray(answer)) return undefined;
162
+ const selected = [
163
+ ...new Set(
164
+ answer.filter(
165
+ (entry): entry is string => typeof entry === "string" && field.values.has(entry),
166
+ ),
167
+ ),
168
+ ];
169
+ // `[]` is an explicit empty selection, but a selection of only unknown
170
+ // options is not one.
171
+ if (selected.length === 0 && answer.length > 0) return undefined;
172
+ return selected.length >= field.minItems && selected.length <= field.maxItems
173
+ ? selected
174
+ : undefined;
175
+ }
176
+ }
177
+}
178
+
179
+// Decline unaskable forms; validate types and selection counts, leaving other constraints to the agent.
180
+export function parseElicitationForm(
181
+ requestedSchema: unknown,
182
+ message: string,
183
+): ElicitationForm | undefined {
184
+ const schema = unknownRecord(requestedSchema);
185
+ const required = new Set(
186
+ Array.isArray(schema?.required)
187
+ ? schema.required.filter((key): key is string => typeof key === "string")
188
+ : [],
189
+ );
190
+ const fields = new Map<string, Field>();
191
+ const questions: OrchestrationV2UserInputQuestion[] = [];
192
+ for (const [id, value] of Object.entries(unknownRecord(schema?.properties) ?? {})) {
193
+ const property = unknownRecord(value);
194
+ const parsed = property === undefined ? undefined : parseField(property);
195
+ // Question ids must survive the contract's trim to round-trip answers.
196
+ if (property === undefined || parsed === undefined || text(id) !== id) return undefined;
197
+ fields.set(id, parsed.field);
198
+ questions.push({
199
+ id,
200
+ header: text(property.title) ?? `Question ${questions.length + 1}`,
201
+ question: text(property.description) ?? message,
202
+ options: parsed.options,
203
+ ...(parsed.field.kind === "text" || parsed.field.kind === "number"
204
+ ? {}
205
+ : { allowCustomAnswer: false }),
206
+ ...(parsed.field.kind === "multiChoice" ? { multiSelect: true } : {}),
207
+ });
208
+ }
209
+ return {
210
+ questions,
211
+ content: (answers) => {
212
+ const entries: Array<[string, EffectAcpSchema.ElicitationContentValue]> = [];
213
+ for (const [id, field] of fields) {
214
+ const typed = Object.hasOwn(answers, id) ? typedAnswer(field, answers[id]) : undefined;
215
+ if (typed !== undefined) entries.push([id, typed]);
216
+ else if (required.has(id)) return undefined;
217
+ }
218
+ // Own properties for every field, `__proto__` included; assigning to
219
+ // `{}` would hit its inherited setter instead.
220
+ return Object.fromEntries(entries);
221
+ },
222
+ };
223
+}