diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index fb908ef38d..3f07fe70ac 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -1,6 +1,7 @@ // @effect-diagnostics nodeBuiltinImport:off import * as NodeChildProcess from "node:child_process"; import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; @@ -67,6 +68,7 @@ import { AcpProviderCapabilitiesV2, acpCanonicalJson, acpClaimNativeTransportRequest, + acpPermissionDisposition, acpNativeUserInputRequestMatches, acpPostSettleContinuationOfferEvidence, acpIsAppOwnedWakeTurn, @@ -88,6 +90,82 @@ const testLayer = Layer.mergeAll(NodeServices.layer, idAllocatorLayer, serverCon const ACP_TEST_DRIVER = ProviderDriverKind.make("acp-test"); const decodeUnknownJson = Schema.decodeUnknownOption(Schema.UnknownFromJsonString); +function permissionRequest( + kind: NonNullable, + locations?: ReadonlyArray, +): EffectAcpSchema.RequestPermissionRequest { + return { + options: [], + sessionId: "permission-session", + toolCall: { + kind, + ...(locations === undefined ? {} : { locations }), + toolCallId: "permission-tool-call", + }, + }; +} + +describe("acpPermissionDisposition", () => { + const cwd = NodePath.resolve(process.cwd(), "acp-permission-workspace"); + const writableRoot = NodePath.resolve(process.cwd(), "acp-additional-writable-root"); + const policy = ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd, + approvalPolicy: "never", + sandboxPolicy: { + type: "workspaceWrite", + writableRoots: [writableRoot], + networkAccess: false, + }, + }); + + it("auto-allows mutations only when every location is in cwd or an additional writable root", () => { + assert.equal( + acpPermissionDisposition(policy, permissionRequest("edit", [{ path: "src/index.ts" }])), + "allow", + ); + assert.equal( + acpPermissionDisposition( + policy, + permissionRequest("delete", [{ path: NodePath.join(writableRoot, "generated.ts") }]), + ), + "allow", + ); + assert.equal( + acpPermissionDisposition( + policy, + permissionRequest("move", [ + { path: NodePath.join(cwd, "from.ts") }, + { path: NodePath.join(writableRoot, "to.ts") }, + ]), + ), + "allow", + ); + }); + + it("denies missing or out-of-root mutation locations", () => { + const outside = NodePath.resolve(process.cwd(), "outside-acp-permission-workspace", "file.ts"); + assert.equal(acpPermissionDisposition(policy, permissionRequest("edit")), "deny"); + assert.equal( + acpPermissionDisposition(policy, permissionRequest("delete", [{ path: "../escape.ts" }])), + "deny", + ); + assert.equal( + acpPermissionDisposition( + policy, + permissionRequest("move", [{ path: NodePath.join(cwd, "inside.ts") }, { path: outside }]), + ), + "deny", + ); + }); + + it("keeps non-mutating workspace permissions and denials unchanged", () => { + assert.equal(acpPermissionDisposition(policy, permissionRequest("read")), "allow"); + assert.equal(acpPermissionDisposition(policy, permissionRequest("execute")), "deny"); + }); +}); + describe("acpProjectedCommandExitCode", () => { const successOutput = { type: "Bash", exit_code: 0 }; const failedOutput = { type: "Bash", exit_code: 1 }; @@ -5965,7 +6043,7 @@ describe("AcpAdapterV2", () => { ); it.effect( - "pre-settle ext completion arm is cleared when the injected report streams into the held turn", + "pre-settle ext completion arm is cleared when the report precedes its end notice", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; @@ -6122,7 +6200,15 @@ describe("AcpAdapterV2", () => { "settle must hold for deferred background work; midTurn alone must not offer mid-hold", ); - // Injected-turn end notice arms pendingInjectedReport on the held turn. + // The injected report can race ahead of the end notice. It must be + // remembered so the later notice consumes the pre-settle arm. + yield* sessionUpdateHandler!({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Monitor finished. MONITOR_REPORT_TOKEN" }, + }, + }); yield* sessionUpdateHandler!({ sessionId: "mock-session-1", update: { @@ -6133,15 +6219,6 @@ describe("AcpAdapterV2", () => { }, }, }); - // Injected report streams into the held turn; must clear the pre-settle - // midTurn arm so finalize does not open a duplicate wake. - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: "Monitor finished. MONITOR_REPORT_TOKEN" }, - }, - }); yield* Effect.yieldNow; yield* Effect.yieldNow; yield* Effect.yieldNow; diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts index f744301556..2fbaab9dd2 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts @@ -1,3 +1,6 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodePath from "node:path"; + import { type ChatAttachment, type ModelSelection, @@ -835,6 +838,57 @@ function selectAutoApprovedPermissionOption( export type AcpPermissionDisposition = "allow" | "ask" | "deny"; +function resolveAcpPermissionPath(path: string, cwd: string | null): string | undefined { + const trimmed = path.trim(); + if (trimmed.length === 0) return undefined; + if (NodePath.isAbsolute(trimmed)) return NodePath.resolve(trimmed); + if (cwd === null || cwd.trim().length === 0) return undefined; + return NodePath.resolve(cwd, trimmed); +} + +function acpPathIsWithinRoot(path: string, root: string): boolean { + const relative = NodePath.relative(root, path); + return ( + relative === "" || + (relative !== ".." && + !relative.startsWith(`..${NodePath.sep}`) && + !NodePath.isAbsolute(relative)) + ); +} + +function acpWorkspaceWriteAllowsMutation( + runtimePolicy: ProviderAdapterV2RuntimePolicy, + sandboxPolicy: Record, + request: EffectAcpSchema.RequestPermissionRequest, +): boolean { + const cwd = + typeof runtimePolicy.cwd === "string" && runtimePolicy.cwd.trim().length > 0 + ? NodePath.resolve(runtimePolicy.cwd) + : null; + const roots = cwd === null ? [] : [cwd]; + const writableRoots = sandboxPolicy.writableRoots; + if (Array.isArray(writableRoots)) { + for (const writableRoot of writableRoots) { + if (typeof writableRoot !== "string") continue; + const resolved = resolveAcpPermissionPath(writableRoot, cwd); + if (resolved !== undefined) roots.push(resolved); + } + } + if (roots.length === 0) return false; + + const locations = request.toolCall.locations; + if (locations === undefined || locations === null || locations.length === 0) { + return false; + } + for (const location of locations) { + const resolved = resolveAcpPermissionPath(location.path, cwd); + if (resolved === undefined || !roots.some((root) => acpPathIsWithinRoot(resolved, root))) { + return false; + } + } + return true; +} + export function acpPermissionDisposition( runtimePolicy: ProviderAdapterV2RuntimePolicy, request: EffectAcpSchema.RequestPermissionRequest, @@ -857,14 +911,15 @@ export function acpPermissionDisposition( ? "allow" : "deny"; case "workspaceWrite": - return toolKind === "read" || - toolKind === "search" || - toolKind === "think" || - toolKind === "edit" || - toolKind === "delete" || - toolKind === "move" - ? "allow" - : "deny"; + if (toolKind === "read" || toolKind === "search" || toolKind === "think") { + return "allow"; + } + if (toolKind === "edit" || toolKind === "delete" || toolKind === "move") { + return acpWorkspaceWriteAllowsMutation(runtimePolicy, sandboxPolicy ?? {}, request) + ? "allow" + : "deny"; + } + return "deny"; case "dangerFullAccess": case "externalSandbox": return "allow"; @@ -935,6 +990,12 @@ interface ActiveAcpTurn { * the safety timeout elapses. */ readonly pendingInjectedReport: Set; + /** + * An injected assistant report can race ahead of its monitor end notice. + * Remember that unmatched report so the later notice consumes, rather than + * re-arming, the task's pre-settle completion marker. + */ + earlyInjectedReportObserved: boolean; plan: { readonly id: OrchestrationV2PlanArtifact["id"]; readonly startedAt: DateTime.Utc; @@ -2270,6 +2331,17 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV }).pipe(Effect.forkIn(sessionScope), Effect.asVoid); }); + const clearMidTurnUnreportedTaskIds = (taskIds: ReadonlyArray) => + Ref.update(midTurnUnreportedCompletedTaskIds, (current) => { + let next: Set | null = null; + for (const taskId of taskIds) { + if (!current.has(taskId)) continue; + if (next === null) next = new Set(current); + next.delete(taskId); + } + return next ?? current; + }); + emitTool = Effect.fnUntraced(function* ( context: ActiveAcpTurn, incoming: AcpToolCallState, @@ -3073,6 +3145,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV switch (update.sessionUpdate) { case "agent_message_chunk": if (update.content.type === "text") { + const startsNewAssistantSegment = context.assistant.current === null; // The injected-turn report is streaming; the normal debounce // after the last chunk takes over from here. Drop matching // mid-turn armed ids so finalize does not open a duplicate @@ -3080,15 +3153,17 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV if (context.pendingInjectedReport.size > 0) { const reportedTaskIds = [...context.pendingInjectedReport]; context.pendingInjectedReport.clear(); - yield* Ref.update(midTurnUnreportedCompletedTaskIds, (current) => { - let next: Set | null = null; - for (const taskId of reportedTaskIds) { - if (!current.has(taskId)) continue; - if (next === null) next = new Set(current); - next.delete(taskId); - } - return next ?? current; - }); + yield* clearMidTurnUnreportedTaskIds(reportedTaskIds); + } else if ( + startsNewAssistantSegment && + context.promptSettled && + (yield* Ref.get(midTurnUnreportedCompletedTaskIds)).size > 0 + ) { + // Some ACP implementations deliver the injected assistant + // report before the synthetic monitor end notice. Correlation + // arrives with that notice, so remember the unmatched report + // and consume its task id when the notice follows. + context.earlyInjectedReportObserved = true; } yield* appendText(context, "assistant", update.content.text); } @@ -3100,7 +3175,17 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV break; case "user_message_chunk": if (update.content.type === "text" && flavor.extractBackgroundToolMutation) { - for (const mutation of flavor.extractBackgroundToolMutation(update.content.text)) { + const mutations = flavor.extractBackgroundToolMutation(update.content.text); + const terminalTaskIds = mutations + .filter((mutation) => mutation.status !== "running") + .map((mutation) => mutation.taskId); + const reportArrivedBeforeNotice = + context.earlyInjectedReportObserved && terminalTaskIds.length > 0; + if (reportArrivedBeforeNotice) { + context.earlyInjectedReportObserved = false; + yield* clearMidTurnUnreportedTaskIds(terminalTaskIds); + } + for (const mutation of mutations) { const toolCallId = context.toolCallIdsByBackgroundTaskId.get(mutation.taskId); const previous = toolCallId !== undefined ? context.tools.get(toolCallId) : undefined; @@ -3131,7 +3216,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV // the mutation's semantic status. Also tracks monitors that // never surfaced a tool_call row at all. yield* applyBackgroundTaskMutationRunning(mutation); - if (mutation.status !== "running") { + if (mutation.status !== "running" && !reportArrivedBeforeNotice) { yield* markPendingInjectedReport(context, mutation.taskId); } } @@ -4527,6 +4612,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV persistentBackgroundTaskIds: new Set(), awaitingBackgroundHydration: new Set(), pendingInjectedReport: new Set(), + earlyInjectedReportObserved: false, plan: null, interrupted: false, finalized: false, diff --git a/apps/server/src/provider/acp/XAiAcpExtension.test.ts b/apps/server/src/provider/acp/XAiAcpExtension.test.ts index 0086c08278..77ed674147 100644 --- a/apps/server/src/provider/acp/XAiAcpExtension.test.ts +++ b/apps/server/src/provider/acp/XAiAcpExtension.test.ts @@ -241,6 +241,42 @@ describe("XAiAcpExtension", () => { }); }); + it("does not treat a subagent_id mentioned in result text as the completed identity", () => { + const requestedTaskId = "019f44a6-4820-7402-925d-bc862ee711dd"; + const mentionedTaskId = "019f44b0-1b73-7f32-bb1b-1ff696f536e3"; + const toolCall = { + toolCallId: "call-get-mentioned-id", + title: "get_command_or_subagent_output", + status: "completed" as const, + data: { + rawInput: { + variant: "TaskOutput", + task_ids: [requestedTaskId], + }, + rawOutput: { + type: "TaskOutput", + Result: { + status: "completed", + exit_code: 0, + output: `Audited subagent_id: ${mentionedTaskId}; no issues found.`, + }, + }, + }, + }; + + expect(extractXAiAcpSubagentUpdate(toolCall)).toMatchObject({ + childSessionId: requestedTaskId, + status: "completed", + }); + expect(extractXAiBackgroundTaskCompletion(toolCall)).toEqual([ + { + taskId: requestedTaskId, + status: "completed", + appendOutput: `Audited subagent_id: ${mentionedTaskId}; no issues found.`, + }, + ]); + }); + it("hydrates structured ACP TaskOutput tool envelopes", () => { expect( extractXAiAcpSubagentUpdate({ @@ -628,6 +664,42 @@ describe("XAiAcpExtension", () => { ]); }); + it("keeps every requested monitor running when a completed poll has no terminal task status", () => { + expect( + extractXAiBackgroundTaskCompletion({ + toolCallId: "call-get-running-monitors", + title: "get_command_or_subagent_output", + status: "completed", + data: { + rawInput: { + variant: "TaskOutput", + task_ids: [ + "019f44a6-4820-7402-925d-bc862ee711dd", + "019f44b0-1b73-7f32-bb1b-1ff696f536e3", + ], + }, + rawOutput: { + type: "TaskOutput", + Result: { + output: "No task has reached a terminal state.", + }, + }, + }, + }), + ).toEqual([ + { + taskId: "019f44a6-4820-7402-925d-bc862ee711dd", + status: "running", + appendOutput: "No task has reached a terminal state.", + }, + { + taskId: "019f44b0-1b73-7f32-bb1b-1ff696f536e3", + status: "running", + appendOutput: "No task has reached a terminal state.", + }, + ]); + }); + it("treats Exit Code: -1 text envelopes as failed", () => { expect( extractXAiBackgroundTaskCompletion({ diff --git a/apps/server/src/provider/acp/XAiAcpExtension.ts b/apps/server/src/provider/acp/XAiAcpExtension.ts index ab8c7acefa..1e05248b22 100644 --- a/apps/server/src/provider/acp/XAiAcpExtension.ts +++ b/apps/server/src/provider/acp/XAiAcpExtension.ts @@ -665,8 +665,7 @@ function resultTaskIdFromGetOutputTool( output, new RegExp(`===\\s*Task\\s+(${XAI_UUID_RE})\\s*===`, "i"), ); - if (taskHeader !== undefined) return taskHeader; - return firstUuidMatch(output, new RegExp(`subagent_id:\\s*(${XAI_UUID_RE})\\b`, "i")); + return taskHeader; } function resultFromGetOutputTool( @@ -719,7 +718,10 @@ function statusFromGetOutputTool( return "running"; } } - return toolCall.status === "completed" ? "completed" : "running"; + // A completed get_output tool call only means the poll RPC returned. Without + // a task-level terminal status or exit code, the requested task is still + // running and must remain registered for subsequent polling. + return "running"; } /**