mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-16 03:31:44 +01:00
feat(acpx): give Claude's own cycles to the adapter as one ordered stream (#21421)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Paperclip Runner runs Claude Code through the ACPX sidecar. > - Claude can start a shell command in the background and end its turn. When the command finishes, Claude Code starts a cycle of its own to continue. Today the Runner stops Claude at the end of the turn, so the command stops and the run fails with `native_finalization_missing`. > - A stack of pull requests lets the Runner accept that cycle as a new turn of the same run, when a controller asks for it. > - Claude Code starts a cycle of its own when a background task finishes and no prompt is in flight. The Runner sees the raw messages of that cycle. > - #21293 only marks the background state as unknown when it sees such activity. > - This pull request gives each such cycle to the caller of the adapter as one ordered stream: started, its events, ended with its result. Nothing reads the stream yet. > - The benefit is one place that knows where a cycle starts and ends, with cycles that cannot overlap. ## Linked Issues or Issue Description No public issue exists. The issue is described here. This pull request is one part of a change that was first opened as one large pull request (#21316). The parts, in stack order after #21311: 1. #21419: sidecar preparation (a refactor). 2. #21420: converter for raw ACP session updates. 3. #21421: cycle stream at the adapter. 4. #21422: contract for provider-started turns. 5. #21423: `paperclip-runnerd` waits for a provider-started turn. 6. #21316: the sidecar adopts a cycle. This is part 3. Its base branch is `feat/acp-session-update-event-converter`. After each part, a production run does the same as today, because no controller sends the opt-in. Refs #19912 (design). **What existing behavior does this improve?** Nothing in production yet. How the ACPX adapter sees the cycles that Claude starts by itself. **Subsystem affected** Paperclip Runner: `src/drivers/acpx` (the adapter, the runtime host, the Claude background task tracker). Claude only. **Current behavior** - The raw ACP observer gives each message to the background task tracker. - Activity of Claude with no client request in flight makes the background state unknown. The messages of that cycle are not kept. **Proposed behavior** - `ClaudeProviderCycles` puts each cycle on one ordered stream. A cycle starts at the first update of the own session with no client request and no prompt in flight. It ends at the `usage_update` that has `_meta._claude/origin`. - A caller gets the stream with `providerCycles()`, reads it with `next()`, and calls `adopt()` or `drop()` for each cycle. A permission request waits for the decision of its own cycle. The stream records the cycle of each tool call, and `decisionFor(toolCallId)` gives that decision. The binding that a caller gives to `adopt()` can also carry `onPlanProposal`, so a plan that an adopted cycle proposes goes to the caller as it does for a normal turn. - With no caller, a cycle is declined and the background state becomes unknown, as before. The sidecar does not call `providerCycles()` in this pull request, so production does the same as today. - The tracker reports `{ live: N }` only while N shells are running, `{ live: 0 }` only if the process never had a background task and Claude never acted between prompts, and unknown in each other case. A dropped, failed or cancelled cycle makes the state unknown. - An empty result that directly follows the end of a cycle (zero usage, same context use and cost) is ignored. Claude Code sometimes sends it. It must not become a cycle, and its usage must not be reported two times. **Reason and benefit** - One producer and one reader make the order of cycles a property of the structure. - The tracker does not read the order of messages to decide which finished task a cycle reported on. Captures showed that Claude Code can put two notifications in one cycle, start a second cycle, or give a notification to a cycle in progress, and the ACP stream does not say which. ## What Changed - `src/drivers/acpx/claude-provider-turns.ts` (new, 303 lines): `ClaudeProviderCycles`. - `acpx-runtime-adapter.ts` (78 added, 8 removed) and `runtime-host.ts` (24 added): `providerCycles()` and `providerTurnsAvailable()`, and the permission path that waits for the decision. - `claude-background-tasks.ts` (16 added, 7 removed): the rule above. - Tests (764 lines): `claude-provider-turns.test.ts`, `claude-provider-turn-tasks.test.ts`, `claude-background-tasks.test.ts`, a permission test in `acpx-runtime-adapter.test.ts`, two tests with the real `claude-agent-acp` (`acpx-runtime-adapter.claude-provider-turn.test.ts`, `acpx-runtime-adapter.claude-overlapping-shells.test.ts`), and a captured raw stream as a fixture. ## Verification At the head of this branch, from `packages/paperclip-runner`: - `npx tsc --noEmit -p tsconfig.json`, `npx tsc --noEmit -p tsconfig.test.json`, `pnpm run typecheck:typescript`, `pnpm run build:typescript`, `node --test test/acpx-sidecar-contract.test.mjs test/protocol-contract.test.mjs`, the server check `node scripts/verify-runner-vendor-dependencies.mjs`, `node --test scripts/__tests__/runner-release-crate-cache.test.mjs`, `cargo fmt --check` and `cargo build -p paperclip-runner-core --bins` (no new warning): all passed. - 10 test files, 294 passed. This includes the test of #21293 with the real `claude-agent-acp`, not changed: with no caller of the stream it still gets `{ live: 1 }` at the end of the turn and an unknown state after the cycle of Claude. - Real `claude-agent-acp` with a local fake Anthropic API: a background shell finishes, and the stream gives one cycle with its own usage. With two shells where the second finishes before the first cycle sends its first update, the first cycle ends with an unknown state. - Mutation checks, each made the named tests fail: an end item before the last message of a cycle; a drop that does not make the state unknown; a finished task that reports `{ live: 0 }`; the empty result not ignored; a permission request that does not wait. - Live run with a real Claude account, not in CI, on the full change: one background shell gave `{ live: 1 }`, one cycle, then unknown. Two shells of 8 s and 28 s gave `{ live: 2 }`, `{ live: 1 }`, then unknown. Not run: the full suite. CI supplies that coverage. ## Risks - **The time at which the state becomes unknown changes a little.** With no caller, a cycle makes the state unknown at its first message. Before, it was at the first message of an activity kind. The result for the Runner is the same: a restart at the end of the turn. - **Limit, by design.** After a cycle, `{ live: N }` counts only running shells. A command that finishes while Claude already reports on an earlier one gets no cycle that the Runner waits for. - **The rule for the empty result is narrow** and comes from captures of one Claude Code version. The reason that Claude Code sends it is not known. - **A queue of 4,096 messages for one cycle.** A cycle that is larger fails, and the state becomes unknown. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Fable 5.2 (`claude-fable-5-2`) in Claude Code planned the change and the split, reviewed the diff, and ran a part of the verification again. - Claude Opus 5.5 (`claude-opus-5-5`), as a Claude Code subagent with tool use (shell, file edits, local test runs), wrote the change and the tests and cut this slice from the full change. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1140984b82
commit
e5ad224cc5
11 files changed
+1304
-15
No files matched your search
+148
@@ -0,0 +1,148 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { mkdir, mkdtemp, rm } from "node:fs/promises";
|
||||
import { createServer } from "node:http";
|
||||
import { createRequire } from "node:module";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { createAcpRuntime } from "acpx/runtime";
|
||||
import { expect, it, vi } from "vitest";
|
||||
|
||||
import { openCodexAcpxRuntime } from "./acpx-runtime-adapter.js";
|
||||
import type { ClaudeBackgroundTaskState } from "./claude-background-tasks.js";
|
||||
import type { VerifiedAcpxCommandLease } from "./installation-integrity.js";
|
||||
import { resolveQualifiedAcpxProfile } from "./qualified-profiles.js";
|
||||
import type { AcpxRuntimePortOpenOptions } from "./runtime-host.js";
|
||||
|
||||
type Block = { type: string; text?: string };
|
||||
type Message = { role: string; content: string | Block[] };
|
||||
|
||||
const textOf = (content: string | Block[] | undefined): string => typeof content === "string" ? content
|
||||
: (content ?? []).map(block => block.text ?? "").join("\n");
|
||||
const record = (value: unknown): Record<string, unknown> =>
|
||||
value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
|
||||
it("is unknown after a cycle whose first update came after a second shell finished, through the real Claude ACP stream", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "claude-overlapping-shells-"));
|
||||
const home = join(root, "home"), cwd = join(root, "workspace"), config = join(home, ".claude");
|
||||
await Promise.all([mkdir(config, { recursive: true }), mkdir(cwd)]);
|
||||
const finishedTasks = new Set<string>();
|
||||
let releaseFirstCycle!: () => void;
|
||||
const secondFinished = new Promise<void>((resolve) => { releaseFirstCycle = resolve; });
|
||||
let notifications = 0;
|
||||
let sequence = 0;
|
||||
const api = createServer(async (request, response) => {
|
||||
let raw = "";
|
||||
for await (const chunk of request) raw += chunk;
|
||||
const json = (body: unknown) => { response.writeHead(200, { "content-type": "application/json" }); response.end(JSON.stringify(body)); };
|
||||
if (request.method === "GET") return json({ data: [], has_more: false });
|
||||
if (request.url?.includes("count_tokens")) return json({ input_tokens: 1 });
|
||||
const body = JSON.parse(raw || "{}") as { model?: string; stream?: boolean; messages?: Message[]; tools?: Array<{ name: string }> };
|
||||
const model = body.model ?? "claude-sonnet-5";
|
||||
if (body.stream !== true) {
|
||||
return json({ id: "msg_fixture", type: "message", role: "assistant", model, content: [{ type: "text", text: "OK" }],
|
||||
stop_reason: "end_turn", usage: { input_tokens: 1, output_tokens: 1 } });
|
||||
}
|
||||
const last = (body.messages ?? []).filter(message => message.role === "user" || message.role === "assistant").at(-1)?.content;
|
||||
const frames: Array<Record<string, unknown>> = [{ type: "message_start", message: { id: `msg_${++sequence}`, type: "message",
|
||||
role: "assistant", model, content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: 3, output_tokens: 0 } } }];
|
||||
const text = (value: string) => frames.push({ type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
|
||||
{ type: "content_block_delta", index: 0, delta: { type: "text_delta", text: value } },
|
||||
{ type: "content_block_stop", index: 0 },
|
||||
{ type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 2 } });
|
||||
const bash = (index: number, command: string) => frames.push(
|
||||
{ type: "content_block_start", index, content_block: { type: "tool_use", id: `toolu_01Shell${index}`, name: "Bash", input: {} } },
|
||||
{ type: "content_block_delta", index, delta: { type: "input_json_delta", partial_json: JSON.stringify({ command, description: `shell ${index}`, run_in_background: true }) } },
|
||||
{ type: "content_block_stop", index });
|
||||
if (/<task-notification>/.test(textOf(last))) {
|
||||
notifications += 1;
|
||||
if (notifications === 1) await secondFinished;
|
||||
text("Handled a notification.");
|
||||
} else if (Array.isArray(last) && last.some(block => block.type === "tool_result")) {
|
||||
text("Started.");
|
||||
} else if ((body.tools ?? []).some(tool => tool.name === "Bash") && /BACKGROUND-TURN/.test(textOf(last))) {
|
||||
bash(0, "sleep 2; echo first");
|
||||
bash(1, "sleep 3; echo second");
|
||||
frames.push({ type: "message_delta", delta: { stop_reason: "tool_use", stop_sequence: null }, usage: { output_tokens: 2 } });
|
||||
} else {
|
||||
text("Nothing to run.");
|
||||
}
|
||||
frames.push({ type: "message_stop" });
|
||||
response.writeHead(200, { "content-type": "text/event-stream" });
|
||||
for (const frame of frames) response.write(`event: ${frame.type}\ndata: ${JSON.stringify(frame)}\n\n`);
|
||||
response.end();
|
||||
});
|
||||
await new Promise<void>(resolve => api.listen(0, "127.0.0.1", resolve));
|
||||
const address = api.address() as { port: number };
|
||||
const entry = createRequire(import.meta.url).resolve("@agentclientprotocol/claude-agent-acp/dist/index.js");
|
||||
const command: VerifiedAcpxCommandLease = {
|
||||
spawn: (args, input) => spawn(process.execPath, [entry, ...(args ?? [])], { ...input, detached: true, stdio: ["pipe", "pipe", "pipe"] }),
|
||||
close: async () => undefined,
|
||||
};
|
||||
const options = {
|
||||
command,
|
||||
profile: resolveQualifiedAcpxProfile("claude", "claude-sonnet-5"),
|
||||
cwd,
|
||||
stateDirectory: join(root, "state"),
|
||||
providerSessionKey: "claude-overlapping-shells",
|
||||
permissionMode: "approve-all",
|
||||
permissionPolicy: { autoApprove: ["read", "write", "execute", "other"], defaultAction: "approve" },
|
||||
launchEnvironment: { HOME: home, CLAUDE_CONFIG_DIR: config, PATH: "/usr/bin:/bin", TMPDIR: root,
|
||||
ANTHROPIC_API_KEY: "local-fixture-only", ANTHROPIC_BASE_URL: `http://127.0.0.1:${address.port}`,
|
||||
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_TELEMETRY: "1", DISABLE_ERROR_REPORTING: "1", ENABLE_TOOL_SEARCH: "false" },
|
||||
credentialFenceFds: [42, 43] as const,
|
||||
activateCredentialFenceOwner: async () => undefined,
|
||||
systemInstructions: "Run the requested commands.",
|
||||
mcpServers: [],
|
||||
retainFailedAdmissionCleanup: vi.fn(),
|
||||
} as AcpxRuntimePortOpenOptions;
|
||||
let port: Awaited<ReturnType<typeof openCodexAcpxRuntime>> | undefined;
|
||||
try {
|
||||
port = await openCodexAcpxRuntime(options, {
|
||||
awaitProviderOwnership: async () => undefined,
|
||||
awaitProviderExit: child => new Promise<void>(resolve => child.once("exit", () => resolve())),
|
||||
createRuntime: (created) => {
|
||||
const observe = created.onAcpMessage;
|
||||
created.onAcpMessage = (direction, message) => {
|
||||
observe?.(direction, message);
|
||||
const update = record(record(record(message).params).update);
|
||||
if (update.sessionUpdate === "async_task_state_update" && update.state === "completed") {
|
||||
finishedTasks.add(String(update.asyncTaskId));
|
||||
if (finishedTasks.size === 2) releaseFirstCycle();
|
||||
}
|
||||
};
|
||||
return createAcpRuntime(created);
|
||||
},
|
||||
});
|
||||
const cycles = port.providerCycles!()!;
|
||||
let started = 0;
|
||||
const ended: Array<ClaudeBackgroundTaskState | null> = [];
|
||||
void (async () => {
|
||||
for (let item = await cycles.next(); item !== null; item = await cycles.next()) {
|
||||
if (item.type === "started") {
|
||||
started += 1;
|
||||
cycles.adopt({ onPermissionRequest: async () => ({ outcome: "allow_once" }), busy: () => false });
|
||||
}
|
||||
if (item.type === "ended") ended.push(port!.backgroundTaskState?.() ?? null);
|
||||
}
|
||||
})();
|
||||
const turn = port.startTurn({ text: "BACKGROUND-TURN: start both commands in the background.", requestId: "turn-1",
|
||||
onPermissionRequest: async () => ({ outcome: "allow_once" }) });
|
||||
for await (const _event of turn.events) void _event;
|
||||
expect(await turn.result).toMatchObject({ status: "completed" });
|
||||
expect(port.backgroundTaskState?.()).toEqual({ live: 2 });
|
||||
await vi.waitFor(() => expect(ended.length).toBeGreaterThanOrEqual(1), { timeout: 20_000, interval: 50 });
|
||||
expect(ended[0]).toBeNull();
|
||||
await vi.waitFor(() => expect(notifications).toBe(2), { timeout: 20_000, interval: 50 });
|
||||
await vi.waitFor(() => expect(ended).toHaveLength(2), { timeout: 20_000, interval: 50 });
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
expect({ started, ended }).toEqual({ started: 2, ended: [null, null] });
|
||||
} finally {
|
||||
try { await port?.close({ reason: "overlapping shells verified" }); }
|
||||
finally {
|
||||
api.closeAllConnections();
|
||||
await new Promise<void>(resolve => api.close(() => resolve()));
|
||||
await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });
|
||||
}
|
||||
}
|
||||
}, 60_000);
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { mkdir, mkdtemp, rm } from "node:fs/promises";
|
||||
import { createServer } from "node:http";
|
||||
import { createRequire } from "node:module";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import type { AcpRuntimeEvent } from "acpx/runtime";
|
||||
import { expect, it, vi } from "vitest";
|
||||
|
||||
import { startRunnerToolBridge } from "../runner-tool-bridge.js";
|
||||
import { openCodexAcpxRuntime } from "./acpx-runtime-adapter.js";
|
||||
import { CLAUDE_TOOL_USE_META_KEY, ClaudeToolUseAdmission } from "./claude-tool-use-admission.js";
|
||||
import type { ClaudeProviderTurnResult } from "./claude-provider-turns.js";
|
||||
import type { VerifiedAcpxCommandLease } from "./installation-integrity.js";
|
||||
import { resolveQualifiedAcpxProfile } from "./qualified-profiles.js";
|
||||
import type { AcpxRuntimePortOpenOptions } from "./runtime-host.js";
|
||||
|
||||
type Block = { type: string; text?: string; tool_use_id?: string };
|
||||
type Message = { role: string; content: string | Block[] };
|
||||
|
||||
const textOf = (content: string | Block[] | undefined): string => typeof content === "string" ? content
|
||||
: (content ?? []).map(block => block.text ?? "").join("\n");
|
||||
|
||||
it("adopts Claude's own task-notification cycle as a provider-started turn through the real ACP stream", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "claude-provider-turn-"));
|
||||
const home = join(root, "home"), cwd = join(root, "workspace"), config = join(home, ".claude");
|
||||
await Promise.all([mkdir(config, { recursive: true }), mkdir(cwd)]);
|
||||
let sequence = 0;
|
||||
let cycleToolUseId = "";
|
||||
const api = createServer(async (request, response) => {
|
||||
let raw = "";
|
||||
for await (const chunk of request) raw += chunk;
|
||||
if (request.method === "GET") {
|
||||
response.writeHead(200, { "content-type": "application/json" });
|
||||
response.end(JSON.stringify({ data: [], has_more: false }));
|
||||
return;
|
||||
}
|
||||
if (request.url?.includes("count_tokens")) {
|
||||
response.writeHead(200, { "content-type": "application/json" });
|
||||
response.end(JSON.stringify({ input_tokens: 1 }));
|
||||
return;
|
||||
}
|
||||
const body = JSON.parse(raw || "{}") as { model?: string; stream?: boolean; messages?: Message[]; tools?: Array<{ name: string }> };
|
||||
const model = body.model ?? "claude-sonnet-5";
|
||||
if (body.stream !== true) {
|
||||
response.writeHead(200, { "content-type": "application/json" });
|
||||
response.end(JSON.stringify({ id: "msg_fixture", type: "message", role: "assistant", model,
|
||||
content: [{ type: "text", text: "OK" }], stop_reason: "end_turn", usage: { input_tokens: 1, output_tokens: 1 } }));
|
||||
return;
|
||||
}
|
||||
const conversation = (body.messages ?? []).filter(message => message.role === "user" || message.role === "assistant");
|
||||
const last = conversation.at(-1)?.content;
|
||||
const results = Array.isArray(last) ? last.filter(block => block.type === "tool_result") : [];
|
||||
const frames: Array<Record<string, unknown>> = [{ type: "message_start", message: { id: `msg_${++sequence}`, type: "message",
|
||||
role: "assistant", model, content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: 7, output_tokens: 0 } } }];
|
||||
const text = (value: string) => frames.push({ type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
|
||||
{ type: "content_block_delta", index: 0, delta: { type: "text_delta", text: value } },
|
||||
{ type: "content_block_stop", index: 0 },
|
||||
{ type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 3 } });
|
||||
const tool = (id: string, name: string, input: Record<string, unknown>) => frames.push(
|
||||
{ type: "content_block_start", index: 0, content_block: { type: "tool_use", id, name, input: {} } },
|
||||
{ type: "content_block_delta", index: 0, delta: { type: "input_json_delta", partial_json: JSON.stringify(input) } },
|
||||
{ type: "content_block_stop", index: 0 },
|
||||
{ type: "message_delta", delta: { stop_reason: "tool_use", stop_sequence: null }, usage: { output_tokens: 3 } });
|
||||
if (results.length > 0) {
|
||||
text("Done.");
|
||||
} else if (/<task-notification>/.test(textOf(last))) {
|
||||
cycleToolUseId = `toolu_01Cycle${sequence}`;
|
||||
tool(cycleToolUseId, "mcp__paperclip__probe", { tag: "finished" });
|
||||
} else if (/BACKGROUND-TURN/.test(textOf(last))) {
|
||||
tool(`toolu_01Background${sequence}`, "Bash", { command: "sleep 3; echo background-done", description: "background sleep", run_in_background: true });
|
||||
} else {
|
||||
text("Nothing to run.");
|
||||
}
|
||||
frames.push({ type: "message_stop" });
|
||||
response.writeHead(200, { "content-type": "text/event-stream" });
|
||||
for (const frame of frames) response.write(`event: ${frame.type}\ndata: ${JSON.stringify(frame)}\n\n`);
|
||||
response.end();
|
||||
});
|
||||
await new Promise<void>(resolve => api.listen(0, "127.0.0.1", resolve));
|
||||
const address = api.address() as { port: number };
|
||||
|
||||
const admission = new ClaudeToolUseAdmission();
|
||||
let activeTurn = "";
|
||||
const dispatched: Array<{ turn: string; callId: string; tag: unknown }> = [];
|
||||
const bridge = await startRunnerToolBridge({
|
||||
tools: [{ name: "probe", description: "Local stand-in for paperclip_finish.", inputSchema: { type: "object", properties: { tag: { type: "string" } } } }],
|
||||
preserveToolNames: true,
|
||||
providerToolUseIdMetaKey: CLAUDE_TOOL_USE_META_KEY,
|
||||
timeoutMs: null,
|
||||
handler: async call => {
|
||||
const turn = activeTurn;
|
||||
const callId = await admission.admit(turn, call.providerToolUseId, call.signal);
|
||||
dispatched.push({ turn, callId, tag: (call.arguments as { tag?: unknown }).tag });
|
||||
return { ok: true };
|
||||
},
|
||||
});
|
||||
const entry = createRequire(import.meta.url).resolve("@agentclientprotocol/claude-agent-acp/dist/index.js");
|
||||
const command: VerifiedAcpxCommandLease = {
|
||||
spawn: (args, input) => spawn(process.execPath, [entry, ...(args ?? [])], { ...input, detached: true, stdio: ["pipe", "pipe", "pipe"] }),
|
||||
close: async () => undefined,
|
||||
};
|
||||
const options: AcpxRuntimePortOpenOptions = {
|
||||
command,
|
||||
profile: resolveQualifiedAcpxProfile("claude", "claude-sonnet-5"),
|
||||
cwd,
|
||||
stateDirectory: join(root, "state"),
|
||||
providerSessionKey: "claude-provider-turn",
|
||||
permissionMode: "approve-all",
|
||||
permissionPolicy: { autoApprove: ["read", "write", "execute", "other"], defaultAction: "approve" },
|
||||
launchEnvironment: { HOME: home, CLAUDE_CONFIG_DIR: config, PATH: "/usr/bin:/bin", TMPDIR: root,
|
||||
ANTHROPIC_API_KEY: "local-fixture-only", ANTHROPIC_BASE_URL: `http://127.0.0.1:${address.port}`,
|
||||
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_TELEMETRY: "1", DISABLE_ERROR_REPORTING: "1", ENABLE_TOOL_SEARCH: "false" },
|
||||
credentialFenceFds: [42, 43] as const,
|
||||
activateCredentialFenceOwner: async () => undefined,
|
||||
systemInstructions: "Use Paperclip tools.",
|
||||
mcpServers: [{ name: "paperclip", url: bridge.url, bearerToken: bridge.secret, runnerOwned: true }],
|
||||
retainFailedAdmissionCleanup: vi.fn(),
|
||||
} as AcpxRuntimePortOpenOptions;
|
||||
const adopted: Array<{ requestId: string; events: AcpRuntimeEvent[]; result: Promise<ClaudeProviderTurnResult> }> = [];
|
||||
const replay = (id: number, toolUseId: string, tag: string) => fetch(bridge.url, { method: "POST",
|
||||
headers: { Authorization: `Bearer ${bridge.secret}`, "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ jsonrpc: "2.0", id, method: "tools/call",
|
||||
params: { name: "probe", arguments: { tag }, _meta: { [CLAUDE_TOOL_USE_META_KEY]: toolUseId } } }) })
|
||||
.then(response => response.json() as Promise<{ result: { isError?: boolean; content: Array<{ text: string }> } }>);
|
||||
let port: Awaited<ReturnType<typeof openCodexAcpxRuntime>> | undefined;
|
||||
try {
|
||||
port = await openCodexAcpxRuntime(options, {
|
||||
awaitProviderOwnership: async () => undefined,
|
||||
awaitProviderExit: child => new Promise<void>(resolve => child.once("exit", () => resolve())),
|
||||
});
|
||||
const cycles = port.providerCycles!()!;
|
||||
void (async () => {
|
||||
for (let item = await cycles.next(); item !== null; item = await cycles.next()) {
|
||||
if (item.type !== "started") continue;
|
||||
const requestId = item.requestId;
|
||||
activeTurn = requestId;
|
||||
admission.beginTurn(requestId);
|
||||
cycles.adopt({ onPermissionRequest: async () => ({ outcome: "allow_once" }), busy: () => false });
|
||||
const events: AcpRuntimeEvent[] = [];
|
||||
let settle!: (result: ClaudeProviderTurnResult) => void;
|
||||
adopted.push({ requestId, events, result: new Promise((resolve) => { settle = resolve; }) });
|
||||
let next = await cycles.next();
|
||||
for (; next?.type === "event"; next = await cycles.next()) {
|
||||
events.push(next.event);
|
||||
admission.observe(requestId, next.event);
|
||||
}
|
||||
admission.endTurn(requestId);
|
||||
settle(next?.type === "ended" ? next.result : { status: "failed", error: { code: "closed", message: "closed", retryable: false } });
|
||||
}
|
||||
})();
|
||||
activeTurn = "turn-1";
|
||||
admission.beginTurn("turn-1");
|
||||
const turn = port.startTurn({ text: "BACKGROUND-TURN: start the command in the background.", requestId: "turn-1",
|
||||
onPermissionRequest: async () => ({ outcome: "allow_once" }) });
|
||||
for await (const event of turn.events) admission.observe("turn-1", event);
|
||||
expect(await turn.result).toMatchObject({ status: "completed" });
|
||||
admission.endTurn("turn-1");
|
||||
expect(port.backgroundTaskState?.()).toEqual({ live: 1 });
|
||||
|
||||
await vi.waitFor(() => expect(adopted).toHaveLength(1), { timeout: 20_000, interval: 50 });
|
||||
const [cycle] = adopted;
|
||||
const result = await cycle!.result;
|
||||
expect(cycle!.requestId).toMatch(/^provider-/);
|
||||
expect(result).toMatchObject({ status: "completed", stopReason: "end_turn",
|
||||
usage: { tag: "usage_update", text: "terminal prompt usage", breakdown: { inputTokens: expect.any(Number), outputTokens: expect.any(Number) } } });
|
||||
expect(cycle!.events.some(event => event.type === "tool_call" && event.toolCallId === cycleToolUseId)).toBe(true);
|
||||
expect(dispatched).toEqual([{ turn: cycle!.requestId, callId: `tool-use:${cycleToolUseId}`, tag: "finished" }]);
|
||||
expect(port.backgroundTaskState?.()).toBeNull();
|
||||
|
||||
const conflicting = await replay(901, cycleToolUseId, "replayed");
|
||||
expect(conflicting.result.isError).toBe(true);
|
||||
await expect(admission.admit(cycle!.requestId, cycleToolUseId, new AbortController().signal))
|
||||
.rejects.toThrow("not bound to the active turn");
|
||||
expect(dispatched).toHaveLength(1);
|
||||
} finally {
|
||||
try { await port?.close({ reason: "provider-started turn verified" }); }
|
||||
finally {
|
||||
await bridge.close();
|
||||
api.closeAllConnections();
|
||||
await new Promise<void>(resolve => api.close(() => resolve()));
|
||||
await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });
|
||||
}
|
||||
}
|
||||
}, 60_000);
|
||||
@@ -822,6 +822,107 @@ describe("Codex ACPX runtime adapter", () => {
|
||||
expect(port.steeringCapability!()).toBeNull();
|
||||
await port.close({ reason: "test finished" });
|
||||
});
|
||||
it.each([true, false])("holds a permission request of Claude's own cycle until the cycle is adopted (%s) or dropped", async (adopt) => {
|
||||
const options = openOptions(fakeCommand());
|
||||
options.profile = { ...options.profile, agent: "claude" };
|
||||
let runtimeOptions: AcpRuntimeOptions | undefined;
|
||||
const port = await openCodexAcpxRuntime(options, {
|
||||
createRegistry: () => registry(), createStore: () => store(),
|
||||
createRuntime: (created) => { runtimeOptions = created; return fakeRuntime(); },
|
||||
});
|
||||
const cycles = port.providerCycles!()!;
|
||||
runtimeOptions!.onAcpMessage!("inbound", { jsonrpc: "2.0", method: "session/update", params: { sessionId: "backend-1",
|
||||
update: { sessionUpdate: "tool_call", toolCallId: "toolu_cycle", title: "Bash", kind: "execute", status: "pending" } } });
|
||||
runtimeOptions!.onAcpMessage!("inbound", { jsonrpc: "2.0", id: 5, method: "session/request_permission",
|
||||
params: { sessionId: "backend-1", toolCall: { toolCallId: "toolu_cycle" }, options: [] } });
|
||||
const answer = vi.fn(async () => ({ outcome: "allow_once" as const }));
|
||||
let outcome: unknown;
|
||||
const decided = runtimeOptions!.onPermissionRequest!(permissionRequest("backend-1", "execute"), { signal: new AbortController().signal })
|
||||
.then((value) => { outcome = value; });
|
||||
try {
|
||||
expect(await cycles.next()).toMatchObject({ type: "started" });
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
expect(outcome).toBeUndefined();
|
||||
if (adopt) expect(cycles.adopt({ onPermissionRequest: answer, busy: () => false })).toBe(true);
|
||||
else cycles.drop();
|
||||
await decided;
|
||||
expect(answer).toHaveBeenCalledTimes(adopt ? 1 : 0);
|
||||
expect(outcome).toEqual({ outcome: adopt ? "allow_once" : "cancel" });
|
||||
} finally {
|
||||
await port.close({ reason: "test finished" });
|
||||
}
|
||||
});
|
||||
it.each([true, false])("hands a plan proposed in Claude's own cycle to that cycle's plan handler once adopted (%s) or cancels it", async (adopt) => {
|
||||
const options = openOptions(fakeCommand());
|
||||
options.profile = { ...options.profile, agent: "claude" };
|
||||
let runtimeOptions: AcpRuntimeOptions | undefined;
|
||||
const port = await openCodexAcpxRuntime(options, {
|
||||
createRegistry: () => registry(), createStore: () => store(),
|
||||
createRuntime: (created) => { runtimeOptions = created; return fakeRuntime(); },
|
||||
});
|
||||
const cycles = port.providerCycles!()!;
|
||||
const toolCall = { toolCallId: "toolu_plan", kind: "switch_mode", rawInput: { plan: "# Plan\n\nShip it." } };
|
||||
runtimeOptions!.onAcpMessage!("inbound", { jsonrpc: "2.0", method: "session/update", params: { sessionId: "backend-1",
|
||||
update: { sessionUpdate: "tool_call", toolCallId: "toolu_plan", title: "Ready to code?", kind: "switch_mode", status: "pending" } } });
|
||||
runtimeOptions!.onAcpMessage!("inbound", { jsonrpc: "2.0", id: 7, method: "session/request_permission",
|
||||
params: { sessionId: "backend-1", toolCall, options: [] } });
|
||||
const proposals: unknown[] = [];
|
||||
const answer = vi.fn(async () => ({ outcome: "allow_once" as const }));
|
||||
const outcome = runtimeOptions!.onPermissionRequest!(permissionRequest("backend-1", "switch_mode" as never,
|
||||
{ sessionId: "backend-1", toolCall, options: [] }), { signal: new AbortController().signal });
|
||||
try {
|
||||
expect(await cycles.next()).toMatchObject({ type: "started" });
|
||||
if (adopt) {
|
||||
expect(cycles.adopt({ onPermissionRequest: answer, onPlanProposal: (proposal) => proposals.push(proposal), busy: () => false })).toBe(true);
|
||||
} else cycles.drop();
|
||||
expect(await outcome).toEqual({ outcome: adopt ? "reject_once" : "cancel" });
|
||||
expect(proposals).toEqual(adopt ? [{ toolCallId: "toolu_plan", markdown: "# Plan\n\nShip it." }] : []);
|
||||
expect(answer).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
await port.close({ reason: "test finished" });
|
||||
}
|
||||
});
|
||||
it.each([true, false])("answers a later cycle's permission request only through that cycle once it is adopted (%s) or cancels it", async (adoptLater) => {
|
||||
const options = openOptions(fakeCommand());
|
||||
options.profile = { ...options.profile, agent: "claude" };
|
||||
let runtimeOptions: AcpRuntimeOptions | undefined;
|
||||
const port = await openCodexAcpxRuntime(options, {
|
||||
createRegistry: () => registry(), createStore: () => store(),
|
||||
createRuntime: (created) => { runtimeOptions = created; return fakeRuntime(); },
|
||||
});
|
||||
const cycles = port.providerCycles!()!;
|
||||
const update = (body: Record<string, unknown>) => runtimeOptions!.onAcpMessage!("inbound",
|
||||
{ jsonrpc: "2.0", method: "session/update", params: { sessionId: "backend-1", update: body } });
|
||||
const end = () => update({ sessionUpdate: "usage_update", used: 5, size: 100, cost: { amount: 0.1, currency: "USD" },
|
||||
_meta: { "_claude/origin": { kind: "task-notification" }, usage: { input_tokens: 1, output_tokens: 1, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 } } });
|
||||
update({ sessionUpdate: "tool_call", toolCallId: "toolu_first", title: "Read", kind: "read", status: "pending" });
|
||||
end();
|
||||
update({ sessionUpdate: "tool_call", toolCallId: "toolu_later", title: "Bash", kind: "execute", status: "pending" });
|
||||
runtimeOptions!.onAcpMessage!("inbound", { jsonrpc: "2.0", id: 6, method: "session/request_permission",
|
||||
params: { sessionId: "backend-1", toolCall: { toolCallId: "toolu_later" }, options: [] } });
|
||||
const first = vi.fn(async () => ({ outcome: "allow_once" as const }));
|
||||
const later = vi.fn(async () => ({ outcome: "allow_once" as const }));
|
||||
let outcome: unknown;
|
||||
const decided = runtimeOptions!.onPermissionRequest!(permissionRequest("backend-1", "execute",
|
||||
{ sessionId: "backend-1", toolCall: { toolCallId: "toolu_later" }, options: [] }), { signal: new AbortController().signal })
|
||||
.then((value) => { outcome = value; });
|
||||
try {
|
||||
expect(await cycles.next()).toMatchObject({ type: "started" });
|
||||
expect(cycles.adopt({ onPermissionRequest: first, busy: () => false })).toBe(true);
|
||||
for (let item = await cycles.next(); item?.type !== "ended"; item = await cycles.next()) void item;
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
expect(outcome).toBeUndefined();
|
||||
expect(await cycles.next()).toMatchObject({ type: "started" });
|
||||
if (adoptLater) expect(cycles.adopt({ onPermissionRequest: later, busy: () => false })).toBe(true);
|
||||
else cycles.drop();
|
||||
await decided;
|
||||
expect(first).not.toHaveBeenCalled();
|
||||
expect(later).toHaveBeenCalledTimes(adoptLater ? 1 : 0);
|
||||
expect(outcome).toEqual({ outcome: adoptLater ? "allow_once" : "cancel" });
|
||||
} finally {
|
||||
await port.close({ reason: "test finished" });
|
||||
}
|
||||
});
|
||||
it.each(["approve-reads", "approve-paperclip"] as const)("%s stops unassigned operations when approval has no handler", async (permissionMode) => {
|
||||
const runtime = fakeRuntime();
|
||||
let runtimeOptions: AcpRuntimeOptions | undefined;
|
||||
|
||||
@@ -6,7 +6,8 @@ import { resolveGrokDisableWebSearch } from "./grok-web-search.js";
|
||||
import { resolveGrokEffort, createGrokEffortAdmission } from "./grok-effort.js";
|
||||
import { createGrokSessionOpenGuard } from "./grok-session-rules.js";
|
||||
import { resolveClaudeEffort, createClaudeEffortAdmission } from "./claude-effort.js";
|
||||
import { CLAUDE_ASYNC_TASKS_CAPABILITY, ClaudeBackgroundTaskTracker } from "./claude-background-tasks.js";
|
||||
import { CLAUDE_ASYNC_TASKS_CAPABILITY } from "./claude-background-tasks.js";
|
||||
import { ClaudeProviderCycles } from "./claude-provider-turns.js";
|
||||
import { acpxProviderFailure, acpxTypedSessionFailureClientCapabilities, acpxTypedTerminalSessionFailure, type AcpxTerminalSessionFailure } from "./provider-failure.js";
|
||||
import type { ProviderFailure } from "../../contracts/provider-failure.generated.js";
|
||||
import { createPiThinkingAdmission, resolvePiThinkingLevel } from "./pi-thinking.js";
|
||||
@@ -31,6 +32,7 @@ import {
|
||||
|
||||
import type {
|
||||
AcpxPlanProposal,
|
||||
AcpxProviderCycleStream,
|
||||
AcpxRuntimeGoalCapability,
|
||||
AcpxRuntimeGoalSnapshot,
|
||||
AcpxRuntimeSteeringCapability,
|
||||
@@ -369,7 +371,7 @@ export async function openQualifiedAcpxRuntime(
|
||||
const extensionNotifications = new Set(extensionProfile.extensionNotifications);
|
||||
const promptUsage = options.profile.agent === "grok" ? createGrokPromptUsageCollector() : undefined;
|
||||
const promptReceipts = createAcpxPromptReceiptCollector(options.profile.agent);
|
||||
const backgroundTasks = options.profile.agent === "claude" ? new ClaudeBackgroundTaskTracker() : null;
|
||||
const providerCycleTurn: { active: AcpxRuntimeExtensionTurn | null } = { active: null };
|
||||
const permissionReplies = createAcpxPermissionReplyConfirmations();
|
||||
const modelGate = createAcpxEffectiveModelGate(options.profile.reportedModelId);
|
||||
// Copilot's admitted permission policy is enforced from the observed wire:
|
||||
@@ -384,6 +386,10 @@ export async function openQualifiedAcpxRuntime(
|
||||
const extensionBoundary: AcpxRuntimeExtensionBoundary = {
|
||||
active: null, sessionIds: new Set(), steering: null, promptDispatch: null,
|
||||
};
|
||||
const providerCycles = options.profile.agent === "claude" ? new ClaudeProviderCycles({
|
||||
sessionId: () => extensionBoundary.sessionIds.values().next().value ?? null,
|
||||
promptActive: () => extensionBoundary.active !== null && extensionBoundary.active !== providerCycleTurn.active,
|
||||
}) : null;
|
||||
const ownsExtensionTurn = (active: AcpxRuntimeExtensionTurn, params: Record<string, unknown>): boolean =>
|
||||
extensionBoundary.active === active && !active.signal.aborted
|
||||
&& (params.sessionId === undefined || (typeof params.sessionId === "string" && extensionBoundary.sessionIds.has(params.sessionId)));
|
||||
@@ -474,7 +480,7 @@ export async function openQualifiedAcpxRuntime(
|
||||
elicitationModes: ["form"],
|
||||
clientCapabilities: acpxTypedSessionFailureClientCapabilities(
|
||||
options.clientCapabilities,
|
||||
backgroundTasks ? [CLAUDE_ASYNC_TASKS_CAPABILITY] : [],
|
||||
providerCycles ? [CLAUDE_ASYNC_TASKS_CAPABILITY] : [],
|
||||
),
|
||||
extensionMethods: [...new Set([...extensionRequests, ...extensionNotifications])],
|
||||
onExtensionRequest: async (method, params, context) => {
|
||||
@@ -531,6 +537,8 @@ export async function openQualifiedAcpxRuntime(
|
||||
|| (rawSessionId !== undefined && rawSessionId !== request.sessionId)) {
|
||||
return { outcome: "reject_once" };
|
||||
}
|
||||
const cycleDecision = providerCycles?.decisionFor(objectRecord(objectRecord(request.raw).toolCall).toolCallId);
|
||||
if (cycleDecision && !(await cycleDecision)) return { outcome: "cancel" };
|
||||
if ((permissionBoundary.hasAdmittedTurn && !extensionBoundary.active)
|
||||
|| extensionBoundary.active?.signal.aborted || context.signal.aborted) return { outcome: "cancel" };
|
||||
if (options.profile.agent === "claude") {
|
||||
@@ -589,7 +597,7 @@ export async function openQualifiedAcpxRuntime(
|
||||
return { outcome: disposition };
|
||||
},
|
||||
onAcpMessage: (direction, message) => {
|
||||
backgroundTasks?.observe(direction, message);
|
||||
providerCycles?.observe(direction, message);
|
||||
observeAgentInitialize(direction, message);
|
||||
copilotPolicy?.observe(direction, message);
|
||||
modelGate.observe(direction, message);
|
||||
@@ -837,7 +845,7 @@ export async function openQualifiedAcpxRuntime(
|
||||
copilotPolicy,
|
||||
modelGate,
|
||||
promptReceipts,
|
||||
backgroundTasks,
|
||||
providerCycles ? { cycles: providerCycles, turn: providerCycleTurn } : null,
|
||||
);
|
||||
} catch (error) {
|
||||
const cleanupReason = "ACPX runtime identity validation failed";
|
||||
@@ -1292,9 +1300,10 @@ function runtimePort(
|
||||
copilotPolicy?: CopilotPolicyEnforcement | null,
|
||||
modelGate?: AcpxEffectiveModelGate,
|
||||
promptReceipts?: ReturnType<typeof createAcpxPromptReceiptCollector>,
|
||||
backgroundTasks?: ClaudeBackgroundTaskTracker | null,
|
||||
providerCycles?: { cycles: ClaudeProviderCycles; turn: { active: AcpxRuntimeExtensionTurn | null } } | null,
|
||||
): AcpxRuntimePort {
|
||||
extensionBoundary.sessionIds = new Set([identity.backendSessionId]);
|
||||
let cycleStream: AcpxProviderCycleStream | null = null;
|
||||
let extensionControls: Promise<void> = Promise.resolve();
|
||||
const controlActiveTurn = (method: "pi/steer" | "pi/follow_up", text: string, requestId: string): Promise<void> => {
|
||||
const active = extensionBoundary.active;
|
||||
@@ -1583,7 +1592,15 @@ function runtimePort(
|
||||
: structuredClone(goalState.capability);
|
||||
},
|
||||
backgroundTaskState() {
|
||||
return backgroundTasks?.state() ?? null;
|
||||
return providerCycles?.cycles.backgroundTasks() ?? null;
|
||||
},
|
||||
providerCycles() {
|
||||
providerCycles?.cycles.subscribe();
|
||||
return cycleStream;
|
||||
},
|
||||
providerTurnsAvailable() {
|
||||
return providerCycles !== null && providerCycles !== undefined && !providerCycles.cycles.retired
|
||||
&& !providerProcessLost && !runtimeClosed && !runtimeCloseAttempt;
|
||||
},
|
||||
goalSnapshot() {
|
||||
return goalState.snapshot === null
|
||||
@@ -1814,8 +1831,63 @@ function runtimePort(
|
||||
})(),
|
||||
};
|
||||
},
|
||||
close: closeRuntime,
|
||||
close: (input) => {
|
||||
providerCycles?.cycles.close();
|
||||
return closeRuntime(input);
|
||||
},
|
||||
};
|
||||
if (providerCycles) {
|
||||
const { cycles, turn: cycleTurn } = providerCycles;
|
||||
let started: string | null = null;
|
||||
let approval: AbortController | null = null;
|
||||
const release = (): void => {
|
||||
const extensionTurn = cycleTurn.active;
|
||||
const adopted = approval;
|
||||
cycleTurn.active = null;
|
||||
approval = null;
|
||||
if (!extensionTurn || !adopted) return;
|
||||
extensionTurn.controller.abort(new Error("ACPX provider turn expired"));
|
||||
if (extensionBoundary.active === extensionTurn) extensionBoundary.active = null;
|
||||
if (permissionBoundary.active === adopted) {
|
||||
permissionBoundary.active = null;
|
||||
permissionBoundary.handler = undefined;
|
||||
adopted.abort();
|
||||
}
|
||||
};
|
||||
children.watchProviderExit(() => {
|
||||
if (cycleTurn.active) providerProcessLost = true;
|
||||
cycles.lost();
|
||||
});
|
||||
cycleStream = {
|
||||
async next() {
|
||||
const item = await cycles.next();
|
||||
if (item?.type === "started") started = item.requestId;
|
||||
else if (item?.type !== "event") release();
|
||||
return item;
|
||||
},
|
||||
adopt(binding) {
|
||||
if (started === null || extensionBoundary.active || providerProcessLost || runtimeClosed || runtimeCloseAttempt) return false;
|
||||
approval = new AbortController();
|
||||
const controller = new AbortController();
|
||||
const extensionTurn: AcpxRuntimeExtensionTurn = {
|
||||
requestId: started, sessionId: identity.backendSessionId, controller,
|
||||
signal: AbortSignal.any([controller.signal, approval.signal]), promptStarted: Promise.resolve(),
|
||||
onPlanProposal: binding.onPlanProposal,
|
||||
};
|
||||
cycleTurn.active = extensionTurn;
|
||||
extensionBoundary.active = extensionTurn;
|
||||
permissionBoundary.hasAdmittedTurn = true;
|
||||
permissionBoundary.active = approval;
|
||||
permissionBoundary.handler = binding.onPermissionRequest;
|
||||
cycles.adopt(binding.busy);
|
||||
return true;
|
||||
},
|
||||
drop: () => cycles.drop(),
|
||||
cancel: () => cycles.cancel(),
|
||||
undecided: () => cycles.undecided(),
|
||||
decisionFor: (toolCallId) => cycles.decisionFor(toolCallId),
|
||||
};
|
||||
}
|
||||
return port;
|
||||
}
|
||||
|
||||
|
||||
@@ -173,4 +173,32 @@ describe("ClaudeBackgroundTaskTracker", () => {
|
||||
}
|
||||
expect(tasks.state()).toBeNull();
|
||||
});
|
||||
|
||||
it("counts only running shells once a shell finished or Claude acted, and is unknown when none runs", () => {
|
||||
const finishedOne = negotiated();
|
||||
prompt(finishedOne, 1, [spawned(), backgrounded, { ...spawned(), asyncTaskId: "task-2" }]);
|
||||
finishedOne.observe("inbound", update(settled("completed")));
|
||||
expect(finishedOne.state()).toEqual({ live: 1 });
|
||||
finishedOne.providerTurnStarted();
|
||||
finishedOne.observe("inbound", update({ sessionUpdate: "tool_call", toolCallId: "toolu_9", _meta: { claudeCode: { toolName: "Read" } } }), true);
|
||||
finishedOne.observe("inbound", { jsonrpc: "2.0", id: 4, method: "session/request_permission", params: {} }, true);
|
||||
finishedOne.providerTurnEnded(true);
|
||||
expect(finishedOne.state()).toEqual({ live: 1 });
|
||||
finishedOne.observe("inbound", update({ ...settled("completed"), asyncTaskId: "task-2" }));
|
||||
expect(finishedOne.state()).toBeNull();
|
||||
|
||||
const acted = negotiated();
|
||||
prompt(acted, 1, []);
|
||||
acted.providerTurnStarted();
|
||||
acted.providerTurnEnded(true);
|
||||
expect(acted.state()).toBeNull();
|
||||
});
|
||||
|
||||
it("stays unknown after a cycle that did not complete, even while a shell runs", () => {
|
||||
const failed = negotiated();
|
||||
prompt(failed, 1, [spawned(), backgrounded]);
|
||||
failed.providerTurnStarted();
|
||||
failed.providerTurnEnded(false);
|
||||
expect(failed.state()).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -30,12 +30,13 @@ export class ClaudeBackgroundTaskTracker {
|
||||
#observedTask = false;
|
||||
readonly #tasks = new Map<string, Task>();
|
||||
readonly #pending = new Map<RequestId, { method: string; advertised: boolean }>();
|
||||
#acted = false;
|
||||
|
||||
observe(direction: "inbound" | "outbound", message: unknown): void {
|
||||
observe(direction: "inbound" | "outbound", message: unknown, providerTurn = false): void {
|
||||
if (this.#unknown) return;
|
||||
try {
|
||||
if (direction === "outbound") this.#outbound(record(message));
|
||||
else this.#inbound(record(message));
|
||||
else this.#inbound(record(message), providerTurn);
|
||||
} catch {
|
||||
this.#unknown = true;
|
||||
}
|
||||
@@ -43,14 +44,22 @@ export class ClaudeBackgroundTaskTracker {
|
||||
|
||||
state(): ClaudeBackgroundTaskState | null {
|
||||
if (this.#unknown || !this.#negotiated) return null;
|
||||
if (!this.#observedTask) return { live: 0 };
|
||||
let live = 0;
|
||||
for (const task of this.#tasks.values()) {
|
||||
if (!task.live) continue;
|
||||
if (!task.shell) return null;
|
||||
live += 1;
|
||||
}
|
||||
return live > 0 ? { live } : null;
|
||||
if (live > 0) return { live };
|
||||
return this.#observedTask || this.#acted ? null : { live: 0 };
|
||||
}
|
||||
|
||||
providerTurnStarted(): void {
|
||||
this.#acted = true;
|
||||
}
|
||||
|
||||
providerTurnEnded(completed: boolean): void {
|
||||
if (!completed) this.#unknown = true;
|
||||
}
|
||||
|
||||
#outbound(message: Record<string, unknown>): void {
|
||||
@@ -65,7 +74,7 @@ export class ClaudeBackgroundTaskTracker {
|
||||
this.#pending.set(id, { method: message.method, advertised });
|
||||
}
|
||||
|
||||
#inbound(message: Record<string, unknown>): void {
|
||||
#inbound(message: Record<string, unknown>, providerTurn: boolean): void {
|
||||
const id = message.id;
|
||||
const hasId = typeof id === "string" || typeof id === "number";
|
||||
if (hasId && message.method === undefined) {
|
||||
@@ -81,7 +90,7 @@ export class ClaudeBackgroundTaskTracker {
|
||||
return;
|
||||
}
|
||||
if (hasId) {
|
||||
if (this.#pending.size === 0) this.#unknown = true;
|
||||
if (this.#pending.size === 0 && !providerTurn) this.#unknown = true;
|
||||
return;
|
||||
}
|
||||
if (message.method !== "session/update") return;
|
||||
@@ -104,7 +113,7 @@ export class ClaudeBackgroundTaskTracker {
|
||||
this.#unknown = true;
|
||||
}
|
||||
const origin = record(update._meta)["_claude/origin"];
|
||||
if (this.#pending.size === 0 && (IDLE_ACTIVITY.has(kind) || (kind === "usage_update" && origin !== undefined))) {
|
||||
if (this.#pending.size === 0 && !providerTurn && (IDLE_ACTIVITY.has(kind) || (kind === "usage_update" && origin !== undefined))) {
|
||||
this.#unknown = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { ClaudeBackgroundTaskState } from "./claude-background-tasks.js";
|
||||
import { ClaudeProviderCycles } from "./claude-provider-turns.js";
|
||||
|
||||
const SESSION = "session-1";
|
||||
const air = { jetbrains: { air: { version: 1, capabilities: ["sessionFailure", "asyncTasks"] } } };
|
||||
const update = (body: Record<string, unknown>) => ({ jsonrpc: "2.0", method: "session/update", params: { sessionId: SESSION, update: body } });
|
||||
const spawned = (id: string) => update({ sessionUpdate: "async_task_spawned", asyncTaskId: id, name: id, taskType: "shell", description: id, showInTranscript: false, canStop: true });
|
||||
const finished = (id: string) => update({ sessionUpdate: "async_task_state_update", asyncTaskId: id, state: "completed" });
|
||||
const usage = () => update({ sessionUpdate: "usage_update", used: 3, size: 100 });
|
||||
const text = () => update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Handled a notification." } });
|
||||
const toolCall = (id: string) => update({ sessionUpdate: "tool_call", toolCallId: id, title: "Read", kind: "read", status: "pending" });
|
||||
const endMarker = (tokens = 1) => update({ sessionUpdate: "usage_update", used: 5, size: 100, cost: { amount: 0.000104, currency: "USD" },
|
||||
_meta: { "_claude/origin": { kind: "task-notification", producer: "session-task" }, usage: { input_tokens: tokens, output_tokens: tokens, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 } } });
|
||||
const humanEnd = () => update({ sessionUpdate: "usage_update", used: 5, size: 100, _meta: { "_claude/origin": { kind: "human" } } });
|
||||
|
||||
type Seen = { started: number; ended: Array<ClaudeBackgroundTaskState | null> };
|
||||
|
||||
function wiring() {
|
||||
const cycles = new ClaudeProviderCycles({ sessionId: () => SESSION, promptActive: () => false }).subscribe();
|
||||
const seen: Seen = { started: 0, ended: [] };
|
||||
void (async () => {
|
||||
for (let item = await cycles.next(); item !== null; item = await cycles.next()) {
|
||||
if (item.type === "started") {
|
||||
seen.started += 1;
|
||||
cycles.adopt(() => false);
|
||||
}
|
||||
if (item.type === "ended") seen.ended.push(cycles.backgroundTasks());
|
||||
}
|
||||
})();
|
||||
const deliver = (...messages: unknown[]) => { for (const message of messages) cycles.observe("inbound", message); };
|
||||
let id = 0;
|
||||
const prompt = (...messages: unknown[]) => {
|
||||
const request = ++id;
|
||||
cycles.observe("outbound", { jsonrpc: "2.0", id: request, method: "session/prompt", params: { sessionId: SESSION } });
|
||||
deliver(...messages, humanEnd(), { jsonrpc: "2.0", id: request, result: { stopReason: "end_turn" } });
|
||||
return cycles.backgroundTasks();
|
||||
};
|
||||
const ended = async (count: number) => {
|
||||
while (seen.ended.length < count) await new Promise(resolve => setTimeout(resolve, 1));
|
||||
return seen.ended[count - 1];
|
||||
};
|
||||
cycles.observe("outbound", { jsonrpc: "2.0", id: 1_000, method: "initialize", params: { clientCapabilities: { _meta: air } } });
|
||||
deliver({ jsonrpc: "2.0", id: 1_000, result: { protocolVersion: 1, _meta: air } });
|
||||
return { cycles, seen, deliver, prompt, ended };
|
||||
}
|
||||
|
||||
describe("Claude provider-started turns and background task accounting", () => {
|
||||
it("knows a process without background work is quiet at every terminal", () => {
|
||||
const { prompt } = wiring();
|
||||
expect(prompt(toolCall("toolu_1"))).toEqual({ live: 0 });
|
||||
expect(prompt(text())).toEqual({ live: 0 });
|
||||
});
|
||||
|
||||
it("waits for a single shell, then is unknown once its cycle ran", async () => {
|
||||
const { prompt, deliver, ended } = wiring();
|
||||
expect(prompt(spawned("task-1"))).toEqual({ live: 1 });
|
||||
deliver(finished("task-1"), usage(), text(), endMarker());
|
||||
expect(await ended(1)).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps the shells that still run live after each cycle and is unknown after the last one", async () => {
|
||||
const { prompt, deliver, ended } = wiring();
|
||||
expect(prompt(spawned("task-1"), spawned("task-2"))).toEqual({ live: 2 });
|
||||
deliver(finished("task-1"));
|
||||
deliver(usage(), text(), endMarker());
|
||||
expect(await ended(1)).toEqual({ live: 1 });
|
||||
deliver(finished("task-2"), usage(), text(), endMarker(2));
|
||||
expect(await ended(2)).toBeNull();
|
||||
});
|
||||
|
||||
it("is unknown when a second shell finishes before the first cycle's first update", async () => {
|
||||
const { prompt, deliver, ended } = wiring();
|
||||
expect(prompt(spawned("task-1"), spawned("task-2"))).toEqual({ live: 2 });
|
||||
deliver(finished("task-1"), finished("task-2"), usage(), text(), endMarker());
|
||||
expect(await ended(1)).toBeNull();
|
||||
});
|
||||
|
||||
it("is unknown when a second shell's notification may be consumed inside the running cycle", async () => {
|
||||
const { prompt, deliver, ended } = wiring();
|
||||
expect(prompt(spawned("task-1"), spawned("task-2"))).toEqual({ live: 2 });
|
||||
deliver(finished("task-1"), usage(), toolCall("toolu_cycle"), finished("task-2"), text(), endMarker());
|
||||
expect(await ended(1)).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores an empty result right after a cycle's end, as in the E2 capture, and adopts the next real cycle", async () => {
|
||||
const { prompt, deliver, ended, seen } = wiring();
|
||||
expect(prompt(spawned("task-1"), spawned("task-2"), spawned("task-3"))).toEqual({ live: 3 });
|
||||
deliver(finished("task-1"), finished("task-2"), finished("task-3"), usage(), text(), usage(), endMarker(), endMarker(0));
|
||||
expect(await ended(1)).toBeNull();
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
expect(seen.started).toBe(1);
|
||||
deliver(usage(), text(), usage(), endMarker(2));
|
||||
expect(await ended(2)).toBeNull();
|
||||
expect(seen.started).toBe(2);
|
||||
});
|
||||
|
||||
it("keeps a running shell live through an empty result after a cycle", async () => {
|
||||
const { prompt, deliver, ended, cycles, seen } = wiring();
|
||||
expect(prompt(spawned("task-1"), spawned("task-2"))).toEqual({ live: 2 });
|
||||
deliver(finished("task-1"), usage(), text(), endMarker());
|
||||
expect(await ended(1)).toEqual({ live: 1 });
|
||||
deliver(endMarker(0));
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
expect(seen.started).toBe(1);
|
||||
expect(cycles.backgroundTasks()).toEqual({ live: 1 });
|
||||
});
|
||||
|
||||
it("still adopts a failed cycle's lone end marker after a task finished, even when it repeats the last one", async () => {
|
||||
const { prompt, deliver, ended, seen } = wiring();
|
||||
expect(prompt(spawned("task-1"), spawned("task-2"))).toEqual({ live: 2 });
|
||||
deliver(finished("task-1"), endMarker(0));
|
||||
expect(await ended(1)).toEqual({ live: 1 });
|
||||
deliver(finished("task-2"), endMarker(0));
|
||||
expect(await ended(2)).toBeNull();
|
||||
expect(seen.started).toBe(2);
|
||||
});
|
||||
|
||||
it("replays the captured claude-agent-acp stream of three shells and a duplicate end marker as two cycles that end unknown", async () => {
|
||||
const capture = JSON.parse(readFileSync(new URL("../../test-support/claude-acp-overlapping-notifications.json", import.meta.url), "utf8")) as
|
||||
Array<{ direction: "inbound" | "outbound"; message: { id?: number; result?: unknown; params?: { sessionId?: string } } }>;
|
||||
const session = capture.find(({ message }) => message.params?.sessionId)!.message.params!.sessionId!;
|
||||
const cycles = new ClaudeProviderCycles({ sessionId: () => session, promptActive: () => false }).subscribe();
|
||||
const seen: Seen = { started: 0, ended: [] };
|
||||
void (async () => {
|
||||
for (let item = await cycles.next(); item !== null; item = await cycles.next()) {
|
||||
if (item.type === "started") {
|
||||
seen.started += 1;
|
||||
cycles.adopt(() => false);
|
||||
}
|
||||
if (item.type === "ended") seen.ended.push(cycles.backgroundTasks());
|
||||
}
|
||||
})();
|
||||
let atPromptEnd: ClaudeBackgroundTaskState | null = null;
|
||||
for (const { direction, message } of capture) {
|
||||
cycles.observe(direction, message);
|
||||
if (direction === "inbound" && message.id === 3 && message.result) atPromptEnd = cycles.backgroundTasks();
|
||||
}
|
||||
expect(atPromptEnd).toEqual({ live: 3 });
|
||||
while (seen.ended.length < 2) await new Promise(resolve => setTimeout(resolve, 1));
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
expect(seen).toEqual({ started: 2, ended: [null, null] });
|
||||
});
|
||||
|
||||
it("makes the background state unknown when a cycle is dropped", async () => {
|
||||
const cycles = new ClaudeProviderCycles({ sessionId: () => SESSION, promptActive: () => false }).subscribe();
|
||||
cycles.observe("outbound", { jsonrpc: "2.0", id: 0, method: "initialize", params: { clientCapabilities: { _meta: air } } });
|
||||
cycles.observe("inbound", { jsonrpc: "2.0", id: 0, result: { protocolVersion: 1, _meta: air } });
|
||||
cycles.observe("inbound", spawned("task-1"));
|
||||
cycles.observe("inbound", spawned("task-2"));
|
||||
cycles.observe("inbound", finished("task-1"));
|
||||
cycles.observe("inbound", usage());
|
||||
expect(cycles.backgroundTasks()).toEqual({ live: 1 });
|
||||
expect(await cycles.next()).toMatchObject({ type: "started" });
|
||||
cycles.drop();
|
||||
expect(cycles.backgroundTasks()).toBeNull();
|
||||
expect(await cycles.next()).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,231 @@
|
||||
import type { AcpRuntimeEvent } from "acpx/runtime";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
CLAUDE_PROVIDER_TURN_PROCESS_LOST,
|
||||
CLAUDE_PROVIDER_TURN_SILENT,
|
||||
ClaudeProviderCycles,
|
||||
parseAcpxProviderTurnArming,
|
||||
type ClaudeProviderCycleSource,
|
||||
type ClaudeProviderTurnResult,
|
||||
} from "./claude-provider-turns.js";
|
||||
|
||||
const SESSION = "session-1";
|
||||
const update = (body: Record<string, unknown>, sessionId = SESSION) => ({ jsonrpc: "2.0", method: "session/update", params: { sessionId, update: body } });
|
||||
const endMarker = (usage: Record<string, unknown> = { input_tokens: 6, output_tokens: 4, cache_read_input_tokens: 1, cache_creation_input_tokens: 2 }) =>
|
||||
update({ sessionUpdate: "usage_update", used: 9, size: 100, cost: { amount: 0.25, currency: "USD" }, _meta: { "_claude/origin": { kind: "task-notification", producer: "session-task" }, usage } });
|
||||
const toolCall = (id: string) => update({ sessionUpdate: "tool_call", toolCallId: id, title: "mcp__paperclip__probe", kind: "other", status: "pending", rawInput: { tag: id } });
|
||||
|
||||
type Adopted = { requestId: string; events: AcpRuntimeEvent[]; done: Promise<ClaudeProviderTurnResult>; settled: boolean };
|
||||
|
||||
function harness(overrides: Partial<ClaudeProviderCycleSource> = {}, adopt = true) {
|
||||
const adopted: Adopted[] = [];
|
||||
let promptActive = false;
|
||||
let busy = false;
|
||||
let next = 0;
|
||||
const cycles = new ClaudeProviderCycles({
|
||||
sessionId: () => SESSION,
|
||||
promptActive: () => promptActive,
|
||||
mintTurnId: () => `provider-${++next}`,
|
||||
...overrides,
|
||||
}).subscribe();
|
||||
void (async () => {
|
||||
let settle: (result: ClaudeProviderTurnResult) => void = () => undefined;
|
||||
for (let item = await cycles.next(); item !== null; item = await cycles.next()) {
|
||||
if (item.type === "started") {
|
||||
if (!adopt) {
|
||||
cycles.drop();
|
||||
continue;
|
||||
}
|
||||
cycles.adopt(() => busy);
|
||||
const entry: Adopted = { requestId: item.requestId, events: [], done: new Promise((resolve) => { settle = resolve; }), settled: false };
|
||||
adopted.push(entry);
|
||||
} else if (item.type === "event") {
|
||||
adopted.at(-1)!.events.push(item.event);
|
||||
} else if (item.type === "ended") {
|
||||
adopted.at(-1)!.settled = true;
|
||||
settle(item.result);
|
||||
}
|
||||
}
|
||||
})();
|
||||
return {
|
||||
cycles, adopted,
|
||||
setPrompt: (value: boolean) => { promptActive = value; },
|
||||
setBusy: (value: boolean) => { busy = value; },
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(() => { vi.useRealTimers(); });
|
||||
|
||||
describe("Claude provider-started turns", () => {
|
||||
it("opens at the first idle cycle message and ends at the origin-tagged usage update with the cycle's usage", async () => {
|
||||
const { cycles, adopted } = harness();
|
||||
expect(cycles.observe("inbound", update({ sessionUpdate: "session_info_update", title: "A title" }))).toBe(false);
|
||||
expect(cycles.observe("inbound", update({ sessionUpdate: "available_commands_update", availableCommands: [] }))).toBe(false);
|
||||
expect(cycles.observe("inbound", update({ sessionUpdate: "async_task_state_update", asyncTaskId: "b1", state: "completed" }))).toBe(false);
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
expect(adopted).toHaveLength(0);
|
||||
expect(cycles.observe("inbound", update({ sessionUpdate: "usage_update", used: 3, size: 100 }))).toBe(true);
|
||||
await vi.waitFor(() => expect(adopted).toHaveLength(1));
|
||||
expect(adopted[0]!.requestId).toBe("provider-1");
|
||||
expect(cycles.observe("inbound", toolCall("toolu_1"))).toBe(true);
|
||||
expect(cycles.observe("inbound", { jsonrpc: "2.0", id: 0, method: "session/request_permission", params: { sessionId: SESSION, toolCall: { toolCallId: "toolu_1" }, options: [] } })).toBe(true);
|
||||
expect(cycles.observe("inbound", update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "done" } }))).toBe(true);
|
||||
expect(cycles.observe("inbound", endMarker())).toBe(true);
|
||||
const result = await adopted[0]!.done;
|
||||
expect(result).toEqual({ status: "completed", stopReason: "end_turn", usage: { type: "status", tag: "usage_update", text: "terminal prompt usage",
|
||||
cost: { amount: 0.25, currency: "USD" },
|
||||
breakdown: { inputTokens: 6, outputTokens: 4, cachedReadTokens: 1, cachedWriteTokens: 2, thoughtTokens: undefined, totalTokens: undefined } } });
|
||||
expect(adopted[0]!.events.map(event => [event.type, (event as { tag?: unknown }).tag])).toEqual([
|
||||
["status", "usage_update"], ["tool_call", "tool_call"], ["text_delta", "agent_message_chunk"], ["status", "usage_update"]]);
|
||||
expect(cycles.observe("inbound", update({ sessionUpdate: "tool_call_update", toolCallId: "toolu_2", status: "pending" }))).toBe(true);
|
||||
await vi.waitFor(() => expect(adopted).toHaveLength(2));
|
||||
});
|
||||
|
||||
it("treats an end marker that arrives alone, as after a failed API call, as a whole turn", async () => {
|
||||
const { cycles, adopted } = harness();
|
||||
expect(cycles.observe("inbound", endMarker({ input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 }))).toBe(true);
|
||||
await vi.waitFor(() => expect(adopted).toHaveLength(1));
|
||||
expect(await adopted[0]!.done).toMatchObject({ status: "completed", usage: { breakdown: { inputTokens: 0, outputTokens: 0 } } });
|
||||
});
|
||||
|
||||
it("never opens while a prompt or client request is in flight or for another session", async () => {
|
||||
const { cycles, adopted, setPrompt } = harness();
|
||||
setPrompt(true);
|
||||
expect(cycles.observe("inbound", toolCall("toolu_prompt"))).toBe(false);
|
||||
setPrompt(false);
|
||||
cycles.observe("outbound", { jsonrpc: "2.0", id: 7, method: "session/set_mode", params: {} });
|
||||
expect(cycles.observe("inbound", toolCall("toolu_pending"))).toBe(false);
|
||||
cycles.observe("inbound", { jsonrpc: "2.0", id: 7, result: {} });
|
||||
expect(cycles.observe("inbound", toolCall("toolu_other"), )).toBe(true);
|
||||
await vi.waitFor(() => expect(adopted).toHaveLength(1));
|
||||
expect(cycles.observe("inbound", update({ sessionUpdate: "tool_call", toolCallId: "x", title: "t" }, "child-session"))).toBe(false);
|
||||
});
|
||||
|
||||
it("retires adoption when the turn is not admitted so the background state stays unknown", async () => {
|
||||
const { cycles } = harness({}, false);
|
||||
expect(cycles.observe("inbound", toolCall("toolu_1"))).toBe(true);
|
||||
await vi.waitFor(() => expect(cycles.retired).toBe(true));
|
||||
expect(cycles.observe("inbound", toolCall("toolu_2"))).toBe(false);
|
||||
expect(cycles.backgroundTasks()).toBeNull();
|
||||
});
|
||||
|
||||
it("fails the turn when the provider exits and cancels it on request", async () => {
|
||||
const exited = harness();
|
||||
exited.cycles.observe("inbound", toolCall("toolu_1"));
|
||||
await vi.waitFor(() => expect(exited.adopted).toHaveLength(1));
|
||||
exited.cycles.lost();
|
||||
expect(await exited.adopted[0]!.done).toEqual({ status: "failed", error: { code: CLAUDE_PROVIDER_TURN_PROCESS_LOST,
|
||||
message: "The owned ACPX provider exited during Claude's own turn", retryable: false } });
|
||||
expect(exited.cycles.observe("inbound", toolCall("toolu_2"))).toBe(false);
|
||||
|
||||
const cancelled = harness();
|
||||
expect(cancelled.cycles.cancel()).toBe(false);
|
||||
cancelled.cycles.observe("inbound", toolCall("toolu_1"));
|
||||
await vi.waitFor(() => expect(cancelled.adopted).toHaveLength(1));
|
||||
expect(cancelled.cycles.cancel()).toBe(true);
|
||||
expect(await cancelled.adopted[0]!.done).toEqual({ status: "cancelled", stopReason: "cancelled" });
|
||||
});
|
||||
|
||||
it("fails a silent turn after the bound unless Paperclip still owns pending work", async () => {
|
||||
vi.useFakeTimers();
|
||||
const { cycles, adopted, setBusy } = harness({ silenceMs: 1_000 });
|
||||
cycles.observe("inbound", toolCall("toolu_1"));
|
||||
await vi.waitFor(() => expect(adopted).toHaveLength(1));
|
||||
setBusy(true);
|
||||
await vi.advanceTimersByTimeAsync(2_500);
|
||||
expect(adopted[0]!.settled).toBe(false);
|
||||
setBusy(false);
|
||||
cycles.observe("inbound", update({ sessionUpdate: "tool_call_update", toolCallId: "toolu_1", status: "completed" }));
|
||||
while (adopted[0]!.events.length < 2) await vi.advanceTimersByTimeAsync(0);
|
||||
await vi.advanceTimersByTimeAsync(999);
|
||||
expect(adopted[0]!.settled).toBe(false);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
vi.useRealTimers();
|
||||
expect(await adopted[0]!.done).toMatchObject({ status: "failed", error: { code: CLAUDE_PROVIDER_TURN_SILENT } });
|
||||
expect(cycles.retired).toBe(true);
|
||||
});
|
||||
|
||||
it("lets callbacks of a started cycle wait for the consumer's decision", async () => {
|
||||
const cycles = new ClaudeProviderCycles({ sessionId: () => SESSION, promptActive: () => false }).subscribe();
|
||||
expect(cycles.undecided()).toBeNull();
|
||||
cycles.observe("inbound", toolCall("toolu_1"));
|
||||
const first = cycles.undecided();
|
||||
expect(first).not.toBeNull();
|
||||
expect(await cycles.next()).toMatchObject({ type: "started" });
|
||||
cycles.adopt(() => false);
|
||||
expect(await first).toBe(true);
|
||||
expect(cycles.undecided()).toBeNull();
|
||||
cycles.observe("inbound", endMarker());
|
||||
cycles.observe("inbound", toolCall("toolu_2"));
|
||||
const second = cycles.undecided();
|
||||
for (let item = await cycles.next(); item?.type !== "started"; item = await cycles.next()) void item;
|
||||
cycles.drop();
|
||||
expect(await second).toBe(false);
|
||||
expect(cycles.undecided()).toBeNull();
|
||||
});
|
||||
|
||||
it("binds a tool call or permission request to the decision of the cycle that sent it", async () => {
|
||||
const cycles = new ClaudeProviderCycles({ sessionId: () => SESSION, promptActive: () => false }).subscribe();
|
||||
cycles.observe("inbound", toolCall("toolu_1"));
|
||||
cycles.observe("inbound", endMarker());
|
||||
cycles.observe("inbound", toolCall("toolu_2"));
|
||||
cycles.observe("inbound", { jsonrpc: "2.0", id: 3, method: "session/request_permission", params: { sessionId: SESSION, toolCall: { toolCallId: "toolu_3" }, options: [] } });
|
||||
const first = cycles.decisionFor("toolu_1");
|
||||
const second = cycles.decisionFor("toolu_2");
|
||||
expect(cycles.decisionFor("toolu_3")).toBe(second);
|
||||
expect(cycles.decisionFor("toolu_unknown")).toBe(second);
|
||||
expect(second).not.toBe(first);
|
||||
let secondDecided = false;
|
||||
void second!.then(() => { secondDecided = true; });
|
||||
expect(await cycles.next()).toMatchObject({ type: "started" });
|
||||
cycles.adopt(() => false);
|
||||
expect(await first).toBe(true);
|
||||
for (let item = await cycles.next(); item?.type !== "started"; item = await cycles.next()) void item;
|
||||
expect(secondDecided).toBe(false);
|
||||
cycles.drop();
|
||||
expect(await second).toBe(false);
|
||||
});
|
||||
|
||||
it("parses only the closed arming contract runnerd sends", () => {
|
||||
expect(parseAcpxProviderTurnArming({ turnId: "turn-1", armed: true })).toEqual({ turnId: "turn-1", armed: true });
|
||||
expect(parseAcpxProviderTurnArming({ armed: false, turnId: "provider-1" })).toEqual({ turnId: "provider-1", armed: false });
|
||||
for (const params of [{ turnId: "turn-1" }, { turnId: "turn-1", armed: "true" }, { turnId: "bad id", armed: true },
|
||||
{ turnId: "turn-1", armed: true, extra: 1 }, { turnId: "x".repeat(241), armed: true }]) {
|
||||
expect(() => parseAcpxProviderTurnArming(params)).toThrow("bounded contract");
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the next cycle's first messages when they arrive before the previous cycle has been consumed", async () => {
|
||||
const { cycles, adopted } = harness();
|
||||
cycles.observe("inbound", toolCall("toolu_1"));
|
||||
cycles.observe("inbound", endMarker());
|
||||
expect(cycles.observe("inbound", update({ sessionUpdate: "usage_update", used: 4, size: 100 }))).toBe(true);
|
||||
expect(cycles.observe("inbound", toolCall("toolu_2"))).toBe(true);
|
||||
await vi.waitFor(() => expect(adopted.length).toBeGreaterThan(0));
|
||||
expect(await adopted[0]!.done).toMatchObject({ status: "completed" });
|
||||
expect(adopted[0]!.events.map(event => (event as { toolCallId?: unknown }).toolCallId).filter(Boolean)).toEqual(["toolu_1"]);
|
||||
await vi.waitFor(() => expect(adopted).toHaveLength(2));
|
||||
cycles.observe("inbound", endMarker());
|
||||
expect(await adopted[1]!.done).toMatchObject({ status: "completed" });
|
||||
expect(adopted[1]!.events.map(event => [event.type, (event as { tag?: unknown }).tag])).toEqual([
|
||||
["status", "usage_update"], ["tool_call", "tool_call"], ["status", "usage_update"]]);
|
||||
});
|
||||
|
||||
it("ignores a task report that arrives between cycles and does not count it as a declined cycle", async () => {
|
||||
const { cycles, adopted } = harness();
|
||||
const progress = update({ sessionUpdate: "async_task_progress", asyncTaskId: "task-2" });
|
||||
cycles.observe("inbound", toolCall("toolu_1"));
|
||||
cycles.observe("inbound", endMarker());
|
||||
expect(cycles.observe("inbound", progress)).toBe(false);
|
||||
await vi.waitFor(() => expect(adopted).toHaveLength(1));
|
||||
expect(await adopted[0]!.done).toMatchObject({ status: "completed" });
|
||||
expect(cycles.retired).toBe(false);
|
||||
expect(cycles.observe("inbound", toolCall("toolu_2"))).toBe(true);
|
||||
expect(cycles.observe("inbound", progress)).toBe(true);
|
||||
cycles.observe("inbound", endMarker());
|
||||
await vi.waitFor(() => expect(adopted).toHaveLength(2));
|
||||
expect(await adopted[1]!.done).toMatchObject({ status: "completed" });
|
||||
expect(cycles.retired).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,325 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import type { AcpRuntimeEvent } from "acpx/runtime";
|
||||
|
||||
import { createAcpSessionUpdateEventConverter, type AcpSessionUpdateEventConverter } from "./acp-session-update-event.js";
|
||||
import { ClaudeBackgroundTaskTracker, type ClaudeBackgroundTaskState } from "./claude-background-tasks.js";
|
||||
|
||||
export const CLAUDE_PROVIDER_TURN_SILENCE_MS = 660_000;
|
||||
export const CLAUDE_PROVIDER_TURN_PROCESS_LOST = "ACPX_PROVIDER_PROCESS_LOST";
|
||||
export const CLAUDE_PROVIDER_TURN_SILENT = "ACPX_PROVIDER_TURN_SILENT";
|
||||
export const CLAUDE_PROVIDER_TURN_CLOSED = "ACPX_PROVIDER_TURN_CLOSED";
|
||||
export const CLAUDE_PROVIDER_TURN_OVERFLOW = "ACPX_PROVIDER_TURN_OVERFLOW";
|
||||
|
||||
const START_KINDS = new Set(["usage_update", "tool_call", "tool_call_update", "agent_message_chunk", "agent_thought_chunk", "plan"]);
|
||||
const startsCycle = (update: Record<string, unknown>): boolean =>
|
||||
typeof update.sessionUpdate === "string" && START_KINDS.has(update.sessionUpdate);
|
||||
const MAX_PENDING_REQUESTS = 256;
|
||||
const MAX_QUEUED_MESSAGES = 4_096;
|
||||
const MAX_TOOL_DECISIONS = 1_024;
|
||||
const EMPTY_RESULT_USAGE = ["input_tokens", "output_tokens", "cache_read_input_tokens", "cache_creation_input_tokens"];
|
||||
|
||||
export type ClaudeProviderTurnResult =
|
||||
| { status: "completed"; stopReason: "end_turn"; usage: Record<string, unknown> | null }
|
||||
| { status: "cancelled"; stopReason: "cancelled" }
|
||||
| { status: "failed"; error: { code: string; message: string; retryable: false } };
|
||||
|
||||
export type ClaudeProviderCycleItem =
|
||||
| { type: "started"; requestId: string }
|
||||
| { type: "event"; event: AcpRuntimeEvent }
|
||||
| { type: "ended"; result: ClaudeProviderTurnResult }
|
||||
| { type: "lost" };
|
||||
|
||||
export interface ClaudeProviderCycleSource {
|
||||
sessionId(): string | null;
|
||||
promptActive(): boolean;
|
||||
silenceMs?: number;
|
||||
mintTurnId?: () => string;
|
||||
}
|
||||
|
||||
type Queued =
|
||||
| { type: "started"; requestId: string; decision: Decision }
|
||||
| { type: "message"; message: unknown }
|
||||
| { type: "ended"; result: ClaudeProviderTurnResult }
|
||||
| { type: "lost" };
|
||||
|
||||
type Decision = { promise: Promise<boolean>; settle(adopted: boolean): void };
|
||||
|
||||
const ARMING_TURN_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,239}$/;
|
||||
|
||||
export function parseAcpxProviderTurnArming(params: Record<string, unknown>): { turnId: string; armed: boolean } {
|
||||
const keys = Object.keys(params).sort();
|
||||
if (keys.length !== 2 || keys[0] !== "armed" || keys[1] !== "turnId"
|
||||
|| typeof params.armed !== "boolean" || typeof params.turnId !== "string" || !ARMING_TURN_ID.test(params.turnId)) {
|
||||
throw new Error("ACPX provider turn arming violates its bounded contract");
|
||||
}
|
||||
return { turnId: params.turnId, armed: params.armed };
|
||||
}
|
||||
|
||||
const record = (value: unknown): Record<string, unknown> =>
|
||||
value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
|
||||
const failed = (code: string, message: string): ClaudeProviderTurnResult => ({ status: "failed", error: { code, message, retryable: false } });
|
||||
|
||||
export function claudeProviderTurnEndMarker(update: Record<string, unknown>): boolean {
|
||||
return update.sessionUpdate === "usage_update" && record(record(update._meta)["_claude/origin"]).kind !== undefined;
|
||||
}
|
||||
|
||||
function cycleUsage(update: Record<string, unknown>): Record<string, unknown> | null {
|
||||
const usage = record(record(update._meta).usage);
|
||||
const count = (key: string) => typeof usage[key] === "number" && Number.isFinite(usage[key]) ? usage[key] : undefined;
|
||||
if (count("input_tokens") === undefined || count("output_tokens") === undefined) return null;
|
||||
const cost = record(update.cost);
|
||||
const amount = typeof cost.amount === "number" && Number.isFinite(cost.amount) ? cost.amount : undefined;
|
||||
const currency = typeof cost.currency === "string" && cost.currency.trim() ? cost.currency.trim() : undefined;
|
||||
return {
|
||||
type: "status",
|
||||
tag: "usage_update",
|
||||
text: "terminal prompt usage",
|
||||
cost: amount === undefined && currency === undefined ? undefined : { ...(amount === undefined ? {} : { amount }), ...(currency ? { currency } : {}) },
|
||||
breakdown: {
|
||||
inputTokens: count("input_tokens"),
|
||||
outputTokens: count("output_tokens"),
|
||||
cachedReadTokens: count("cache_read_input_tokens"),
|
||||
cachedWriteTokens: count("cache_creation_input_tokens"),
|
||||
thoughtTokens: count("thought_tokens"),
|
||||
totalTokens: count("total_tokens"),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function decision(): Decision {
|
||||
let settle!: (adopted: boolean) => void;
|
||||
let settled = false;
|
||||
const promise = new Promise<boolean>((resolve) => { settle = resolve; });
|
||||
return { promise, settle: (adopted) => { if (!settled) { settled = true; settle(adopted); } } };
|
||||
}
|
||||
|
||||
export class ClaudeProviderCycles {
|
||||
readonly #source: ClaudeProviderCycleSource;
|
||||
readonly #tasks = new ClaudeBackgroundTaskTracker();
|
||||
readonly #pending = new Set<string | number>();
|
||||
readonly #queue: Queued[] = [];
|
||||
readonly #undecided: Decision[] = [];
|
||||
readonly #toolDecisions = new Map<string, Decision>();
|
||||
#openDecision: Decision | null = null;
|
||||
#queuedMessages = 0;
|
||||
#waiter: (() => void) | null = null;
|
||||
#open = false;
|
||||
#subscribed = false;
|
||||
#retired = false;
|
||||
#closed = false;
|
||||
#current: { converter: AcpSessionUpdateEventConverter; busy: () => boolean } | null = null;
|
||||
#lastEndMarker: string | null = null;
|
||||
|
||||
constructor(source: ClaudeProviderCycleSource) {
|
||||
this.#source = source;
|
||||
}
|
||||
|
||||
get retired(): boolean {
|
||||
return this.#retired;
|
||||
}
|
||||
|
||||
backgroundTasks(): ClaudeBackgroundTaskState | null {
|
||||
return this.#tasks.state();
|
||||
}
|
||||
|
||||
observe(direction: "inbound" | "outbound", message: unknown): boolean {
|
||||
if (direction === "inbound" && this.#repeatsEndMarker(message)) return false;
|
||||
const inCycle = this.#classify(direction, message);
|
||||
this.#tasks.observe(direction, message, inCycle);
|
||||
return inCycle;
|
||||
}
|
||||
|
||||
subscribe(): this {
|
||||
this.#subscribed = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
undecided(): Promise<boolean> | null {
|
||||
return this.#undecided[0]?.promise ?? null;
|
||||
}
|
||||
|
||||
decisionFor(toolCallId: unknown): Promise<boolean> | null {
|
||||
const bound = typeof toolCallId === "string" ? this.#toolDecisions.get(toolCallId) : undefined;
|
||||
return (bound ?? this.#undecided.at(-1))?.promise ?? null;
|
||||
}
|
||||
|
||||
async next(): Promise<ClaudeProviderCycleItem | null> {
|
||||
for (;;) {
|
||||
const item = this.#queue.shift();
|
||||
if (item === undefined) {
|
||||
if (this.#closed) return null;
|
||||
if (await this.#wait()) continue;
|
||||
if (this.#current?.busy()) continue;
|
||||
return this.#end(failed(CLAUDE_PROVIDER_TURN_SILENT, "Claude's own turn sent nothing within the silence bound."));
|
||||
}
|
||||
if (item.type === "started") {
|
||||
this.#current = { converter: createAcpSessionUpdateEventConverter(), busy: () => false };
|
||||
return { type: "started", requestId: item.requestId };
|
||||
}
|
||||
if (item.type === "message") {
|
||||
this.#queuedMessages -= 1;
|
||||
const event = this.#current ? await this.#current.converter.convert(item.message) : null;
|
||||
if (event) return { type: "event", event };
|
||||
continue;
|
||||
}
|
||||
if (item.type === "ended") {
|
||||
const current = this.#current;
|
||||
this.#current = null;
|
||||
current?.converter.close();
|
||||
this.#tasks.providerTurnEnded(item.result.status === "completed");
|
||||
return item;
|
||||
}
|
||||
return item;
|
||||
}
|
||||
}
|
||||
|
||||
adopt(busy: () => boolean): void {
|
||||
if (this.#current) this.#current.busy = busy;
|
||||
this.#undecided.shift()?.settle(true);
|
||||
}
|
||||
|
||||
drop(): void {
|
||||
const current = this.#current;
|
||||
this.#current = null;
|
||||
current?.converter.close();
|
||||
this.#tasks.providerTurnEnded(false);
|
||||
this.#retired = true;
|
||||
this.#open = false;
|
||||
this.#queue.splice(0);
|
||||
this.#close();
|
||||
}
|
||||
|
||||
cancel(): boolean {
|
||||
if (!this.#open) return false;
|
||||
this.#stop({ status: "cancelled", stopReason: "cancelled" });
|
||||
return true;
|
||||
}
|
||||
|
||||
lost(): void {
|
||||
this.#stop(failed(CLAUDE_PROVIDER_TURN_PROCESS_LOST, "The owned ACPX provider exited during Claude's own turn"), true);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.#stop(failed(CLAUDE_PROVIDER_TURN_CLOSED, "The ACPX runtime closed during Claude's own turn."));
|
||||
}
|
||||
|
||||
retire(): void {
|
||||
this.#retired = true;
|
||||
}
|
||||
|
||||
#classify(direction: "inbound" | "outbound", message: unknown): boolean {
|
||||
if (this.#closed) return false;
|
||||
const envelope = record(message);
|
||||
const id = envelope.id;
|
||||
const hasId = typeof id === "string" || typeof id === "number";
|
||||
if (direction === "outbound") {
|
||||
if (hasId && typeof envelope.method === "string") {
|
||||
if (this.#pending.size >= MAX_PENDING_REQUESTS) this.retire();
|
||||
else this.#pending.add(id);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (hasId && envelope.method === undefined) {
|
||||
this.#pending.delete(id);
|
||||
return false;
|
||||
}
|
||||
const params = record(envelope.params);
|
||||
const ownSession = params.sessionId === undefined || params.sessionId === this.#source.sessionId();
|
||||
if (hasId) {
|
||||
if (!this.#open || !ownSession || envelope.method !== "session/request_permission") return false;
|
||||
this.#bindTool(record(params.toolCall).toolCallId);
|
||||
return true;
|
||||
}
|
||||
if (envelope.method !== "session/update" || !ownSession) return false;
|
||||
const update = record(params.update);
|
||||
if (!this.#open) {
|
||||
if (this.#retired || this.#pending.size > 0 || this.#source.promptActive() || !startsCycle(update)) return false;
|
||||
if (!this.#subscribed) {
|
||||
this.#tasks.providerTurnEnded(false);
|
||||
this.retire();
|
||||
return false;
|
||||
}
|
||||
const started = decision();
|
||||
this.#undecided.push(started);
|
||||
this.#openDecision = started;
|
||||
this.#open = true;
|
||||
this.#tasks.providerTurnStarted();
|
||||
this.#push({ type: "started", requestId: this.#source.mintTurnId?.() ?? `provider-${randomUUID()}`, decision: started });
|
||||
}
|
||||
if (this.#queuedMessages >= MAX_QUEUED_MESSAGES) {
|
||||
this.#stop(failed(CLAUDE_PROVIDER_TURN_OVERFLOW, "Claude's own turn outran its bounded queue."));
|
||||
return false;
|
||||
}
|
||||
this.#queuedMessages += 1;
|
||||
this.#push({ type: "message", message });
|
||||
this.#bindTool(update.toolCallId);
|
||||
if (claudeProviderTurnEndMarker(update)) {
|
||||
this.#open = false;
|
||||
this.#push({ type: "ended", result: { status: "completed", stopReason: "end_turn", usage: cycleUsage(update) } });
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#repeatsEndMarker(message: unknown): boolean {
|
||||
const envelope = record(message);
|
||||
const params = record(envelope.params);
|
||||
const update = record(params.update);
|
||||
const usage = record(record(update._meta).usage);
|
||||
const marker = envelope.method === "session/update" && claudeProviderTurnEndMarker(update)
|
||||
? JSON.stringify([params.sessionId, update.used, update.size, update.cost])
|
||||
: null;
|
||||
const empty = EMPTY_RESULT_USAGE.every((key) => usage[key] === 0);
|
||||
const repeated = marker !== null && marker === this.#lastEndMarker && empty && !this.#open;
|
||||
this.#lastEndMarker = marker;
|
||||
return repeated;
|
||||
}
|
||||
|
||||
#stop(result: ClaudeProviderTurnResult, lost = false): void {
|
||||
this.#retired = true;
|
||||
if (this.#closed) return;
|
||||
if (this.#open) this.#push({ type: "ended", result });
|
||||
this.#open = false;
|
||||
if (lost) this.#push({ type: "lost" });
|
||||
this.#close();
|
||||
}
|
||||
|
||||
#end(result: ClaudeProviderTurnResult): ClaudeProviderCycleItem {
|
||||
this.drop();
|
||||
return { type: "ended", result };
|
||||
}
|
||||
|
||||
#bindTool(toolCallId: unknown): void {
|
||||
if (typeof toolCallId !== "string" || this.#openDecision === null) return;
|
||||
if (!this.#toolDecisions.has(toolCallId) && this.#toolDecisions.size >= MAX_TOOL_DECISIONS) {
|
||||
this.#toolDecisions.delete(this.#toolDecisions.keys().next().value!);
|
||||
}
|
||||
this.#toolDecisions.set(toolCallId, this.#openDecision);
|
||||
}
|
||||
|
||||
#close(): void {
|
||||
this.#closed = true;
|
||||
for (const pending of this.#undecided.splice(0)) pending.settle(false);
|
||||
this.#wake();
|
||||
}
|
||||
|
||||
#push(item: Queued): void {
|
||||
this.#queue.push(item);
|
||||
this.#wake();
|
||||
}
|
||||
|
||||
#wait(): Promise<boolean> {
|
||||
return new Promise<boolean>((resolve) => {
|
||||
const timer = this.#current ? setTimeout(() => { this.#waiter = null; resolve(false); }, this.#source.silenceMs ?? CLAUDE_PROVIDER_TURN_SILENCE_MS) : null;
|
||||
timer?.unref?.();
|
||||
this.#waiter = () => { if (timer) clearTimeout(timer); resolve(true); };
|
||||
});
|
||||
}
|
||||
|
||||
#wake(): void {
|
||||
const waiter = this.#waiter;
|
||||
this.#waiter = null;
|
||||
waiter?.();
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { piProviderConfiguration } from "./pi-provider-config.js";
|
||||
import { withAcpxTurnCancellation } from "./turn-cancellation.js";
|
||||
import type { AcpxTerminalSessionFailure } from "./provider-failure.js";
|
||||
import type { ClaudeBackgroundTaskState } from "./claude-background-tasks.js";
|
||||
import type { ClaudeProviderCycleItem } from "./claude-provider-turns.js";
|
||||
import { resolveAcpxProviderMode } from "./provider-mode.js";
|
||||
import { resolvePiThinkingLevel, type PiThinkingLevel } from "./pi-thinking.js";
|
||||
import { preparedHarnessHome, preconfiguredHomeEnvironment, usesPreconfiguredHome } from "../preconfigured-home.js";
|
||||
@@ -158,6 +159,21 @@ export interface AcpxRuntimeTurn {
|
||||
}
|
||||
|
||||
/** Minimal third-party ACP runtime surface admitted by the host boundary. */
|
||||
export type AcpxProviderTurnBinding = {
|
||||
onPermissionRequest: AcpxHostPermissionHandler;
|
||||
onPlanProposal?: (proposal: AcpxPlanProposal) => void;
|
||||
busy(): boolean;
|
||||
};
|
||||
|
||||
export interface AcpxProviderCycleStream {
|
||||
next(): Promise<ClaudeProviderCycleItem | null>;
|
||||
adopt(binding: AcpxProviderTurnBinding): boolean;
|
||||
drop(): void;
|
||||
cancel(): boolean;
|
||||
undecided(): Promise<boolean> | null;
|
||||
decisionFor(toolCallId: unknown): Promise<boolean> | null;
|
||||
}
|
||||
|
||||
export interface AcpxRuntimePort {
|
||||
identity(): Promise<AcpxRuntimePortIdentity>;
|
||||
getStatus(): Promise<AcpxModelStatus>;
|
||||
@@ -168,6 +184,8 @@ export interface AcpxRuntimePort {
|
||||
goalCapability?(): AcpxRuntimeGoalCapability | null;
|
||||
goalSnapshot?(): AcpxRuntimeGoalSnapshot | null;
|
||||
backgroundTaskState?(): ClaudeBackgroundTaskState | null;
|
||||
providerCycles?(): AcpxProviderCycleStream | null;
|
||||
providerTurnsAvailable?(): boolean;
|
||||
controlGoal?(
|
||||
action: "set" | "pause" | "resume" | "clear",
|
||||
objective?: string,
|
||||
@@ -897,6 +915,14 @@ export class AcpxRuntimeHost {
|
||||
return this.#runtime.backgroundTaskState?.() ?? null;
|
||||
}
|
||||
|
||||
providerCycles(): AcpxProviderCycleStream | null {
|
||||
return this.#runtime.providerCycles?.() ?? null;
|
||||
}
|
||||
|
||||
providerTurnsAvailable(): boolean {
|
||||
return this.#runtime.providerTurnsAvailable?.() ?? false;
|
||||
}
|
||||
|
||||
async controlGoal(
|
||||
action: "set" | "pause" | "resume" | "clear",
|
||||
objective?: string,
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
[{"direction":"outbound","message":{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{"_meta":{"jetbrains":{"air":{"version":1,"capabilities":["sessionFailure","asyncTasks"]}}},"fs":{"readTextFile":true,"writeTextFile":true},"terminal":true,"elicitation":{"form":{}}},"clientInfo":{"name":"acpx","version":"0.22.0"}}}},{"direction":"inbound","message":{"jsonrpc":"2.0","id":0,"result":{"protocolVersion":1,"agentCapabilities":{"_meta":{"claudeCode":{"promptQueueing":true}},"promptCapabilities":{"image":true,"embeddedContext":true},"mcpCapabilities":{"http":true,"sse":true},"auth":{"logout":{}},"providers":{},"loadSession":true,"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"resume":{},"subagents":{}}},"agentInfo":{"name":"@agentclientprotocol/claude-agent-acp","title":"Claude Agent","version":"0.73.0"},"authMethods":[],"_meta":{"jetbrains":{"air":{"version":1,"capabilities":["sessionFailure","agentFileChangeReport","nativeSubagentSessions","asyncTasks"]}},"steering":{"supported":true},"goal":{"version":1,"controlMethod":"_session/goal","actions":["set","clear"]}}}}},{"direction":"outbound","message":{"jsonrpc":"2.0","id":1,"method":"session/new","params":{"cwd":"/workspace","mcpServers":[]}}},{"direction":"inbound","message":{"jsonrpc":"2.0","id":1,"result":{"sessionId":"c2125061-7336-450e-ae9b-b77f4ff58928","modes":{"currentModeId":"default","availableModes":[{"id":"default","name":"Manual","description":"Always ask before making changes","_meta":{"kind":"standard"}},{"id":"acceptEdits","name":"Accept edits","description":"Automatically accept all file edits","_meta":{"kind":"standard"}},{"id":"plan","name":"Plan","description":"Create a plan before making changes","_meta":{"kind":"plan"}},{"id":"auto","name":"Auto","description":"Claude handles permission decisions","_meta":{"kind":"auto_review"}},{"id":"bypassPermissions","name":"Bypass permissions","description":"Accepts all permissions","_meta":{"kind":"full_access"}}]},"configOptions":[]}}},{"direction":"inbound","message":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"c2125061-7336-450e-ae9b-b77f4ff58928","update":{"sessionUpdate":"available_commands_update","availableCommands":[]}}}},{"direction":"outbound","message":{"jsonrpc":"2.0","id":2,"method":"session/set_config_option","params":{"sessionId":"c2125061-7336-450e-ae9b-b77f4ff58928","configId":"model","value":"claude-sonnet-5"}}},{"direction":"inbound","message":{"jsonrpc":"2.0","id":2,"result":{"configOptions":[]}}},{"direction":"outbound","message":{"jsonrpc":"2.0","id":3,"method":"session/prompt","params":{"sessionId":"c2125061-7336-450e-ae9b-b77f4ff58928","prompt":[{"type":"text","text":"BACKGROUND-TURN"}]}}},{"direction":"inbound","message":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"c2125061-7336-450e-ae9b-b77f4ff58928","update":{"sessionUpdate":"available_commands_update","availableCommands":[]}}}},{"direction":"inbound","message":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"c2125061-7336-450e-ae9b-b77f4ff58928","update":{"sessionUpdate":"usage_update","used":3,"size":200000}}}},{"direction":"inbound","message":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"c2125061-7336-450e-ae9b-b77f4ff58928","update":{"_meta":{"claudeCode":{"toolName":"Bash"}},"toolCallId":"toolu_01Bg1x0","sessionUpdate":"tool_call","rawInput":{},"status":"pending","title":"Terminal","kind":"execute","content":[]}}}},{"direction":"inbound","message":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"c2125061-7336-450e-ae9b-b77f4ff58928","update":{"_meta":{"claudeCode":{"toolName":"Bash","title":"task 0"}},"toolCallId":"toolu_01Bg1x0","sessionUpdate":"tool_call_update","rawInput":{"command":"sleep 2; echo t0","description":"task 0","run_in_background":true},"title":"sleep 2; echo t0","kind":"execute","content":[{"type":"content","content":{"type":"text","text":"task 0"}}]}}}},{"direction":"inbound","message":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"c2125061-7336-450e-ae9b-b77f4ff58928","update":{"_meta":{"claudeCode":{"toolName":"Bash"}},"toolCallId":"toolu_01Bg1x1","sessionUpdate":"tool_call","rawInput":{},"status":"pending","title":"Terminal","kind":"execute","content":[]}}}},{"direction":"inbound","message":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"c2125061-7336-450e-ae9b-b77f4ff58928","update":{"_meta":{"claudeCode":{"toolName":"Bash","title":"task 1"}},"toolCallId":"toolu_01Bg1x1","sessionUpdate":"tool_call_update","rawInput":{"command":"sleep 3; echo t1","description":"task 1","run_in_background":true},"title":"sleep 3; echo t1","kind":"execute","content":[{"type":"content","content":{"type":"text","text":"task 1"}}]}}}},{"direction":"inbound","message":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"c2125061-7336-450e-ae9b-b77f4ff58928","update":{"_meta":{"claudeCoLine truncated
|
||||
Reference in new issue
Block a user