Skip to content
TypeScript

fix(acp): Droid answers no longer cancel AskUser (#20417)

travelvector4296624ddf3d
diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
index abc2ae1fabd..82cd3d7a3a1 100644
--- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
@@ -4,7 +4,11 @@ import {
normalizeDevinSessionUpdate,
normalizeDevinToolCall,
extractDevinSubagentUpdate,
+ makeAcpRegistryAdapterV2,
} from "@t3tools/provider-acp-registry/testing";
+import { AcpRegistrySettings } from "@t3tools/provider-acp-registry/settings";
+import { AcpRegistryCatalog } from "@t3tools/provider-acp-registry/server/AcpRegistrySupport";
+import { decodeAcpReplayTranscript, makeAcpReplayRuntime } from "./AcpAdapterV2.testkit.ts";
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeChildProcess from "node:child_process";
import * as NodeFS from "node:fs";
@@ -24,6 +28,7 @@ import {
type OrchestrationV2ProviderThread,
type OrchestrationV2TurnItem,
type ProviderOptionDescriptor,
+ type ProviderUserInputAnswers,
} from "@t3tools/contracts";
import { GrokSettings } from "@t3tools/provider-grok/settings";
import * as HostProcess from "@t3tools/shared/HostProcess";
@@ -92,6 +97,8 @@ import {
type AcpAdapterV2SubagentUpdate,
} from "@t3tools/provider-acp/server/adapter";
+import { appendUserInputAttachmentPaths } from "../../provider/userInputAttachments.ts";
+
import { makeGrokAdapterV2, makeGrokAcpAdapterFlavor } from "@t3tools/provider-grok/testing";
import {
acpRegistryPromptFailure,
@@ -99,6 +106,7 @@ import {
} from "@t3tools/provider-acp-registry/testing";
const DEFAULT_GROK_SETTINGS = Schema.decodeSync(GrokSettings)({});
+const DROID_SETTINGS = Schema.decodeSync(AcpRegistrySettings)({ agentId: "factory-droid" });
const layerHost = TestProviderHost.layer().pipe(Layer.provide(NodeServices.layer));
@@ -633,6 +641,269 @@ function assertReinjectedInstructions(
}
describe("AcpAdapterV2", () => {
+ // Factory Droid 0.243.0 sends an optional text companion for every AskUser choice.
+ const droidChoice = {
+ type: "string",
+ title: "Format",
+ description: "Which reply format?",
+ oneOf: [
+ { const: "option_0", title: "JSON" },
+ { const: "option_1", title: "Plain text" },
+ { const: "other", title: "Other answer" },
+ ],
+ };
+ const droidSchema = {
+ type: "object",
+ properties: {
+ question_1: droidChoice,
+ question_1_other: { type: "string" },
+ question_2: { ...droidChoice, title: "Alternative" },
+ question_2_other: { type: "string" },
+ },
+ required: ["question_1", "question_2"],
+ };
+ const droidQuestions = ["question_1", "question_2"].map((id, index) => ({
+ id,
+ header: index === 0 ? "Format" : "Alternative",
+ question: "Which reply format?",
+ options: [
+ { label: "JSON", description: "JSON", value: "option_0" },
+ { label: "Plain text", description: "Plain text", value: "option_1" },
+ ],
+ }));
+
+ it.live.each([
+ {
+ scenario: "preserves selected IDs and encodes custom answers",
+ schema: droidSchema,
+ questions: droidQuestions,
+ answers: { question_1: "option_1", question_2: "Markdown" },
+ result: {
+ action: "accept",
+ content: { question_1: "option_1", question_2: "other", question_2_other: "Markdown" },
+ },
+ },
+ {
+ scenario: "preserves selected labels and attachment paths in custom answers",
+ schema: droidSchema,
+ questions: droidQuestions,
+ withAttachments: true,
+ answers: {
+ question_1: "option_1",
+ question_2: "option_1\n\nAttached notes: keep this custom text",
+ },
+ result: (directory: string) => ({
+ action: "accept",
+ content: {
+ question_1: "other",
+ question_1_other: `Plain text\n\nAttached image "shot.png": ${JSON.stringify(NodePath.join(directory, "droid-shot.png"))}\nAttached file "spec.txt": ${JSON.stringify(NodePath.join(directory, "droid-spec.txt"))}`,
+ question_2: "other",
+ question_2_other: "option_1\n\nAttached notes: keep this custom text",
+ },
+ }),
+ },
+ {
+ scenario: "cancels without accepting answers",
+ schema: droidSchema,
+ questions: droidQuestions,
+ answers: undefined,
+ result: { action: "cancel" },
+ },
+ {
+ scenario: "falls back for an unrelated form",
+ schema: { type: "object", properties: { name: { type: "string" } } },
+ questions: [{ id: "name", header: "Question 1", question: "Your answer?", options: [] }],
+ answers: { name: "Ada" },
+ result: { action: "accept", content: { name: "Ada" } },
+ },
+ {
+ scenario: "falls back when the companion field is missing",
+ schema: {
+ type: "object",
+ properties: { question_1: droidChoice },
+ required: ["question_1"],
+ },
+ questions: [
+ { id: "question_1", header: "Format", question: "Which reply format?", options: [] },
+ ],
+ answers: { question_1: "Markdown" },
+ result: { action: "accept", content: { question_1: "Markdown" } },
+ },
+ ])("Droid elicitation $scenario", ({ schema, questions, answers, result, withAttachments }) =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-droid-form-" });
+ const statusPath = path.join(directory, "status.json");
+ const expectedResult = typeof result === "function" ? result(directory) : result;
+ let preparedAnswers: ProviderUserInputAnswers | undefined = answers;
+ if (withAttachments && answers !== undefined) {
+ yield* fileSystem.writeFileString(path.join(directory, "droid-shot.png"), "image");
+ yield* fileSystem.writeFileString(path.join(directory, "droid-spec.txt"), "spec");
+ preparedAnswers = yield* appendUserInputAttachmentPaths({
+ answers,
+ attachmentsDir: directory,
+ attachmentsByQuestionId: {
+ question_1: [
+ {
+ type: "image",
+ id: "droid-shot",
+ name: "shot.png",
+ mimeType: "image/png",
+ sizeBytes: 5,
+ },
+ {
+ type: "file",
+ id: "droid-spec",
+ name: "spec.txt",
+ mimeType: "text/plain",
+ sizeBytes: 4,
+ },
+ ],
+ },
+ });
+ }
+ const driver = ProviderDriverKind.make("acpRegistry");
+ const transcript = yield* decodeAcpReplayTranscript(
+ {
+ provider: driver,
+ protocol: "acp.ndjson-jsonrpc",
+ version: "1",
+ scenario: "droid-form",
+ entries: [
+ {
+ type: "expect_outbound",
+ frame: { kind: "request", method: "initialize", params: "<any>" },
+ },
+ {
+ type: "emit_inbound",
+ frame: {
+ kind: "response",
+ method: "initialize",
+ result: { protocolVersion: 1, agentCapabilities: {}, authMethods: [] },
+ },
+ },
+ {
+ type: "expect_outbound",
+ frame: { kind: "request", method: "session/new", params: "<any>" },
+ },
+ {
+ type: "emit_inbound",
+ frame: {
+ kind: "response",
+ method: "session/new",
+ result: { sessionId: "droid-session" },
+ },
+ },
+ {
+ type: "expect_outbound",
+ frame: { kind: "request", method: "session/prompt", params: "<any>" },
+ },
+ {
+ type: "emit_inbound",
+ frame: {
+ kind: "request",
+ method: "elicitation/create",
+ params: {
+ mode: "form",
+ sessionId: "droid-session",
+ message: "Your answer?",
+ requestedSchema: schema,
+ },
+ },
+ },
+ {
+ type: "expect_outbound",
+ frame: {
+ kind: "response",
+ method: "elicitation/create",
+ result: expectedResult,
+ },
+ },
+ {
+ type: "emit_inbound",
+ frame: {
+ kind: "response",
+ method: "session/prompt",
+ result: { stopReason: "end_turn" },
+ },
+ },
+ { type: "runtime_exit", status: "success" },
+ ],
+ },
+ driver,
+ );
+ const instanceId = ProviderInstanceId.make("droid-form-test");
+ const adapter = yield* makeAcpRegistryAdapterV2({
+ instanceId,
+ selfInvocation: yield* resolveSelfInvocation(),
+ settings: DROID_SETTINGS,
+ environment: {},
+ makeRuntime: makeAcpReplayRuntime({
+ transcript,
+ statusPath,
+ fileSystem,
+ scriptPath: yield* path.fromFileUrl(
+ new URL("../../../scripts/acp-replay-agent.ts", import.meta.url),
+ ),
+ childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner,
+ }),
+ }).pipe(
+ Effect.provide(
+ Layer.mock(AcpRegistryCatalog)({ resolve: () => Effect.die("runtime is injected") }),
+ ),
+ );
+ const threadId = ThreadId.make("droid-form-thread");
+ const modelSelection = { instanceId, model: "default" } as const;
+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
+ runtimeMode: "approval-required",
+ interactionMode: "default",
+ cwd: directory,
+ });
+ const runtime = yield* adapter.openSession({
+ threadId,
+ modelSelection,
+ runtimePolicy,
+ providerSessionId: ProviderSessionId.make("droid-form-session"),
+ });
+ const providerThread = yield* runtime.ensureThread({
+ threadId,
+ modelSelection,
+ runtimePolicy,
+ });
+ yield* runtime.startTurn(
+ makeTurnInput({
+ threadId,
+ providerThread,
+ instanceId,
+ runtimePolicy,
+ now: yield* DateTime.now,
+ }),
+ );
+ const item = Option.getOrThrow(
+ yield* runtime.events.pipe(
+ Stream.filter(
+ (event) =>
+ event.type === "turn_item.updated" && event.turnItem.type === "user_input_request",
+ ),
+ Stream.runHead,
+ ),
+ );
+ if (item.type !== "turn_item.updated" || item.turnItem.type !== "user_input_request")
+ return yield* Effect.die("Expected Droid question");
+ assert.deepEqual(item.turnItem.questions, questions);
+ yield* runtime.respondToRuntimeRequest({
+ requestId: item.turnItem.requestId,
+ ...(preparedAnswers === undefined ? {} : { answers: preparedAnswers }),
+ });
+ const terminal = yield* runtime.events.pipe(
+ Stream.filter((event) => event.type === "turn.terminal"),
+ Stream.runHead,
+ );
+ assert.equal(Option.getOrThrow(terminal).status, "completed");
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
+ );
+
it.live.each(["failed", "recovered", "completed", "cancelled"] as const)(
"projects Mistral retry notices and their %s outcome",
(outcome) =>
diff --git a/packages/provider-acp-registry/src/server/adapter.ts b/packages/provider-acp-registry/src/server/adapter.ts
index f6f407394d9..d8eeca222bd 100644
--- a/packages/provider-acp-registry/src/server/adapter.ts
+++ b/packages/provider-acp-registry/src/server/adapter.ts
@@ -8,6 +8,7 @@ import {
normalizeDevinToolCall,
extractDevinSubagentUpdate,
} from "./devinAcp.ts";
+import { extractDroidElicitationForm } from "./droidAcp.ts";
import {
copilotClientCapabilitiesMeta,
extractCopilotSubagentUpdate,
@@ -212,6 +213,9 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu
capabilities: AcpProviderCapabilitiesV2,
customModels: readCustomModelEntries(options.settings.customModels).map((entry) => entry.slug),
promptFailure: (cause) => acpRegistryPromptFailure(registryAgentId, cause),
+ ...(registryAgentId === "factory-droid"
+ ? { extractElicitationForm: extractDroidElicitationForm }
+ : {}),
...(registryAgentId === "mistral-vibe"
? { registerExtensions: registerMistralVibeAcpExtensions }
: {}),
diff --git a/packages/provider-acp-registry/src/server/droidAcp.ts b/packages/provider-acp-registry/src/server/droidAcp.ts
new file mode 100644
index 00000000000..d5ad446a8c7
--- /dev/null
+++ b/packages/provider-acp-registry/src/server/droidAcp.ts
@@ -0,0 +1,84 @@
+import { type OrchestrationV2UserInputQuestion, TrimmedNonEmptyString } from "@t3tools/contracts";
+import type { AcpAdapterV2Flavor } from "@t3tools/provider-acp/server/adapter";
+import * as Predicate from "effect/Predicate";
+import * as Schema from "effect/Schema";
+
+const isDroidForm = Schema.is(
+ Schema.Struct({
+ properties: Schema.Record(Schema.String, Schema.Unknown),
+ required: Schema.Array(Schema.String),
+ }),
+);
+const isDroidQuestion = Schema.is(
+ Schema.Struct({
+ type: Schema.Literal("string"),
+ title: TrimmedNonEmptyString,
+ description: TrimmedNonEmptyString,
+ oneOf: Schema.Array(
+ Schema.Struct({
+ const: Schema.String.check(Schema.isPattern(/^(?:option_\d+|other)$/)),
+ title: TrimmedNonEmptyString,
+ }),
+ ),
+ }),
+);
+const isDroidCompanion = Schema.is(Schema.Struct({ type: Schema.Literal("string") }));
+
+// Droid pairs each choice with an optional *_other field. The client already
+// offers custom answers, so hide the companion and restore it in the response.
+export const extractDroidElicitationForm: NonNullable<
+ AcpAdapterV2Flavor["extractElicitationForm"]
+> = (request) => {
+ if (request.mode !== "form" || !isDroidForm(request.requestedSchema)) return undefined;
+ const { properties, required } = request.requestedSchema;
+ const questions: Array<OrchestrationV2UserInputQuestion> = [];
+ for (const [id, field] of Object.entries(properties)) {
+ if (!/^question_[1-9]\d*$/.test(id)) continue;
+ if (!isDroidQuestion(field) || !isDroidCompanion(properties[`${id}_other`])) return undefined;
+ const options = field.oneOf
+ .filter((option) => option.const !== "other")
+ .map((option) => ({ label: option.title, description: option.title, value: option.const }));
+ if (options.length === 0 || !field.oneOf.some((option) => option.const === "other")) {
+ return undefined;
+ }
+ questions.push({ id, header: field.title, question: field.description, options });
+ }
+ // Recognize only complete forms; leave every other schema to the ACP fallback.
+ const requiredIds = new Set(required);
+ if (
+ questions.length === 0 ||
+ Object.keys(properties).length !== questions.length * 2 ||
+ requiredIds.size !== questions.length ||
+ questions.some((question) => !requiredIds.has(question.id))
+ ) {
+ return undefined;
+ }
+ return {
+ questions,
+ respond: (answers) => {
+ const entries: Array<[string, string]> = [];
+ for (const question of questions) {
+ const answer = Object.hasOwn(answers, question.id) ? answers[question.id] : undefined;
+ if (!Predicate.isString(answer) || answer.trim().length === 0) return { action: "cancel" };
+ if (question.options.some((option) => option.value === answer)) {
+ entries.push([question.id, answer]);
+ } else {
+ // Intake appends server attachment references to the selected choice ID.
+ const attachmentStart = answer.indexOf("\n\n");
+ const selectedOption = question.options.find(
+ (option) =>
+ option.value === answer.slice(0, attachmentStart) &&
+ /^\n\nAttached (?:image|file) "(?:\\.|[^"\\\r\n])*": "/.test(
+ answer.slice(attachmentStart),
+ ),
+ );
+ const text = selectedOption
+ ? `${selectedOption.label}${answer.slice(attachmentStart)}`
+ : answer;
+ entries.push([question.id, "other"], [`${question.id}_other`, text]);
+ }
+ }
+ return { action: "accept", content: Object.fromEntries(entries) };
+ },
+ };
+};
diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts
index 4faedb4a93c..2c007db0ce0 100644
--- a/packages/provider-acp/src/server/adapter.ts
+++ b/packages/provider-acp/src/server/adapter.ts
@@ -224,6 +224,14 @@ export interface AcpAdapterV2Flavor {
readonly url: string;
readonly message: string;
}) => Effect.Effect<boolean>;
+ readonly extractElicitationForm?: (request: EffectAcpSchema.CreateElicitationRequest) =>
+ | {
+ readonly questions: ReadonlyArray<OrchestrationV2UserInputQuestion>;
+ readonly respond: (
+ answers: ProviderUserInputAnswers,
+ ) => EffectAcpSchema.CreateElicitationResponse;
+ }
+ | undefined;
readonly withRuntimeStartup?: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
readonly makeRuntime: (
input: AcpAdapterV2RuntimeInput,
@@ -6141,31 +6149,34 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
}
const requestedSchema = unknownRecord(params.requestedSchema);
const properties = unknownRecord(requestedSchema?.properties) ?? {};
+ const nativeForm = flavor.extractElicitationForm?.(params);
const elicitationScopeId =
"sessionId" in params ? params.sessionId : `request:${params.requestId}`;
- const questions = Object.entries(properties).map(
- ([id, property], index): OrchestrationV2UserInputQuestion => {
- const record = unknownRecord(property);
- const enumValues = Array.isArray(record?.enum)
- ? record.enum.filter((value): value is string => typeof value === "string")
- : [];
- const options =
- enumValues.length > 0
- ? enumValues.map((value) => ({ label: value, description: value }))
- : record?.type === "boolean"
- ? [
- { label: "true", description: "Yes" },
- { label: "false", description: "No" },
- ]
- : [];
- return {
- id,
- header: nonEmptyText(record?.title, `Question ${index + 1}`),
- question: nonEmptyText(record?.description, params.message),
- options,
- };
- },
- );
+ const questions =
+ nativeForm?.questions ??
+ Object.entries(properties).map(
+ ([id, property], index): OrchestrationV2UserInputQuestion => {
+ const record = unknownRecord(property);
+ const enumValues = Array.isArray(record?.enum)
+ ? record.enum.filter((value): value is string => typeof value === "string")
+ : [];
+ const options =
+ enumValues.length > 0
+ ? enumValues.map((value) => ({ label: value, description: value }))
+ : record?.type === "boolean"
+ ? [
+ { label: "true", description: "Yes" },
+ { label: "false", description: "No" },
+ ]
+ : [];
+ return {
+ id,
+ header: nonEmptyText(record?.title, `Question ${index + 1}`),
+ question: nonEmptyText(record?.description, params.message),
+ options,
+ };
+ },
+ );
const userInput = yield* requestUserInputWithAdmission(
handlerGeneration,
Effect.gen(function* () {
@@ -6185,13 +6196,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
const response =
userInput.answers === null
? ({ action: "cancel" } as const)
- : ({
+ : (nativeForm?.respond(userInput.answers) ??
+ ({
action: "accept",
content: elicitationContent(
userInput.answers,
new Set(Object.keys(properties)),
),
- } as const);
+ } as const));
yield* userInput.acknowledgeNativeResponse;
return response;
}).pipe(holdingAgentRequest(handlerGeneration)),