The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
fix(acpx): record whether a stalled tool call's permission request arrived (#16688)
Devin Foley63306f666020
diff --git a/doc/observability.md b/doc/observability.mdindex 9d054b2ff8..7703888f8f 100644--- a/doc/observability.md+++ b/doc/observability.md@@ -993,8 +993,20 @@ same cancel and fail-fast deadline as a duplex channel loss. The run fails with`acpStalledToolKind` (one closed `ToolKind` label or `unknown`) and`acpStalledToolSilentMs`. The stop-time fields above are measured when thewatchdog fired. A live subagent's Task call keeps receiving heartbeats, so only-a call that itself went silent trips the watchdog. Other ACP agents are watched-only when `stalledToolTimeoutSec` is set.+a call that itself went silent trips the watchdog. A background subagent's Task+call completes when the subagent starts, so the watchdog watches that subagent's+own tool calls instead. Other ACP agents are watched only when+`stalledToolTimeoutSec` is set.++The engine also observes ACP permission requests without deciding them; ACPX's+permission mode still decides each one. A stalled run records+`acpStalledToolPermissionRequested` (whether the stalled call's permission+request reached Paperclip) and `acpPendingToolPermissionRequestedCount` (how many+pending calls had one). These fields record only that a request arrived, not+that the reply reached the agent. A call whose request never arrived stalled+before the request reached Paperclip. A call whose request arrived stalled+later: on the reply's return trip, or after the agent received the decision.+Both fields hold only a boolean and a count.ACP and legacy OpenCode results retain the adapter's resolved wall-clock timeout as`adapterExecutionTimeout` in the instance run result. Finalization uses it fordiff --git a/packages/adapter-utils/src/acpx-engine/execute.test.ts b/packages/adapter-utils/src/acpx-engine/execute.test.tsindex 28dacdf508..3d58d77bd4 100644--- a/packages/adapter-utils/src/acpx-engine/execute.test.ts+++ b/packages/adapter-utils/src/acpx-engine/execute.test.ts@@ -3521,16 +3521,23 @@ describe("ACP activity diagnostics", () => {const turnCancelled = new Promise<void>((resolve) => { releaseTurn = resolve; });const cancelReasons: Array<string | undefined> = [];const logs: string[] = [];+ const permissionDecisions: unknown[] = [];const execute = createAcpxEngineExecutor({now: () => currentNow,stalledToolTimeoutMs: 5000,stalledToolCheckIntervalMs: 5,- createRuntime: () => ({+ createRuntime: (options) => ({...buildRuntime(),startTurn: () => ({events: (async function* () {// A live subagent keeps its Task call fresh, but one of its tool- // calls never gets another update.+ // calls never gets another update. Only the Task call's permission+ // request reaches the host.+ permissionDecisions.push(await options.onPermissionRequest?.({+ sessionId: "session-1",+ raw: { sessionId: "session-1", toolCall: { toolCallId: "private-task" }, options: [] },+ inferredKind: "think",+ } as never, { signal: new AbortController().signal }));yield { type: "tool_call", toolCallId: "private-task", title: "private task", kind: "think", status: "in_progress" };yield { type: "tool_call", toolCallId: "private-call", title: "private lookup", kind: "other", status: "pending" };currentNow = 7000;@@ -3563,8 +3570,14 @@ describe("ACP activity diagnostics", () => {acpLastEventAgeAtStopMs: 0,acpOldestPendingToolAgeAtStopMs: 6000,acpPendingToolKinds: "other,think",+ acpStalledToolPermissionRequested: false,+ acpPendingToolPermissionRequestedCount: 1,});- expect(logs.join("")).toContain("[paperclip] A pending tool call (kind other) had no update for 6s");+ // The host only observes the request; ACPX's permission mode decides it.+ expect(permissionDecisions).toEqual([undefined]);+ expect(logs.join("")).toContain(+ "[paperclip] A pending tool call (kind other) had no update for 6s; ending the turn. Its permission request did not reach Paperclip.",+ );const diagnostics = Object.fromEntries(Object.entries(result.resultJson ?? {}).filter(([key]) => key.startsWith("acp")));expect(JSON.stringify(diagnostics)).not.toContain("private");expect(result.errorMessage).not.toContain("private");@@ -3615,6 +3628,51 @@ describe("ACP activity diagnostics", () => {});}, 15_000);+ it("records that a stalled tool call's permission request reached the host", async () => {+ const root = await makeTempRoot();+ const cwd = path.join(root, "worktree");+ await fs.mkdir(cwd, { recursive: true });+ let currentNow = 1000;+ let releaseTurn: (() => void) | null = null;+ const turnCancelled = new Promise<void>((resolve) => { releaseTurn = resolve; });+ const logs: string[] = [];+ const execute = createAcpxEngineExecutor({+ now: () => currentNow,+ stalledToolTimeoutMs: 5000,+ stalledToolCheckIntervalMs: 5,+ createRuntime: (options) => ({+ ...buildRuntime(),+ startTurn: () => ({+ events: (async function* () {+ yield { type: "tool_call", toolCallId: "call-1", kind: "other", status: "pending" };+ // The request can reach the host after the relay saw the call.+ await options.onPermissionRequest?.({+ sessionId: "session-1",+ raw: { sessionId: "session-1", toolCall: { toolCallId: "call-1" }, options: [] },+ inferredKind: "other",+ } as never, { signal: new AbortController().signal });+ currentNow = 7000;+ await turnCancelled;+ })(),+ result: turnCancelled.then(() => ({ status: "cancelled", stopReason: "cancelled" })),+ cancel: async () => { releaseTurn?.(); },+ }),+ }) as never,+ });+ const result = await execute({+ runId: "stalled-tool-after-permission", agent: { id: "agent-1", companyId: "company-1" }, runtime: {},+ config: { agent: "custom", agentCommand: "node ./fake-acp.js", stateDir: path.join(root, "state"), cwd },+ context: {}, onMeta: async () => {}, onLog: async (_stream: string, text: string) => { logs.push(text); },+ } as never);+ expect(result.errorCode).toBe("acpx_tool_stalled");+ expect(result.resultJson).toMatchObject({+ acpStalledToolKind: "other",+ acpStalledToolPermissionRequested: true,+ acpPendingToolPermissionRequestedCount: 1,+ });+ expect(logs.join("")).toContain("Its permission request reached Paperclip.");+ }, 15_000);+it("leaves a turn alone while its long-running tool keeps receiving updates", async () => {const root = await makeTempRoot();const cwd = path.join(root, "worktree");diff --git a/packages/adapter-utils/src/acpx-engine/execute.ts b/packages/adapter-utils/src/acpx-engine/execute.tsindex 1047805363..82c232930d 100644--- a/packages/adapter-utils/src/acpx-engine/execute.ts+++ b/packages/adapter-utils/src/acpx-engine/execute.ts@@ -4127,13 +4127,27 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) {// turn: the closed ACP kind of the silent tool call and how long it went// without an update. The watchdog cancels the turn and arms the same// fail-fast deadline as a duplex loss.- let stalledTool: { kind: string; silentMs: number } | null = null;+ // `permissionRequested` says whether the agent's permission request for+ // that call reached the host. It records receipt only, not that the reply+ // reached the agent, so it separates a call stalled before its request+ // arrived from one stalled on the return trip or after the decision;+ // `pendingPermissionRequested` counts the pending calls whose request did.+ let stalledTool: {+ kind: string;+ silentMs: number;+ permissionRequested: boolean;+ pendingPermissionRequested: number;+ } | null = null;let stalledToolTimer: ReturnType<typeof setInterval> | undefined;let forcedStop = false;let runtimeStopConfirmed = false;let safeInterruptedSession = false;let preserveInterruptedSession = false;const interruptionTools = new Map<string, { kind?: string; status?: string; firstSeenAt?: number; lastUpdateAt?: number }>();+ // Tool call ids whose permission request reached the host. The request can+ // arrive before the relay sees the call's `tool_call` event, so it is kept+ // apart from `interruptionTools`.+ const permissionRequestedToolCallIds = new Set<string>();let incompleteToolInventory = false;try {await ctx.onCancellationReady?.();@@ -4425,6 +4439,13 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) {// must not merge the Paperclip server's ambient environment back in// when it spawns the provider child.inheritProcessEnv: false,+ // Observe permission requests without deciding them: returning+ // undefined leaves the decision to ACPX's permission-mode resolver.+ onPermissionRequest: async (request) => {+ const toolCallId = request.raw?.toolCall?.toolCallId;+ if (typeof toolCallId === "string" && toolCallId) permissionRequestedToolCallIds.add(toolCallId);+ return undefined;+ },onAgentStderr: prepared.childStderrLogPath? (chunk) => routeChildStderr(childStderrState, chunk): undefined,@@ -5021,12 +5042,15 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) {if (stalledTool !== null || turnStopRequestedAt !== null) return;const checkedAt = now();if (lastToolSettledAt !== null && checkedAt - lastToolSettledAt < stalledToolTimeoutMs) return;- let oldest: { kind?: string; silentMs: number } | null = null;- for (const tool of interruptionTools.values()) {- if (!isPendingAcpTool(tool) || tool.lastUpdateAt === undefined) continue;+ let oldest: { toolCallId: string; kind?: string; silentMs: number } | null = null;+ let pendingPermissionRequested = 0;+ for (const [toolCallId, tool] of interruptionTools) {+ if (!isPendingAcpTool(tool)) continue;+ if (permissionRequestedToolCallIds.has(toolCallId)) pendingPermissionRequested += 1;+ if (tool.lastUpdateAt === undefined) continue;const silentMs = checkedAt - tool.lastUpdateAt;if (silentMs >= stalledToolTimeoutMs && (!oldest || silentMs > oldest.silentMs)) {- oldest = { kind: tool.kind, silentMs };+ oldest = { toolCallId, kind: tool.kind, silentMs };}}if (!oldest) return;@@ -5035,12 +5059,14 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) {stalledTool = {kind: oldest.kind && knownKinds.includes(oldest.kind) ? oldest.kind : "unknown",silentMs: oldest.silentMs,+ permissionRequested: permissionRequestedToolCallIds.has(oldest.toolCallId),+ pendingPermissionRequested,};turnStopRequestedAt = checkedAt;pendingToolsAtStop = [...interruptionTools.values()].filter(isPendingAcpTool);void ctx.onLog("stderr",- `[paperclip] A pending tool call (kind ${stalledTool.kind}) had no update for ${Math.round(stalledTool.silentMs / 1000)}s; ending the turn.\n`,+ `[paperclip] A pending tool call (kind ${stalledTool.kind}) had no update for ${Math.round(stalledTool.silentMs / 1000)}s; ending the turn. Its permission request ${stalledTool.permissionRequested ? "reached" : "did not reach"} Paperclip.\n`,).catch(() => {});void turn.cancel({ reason: "paperclip stalled tool watchdog" }).catch(() => {});armCancelDeadline();@@ -5321,7 +5347,12 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) {status: channelLost || toolStalled ? "failed" : terminal.status,...activityDiagnostics,...(toolStalled && stalledTool- ? { acpStalledToolKind: stalledTool.kind, acpStalledToolSilentMs: stalledTool.silentMs }+ ? {+ acpStalledToolKind: stalledTool.kind,+ acpStalledToolSilentMs: stalledTool.silentMs,+ acpStalledToolPermissionRequested: stalledTool.permissionRequested,+ acpPendingToolPermissionRequestedCount: stalledTool.pendingPermissionRequested,+ }: {}),...(failureDiagnostic ? { terminalSessionFailure: failureDiagnostic } : {}),...(classifiedFailure?.errorFamily ? { errorFamily: classifiedFailure.errorFamily } : {}),diff --git a/server/src/services/__tests__/run-failure-diagnostics.test.ts b/server/src/services/__tests__/run-failure-diagnostics.test.tsindex fae5b5e595..d60f455bd7 100644--- a/server/src/services/__tests__/run-failure-diagnostics.test.ts+++ b/server/src/services/__tests__/run-failure-diagnostics.test.ts@@ -458,11 +458,15 @@ describe("run failure diagnostics", () => {});});- it("includes the stalled tool's closed kind label and silent time", () => {+ it("includes the stalled tool's closed kind label, silent time and permission evidence", () => {const result = sanitizeRunFailureDiagnostics(collectRunFailureDiagnostics(run({ resultJson: {acpStalledToolKind: "other", acpStalledToolSilentMs: 1_800_000, acpStalledToolTitle: "private lookup",+ acpStalledToolPermissionRequested: false, acpPendingToolPermissionRequestedCount: 3,} }), {}));- expect(result.execution).toEqual({ acpStalledToolKind: "other", acpStalledToolSilentMs: 1_800_000 });+ expect(result.execution).toEqual({+ acpStalledToolKind: "other", acpStalledToolSilentMs: 1_800_000,+ acpStalledToolPermissionRequested: false, acpPendingToolPermissionRequestedCount: 3,+ });expect(JSON.stringify(result)).not.toContain("private");});@@ -485,7 +489,8 @@ describe("run failure diagnostics", () => {const result = collectRunFailureDiagnostics(run({ resultJson: {acpLastEventAgeMs: value, acpObservedEventCount: value, acpPendingToolCount: value,acpToolInventoryComplete: value, acpLastEventAgeAtStopMs: value, acpOldestPendingToolAgeAtStopMs: value,- acpStalledToolSilentMs: value,+ acpStalledToolSilentMs: value, acpStalledToolPermissionRequested: value,+ acpPendingToolPermissionRequestedCount: value,} }), {});expect(result.execution).toEqual({});},diff --git a/server/src/services/run-failure-diagnostics.ts b/server/src/services/run-failure-diagnostics.tsindex 627a9206de..e2fcffa093 100644--- a/server/src/services/run-failure-diagnostics.ts+++ b/server/src/services/run-failure-diagnostics.ts@@ -314,6 +314,7 @@ export function collectRunFailureDiagnostics(run: Run, options: RunFailureReportfor (const field of ["acpLastEventAgeMs", "acpObservedEventCount", "acpPendingToolCount","acpLastEventAgeAtStopMs", "acpOldestPendingToolAgeAtStopMs", "acpStalledToolSilentMs",+ "acpPendingToolPermissionRequestedCount",]) {const value = read(result, field);if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0) execution[field] = value;@@ -324,6 +325,10 @@ export function collectRunFailureDiagnostics(run: Run, options: RunFailureReportif (pendingToolKinds) execution.acpPendingToolKinds = pendingToolKinds;const stalledToolKind = readAcpToolKind(read(result, "acpStalledToolKind"));if (stalledToolKind) execution.acpStalledToolKind = stalledToolKind;+ const stalledToolPermissionRequested = read(result, "acpStalledToolPermissionRequested");+ if (typeof stalledToolPermissionRequested === "boolean") {+ execution.acpStalledToolPermissionRequested = stalledToolPermissionRequested;+ }const toolInventoryComplete = read(result, "acpToolInventoryComplete");if (typeof toolInventoryComplete === "boolean") execution.acpToolInventoryComplete = toolInventoryComplete;const restoreFailure = read(result, "workspaceRestoreFailure");