Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

Add four SDK backends across driver, daemon and bot setup (#1164)

Gustavo Yed900db85e7ae
diff --git a/src/daemon/agent-driver/README.md b/src/daemon/agent-driver/README.md
index f407b7fa9..f67db42ef 100644
--- a/src/daemon/agent-driver/README.md
+++ b/src/daemon/agent-driver/README.md
@@ -1,7 +1,8 @@
# @alook/agent-driver
Repository-private logical-session drivers for Claude, Codex, Cursor, Grok,
-OpenCode, Pi, Antigravity ACP, and Antigravity CLI (`agy`).
+OpenCode, Pi, Antigravity ACP, Antigravity CLI (`agy`), Qoder, Copilot,
+Cursor SDK, and Pi Durable.
The package's exported contract owns backend lifecycle, message admission,
buffering, queueing, interrupts, stop deadlines, and normalized events. The
@@ -105,20 +106,89 @@ There is no per-turn built-in fallback.
| Backend | Physical lifetime | Transport | Busy delivery | Terminal owner |
|---|---|---|---|---|
-| Claude | session | `stdio_stream` / `claude.stream-json.v1` | `safe_boundary_queue` | `vendor_message` |
-| Codex | session | `stdio_rpc` / `codex.app-server.v1` | `safe_boundary_queue` | `transport_request` |
+| Claude | session | `stdio_stream` / `claude.stream-json.v1` | `steer` | `vendor_message` |
+| Codex | session | `stdio_rpc` / `codex.app-server.v1` | `steer` | `transport_request` |
| Cursor | session | `stdio_rpc` / `cursor.acp.v1` | `steer` | `transport_request` |
| OpenCode | session | `http_sse` / `opencode.v2.service` | `steer` | `transport_request` |
| Pi | session | `in_process_sdk` / `pi_sdk` | `steer` | `prompt_invocation` |
| Antigravity CLI (`agy`) | session | `stdio_stream` / `agy.stream-json.v1` | `next_turn_queue` | `vendor_message` |
+| Qoder | session | owned SDK worker / `qoder.sdk-worker.v1` | `steer` | `prompt_invocation` |
+| Copilot | session | owned SDK worker / `copilot.sdk-worker.v1` | `steer` | `prompt_invocation` |
+| Cursor SDK | session | owned SDK worker / `cursor-sdk.sdk-worker.v1` | `steer` | `prompt_invocation` |
+| Pi Durable | session | owned SDK worker / `pi-durable.sdk-worker.v1` | `steer` | `prompt_invocation` |
+
+## Optional native SDK entries
+
+Install the SDK for the entry being used. A project-local installation or an npm
+global installation is supported; explicit `npm_config_prefix`/`NPM_CONFIG_PREFIX`
+is also honored. Resolution prefers the package/project installation, then the
+running Node/npm installation and configured prefix. Missing SDKs make only
+their corresponding entries unavailable.
+
+| Backend ID | Optional npm package | Native state and authentication |
+|---|---|---|
+| `qoder` | `@qoder-ai/qoder-agent-sdk` | Native Qoder session; SDK CLI login, personal access token, or service account |
+| `copilot` | `@github/copilot-sdk` | Native Copilot session and its normal SDK/CLI authentication |
+| `cursor-sdk` | `@cursor/sdk` | Local SDK agent with a JSONL store under `.alook/cursor-sdk`; SDK credentials |
+| `pi-durable` | `@earendil-works/pi-durable` | Native Harness/SQLite under `.alook/pi-durable`; selected provider key or ambient provider authentication |
+
+For example, `npm install -g @cursor/sdk` enables SDK discovery without replacing
+the existing `cursor` ACP entry. `pi` remains the Pi coding-agent entry. Pi
+Durable does not import the coding-agent's private credential files.
+
+The tested SDK versions are Qoder 1.0.58, Copilot 1.0.28, Cursor 1.2.0, and Pi
+Durable 1.5.0. These are evidence versions, not accepted-version gates. Their
+runtime API and required native capabilities are checked. Current Cursor SDK
+requires Node >=22.13; Pi Durable requires Node >=22.19; Copilot SDK requires
+Node ^20.19 or >=22.12. Other backends retain the package's existing Node floor.
+
+Cursor SDK requires an explicit model for a fresh local agent. Pi Durable
+requires an explicit `provider/model` selection for a fresh conversation; its
+native catalog supplies these IDs. Both can restore a saved model on resume.
+Reasoning effort is supplied at launch/resume; these entries do not claim a
+live settings update. Missing history is rejected using the existing admission
+contract, without creating a substitute context.
+
+Each SDK runs in one persistent managed Node child. It retains native session
+state across turns; tool and CLI descendants remain under the existing process
+authority. Stop captures the owned tree before TERM invokes native shutdown.
+Pi Durable shutdown closes the Harness; interrupt explicitly aborts its work.
+Its SQLite ownership lock prevents concurrent drivers of the same store.
+
+The public API and adapter-author version remain unchanged. Runtime-specific
+native completion and input acknowledgement are mapped onto existing receipts
+and events. A receipt is not proof of model consumption.
+
+### Codex App executable discovery
+
+On macOS, Codex uses an explicit command first, then PATH, then executable
+`Contents/Resources/codex` files in system/user Codex.app and ChatGPT.app.
+Probe, model discovery and launch use the same selection. This starts a separate
+owned stdio app-server; it does not attach to an active desktop conversation.
+
+### SDK validation
+
+Source tests include real process cleanup, UTF-8 framing and SDK write callback
+regressions. Optional native tests use installed official SDKs with local
+protocol servers or Pi's scripted provider, without paid inference:
-For Claude and Codex, `safe_boundary_queue` waits for at most the next valid
-tool-output event. A tool start closes the boundary for messages that arrive
-after it; the next matching tool output reopens the boundary and flushes queued
-messages even if other concurrent tools remain active. A later tool start
-closes the boundary again. Compaction and review remain closed until their
-matching finished events. Cursor, OpenCode, and Pi steer immediately and do not
-participate in this boundary latch.
+```sh
+ALOOK_NATIVE_SDK_ROOT=/absolute/path/to/isolated/npm-prefix pnpm test
+```
+
+The prefix must contain the four optional packages. The same environment
+variable enables all four SDK worker and daemon-manager journeys in the
+daemon's installed-package test. Cursor's execution fixture verifies its SDK
+mapping and packaged worker; real Cursor account inference and Windows runtime
+verification remain separate checks. Native SDK fixtures do not establish
+external service behavior or account entitlement.
+
+Claude and Codex submit busy inputs immediately through their native persistent
+protocols. Submission is not proof that the model has read the input: Claude may
+echo it after an active tool returns; Codex reports the correlated `turn/steer`
+RPC result. Grok retains `safe_boundary_queue`: a valid tool result opens its
+boundary, while tool starts, compaction and review can close it. A native busy
+refusal retains input responsibility in the existing next-turn queue.
OpenCode selects a private compatibility lane from the actual CLI version.
CLI v1 retains its `--pure` launch and durable event admission frontier; CLI v2
@@ -128,20 +198,19 @@ public contract. Recent-project discovery stays global: v1 uses session list,
while v2 queries its native session API without a project filter. Unknown CLI
majors and missing required capabilities fail explicitly.
-Pi's runtime behavior did not change in this migration. It already kept one
-SDK session and used prompt/steer/abort/dispose on that session; contract v1
-formalizes that existing persistent behavior as an `in_process_sdk`
-`RuntimeLane`.
+Pi retains one `in_process_sdk` session and uses its native
+prompt/steer/abort/dispose methods. Missing saved history now fails with
+`reset_required`; it cannot create an empty context with the requested ID.
-## Repository adapter contract v1 migration
+## Repository adapter contract v2 migration
Repository adapters must import `ADAPTER_AUTHOR_CONTRACT_VERSION` from
`@alook/agent-driver/adapter-author` and set every
`AgentBackendRegistration.contractVersion` to that value (currently the numeric
-literal `1`). Missing, older, and unknown newer versions fail closed before host
+literal `2`). Missing, older, and unknown newer versions fail closed before host
preparation or adapter open.
-For contract v1:
+For contract v2:
- declare `BackendAdapter.execution` with `lifetime`, an opaque
`transport.kind`/`transport.protocol`, `wakeStart`, and `terminalOwnership`;
@@ -159,7 +228,50 @@ For contract v1:
- optionally implement `discoverRecentContext()` for bounded, global,
read-only history discovery. All built-in adapters implement it; extension
adapters that omit it receive `recent_context_discovery_unsupported` from the
- SDK without changing adapter-author contract version 1.
+ SDK. This method remains optional.
+
+- pass every merged `{ commandId, attemptId }` member into the lane; correlate
+ native responses by native IDs, never text or timing;
+- preserve `success | failed | interrupted | unknown` terminal outcomes. An
+ absent outcome becomes `unknown`, and a tool result never inherits root success.
+ ACP normal completion, refusal, execution limits and cancellation remain distinct;
+ `AgentTurnResult.stopReason` preserves their native cause;
+- separate input/control errors from root failures and preserve off-root
+ attribution. Child/unknown events become public `activity` and cannot mutate
+ root text, tools, recovery or terminal ownership;
+- report acquisition using native API/protocol guarantees. A matching session ID
+ alone is `unverified`; missing history requires explicit reset;
+- return `acknowledged` for a settings ACK without value evidence. `applied`
+ requires `observed`; initial configuration without readback is `unverified`.
+
+### Input responsibility and evidence
+
+`AgentMessage.id` remains the logical identity; optional `attemptId` defaults to
+that ID. Repeating the same pair reuses its admission receipt. Only an input whose
+responsibility was returned can use a fresh attempt, with unchanged original
+text, kind and sequence. Optional `delivery: "next_turn"` uses the existing queue.
+
+A `queued` receipt retains provisional responsibility. `command_accepted` means
+the driver owns delivery, not that the native runtime or model consumed it.
+`input_observed` records a correlated native ACK, user echo or conversation fact;
+it does not establish Alook's separate model-seen watermark.
+
+`command_returned` includes the original input, attempt, ordinal, evidence and
+retry eligibility. Daemon retries only proven unsent/rejected eligible inputs,
+with the same command ID and a fresh attempt, ahead of still-unsent work. Already
+admitted later inputs cannot be reordered. Unknown delivery and permanent refusal
+are audited without blind replay; durable unread coverage remains wake-owned.
+Immediate input refusal cannot stop an existing healthy root.
+
+`session_acquired` and `configuration_observed` retain their latest evidence in
+the snapshot. Configuration ACKs settle the daemon's existing revision without
+restarting or repeating it; requested values do not become observed values.
+
+Native correlation is currently available for Claude UUID echoes, Codex RPC IDs,
+Qoder input lifecycle IDs and Copilot message IDs. Other lanes retain exact host
+input references but do not invent native observations. Protocols that expose no
+separate child stream cannot supply child details. Native tool output/outcomes
+are retained when supplied; absent tool outcome is explicitly `unknown`.
Package semver and the numeric adapter-author contract version are independent.
Only an incompatible `/adapter-author` change increments the latter.
diff --git a/src/daemon/agent-driver/RELEASE_NOTES.md b/src/daemon/agent-driver/RELEASE_NOTES.md
index d7205de47..c0a01a268 100644
--- a/src/daemon/agent-driver/RELEASE_NOTES.md
+++ b/src/daemon/agent-driver/RELEASE_NOTES.md
@@ -1,5 +1,40 @@
# Release notes
+## Shared input and execution evidence (adapter-author v2)
+
+- Preserve logical command IDs and per-attempt identity through merged input,
+ native observations and returned responsibility. Reuse daemon queues/revisions;
+ retry only proven-unsent eligible inputs, without failing a healthy root.
+- Publish root/child/unknown attribution, native tool results, explicit execution
+ outcomes, session acquisition and configuration evidence. No result defaults to
+ success; a matching restored ID or an empty settings ACK is not verification.
+- Refuse missing Codex/Pi history without creating a replacement context.
+- Submit Claude/Codex busy input through native steering immediately. Preserve
+ root/attempt fences for late, duplicate, refused and off-root events.
+- Migrate all twelve backend registrations and both OpenCode protocol lanes.
+ Adapter registrations now require numeric contract version 2; settings `applied`
+ requires observed values. Native ACK-only setters return `acknowledged`.
+- Preserve persistent sessions, package boundaries and existing process authority.
+ No new runtime dependencies or additional agent transports.
+
+## Additional native agent entries
+
+- Add persistent Qoder, Copilot, Cursor SDK and Pi Durable entries using optional
+ native SDK installations. Retain existing Cursor ACP and Pi coding-agent
+ entries and adapter-author contract version 1.
+- Reuse the existing process authority through persistent managed SDK workers.
+ Native immediate input, root completion, interruption and resume remain
+ adapter-owned; daemon notification batching remains daemon-owned.
+- Preserve UTF-8 across protocol chunks and all native stdout write overloads
+ when redirecting SDK logs. Bound protocol frames and cleanup the captured
+ process tree before releasing worker resources.
+- Discover the Codex executable inside macOS Codex/ChatGPT applications when
+ no explicit command or PATH installation is selected. Use the same executable
+ for installation probe, native model catalog and launch.
+- Cover native SDK/local runtime journeys and all four workers after the actual
+ daemon Bun build and npm installation, including daemon wake during work.
+ These tests do not claim real-account inference or Windows verification.
+
## OpenCode CLI major compatibility
- Select CLI v1 or v2 within the existing OpenCode harness using the actual
diff --git a/src/daemon/agent-driver/knip.json b/src/daemon/agent-driver/knip.json
index 0dc7a3777..2f0ff85cc 100644
--- a/src/daemon/agent-driver/knip.json
+++ b/src/daemon/agent-driver/knip.json
@@ -2,5 +2,10 @@
"$schema": "https://unpkg.com/knip@5/schema.json",
"entry": ["src/index.ts", "src/host.ts", "src/adapter-author.ts", "src/testing/index.ts", "src/**/*.test.ts"],
"project": ["src/**/*.ts"],
- "ignoreDependencies": ["typescript-eslint"]
+ "ignoreDependencies": [
+ "@cursor/sdk",
+ "@earendil-works/pi-durable",
+ "@earendil-works/pi-ai",
+ "typescript-eslint"
+ ]
}
diff --git a/src/daemon/agent-driver/scripts/test-bundled-sdk-workers.mjs b/src/daemon/agent-driver/scripts/test-bundled-sdk-workers.mjs
new file mode 100644
index 000000000..e88e9e8f2
--- /dev/null
+++ b/src/daemon/agent-driver/scripts/test-bundled-sdk-workers.mjs
@@ -0,0 +1,129 @@
+import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, symlinkSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve, dirname } from 'node:path';
+import { pathToFileURL, fileURLToPath } from 'node:url';
+const entry = process.argv[2];
+if (!entry || !process.argv[3])
+ throw new Error('Usage: test-bundled-sdk-workers.mjs <daemon-entry-url> <isolated-sdk-prefix>');
+const daemon = await import(entry);
+const repository = resolve('.');
+const native = resolve(process.argv[3], 'node_modules');
+const fixtures = resolve(dirname(fileURLToPath(import.meta.url)), '../src/testing/fixtures/sdk');
+const prefix = mkdtempSync(join(tmpdir(), 'alook-bun-sdk-'));
+const scoped = (name) => join(prefix, 'node_modules', ...name.split('/'));
+const link = (name) => { const target = scoped(name); mkdirSync(dirname(target), { recursive: true }); symlinkSync(join(native, ...name.split('/')), target, 'dir'); };
+for (const name of ['@github/copilot-sdk', '@qoder-ai/qoder-agent-sdk', '@earendil-works/pi-ai', '@earendil-works/chord', '@earendil-works/pi-schema', '@earendil-works/pi-telemetry'])
+ link(name);
+const cursor = scoped('@cursor/sdk');
+mkdirSync(cursor, { recursive: true });
+writeFileSync(join(cursor, 'package.json'), JSON.stringify({ name: '@cursor/sdk', version: 'fixture', type: 'module', exports: './index.mjs' }));
+writeFileSync(join(cursor, 'index.mjs'), readFileSync(join(fixtures, 'cursor-sdk.mjs')));
+const durable = scoped('@earendil-works/pi-durable');
+mkdirSync(durable, { recursive: true });
+const pkg = JSON.parse(readFileSync(join(native, '@earendil-works/pi-durable/package.json'), 'utf8'));
+pkg.exports['.'] = './fixture.mjs';
+writeFileSync(join(durable, 'package.json'), JSON.stringify(pkg));
+symlinkSync(join(native, '@earendil-works/pi-durable/dist'), join(durable, 'dist'), 'dir');
+const nativePi = pathToFileURL(join(native, '@earendil-works/pi-durable/dist/index.js')).href;
+writeFileSync(join(durable, 'fixture.mjs'), readFileSync(join(fixtures, 'pi-harness.mjs'), 'utf8').replaceAll("'@earendil-works/pi-durable'", JSON.stringify(nativePi)));
+process.env.QODER_PERSONAL_ACCESS_TOKEN = 'fixture-local-token';
+process.chdir(prefix);
+const wait = async (test, label) => { for (let i = 0; i < 1000; i++) {
+ if (test())
+ return;
+ await new Promise(r => setTimeout(r, 10));
+} throw new Error('Timed out:' + label); };
+try {
+ for (const [id, model, cli] of [['cursor-sdk', 'fixture-model'], ['qoder', 'native-fixture', 'qoder-cli.mjs'], ['copilot', 'native-fixture', 'copilot-cli.mjs'], ['pi-durable', 'faux/faux-1']]) {
+ const root = join(prefix, 'workspace-' + id);
+ mkdirSync(root, { recursive: true });
+ let command;
+ if (cli) {
+ command = join(prefix, id + '-cli.mjs');
+ writeFileSync(command, readFileSync(join(fixtures, cli), 'utf8').replace('#!/usr/bin/env node', '#!' + process.execPath), { mode: 0o700 });
+ }
+ const sdk = daemon.createAgentDriverSdk();
+ const probe = await sdk.probe({ backend: id, command, includeModels: true });
+ if (probe.status !== 'healthy')
+ throw new Error('Probe failed ' + id + ':' + JSON.stringify(probe));
+ const opened = await sdk.open({ backend: id, config: { model: { kind: 'named', name: model }, provider: { kind: 'default' }, command }, launch: { workingDirectory: root, instructions: { format: 'markdown', content: 'Bun fixture' }, launchId: 'bun-' + id } });
+ if (!opened.ok)
+ throw new Error(JSON.stringify(opened));
+ const session = opened.session;
+ const events = [];
+ void (async () => { for await (const e of session.events)
+ events.push(e); })();
+ try {
+ const first = await session.start({ id: 'first', kind: 'user', text: 'hold first' });
+ if (first.status !== 'accepted')
+ throw new Error(id + ':' + JSON.stringify(first));
+ const busy = await session.send({ id: 'second', kind: 'user', text: 'second' });
+ if (busy.status !== 'accepted')
+ throw new Error(id + ':' + JSON.stringify(busy));
+ writeFileSync(join(root, 'release'), 'go');
+ await wait(() => session.snapshot().state === 'idle', id + ' first idle');
+ rmSync(join(root, 'release'));
+ const next = await session.send({ id: 'next', kind: 'user', text: 'hold interrupt' });
+ if (next.status !== 'accepted')
+ throw new Error(id + ':' + JSON.stringify(next));
+ const interrupted = await session.interrupt({ requestId: 'interrupt', reason: 'test' });
+ if (interrupted.status !== 'accepted')
+ throw new Error(id + ':' + JSON.stringify(interrupted));
+ await wait(() => session.snapshot().state === 'idle', id + ' interrupt idle');
+ const results = events.filter(e => e.type === 'turn_completed').map(e => e.result.outcome);
+ if (JSON.stringify(results) !== JSON.stringify(['success', 'interrupted']))
+ throw new Error(id + ':' + JSON.stringify(results));
+ await session.stop({ reason: 'shutdown', forceAfterMs: 300 });
+ console.log(JSON.stringify({ id, probe: probe.status, catalog: probe.reasoning.models.length, first: first.status, busy: busy.delivery, results, closed: (await session.closed).outcome }));
+ const managerRoot = join(prefix, 'manager-' + id);
+ mkdirSync(managerRoot, { recursive: true });
+ let managed;
+ const nativeFactory = daemon.createBuiltinDaemonSessionFactory();
+ const broker = { revokeAgent() { }, revoke() { }, mint() { return { voucher: "fixture", voucherFile: join(prefix, "voucher") }; } };
+ writeFileSync(join(prefix, "voucher"), "fixture");
+ const agentCliPath = join(dirname(fileURLToPath(entry)), "cli", "index.js");
+ let opens = 0;
+ let handler;
+ const acknowledgements = [];
+ const logger = { debug() { }, info() { }, warn() { }, error() { }, child() { return this; } };
+ const manager = new daemon.AgentProcessManager({
+ logger,
+ driverFor: () => ({ id }),
+ baseContextFor: agentId => ({ agentId, workingDirectory: managerRoot, standingPrompt: 'Managed fixture', agentCliPath, credentialProxy: { broker, proxyUrl: 'http://127.0.0.1:9', runnerKey: 'fixture', capabilities: [] } }),
+ sessionFactory: async (input) => {
+ managed = await nativeFactory(input);
+ opens++;
+ return managed;
+ },
+ wakePromptFooter: 'Use alook inbox pull.',
+ });
+ const channel = { onCommand: fn => { handler = fn; }, reportReady: async () => { }, reportAgentSession: async () => { }, reportWakeAck: async (ack) => acknowledgements.push(ack), reportSessionError: async (error) => { throw new Error(JSON.stringify(error)); }, reportAgentTyping() { }, onResync() { } };
+ const router = new daemon.AgentRouter({ manager, channel, logger, runtimeReport: [{ id, status: 'healthy' }], formatUnreadNoticeText: notice => 'hold WAKE ' + notice.latestSeq });
+ try {
+ await router.start();
+ const wake = latestSeq => ({ type: 'agent:wake', agentId: 'fixture-agent', launchId: 'wake-' + latestSeq, config: { version: 1, runtime: id, model: { kind: 'named', name: model }, provider: { kind: 'default' }, mode: { kind: 'default' }, command }, unreadNotice: { kind: 'unread_notice', channel: '/fixture#1234/general', latestSeq } });
+ await handler(wake(1));
+ await wait(() => manager.snapshot().agents['fixture-agent']?.status === 'running', id + ' manager running');
+ await handler(wake(2));
+ await wait(() => managed.snapshot().activeTurn?.commandIds.length === 2, id + ' manager busy admission');
+ if (acknowledgements.length !== 2 || acknowledgements.some(ack => ack.status !== 'ok'))
+ throw new Error(id + ' manager wake ack failed');
+ writeFileSync(join(managerRoot, 'release'), 'go');
+ await wait(() => managed.snapshot().state === 'idle' && !manager.snapshot().agents['fixture-agent']?.turnActive, id + ' manager idle');
+ if (opens !== 1 || managed.snapshot().diagnostics.metrics.physicalOpenCount !== 1)
+ throw new Error(id + ' lost persistent manager lane');
+ console.log(JSON.stringify({ id, manager: 'wake-during-work', acks: acknowledgements.length, opens, turnActive: manager.snapshot().agents['fixture-agent'].turnActive, sessionState: managed.snapshot().state }));
+ }
+ finally {
+ await manager.stopAll();
+ }
+ }
+ finally {
+ await session.stop({ reason: 'shutdown', forceAfterMs: 300 });
+ }
+ }
+}
+finally {
+ process.chdir(repository);
+ rmSync(prefix, { recursive: true, force: true });
+}
diff --git a/src/daemon/agent-driver/src/adapter-author.ts b/src/daemon/agent-driver/src/adapter-author.ts
index 2b5f29452..5d96aba20 100644
--- a/src/daemon/agent-driver/src/adapter-author.ts
+++ b/src/daemon/agent-driver/src/adapter-author.ts
@@ -1,5 +1,5 @@
/** Explicit extension boundary for adapter authors; not part of the consumer root API. */
-export const ADAPTER_AUTHOR_CONTRACT_VERSION = 1 as const;
+export const ADAPTER_AUTHOR_CONTRACT_VERSION = 2 as const;
export type * from "./public-contract.js";
export {
diff --git a/src/daemon/agent-driver/src/adapters/agy/index.test.ts b/src/daemon/agent-driver/src/adapters/agy/index.test.ts
index a6b281170..eed45e8fb 100644
--- a/src/daemon/agent-driver/src/adapters/agy/index.test.ts
+++ b/src/daemon/agent-driver/src/adapters/agy/index.test.ts
@@ -27,7 +27,7 @@ describe("agy native stream ownership", () => {
it("uses native input identity, ignores other sessions and stale/duplicate terminals", () => {
const driver = new AgyDriver();
driver.encodeMessage("first");
- expect(driver.normalizeLine(line({ event: "init", conversation_id: "native" }))).toEqual([{ kind: "session_init", sessionId: "native" }]);
+ expect(driver.normalizeLine(line({ event: "init", conversation_id: "native" }))).toEqual([{ kind: "session_init", sessionId: "native", acquisition: { status: "created", evidence: "native_protocol" } }]);
expect(driver.normalizeLine(step(0, { step_type: "user_input" }))).toMatchObject([{ kind: "turn_owner", receipt: "agy:native:0" }]);
expect(driver.normalizeLine(result(1, {}, "child"))).toEqual([]);
expect(driver.normalizeLine(result(1))).toMatchObject([{ kind: "assistant_message_completed" }, { kind: "turn_end" }]);
@@ -74,7 +74,7 @@ describe("agy native stream ownership", () => {
begin(driver);
driver.normalizeLine(step(1, { text_delta: "partial" }));
expect(driver.normalizeLine(result(1, { status, error }))).toEqual([
- { kind: "error", message: error }, { kind: "turn_end", sessionId: "native", pendingContent: "discard" },
+ { kind: "error", message: error }, { kind: "turn_end", sessionId: "native", pendingContent: "discard" , outcome: "failed" },
]);
});
it.each([{ status: "CANCELLED" }, { status: "ERROR", error: "interrupted" }])("keeps native $status cancellation distinct from failure and discards unfinished content", (terminal) => {
diff --git a/src/daemon/agent-driver/src/adapters/agy/index.ts b/src/daemon/agent-driver/src/adapters/agy/index.ts
index 0cfacd3c0..858e481b1 100644
--- a/src/daemon/agent-driver/src/adapters/agy/index.ts
+++ b/src/daemon/agent-driver/src/adapters/agy/index.ts
@@ -94,7 +94,7 @@ export class AgyDriver implements BackendAdapter<"agy"> {
this.initialInput = undefined;
try { if (initial) this.process?.stdin?.write(initial + "\n"); }
catch { return this.fail("Antigravity CLI input is unavailable"); }
- return [{ kind: "session_init", sessionId: this.currentSessionId! }];
+ return [{ kind: "session_init", sessionId: this.currentSessionId!, acquisition: { status: this.requestedId ? "resumed" : "created", evidence: "native_protocol" } }];
}
if (event?.event === "step_update") {
const step = asRecord(event.step_update);
@@ -154,7 +154,7 @@ export class AgyDriver implements BackendAdapter<"agy"> {
} else if (!interrupted) events.push({ kind: "error", message: typeof result.error === "string" ? result.error : `Antigravity CLI status: ${String(result.status)}` });
events.push({ kind: "turn_end", sessionId: this.currentSessionId!,
...(result.status !== "SUCCESS" ? { pendingContent: "discard" as const } : {}),
- ...(interrupted ? { outcome: "interrupted" as const } : {}),
+ outcome: interrupted ? "interrupted" : result.status === "SUCCESS" ? "success" : "failed",
});
return events;
}
diff --git a/src/daemon/agent-driver/src/adapters/antigravity/acp-lane.ts b/src/daemon/agent-driver/src/adapters/antigravity/acp-lane.ts
index 23ed064b9..b19d9886a 100644
--- a/src/daemon/agent-driver/src/adapters/antigravity/acp-lane.ts
+++ b/src/daemon/agent-driver/src/adapters/antigravity/acp-lane.ts
@@ -188,7 +188,7 @@ export class AntigravityAcpLane implements RuntimeLane {
this.usageReader = this.options.usageReader ?? (this.usageHome ? new NativeUsageReader(this.usageHome, sessionId) : undefined);
this.processActivated = true;
this.ready = true;
- this.events.emit("runtime_event", { kind: "session_init", sessionId } satisfies AdapterEvent);
+ this.events.emit("runtime_event", { kind: "session_init", sessionId, acquisition: { status: input.sessionId ? "resumed" : "created", evidence: "native_api" } } satisfies AdapterEvent);
return this.admitPrompt([this.ctx.standingPrompt, input.text].filter(Boolean).join("\n\n"));
} catch (error) {
this.suppressExit = true;
@@ -329,8 +329,10 @@ export class AntigravityAcpLane implements RuntimeLane {
const catalog = parseAntigravityCatalog(response);
if (!catalog || catalog.currentModelId !== modelId) throw new Error("Antigravity did not confirm the selected model");
this.catalog = catalog;
+ this.events.emit("runtime_event", { kind: "configuration_observed", observation: { evidence: "observed", effective: "next_turn", model: catalog.currentModelId } } satisfies AdapterEvent);
} else {
await this.call("session/set_model", { sessionId: this.sessionId, modelId });
+ this.events.emit("runtime_event", { kind: "configuration_observed", observation: { evidence: "acknowledged", effective: "next_turn" } } satisfies AdapterEvent);
if (this.catalog) this.catalog = { ...this.catalog, currentModelId: modelId };
}
}
@@ -347,7 +349,7 @@ export class AntigravityAcpLane implements RuntimeLane {
if (!modelId) return failed("unsupported_reasoning_effort", "Antigravity did not offer the requested model/effort variant");
try {
await this.setModel(modelId);
- return { status: "applied" };
+ return { status: "acknowledged", effective: "next_turn" };
} catch {
return failed("settings_update_failed", "Antigravity rejected the settings update", true);
}
@@ -416,6 +418,8 @@ export class AntigravityAcpLane implements RuntimeLane {
kind: "turn_end",
sessionId: this.sessionId ?? undefined,
turnOwner: terminalOwner,
+ outcome: result.stopReason === "cancelled" ? "interrupted" : result.stopReason === "end_turn" ? "success" : "failed",
+ stopReason: result.stopReason,
...(result.stopReason === "cancelled" ? { outcome: "interrupted" as const, pendingContent: "discard" as const } : {}),
} satisfies AdapterEvent);
}
@@ -436,6 +440,7 @@ export class AntigravityAcpLane implements RuntimeLane {
pendingContent: "discard",
sessionId: this.sessionId ?? undefined,
turnOwner: terminalOwner,
+ outcome: "failed",
} satisfies AdapterEvent);
}
@@ -704,7 +709,9 @@ export class AntigravityAcpLane implements RuntimeLane {
}
const configuration = record(payload.update);
if (configuration?.sessionUpdate === "config_option_update") {
- this.catalog = parseAntigravityCatalog(configuration) ?? this.catalog;
+ const observed = parseAntigravityCatalog(configuration);
+ this.catalog = observed ?? this.catalog;
+ if (observed?.currentModelId) this.events.emit("runtime_event", { kind: "configuration_observed", observation: { evidence: "observed", effective: "current", model: observed.currentModelId } } satisfies AdapterEvent);
return;
}
if (!this.ready || this.currentPromptRequestId === null) {
@@ -749,6 +756,7 @@ export class AntigravityAcpLane implements RuntimeLane {
this.openToolCalls.delete(update.toolCallId);
this.events.emit("runtime_event", {
kind: "tool_output", callId: update.toolCallId, name: update.title,
+ outcome: update.status === "failed" ? "failed" : "success", output: update.rawOutput,
} satisfies AdapterEvent);
}
return;
@@ -762,6 +770,7 @@ export class AntigravityAcpLane implements RuntimeLane {
this.events.emit("runtime_event", {
kind: "tool_output",
callId: update.toolCallId,
+ outcome: update.status === "failed" ? "failed" : "success", output: update.rawOutput,
name: typeof update.title === "string" ? update.title : "Antigravity tool",
} satisfies AdapterEvent);
}
diff --git a/src/daemon/agent-driver/src/adapters/antigravity/index.test.ts b/src/daemon/agent-driver/src/adapters/antigravity/index.test.ts
index 87fd41545..92631397b 100644
--- a/src/daemon/agent-driver/src/adapters/antigravity/index.test.ts
+++ b/src/daemon/agent-driver/src/adapters/antigravity/index.test.ts
@@ -286,10 +286,10 @@ describe("Antigravity native ACP", () => {
expect(setters()[0]?.params?.value).toBe("gemini-3.8-flash-low");
expect(await h.lane.updateSettings({ reasoningEffort: "high" })).toMatchObject({ status: "failed" });
h.emit({ id: h.prompts()[0]!.id, result: { stopReason: "end_turn" } });
- expect(await h.lane.updateSettings({ reasoningEffort: "high" })).toEqual({ status: "applied" });
+ expect(await h.lane.updateSettings({ reasoningEffort: "high" })).toEqual({ status: "acknowledged", effective: "next_turn" });
expect(setters().at(-1)?.params?.value).toBe("gemini-3.8-flash-high");
expect(await h.lane.updateSettings({ reasoningEffort: "ultra" })).toMatchObject({ status: "failed" });
- expect(await h.lane.updateSettings({ reasoningEffort: null })).toEqual({ status: "applied" });
+ expect(await h.lane.updateSettings({ reasoningEffort: null })).toEqual({ status: "acknowledged", effective: "next_turn" });
expect(h.spawn).toHaveBeenCalledTimes(1);
expect(h.messages.filter((message) => message.method === "session/new")).toHaveLength(1);
await h.lane.stop();
diff --git a/src/daemon/agent-driver/src/adapters/antigravity/session.test.ts b/src/daemon/agent-driver/src/adapters/antigravity/session.test.ts
index d5ca12008..10afd7b44 100644
--- a/src/daemon/agent-driver/src/adapters/antigravity/session.test.ts
+++ b/src/daemon/agent-driver/src/adapters/antigravity/session.test.ts
@@ -64,13 +64,13 @@ createInterface({ input: process.stdin }).on("line", (line) => {
writeFileSync(release, "go");
}
await vi.waitFor(() => expect(events.filter((event) => event.type === "turn_completed")).toHaveLength(2));
- const successful = ["end_turn", "max_tokens", "refusal", "max_turn_requests"].includes(terminal);
+ const hasCompletedContent = ["end_turn", "max_tokens", "refusal", "max_turn_requests"].includes(terminal);
expect(events.filter((event) => event.type === "assistant_message_completed").map((event) => event.text))
- .toEqual(successful ? ["first message", "next message"] : ["next message"]);
+ .toEqual(hasCompletedContent ? ["first message", "next message"] : ["next message"]);
expect(events.filter((event) => event.type === "assistant_reasoning_completed").map((event) => event.text))
- .toEqual(successful ? ["first reasoning", "next reasoning"] : ["next reasoning"]);
+ .toEqual(hasCompletedContent ? ["first reasoning", "next reasoning"] : ["next reasoning"]);
expect(events.filter((event) => event.type === "turn_completed")).toMatchObject([
- { commandIds: ["first"], result: { outcome: terminal === "interrupt" || terminal === "cancelled" ? "interrupted" : successful ? "success" : "failed" } },
+ { commandIds: ["first"], result: { outcome: terminal === "interrupt" || terminal === "cancelled" ? "interrupted" : terminal === "end_turn" ? "success" : "failed" } },
{ commandIds: ["second"], result: { outcome: "success" } },
]);
expect(events.filter((event) => event.type === "command_accepted").map((event) => event.commandId)).toEqual(["first", "second"]);
diff --git a/src/daemon/agent-driver/src/adapters/claude/index.test.ts b/src/daemon/agent-driver/src/adapters/claude/index.test.ts
index 047a447c5..84544cef8 100644
--- a/src/daemon/agent-driver/src/adapters/claude/index.test.ts
+++ b/src/daemon/agent-driver/src/adapters/claude/index.test.ts
@@ -214,8 +214,7 @@ describe("ClaudeDriver", () => {
}))).toEqual([{
kind: "turn_end",
sessionId: undefined,
- turnOwner: receipt,
- }]);
+ turnOwner: receipt, outcome: "success" }]);
expect(process.kill).not.toHaveBeenCalled();
});
diff --git a/src/daemon/agent-driver/src/adapters/claude/index.ts b/src/daemon/agent-driver/src/adapters/claude/index.ts
index aea7f8a63..e0fcff96d 100644
--- a/src/daemon/agent-driver/src/adapters/claude/index.ts
+++ b/src/daemon/agent-driver/src/adapters/claude/index.ts
@@ -1,12 +1,3 @@
-/**
- * Claude Code driver — persistent stream-json process with gated steering.
- *
- * Claude's stdin protocol accepts a stable UUID on every user frame. Normal
- * terminals report the segment's `user_message_uuid`; native interruption may
- * instead emit an ownerless interrupted segment boundary before queued frames
- * replay. The turn protocol binds either vendor sequence back to the logical
- * root receipt without restarting the persistent process.
- */
import type {
BackendAdapter, EncodeMessageOptions, AdapterLaunchContext, AdapterEvent, LaneInterruptInput, RuntimeLane,
RuntimeLaneOpenOptions, SpawnedProcess, SpawnedProcessHandle, ProbeResult,
@@ -32,6 +23,7 @@ const CLAUDE_MODEL_CATALOG = {
};
export class ClaudeDriver implements BackendAdapter {
+ private requestedSessionId?: string;
readonly id = "claude";
readonly modelCatalogOrigin = "adapter_suggestions" as const;
readonly instructionDelivery = { kind: "workspace_file", canonical: "AGENTS.md", aliases: ["CLAUDE.md"] } as const;
@@ -77,6 +69,7 @@ export class ClaudeDriver implements BackendAdapter {
}
async spawn(ctx: AdapterLaunchContext): Promise<SpawnedProcess> {
+ this.requestedSessionId = ctx.config.sessionId;
// The core materializes AGENTS.md (+ CLAUDE.md symlink) before opening the
// lane; Claude Code auto-reads CLAUDE.md from cwd, so no CLI flag is needed.
const { spawnEnv } = await prepareCliTransport(ctx, buildClaudeProviderIsolationEnv(ctx));
@@ -111,7 +104,7 @@ export class ClaudeDriver implements BackendAdapter {
const stdinMsg = JSON.stringify({
type: "user",
message: { role: "user", content: [{ type: "text", text: ctx.prompt }] },
- uuid: this.turnProtocol.rootInputUuid(),
+ uuid: this.turnProtocol.rootInputUuid(ctx.inputs),
...(ctx.config.sessionId ? { session_id: ctx.config.sessionId } : {}),
});
proc.stdin?.write(stdinMsg + "\n");
@@ -121,6 +114,9 @@ export class ClaudeDriver implements BackendAdapter {
normalizeLine(line: string): AdapterEvent[] {
const events = this.eventNormalizer.normalizeLine(line);
+ for (const event of events) {
+ if (event.kind === "session_init") event.acquisition = { status: this.requestedSessionId ? "resumed" : "created", evidence: "native_protocol" };
+ }
this.flushPendingInterrupt();
return events;
}
@@ -171,8 +167,8 @@ export class ClaudeDriver implements BackendAdapter {
/** Both idle and busy messages use the same stream-json user-message shape. */
encodeMessage(text: string, sessionId: string | null, opts?: EncodeMessageOptions): string {
const uuid = opts?.mode === "idle"
- ? this.turnProtocol.rootInputUuid()
- : this.turnProtocol.steeringInputUuid();
+ ? this.turnProtocol.rootInputUuid(opts?.inputs)
+ : this.turnProtocol.steeringInputUuid(opts?.inputs);
return JSON.stringify({
type: "user",
message: { role: "user", content: [{ type: "text", text }] },
diff --git a/src/daemon/agent-driver/src/adapters/claude/normalizer.test.ts b/src/daemon/agent-driver/src/adapters/claude/normalizer.test.ts
index 56e5c6151..b74169675 100644
--- a/src/daemon/agent-driver/src/adapters/claude/normalizer.test.ts
+++ b/src/daemon/agent-driver/src/adapters/claude/normalizer.test.ts
@@ -47,7 +47,7 @@ describe("ClaudeEventNormalizer.normalizeLine", () => {
const out = new ClaudeEventNormalizer().normalizeLine(
J({ type: "user", message: { content: [{ type: "tool_result", content: "done" }] } }),
);
- expect(out).toEqual([{ kind: "tool_output", name: "" }]);
+ expect(out).toEqual([{ kind: "tool_output", name: "", outcome: "success", output: "done" }]);
});
it("compaction lifecycle", () => {
@@ -67,7 +67,7 @@ describe("ClaudeEventNormalizer.normalizeLine", () => {
const kinds = out.map((e) => e.kind);
expect(kinds).toContain("turn_end");
expect(kinds).toContain("telemetry");
- expect(out).toContainEqual({ kind: "turn_end", sessionId: "s1", turnOwner: "claude:root-1" });
+ expect(out).toContainEqual({ kind: "turn_end", sessionId: "s1", turnOwner: "claude:root-1" , outcome: "success" });
expect(out).toContainEqual({
kind: "telemetry",
name: "token_usage",
@@ -368,7 +368,7 @@ describe("ClaudeEventNormalizer.normalizeLine", () => {
const out = new ClaudeEventNormalizer().normalizeLine(
J({ type: "result", subtype: "success", usage: { input_tokens: 3, output_tokens: 5 } }),
);
- expect(out).toEqual([{ kind: "turn_end", sessionId: undefined }]);
+ expect(out).toEqual([{ kind: "turn_end", sessionId: undefined , outcome: "success" }]);
});
it("uses request_id and the invocation fallback when root request identity is absent", () => {
@@ -454,7 +454,7 @@ describe("ClaudeEventNormalizer.normalizeLine", () => {
const n = new ClaudeEventNormalizer();
const first = J({ type: "result", subtype: "success", session_id: "s1", user_message_uuid: "first" });
const second = J({ type: "result", subtype: "success", session_id: "s1", user_message_uuid: "second" });
- expect(n.normalizeLine(first)).toEqual([{ kind: "turn_end", sessionId: "s1", turnOwner: "claude:first" }]);
- expect(n.normalizeLine(second)).toEqual([{ kind: "turn_end", sessionId: "s1", turnOwner: "claude:second" }]);
+ expect(n.normalizeLine(first)).toEqual([{ kind: "turn_end", sessionId: "s1", turnOwner: "claude:first" , outcome: "success" }]);
+ expect(n.normalizeLine(second)).toEqual([{ kind: "turn_end", sessionId: "s1", turnOwner: "claude:second" , outcome: "success" }]);
});
});
diff --git a/src/daemon/agent-driver/src/adapters/claude/normalizer.ts b/src/daemon/agent-driver/src/adapters/claude/normalizer.ts
index eb7e63cdd..819bdf586 100644
--- a/src/daemon/agent-driver/src/adapters/claude/normalizer.ts
+++ b/src/daemon/agent-driver/src/adapters/claude/normalizer.ts
@@ -86,6 +86,18 @@ export class ClaudeEventNormalizer {
normalizeLine(line: string): AdapterEvent[] {
const event = tryParseJsonLine(line) as any;
if (!event) return [];
+ if (typeof event.parent_tool_use_id === "string" && event.parent_tool_use_id) {
+ const attribution = { scope: "child", parentCallId: event.parent_tool_use_id } as const;
+ const activity: AdapterEvent[] = [];
+ for (const block of event.message?.content ?? []) {
+ if (block.type === "text") activity.push({ kind: "assistant_message_completed", text: block.text, attribution });
+ else if (block.type === "thinking") activity.push({ kind: "assistant_reasoning_completed", text: block.thinking, attribution });
+ else if (block.type === "tool_use") activity.push({ kind: "tool_call", callId: block.id, name: block.name, input: block.input, attribution });
+ else if (block.type === "tool_result") activity.push({ kind: "tool_output", callId: block.tool_use_id, name: "", outcome: block.is_error ? "failed" : "success", output: block.content, attribution });
+ }
+ if (event.type === "result") activity.push({ kind: "turn_end", outcome: event.is_error ? "failed" : "success", attribution });
+ return activity;
+ }
if (event?.session_id) this.currentSession = event.session_id;
const out: AdapterEvent[] = [];
@@ -108,6 +120,7 @@ export class ClaudeEventNormalizer {
private handleSystem(event: any, out: AdapterEvent[]): void {
if (event.subtype === "init") {
+ if (typeof event.model === "string") out.push({ kind: "configuration_observed", observation: { evidence: "observed", effective: "current", model: event.model } });
out.push({ kind: "session_init", sessionId: event.session_id ?? this.currentSession ?? "" });
return;
}
@@ -143,7 +156,7 @@ export class ClaudeEventNormalizer {
}
else completedText.push(text);
} else if (block?.type === "tool_use") {
- out.push({ kind: "tool_call", name: block.name ?? "unknown_tool", input: block.input });
+ out.push({ kind: "tool_call", ...(typeof block.id === "string" ? { callId: block.id } : {}), name: block.name ?? "unknown_tool", input: block.input });
}
}
if (completedText.length > 0) {
@@ -154,12 +167,14 @@ export class ClaudeEventNormalizer {
private handleUser(event: any, out: AdapterEvent[]): void {
if (event.isReplay === true && typeof event.uuid === "string") {
this.turnProtocol?.acknowledge(event.uuid);
+ const inputs = this.turnProtocol?.inputReferences(event.uuid) ?? [];
+ if (inputs.length) out.push({ kind: "input_observed", inputs, evidence: "user_message" });
}
if (!this.acceptsTurnWork()) return;
const content = event?.message?.content;
if (!Array.isArray(content)) return;
for (const block of content) {
- if (block?.type === "tool_result") out.push({ kind: "tool_output", name: "" });
+ if (block?.type === "tool_result") out.push({ kind: "tool_output", ...(typeof block.tool_use_id === "string" ? { callId: block.tool_use_id } : {}), name: "", outcome: block.is_error ? "failed" : "success", output: block.content });
}
}
@@ -192,7 +207,7 @@ export class ClaudeEventNormalizer {
kind: "turn_end",
sessionId: event.session_id ?? this.currentSession ?? undefined,
...(turnOwner ? { turnOwner } : {}),
- ...(interruptedTerminal ? { outcome: "interrupted" as const } : {}),
+ outcome: interruptedTerminal ? "interrupted" : event.is_error || CLAUDE_RESULT_ERROR_CODES.has(event.subtype) ? "failed" : event.subtype === "success" ? "success" : "unknown",
});
}
diff --git a/src/daemon/agent-driver/src/adapters/claude/turnProtocol.ts b/src/daemon/agent-driver/src/adapters/claude/turnProtocol.ts
index 8df6b5cfa..cd36b1b17 100644
--- a/src/daemon/agent-driver/src/adapters/claude/turnProtocol.ts
+++ b/src/daemon/agent-driver/src/adapters/claude/turnProtocol.ts
@@ -1,8 +1,10 @@
import { randomUUID } from "node:crypto";
+import type { InputReference } from "../../contract.js";
interface DeliveredInput {
acknowledged: boolean;
followOn: boolean;
+ inputs?: readonly InputReference[];
}
/**
@@ -35,14 +37,15 @@ export class ClaudeTurnProtocol {
return this.receipt(uuid);
}
- rootInputUuid(): string {
+ rootInputUuid(inputs?: readonly InputReference[]): string {
if (!this.rootUuid) this.beginTurn();
+ if (inputs) this.delivered.get(this.rootUuid!)!.inputs = inputs;
return this.rootUuid!;
}
- steeringInputUuid(): string {
+ steeringInputUuid(inputs?: readonly InputReference[]): string {
const uuid = randomUUID();
- this.delivered.set(uuid, { acknowledged: false, followOn: this.awaitingFollowOn });
+ this.delivered.set(uuid, { acknowledged: false, followOn: this.awaitingFollowOn, inputs });
return uuid;
}
@@ -53,6 +56,10 @@ export class ClaudeTurnProtocol {
if (input.followOn) this.segmentOwnerUuid = uuid;
}
+ inputReferences(uuid: string): readonly InputReference[] {
+ return this.delivered.get(uuid)?.inputs ?? [];
+ }
+
acceptsTurnWork(): boolean {
if (!this.rootUuid || this.finalized) return false;
return this.delivered.get(this.rootUuid)?.acknowledged === true;
diff --git a/src/daemon/agent-driver/src/adapters/codex/command.test.ts b/src/daemon/agent-driver/src/adapters/codex/command.test.ts
new file mode 100644
index 000000000..59ba5ee11
--- /dev/null
+++ b/src/daemon/agent-driver/src/adapters/codex/command.test.ts
@@ -0,0 +1,70 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { resolveCodexCommand } from "./command.js";
+
+const roots: string[] = [];
+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
+
+function fixture() {
+ const root = mkdtempSync(join(tmpdir(), "codex app discovery "));
+ roots.push(root);
+ const deps = { homeDir: join(root, "user"), applicationsDirectory: join(root, "Applications"), which: vi.fn((): string | null => null) };
+ const install = (app: string, user = false, executable = true) => {
+ const binary = join(user ? join(deps.homeDir, "Applications") : deps.applicationsDirectory, `${app}.app`, "Contents", "Resources", "codex");
+ mkdirSync(dirname(binary), { recursive: true });
+ writeFileSync(binary, "#!/bin/sh\nexit 0\n");
+ chmodSync(binary, executable ? 0o755 : 0o644);
+ return binary;
+ };
+ return { deps, install };
+}
+
+describe("Codex App command discovery", () => {
+ it("honors an explicit command without probing other installations", () => {
+ const f = fixture();
+ f.install("Codex");
+ expect(resolveCodexCommand(" /custom codex/bin ", f.deps, "darwin")).toBe("/custom codex/bin");
+ expect(f.deps.which).not.toHaveBeenCalled();
+ });
+
+ it("keeps PATH ahead of App bundles", () => {
+ const f = fixture();
+ f.install("Codex");
+ f.deps.which.mockReturnValue("/path/codex");
+ expect(resolveCodexCommand(undefined, f.deps, "darwin")).toBe("/path/codex");
+ });
+
+ it.each(["Codex", "ChatGPT"])("finds the %s App in system and user Applications", (app) => {
+ const f = fixture();
+ const user = f.install(app, true);
+ expect(resolveCodexCommand(undefined, f.deps, "darwin")).toBe(user);
+ const system = f.install(app);
+ expect(resolveCodexCommand(undefined, f.deps, "darwin")).toBe(system);
+ });
+
+ it.skipIf(process.platform === "win32")("skips a non-executable bundle and uses the next runnable candidate", () => {
+ const f = fixture();
+ f.install("Codex", false, false);
+ const usable = f.install("ChatGPT", true);
+ expect(resolveCodexCommand(undefined, f.deps, "darwin")).toBe(usable);
+ });
+
+ it("prefers Codex over the legacy ChatGPT bundle", () => {
+ const f = fixture();
+ f.install("ChatGPT");
+ const current = f.install("Codex", true);
+ expect(resolveCodexCommand(undefined, f.deps, "darwin")).toBe(current);
+ });
+
+ it.each(["linux", "win32"] as const)("does not search macOS bundles on %s", (platform) => {
+ const f = fixture();
+ f.install("Codex");
+ expect(resolveCodexCommand(undefined, f.deps, platform)).toBeUndefined();
+ });
+
+ it("returns unavailable when no runnable candidate exists", () => {
+ expect(resolveCodexCommand(undefined, fixture().deps, "darwin")).toBeUndefined();
+ });
+});
diff --git a/src/daemon/agent-driver/src/adapters/codex/command.ts b/src/daemon/agent-driver/src/adapters/codex/command.ts
new file mode 100644
index 000000000..ca59f1faf
--- /dev/null
+++ b/src/daemon/agent-driver/src/adapters/codex/command.ts
@@ -0,0 +1,33 @@
+import { accessSync, constants, statSync } from "node:fs";
+import { homedir } from "node:os";
+import { join } from "node:path";
+import { resolveCommandOnPath, type ProbeDeps } from "../../internal/probe.js";
+
+interface CodexCommandDeps extends ProbeDeps {
+ readonly applicationsDirectory?: string;
+}
+
+export function resolveCodexCommand(
+ command?: string,
+ deps: CodexCommandDeps = {},
+ platform: NodeJS.Platform = process.platform,
+): string | undefined {
+ const explicit = command?.trim();
+ if (explicit) return explicit;
+ const onPath = resolveCommandOnPath("codex", deps);
+ if (onPath) return onPath;
+ if (platform !== "darwin") return undefined;
+ const roots = [deps.applicationsDirectory ?? "/Applications", join(deps.homeDir ?? homedir(), "Applications")];
+ for (const app of ["Codex.app", "ChatGPT.app"]) {
+ for (const root of roots) {
+ const candidate = join(root, app, "Contents", "Resources", "codex");
+ try {
+ accessSync(candidate, constants.X_OK);
+ if (statSync(candidate).isFile()) return candidate;
+ } catch {
+ continue;
+ }
+ }
+ }
+ return undefined;
+}
diff --git a/src/daemon/agent-driver/src/adapters/codex/index.test.ts b/src/daemon/agent-driver/src/adapters/codex/index.test.ts
index 9b72e62ca..962dda639 100644
--- a/src/daemon/agent-driver/src/adapters/codex/index.test.ts
+++ b/src/daemon/agent-driver/src/adapters/codex/index.test.ts
@@ -11,12 +11,15 @@ import { fakeLaunchContext } from "../../testing/adapter-fixture.js";
const runtimeMocks = vi.hoisted(() => ({
spawnAgentProcess: vi.fn(),
killProcessTree: vi.fn(async () => {}),
+ resolveCodexCommand: vi.fn((command?: string) => command?.trim() || undefined),
probeCliRuntime: vi.fn(async (): Promise<
| { status: "healthy"; version: string }
| { status: "unhealthy"; lastError: string }
> => ({ status: "healthy", version: "0.test" })),
}));
+vi.mock("./command.js", () => ({ resolveCodexCommand: runtimeMocks.resolveCodexCommand }));
+
vi.mock("../../internal/killTree.js", async () => {
const actual = await vi.importActual<typeof import("../../internal/killTree.js")>("../../internal/killTree.js");
return {
@@ -45,6 +48,8 @@ beforeEach(() => {
runtimeMocks.spawnAgentProcess.mockReset();
runtimeMocks.spawnAgentProcess.mockImplementation(simpleProcess);
runtimeMocks.killProcessTree.mockClear();
+ runtimeMocks.resolveCodexCommand.mockReset();
+ runtimeMocks.resolveCodexCommand.mockImplementation((command?: string) => command?.trim() || undefined);
runtimeMocks.probeCliRuntime.mockClear();
runtimeMocks.probeCliRuntime.mockResolvedValue({ status: "healthy", version: "0.test" });
});
@@ -80,6 +85,23 @@ function probingProcess(
}
describe("CodexDriver reasoning catalog probe", () => {
+ it("uses the discovered App binary for the version probe, catalog, and session launch", async () => {
+ const command = "/Applications/Codex.app/Contents/Resources/codex";
+ runtimeMocks.resolveCodexCommand.mockReturnValue(command);
+ const catalog = probingProcess((request) => ({
+ jsonrpc: "2.0", id: request.id,
+ result: request.method === "model/list" ? { data: [{ id: "native-model" }], nextCursor: null } : {},
+ }));
+ runtimeMocks.spawnAgentProcess.mockReturnValueOnce(catalog);
+ const driver = new CodexDriver();
+ expect(await driver.probe()).toMatchObject({ status: "healthy", reasoning: { models: [{ id: "native-model" }] } });
+ expect(runtimeMocks.probeCliRuntime).toHaveBeenCalledWith("codex", {}, command);
+ expect(runtimeMocks.spawnAgentProcess).toHaveBeenNthCalledWith(1, command, ["app-server", "--listen", "stdio://"], expect.any(Object));
+ await driver.spawn(baseCtx());
+ expect(runtimeMocks.spawnAgentProcess).toHaveBeenNthCalledWith(2, command, ["app-server", "--listen", "stdio://"], expect.any(Object));
+ });
+
+
it("checks installation without starting the catalog app-server", async () => {
runtimeMocks.probeCliRuntime.mockResolvedValueOnce({ status: "healthy", version: "1.2.3" });
expect(await new CodexDriver().probe(undefined, false)).toEqual({ status: "healthy", version: "1.2.3" });
@@ -543,48 +565,18 @@ function threadStarts(writes: string[]): any[] {
}
describe("CodexDriver missing-rollout resume recovery", () => {
- it("on a 'no rollout found' resume error, re-issues a FRESH thread/start (no threadId) and swallows the error", async () => {
- const driver = new CodexDriver();
- const ctx = baseCtx();
- ctx.config = { sessionId: "th_prior" }; // resuming a now-dead thread
- const { process: proc } = await driver.spawn(ctx);
- await Promise.resolve(); // flush handshake (writes thread/resume)
-
- const returned = driver.normalizeLine(missingRolloutError());
-
- // The resume error is swallowed — not surfaced to the manager as a fault.
- expect(returned.some((e: any) => e.kind === "error")).toBe(false);
- // A fresh thread/start was issued, with NO threadId (fresh, not resume).
- const starts = threadStarts(stdinWrites(proc));
- expect(starts).toHaveLength(1);
- expect(starts[0].params.threadId).toBeUndefined();
- });
-
- it("after the fallback fresh-thread's session_init, the held prompt is still delivered", async () => {
- const driver = new CodexDriver();
- const ctx = baseCtx();
- ctx.config = { sessionId: "th_prior" };
- const { process: proc } = await driver.spawn(ctx);
- await Promise.resolve();
-
- driver.normalizeLine(missingRolloutError()); // → fresh thread/start, prompt still pending
- driver.normalizeLine(threadStartResult("th_fresh")); // fresh thread adopted
-
- const turns = turnStarts(stdinWrites(proc));
- expect(turns).toHaveLength(1);
- expect(turns[0].params.threadId).toBe("th_fresh");
- expect(turns[0].params.input).toEqual([{ type: "text", text: "hi" }]);
- });
-
- it("recognizes a missing rollout when the error leads with not-found", async () => {
+ it.each(["no rollout found for thread id th_prior", "not found for requested rollout"])("requires reset instead of replacing a missing rollout: %s", async (message) => {
const driver = new CodexDriver();
const ctx = baseCtx();
ctx.config = { sessionId: "th_prior" };
const { process: proc } = await driver.spawn(ctx);
await Promise.resolve();
-
- expect(driver.normalizeLine(missingRolloutError("not found for requested rollout"))).toEqual([]);
- expect(threadStarts(stdinWrites(proc))).toHaveLength(1);
+ expect(driver.normalizeLine(missingRolloutError(message))).toEqual([
+ expect.objectContaining({ kind: "error", code: "reset_required" }),
+ ]);
+ expect(threadStarts(stdinWrites(proc))).toEqual([]);
+ driver.normalizeLine(threadStartResult("th_fresh"));
+ expect(turnStarts(stdinWrites(proc))).toEqual([]);
});
it("a successful resume does NOT trigger the fallback (no spurious fresh thread/start)", async () => {
@@ -619,14 +611,28 @@ describe("CodexDriver encodeMessage — turn/steer expectedTurnId", () => {
expect(msg.params.input).toEqual([{ type: "text", text: "hang on" }]);
});
- it("falls back to a fresh turn/start when there is no live turn to steer", () => {
+ it("correlates native ACK and refusal to exact attempts and suppresses duplicate or late RPC replies", () => {
const driver = new CodexDriver();
- driver.normalizeLine(threadStartResult("th_1")); // thread but no active turn
- const encoded = driver.encodeMessage("hi", "th_1", { mode: "busy" });
- const msg = JSON.parse(encoded!);
- // No turn id → don't send an invalid steer; start a fresh turn instead.
- expect(msg.method).toBe("turn/start");
- expect(msg.params.expectedTurnId).toBeUndefined();
+ driver.normalizeLine(threadStartResult("th_1"));
+ driver.normalizeLine(JSON.stringify({ method: "turn/started", params: { threadId: "th_1", turn: { id: "turn_9" } } }));
+ const first = [{ commandId: "B", attemptId: "B-1" }];
+ const rpc = JSON.parse(driver.encodeMessage("extra", "th_1", { mode: "busy", inputs: first })!);
+ const refusal = JSON.stringify({ id: rpc.id, error: { code: -32602, message: "turn has finished" } });
+ expect(driver.normalizeLine(refusal)).toEqual([{ kind: "input_returned", inputs: first, evidence: "explicitly_rejected", reason: "turn has finished", retryable: true }]);
+ const next = [{ commandId: "B", attemptId: "B-2" }];
+ const retry = JSON.parse(driver.encodeMessage("extra", "th_1", { mode: "busy", inputs: next })!);
+ expect(driver.normalizeLine(refusal)).toEqual([]);
+ const ack = JSON.stringify({ id: retry.id, result: {} });
+ expect(driver.normalizeLine(ack)).toEqual([{ kind: "input_observed", inputs: next, evidence: "native_ack" }]);
+ expect(driver.normalizeLine(ack)).toEqual([]);
+ expect(driver.normalizeLine(JSON.stringify({ id: retry.id, error: { message: "late refusal" } }))).toEqual([]);
+ expect(driver.currentSessionId).toBe("th_1");
+ });
+
+ it("does not create a new turn when a busy steer loses its native turn", () => {
+ const driver = new CodexDriver();
+ driver.normalizeLine(threadStartResult("th_1"));
+ expect(driver.encodeMessage("hi", "th_1", { mode: "busy" })).toBeNull();
});
it("idle message is always a fresh turn/start (no expectedTurnId)", () => {
@@ -715,7 +721,7 @@ describe("CodexDriver live reasoning settings", () => {
.find((message) => message.method === "thread/settings/update");
expect(request.params).toEqual({ threadId: "th_settings", effort: "xhigh" });
expect(driver.normalizeLine(JSON.stringify({ jsonrpc: "2.0", id: request.id, result: {} }))).toEqual([]);
- await expect(pending).resolves.toEqual({ status: "applied" });
+ await expect(pending).resolves.toEqual({ status: "acknowledged", effective: "next_turn" });
});
it("sends null to restore Default and classifies method-not-found as unsupported", async () => {
diff --git a/src/daemon/agent-driver/src/adapters/codex/index.ts b/src/daemon/agent-driver/src/adapters/codex/index.ts
index 8596db3f5..695858ede 100644
--- a/src/daemon/agent-driver/src/adapters/codex/index.ts
+++ b/src/daemon/agent-driver/src/adapters/codex/index.ts
@@ -1,18 +1,3 @@
-/**
- * Codex driver — persistent, JSON-RPC app-server, GATED steering.
- *
- * Codex runs as `app-server --listen stdio://` and speaks JSON-RPC 2.0. Like
- * Claude, a `turn/steer` sent while a tool call / compaction / review is in
- * flight can race the app-server's own turn-state handling, so busy delivery
- * is `gated` — held until a safe boundary by the manager-level mechanism in
- * `manager/managerPolicy.ts`. A
- * busy message becomes a `turn/steer` RPC against the active turn, while an
- * idle message becomes a fresh `turn/start` — the encoding itself is
- * unaffected by gating, only WHEN the manager calls it.
- *
- * Handshake (queued on spawn): `initialize` → then `thread/start` (or
- * `thread/resume` with the prior threadId). The thread id is the session id.
- */
import type {
BackendAdapter, EncodeMessageOptions, AdapterLaunchContext, AdapterEvent, LaneInterruptInput, RuntimeLane,
RuntimeLaneOpenOptions, SpawnedProcess, SpawnedProcessHandle,
@@ -22,6 +7,7 @@ import type {
RuntimeSettingsUpdate,
RuntimeSettingsUpdateResult,
RuntimeReasoningCatalog,
+ InputReference,
} from "../../contract.js";
import { createProcessLane } from "../../controller/process-host.js";
import { prepareCliTransport } from "../../internal/cliTransport.js";
@@ -36,6 +22,7 @@ import {
normalizeRuntimeModelId,
RUNTIME_MODEL_CATALOG_MAX,
} from "../../internal/modelCatalog.js";
+import { resolveCodexCommand } from "./command.js";
import { discoverCodexRecentContext } from "./recent-context.js";
const SETTINGS_UPDATE_TIMEOUT_MS = 5_000;
@@ -93,15 +80,9 @@ export class CodexDriver implements BackendAdapter {
* there is no prompt (a bare wake) — we don't start an empty turn.
*/
private pendingInitialPrompt: string | null = null;
- /**
- * When spawn issued a `thread/resume`, the `thread/start` params to fall back
- * to if that resume fails with "no rollout found" (the prior thread's rollout
- * is gone). Null once we're not resuming, or once the fallback has fired. This
- * powers the missing-rollout recovery in `normalizeLine`: re-issue a FRESH
- * `thread/start` (no threadId) on the same live process, keeping
- * `pendingInitialPrompt` so the fresh thread's `session_init` still delivers it.
- */
- private pendingResumeFallbackParams: Record<string, unknown> | null = null;
+ private requestedSessionId?: string;
+ private pendingInitialInputs: readonly InputReference[] = [];
+ private readonly pendingInputs = new Map<number, { inputs: readonly InputReference[]; steer: boolean; settled?: boolean }>();
private readonly pendingSettingsUpdates = new Map<number, {
resolve(result: RuntimeSettingsUpdateResult): void;
timer: ReturnType<typeof setTimeout>;
@@ -139,12 +120,13 @@ export class CodexDriver implements BackendAdapter {
// package resolves but the aarch64 blob is absent) fails there even
// though resolveCommandOnPath returned a JS wrapper; probing the resolved
// command keeps runtime health tied to what can actually execute.
- const result = await probeCliRuntime("codex", {}, command);
+ const selected = resolveCodexCommand(command);
+ const result = await probeCliRuntime("codex", {}, selected);
if (result.status !== "healthy") return result;
if (!includeModels) return result;
return {
...result,
- reasoning: await this.probeReasoningCatalog(command),
+ reasoning: await this.probeReasoningCatalog(selected),
};
}
@@ -282,7 +264,7 @@ export class CodexDriver implements BackendAdapter {
// host could surface "missing rollout" recovery — see classifyCodexResumeError).
this.codexHomeRoot = resolveCodexHomeRootFromEnv(spawnEnv, { cwd: ctx.workingDirectory });
// Cross-platform spawn: on Windows the codex entry is often a `.cmd` shim.
- const override = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig).command;
+ const override = resolveCodexCommand(resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig).command);
const spec = resolveSpawnSpec("codex", ["app-server", "--listen", "stdio://"], override);
const proc = spawnAgentProcess(spec.command, spec.args, {
cwd: ctx.workingDirectory,
@@ -301,6 +283,8 @@ export class CodexDriver implements BackendAdapter {
// (a bare wake with no message) → no pending prompt, so no empty turn.
const initialPrompt = ctx.prompt?.trim() ? ctx.prompt : null;
this.pendingInitialPrompt = initialPrompt;
+ this.pendingInitialInputs = ctx.inputs ?? [];
+ this.requestedSessionId = ctx.config.sessionId;
// Async handshake: initialize, then thread/start|resume. This ONLY sets up
// the thread — the user prompt is delivered later (see `normalizeLine`), because
@@ -318,9 +302,6 @@ export class CodexDriver implements BackendAdapter {
const f = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig);
const resuming = Boolean(ctx.config.sessionId);
- // Fresh-thread params (no threadId) — used directly for a fresh spawn, and
- // stashed as the resume fallback so a "no rollout found" resume can retry
- // as a fresh thread (see normalizeLine).
const freshParams: Record<string, unknown> = {
cwd: ctx.workingDirectory,
approvalPolicy: "never",
@@ -333,7 +314,6 @@ export class CodexDriver implements BackendAdapter {
if (f.fastMode) freshParams.serviceTier = "fast";
if (resuming) {
- this.pendingResumeFallbackParams = freshParams;
proc.stdin?.write(
jsonRpcRequest("thread/resume", { ...freshParams, threadId: ctx.config.sessionId }, this.nextRequestId()) + "\n",
);
@@ -346,73 +326,41 @@ export class CodexDriver implements BackendAdapter {
return { process: proc };
}
- /**
- * Parse a stdout line AND, as a one-time side-effect, deliver the initial
- * prompt. This is NOT a pure parser: on the FIRST `session_init` (the thread
- * id is now known) it writes the held `pendingInitialPrompt` as a `turn/start`
- * to stdin, then clears it (submit-once latch). This is where the initial user
- * message actually reaches Codex — the spawn handshake only starts the thread.
- *
- * The latch also makes the double `session_init` harmless: `thread/start`
- * emits one from its result and one from the `thread/started` notification, so
- * without the latch we'd submit the prompt twice. Resume takes the same path
- * (thread/resume's result also yields `session_init`), so no separate branch.
- *
- * SECOND side-effect — missing-rollout recovery: if a `thread/resume` fails
- * with "no rollout found" (the prior thread's rollout is gone), Codex emits an
- * `error` event and NO `session_init`. We re-issue a FRESH `thread/start` on
- * the same live process and swallow the error so the manager doesn't fault the
- * turn. `pendingInitialPrompt` is deliberately kept, so the fresh thread's
- * `session_init` delivers it via the latch above. Without this, a stale
- * sessionId wedges the bot: resume errors out, no turn ever runs.
- */
normalizeLine(line: string): AdapterEvent[] {
- const settingsResponse = this.consumeSettingsUpdateResponse(line);
- if (settingsResponse) return [];
- const parsed = tryParseJsonLine(line) as { id?: unknown; method?: unknown } | null;
- const events = this.eventNormalizer.normalizeLine(line);
- if (
- typeof parsed?.id === "number"
- && this.pendingAccountReadRequestIds.delete(parsed.id)
- ) {
- // Establish (and, if needed, rotate) the account-scoped source epoch
- // before asking for limits. Issuing both RPCs concurrently can associate
- // a fast quota response with the previous account after an account swap.
- this.requestQuotaSnapshot();
+ if (this.consumeSettingsUpdateResponse(line)) return [];
+ const parsed = tryParseJsonLine(line) as { id?: number; method?: string; error?: { message?: string }; result?: unknown } | null;
+ const pending = typeof parsed?.id === "number" ? this.pendingInputs.get(parsed.id) : undefined;
+ if (pending && parsed) {
+ if (pending.settled) return [];
+ this.pendingInputs.set(parsed.id!, { inputs: [], steer: pending.steer, settled: true });
+ if (pending.steer && parsed.error) return [{ kind: "input_returned", inputs: pending.inputs, evidence: "explicitly_rejected", reason: parsed.error.message ?? "Codex rejected steering", retryable: true }];
+ if (!parsed.error && pending.steer) return [{ kind: "input_observed", inputs: pending.inputs, evidence: "native_ack" }];
}
+ const events = this.eventNormalizer.normalizeLine(line);
+ if (typeof parsed?.id === "number" && this.pendingAccountReadRequestIds.delete(parsed.id)) this.requestQuotaSnapshot();
if (parsed?.method === "account/updated") this.requestAccountQuotaSnapshot();
-
- // Missing-rollout resume recovery — before any session_init is adopted.
- if (this.pendingResumeFallbackParams && this.proc?.stdin && !this.proc.stdin.destroyed) {
- const rolloutErr = events.find(
- (e) => e.kind === "error" && isCodexMissingRolloutError(e.message),
- );
- if (rolloutErr) {
- const fallback = this.pendingResumeFallbackParams;
- this.pendingResumeFallbackParams = null;
- // Fresh thread/start (no threadId). Keep pendingInitialPrompt so the new
- // thread's session_init delivers it. Swallow the resume error so it's
- // not surfaced as a runtime_error fault.
- this.proc.stdin.write(jsonRpcRequest("thread/start", fallback, this.nextRequestId()) + "\n");
- return events.filter((e) => e !== rolloutErr);
+ if (this.requestedSessionId) {
+ const failure = events.find((event) => event.kind === "error" && isCodexMissingRolloutError(event.message));
+ if (failure?.kind === "error") {
+ this.pendingInitialPrompt = null;
+ return [{ ...failure, code: "reset_required", scope: "session" }];
}
}
-
- if (this.pendingInitialPrompt !== null && events.some((e) => e.kind === "session_init")) {
+ for (const event of events) {
+ if (event.kind !== "session_init") continue;
+ if (this.requestedSessionId && event.sessionId !== this.requestedSessionId) {
+ this.pendingInitialPrompt = null;
+ return [{ kind: "error", code: "reset_required", scope: "session", message: "Codex did not restore the requested thread" }];
+ }
+ event.acquisition = { status: this.requestedSessionId ? "resumed" : "created", evidence: "native_api" };
+ }
+ if (this.pendingInitialPrompt !== null && events.some((event) => event.kind === "session_init")) {
const threadId = this.eventNormalizer.currentSessionId;
- // Defensive: the process is normally alive when its own stdout is being
- // parsed, but guard the write so a mid-teardown line can't throw.
if (threadId && this.proc?.stdin && !this.proc.stdin.destroyed) {
- this.proc.stdin.write(this.buildTurnStart(threadId, this.pendingInitialPrompt) + "\n");
+ this.proc.stdin.write(this.buildTurnStart(threadId, this.pendingInitialPrompt, this.pendingInitialInputs) + "\n");
this.pendingInitialPrompt = null;
}
}
-
- // A successful thread adoption means resume didn't fail — drop the fallback.
- if (events.some((e) => e.kind === "session_init")) {
- this.pendingResumeFallbackParams = null;
- }
-
return events;
}
@@ -484,7 +432,7 @@ export class CodexDriver implements BackendAdapter {
this.pendingSettingsUpdates.delete(record.id);
const error = record.error;
if (!error || typeof error !== "object") {
- pending.resolve({ status: "applied" });
+ pending.resolve({ status: "acknowledged", effective: "next_turn" });
return true;
}
const rpcError = error as Record<string, unknown>;
@@ -555,26 +503,25 @@ export class CodexDriver implements BackendAdapter {
}
/** A `turn/start` RPC — the sole encoder for starting a fresh Codex turn. */
- private buildTurnStart(threadId: string, text: string): string {
- return jsonRpcRequest("turn/start", { threadId, input: [{ type: "text", text }] }, this.nextRequestId());
+ private buildTurnStart(threadId: string, text: string, inputs: readonly InputReference[] = []): string {
+ const id = this.nextRequestId();
+ this.pendingInputs.set(id, { inputs, steer: false });
+ return jsonRpcRequest("turn/start", { threadId, input: [{ type: "text", text }] }, id);
}
/** busy → `turn/steer` against the active turn; idle → fresh `turn/start`. */
encodeMessage(text: string, sessionId: string | null, opts?: EncodeMessageOptions): string | null {
const threadId = sessionId ?? this.eventNormalizer.currentSessionId;
if (!threadId) return null;
- if (opts?.mode === "idle") return this.buildTurnStart(threadId, text);
- // Steer the in-flight turn. Codex requires `expectedTurnId` = the active
- // turn's id (from turn/started's params.turn.id); without it it rejects the
- // steer with "missing field expectedTurnId". If we somehow have no live turn
- // id (raced past turn/completed), fall back to a fresh turn/start rather than
- // send an invalid steer.
+ if (opts?.mode === "idle") return this.buildTurnStart(threadId, text, opts?.inputs);
const turnId = this.eventNormalizer.currentTurnId;
- if (!turnId) return this.buildTurnStart(threadId, text);
+ if (!turnId) return null;
+ const id = this.nextRequestId();
+ this.pendingInputs.set(id, { inputs: opts?.inputs ?? [], steer: true });
return jsonRpcRequest(
"turn/steer",
{ threadId, expectedTurnId: turnId, input: [{ type: "text", text }] },
- this.nextRequestId(),
+ id,
);
}
diff --git a/src/daemon/agent-driver/src/adapters/codex/normalizer.test.ts b/src/daemon/agent-driver/src/adapters/codex/normalizer.test.ts
index 6100e497d..9e71c6c7a 100644
--- a/src/daemon/agent-driver/src/adapters/codex/normalizer.test.ts
+++ b/src/daemon/agent-driver/src/adapters/codex/normalizer.test.ts
@@ -25,7 +25,7 @@ describe("CodexEventNormalizer — tool_call/tool_output symmetry", () => {
expect(started).toEqual([{ kind: "tool_call", name: "file_change", input: {} }]);
const completed = n.normalizeLine(notify("item/completed", { item: { type: "fileChange" } }));
- expect(completed).toEqual([{ kind: "tool_output", name: "file_change" }]);
+ expect(completed).toEqual([{ kind: "tool_output", name: "file_change", outcome: "unknown" }]);
});
it("fileChange consumes raw changes at the adapter boundary and emits only an ordered-unique flat path", () => {
@@ -53,7 +53,7 @@ describe("CodexEventNormalizer — tool_call/tool_output symmetry", () => {
expect(JSON.stringify(started)).not.toContain("secret");
const completed = n.normalizeLine(notify("item/completed", { item: { type: "fileChange" } }));
- expect(completed).toEqual([{ kind: "tool_output", name: "file_change" }]);
+ expect(completed).toEqual([{ kind: "tool_output", name: "file_change", outcome: "unknown" }]);
});
it("fileChange flattens a legacy top-level path when changes are absent", () => {
@@ -86,7 +86,7 @@ describe("CodexEventNormalizer — tool_call/tool_output symmetry", () => {
expect(started).toEqual([{ kind: "tool_call", name: "web_search", input: { type: "webSearch" } }]);
const completed = n.normalizeLine(notify("item/completed", { item: { type: "webSearch" } }));
- expect(completed).toEqual([{ kind: "tool_output", name: "web_search" }]);
+ expect(completed).toEqual([{ kind: "tool_output", name: "web_search", outcome: "unknown" }]);
});
it("collabAgentToolCall: item/started then item/completed emits tool_call then tool_output", () => {
@@ -95,7 +95,7 @@ describe("CodexEventNormalizer — tool_call/tool_output symmetry", () => {
expect(started).toEqual([{ kind: "tool_call", name: "collab_tool_call", input: { type: "collabAgentToolCall" } }]);
const completed = n.normalizeLine(notify("item/completed", { item: { type: "collabAgentToolCall" } }));
- expect(completed).toEqual([{ kind: "tool_output", name: "collab_tool_call" }]);
+ expect(completed).toEqual([{ kind: "tool_output", name: "collab_tool_call", outcome: "unknown" }]);
});
it("commandExecution: item/started then item/completed still pairs correctly (regression — 9b removed markProgress from this handler)", () => {
@@ -104,7 +104,7 @@ describe("CodexEventNormalizer — tool_call/tool_output symmetry", () => {
expect(started).toEqual([{ kind: "tool_call", name: "shell", input: { type: "commandExecution" } }]);
const completed = n.normalizeLine(notify("item/completed", { item: { type: "commandExecution" } }));
- expect(completed).toEqual([{ kind: "tool_output", name: "shell" }]);
+ expect(completed).toEqual([{ kind: "tool_output", name: "shell", outcome: "unknown" }]);
});
it("mcpToolCall: item/started then item/completed still pairs correctly (regression — 9b removed markProgress from this handler)", () => {
@@ -115,7 +115,7 @@ describe("CodexEventNormalizer — tool_call/tool_output symmetry", () => {
]);
const completed = n.normalizeLine(notify("item/completed", { item: { type: "mcpToolCall", name: "search" } }));
- expect(completed).toEqual([{ kind: "tool_output", name: "mcp_search" }]);
+ expect(completed).toEqual([{ kind: "tool_output", name: "mcp_search", outcome: "unknown" }]);
});
it("carries the stable app-server item id across both sides of a tool lifecycle", () => {
@@ -130,6 +130,7 @@ describe("CodexEventNormalizer — tool_call/tool_output symmetry", () => {
}]);
expect(n.normalizeLine(notify("item/completed", { item: { ...item, status: "failed" } }))).toEqual([{
kind: "tool_output",
+ outcome: "failed",
callId: "item-42",
name: "mcp_click",
}]);
@@ -184,7 +185,7 @@ describe("CodexEventNormalizer — turn id tracking (for turn/steer expectedTurn
code: "codex.server_overloaded",
message: "Selected model is at capacity. Please try a different model.",
},
- { kind: "turn_end", sessionId: "th_1", turnOwner: "codex:th_1:turn_x" },
+ { kind: "turn_end", sessionId: "th_1", turnOwner: "codex:th_1:turn_x" , outcome: "failed" },
]);
});
@@ -212,7 +213,7 @@ describe("CodexEventNormalizer — turn id tracking (for turn/steer expectedTurn
expect(n.normalizeLine(notify("turn/completed", {
threadId: "child-thread-1",
turn: { id: "child-turn-1", status: "completed" },
- }))).toEqual([]);
+ }))).toEqual([expect.objectContaining({ attribution: expect.objectContaining({ scope: "unknown" }) })]);
expect(n.normalizeLine(notify("turn/completed", {
threadId: "root-thread",
turn: { id: "unknown-turn", status: "completed" },
@@ -223,7 +224,7 @@ describe("CodexEventNormalizer — turn id tracking (for turn/steer expectedTurn
expect(n.normalizeLine(notify("turn/completed", {
threadId: "root-thread",
turn: { id: "root-turn", status: "completed" },
- }))).toEqual([{ kind: "turn_end", sessionId: "root-thread", turnOwner: "codex:root-thread:root-turn" }]);
+ }))).toEqual([{ kind: "turn_end", sessionId: "root-thread", turnOwner: "codex:root-thread:root-turn" , outcome: "success" }]);
expect(n.currentTurnId).toBeNull();
});
@@ -235,13 +236,13 @@ describe("CodexEventNormalizer — turn id tracking (for turn/steer expectedTurn
turn: { id: "root-turn", status: "completed" },
});
- expect(n.normalizeLine(completed)).toEqual([{ kind: "turn_end", sessionId: "root-thread", turnOwner: "codex:root-thread:root-turn" }]);
+ expect(n.normalizeLine(completed)).toEqual([{ kind: "turn_end", sessionId: "root-thread", turnOwner: "codex:root-thread:root-turn" , outcome: "success" }]);
expect(n.currentTurnId).toBeNull();
expect(n.normalizeLine(completed)).toEqual([]);
expect(n.normalizeLine(notify("rawResponseItem/completed", {
threadId: "child-thread",
turnId: "root-turn",
- }))).toEqual([]);
+ }))).toEqual([expect.objectContaining({ attribution: expect.objectContaining({ scope: "unknown" }) })]);
expect(n.normalizeLine(notify("rawResponseItem/completed", {
threadId: "root-thread",
turnId: "stale-turn",
@@ -251,7 +252,7 @@ describe("CodexEventNormalizer — turn id tracking (for turn/steer expectedTurn
threadId: "root-thread",
turnId: "root-turn",
}))).toEqual([{ kind: "internal_progress", source: "codex_raw_item", itemType: "rawResponseItem" }]);
- expect(n.normalizeLine(completed)).toEqual([{ kind: "turn_end", sessionId: "root-thread", turnOwner: "codex:root-thread:root-turn" }]);
+ expect(n.normalizeLine(completed)).toEqual([{ kind: "turn_end", sessionId: "root-thread", turnOwner: "codex:root-thread:root-turn" , outcome: "success" }]);
expect(n.normalizeLine(completed)).toEqual([]);
expect(n.normalizeLine(notify("turn/started", {
@@ -305,7 +306,7 @@ describe("CodexEventNormalizer — turn id tracking (for turn/steer expectedTurn
expect(n.normalizeLine(notify("rawResponseItem/completed", {
threadId: "old-thread",
turnId: "old-turn",
- }))).toEqual([]);
+ }))).toEqual([expect.objectContaining({ attribution: expect.objectContaining({ scope: "unknown", agentId: "old-thread" }) })]);
expect(n.normalizeLine(notify("turn/completed", {
threadId: "new-thread",
turn: { status: "completed" },
@@ -316,11 +317,11 @@ describe("CodexEventNormalizer — turn id tracking (for turn/steer expectedTurn
const n = new CodexEventNormalizer();
adoptRootTurn(n, "root-thread", "root-turn");
- expect(n.normalizeLine(notify("thread/started", { thread: { id: "child-thread" } }))).toEqual([]);
+ expect(n.normalizeLine(notify("thread/started", { thread: { id: "child-thread" } }))).toEqual([expect.objectContaining({ attribution: expect.objectContaining({ scope: "unknown", agentId: "child-thread" }) })]);
expect(n.normalizeLine(notify("turn/started", {
threadId: "child-thread",
turn: { id: "child-turn", status: "inProgress" },
- }))).toEqual([]);
+ }))).toEqual([expect.objectContaining({ attribution: expect.objectContaining({ scope: "unknown" }) })]);
expect(n.currentSessionId).toBe("root-thread");
expect(n.currentTurnId).toBe("root-turn");
});
@@ -333,12 +334,12 @@ describe("CodexEventNormalizer — turn id tracking (for turn/steer expectedTurn
threadId: "child-thread",
turnId: "child-turn",
delta: "child leak",
- }))).toEqual([]);
+ }))).toEqual([expect.objectContaining({ attribution: expect.objectContaining({ scope: "unknown" }) })]);
expect(n.normalizeLine(notify("item/started", {
threadId: "child-thread",
turnId: "child-turn",
item: { type: "commandExecution", command: "secret" },
- }))).toEqual([]);
+ }))).toEqual([expect.objectContaining({ attribution: expect.objectContaining({ scope: "unknown" }) })]);
expect(n.currentSessionId).toBe("root-thread");
expect(n.currentTurnId).toBe("root-turn");
});
@@ -383,7 +384,7 @@ describe("CodexEventNormalizer — turn id tracking (for turn/steer expectedTurn
expect(n.normalizeLine(notify("turn/completed", {
threadId: "child-thread",
turn: { id: "shared-turn-id", status: "completed" },
- }))).toEqual([]);
+ }))).toEqual([expect.objectContaining({ attribution: expect.objectContaining({ scope: "unknown" }) })]);
expect(n.currentSessionId).toBe("root-thread");
expect(n.currentTurnId).toBe("shared-turn-id");
expect(n.normalizeLine(rootUsage)).toEqual([]);
@@ -392,7 +393,7 @@ describe("CodexEventNormalizer — turn id tracking (for turn/steer expectedTurn
threadId: "root-thread",
turn: { id: "shared-turn-id", status: "completed" },
}))).toEqual([
- { kind: "turn_end", sessionId: "root-thread", turnOwner: "codex:root-thread:shared-turn-id" },
+ { kind: "turn_end", sessionId: "root-thread", turnOwner: "codex:root-thread:shared-turn-id" , outcome: "success" },
]);
});
@@ -412,7 +413,7 @@ describe("CodexEventNormalizer — turn id tracking (for turn/steer expectedTurn
threadId: "child-thread",
turnId: "child-turn",
item: { type: "contextCompaction" },
- }))).toEqual([]);
+ }))).toEqual([expect.objectContaining({ attribution: expect.objectContaining({ scope: "unknown" }) })]);
expect(n.normalizeLine(childUsage)).toHaveLength(1);
});
@@ -577,7 +578,7 @@ describe("CodexEventNormalizer — complete owned event family", () => {
turn: { id: "turn", status: "completed" },
}));
expect(terminal).toEqual([
- { kind: "turn_end", sessionId: "root", turnOwner: "codex:root:turn" },
+ { kind: "turn_end", sessionId: "root", turnOwner: "codex:root:turn" , outcome: "success" },
]);
expect(n.normalizeLine(first)).toEqual([]);
diff --git a/src/daemon/agent-driver/src/adapters/codex/normalizer.ts b/src/daemon/agent-driver/src/adapters/codex/normalizer.ts
index 1f3dbee73..3e971f36a 100644
--- a/src/daemon/agent-driver/src/adapters/codex/normalizer.ts
+++ b/src/daemon/agent-driver/src/adapters/codex/normalizer.ts
@@ -199,7 +199,7 @@ export class CodexEventNormalizer {
}
private adoptAndInit(threadId: string): AdapterEvent[] {
- if (this.threadId !== null && threadId !== this.threadId) return [];
+ if (this.threadId !== null && threadId !== this.threadId) return this.offRootActivity("thread/started", { threadId });
const firstSight = threadId !== this.sessionInitEmittedFor;
this.threadId = threadId;
if (!firstSight) return [];
@@ -241,7 +241,9 @@ export class CodexEventNormalizer {
}
if (msg?.result?.thread?.id) {
- return this.adoptAndInit(msg.result.thread.id);
+ const events = this.adoptAndInit(msg.result.thread.id);
+ if (typeof msg.result.model === "string") events.push({ kind: "configuration_observed", observation: { evidence: "observed", effective: "current", model: msg.result.model, ...(typeof msg.result.reasoningEffort === "string" || msg.result.reasoningEffort === null ? { reasoningEffort: msg.result.reasoningEffort } : {}) } });
+ return events;
}
if (msg?.method) return this.handleNotification(msg.method, msg.params ?? {});
@@ -258,7 +260,7 @@ export class CodexEventNormalizer {
) {
const turnId = this.notificationTurnId(params);
if (turnId) this.releaseUsageForTurn(notificationThreadId, turnId);
- return [];
+ return this.offRootActivity(method, params);
}
if (
method === "item/completed"
@@ -270,13 +272,13 @@ export class CodexEventNormalizer {
if (turnId && itemType === "contextCompaction") {
this.releaseUsageForTurn(notificationThreadId, turnId);
}
- return [];
+ return this.offRootActivity(method, params);
}
if (
this.threadId !== null &&
notificationThreadId !== null &&
notificationThreadId !== this.threadId
- ) return [];
+ ) return this.offRootActivity(method, params);
if (this.isRootWorkNotification(method) && !this.acceptRootWork(params)) return [];
switch (method) {
@@ -334,11 +336,11 @@ export class CodexEventNormalizer {
code: codexErrorInfoCode(error?.codexErrorInfo, "codex.turn_failed"),
message: error?.message ?? "Codex turn failed",
},
- { kind: "turn_end", sessionId: this.threadId ?? undefined, turnOwner: this.turnReceipt(params.threadId, params.turn.id) },
+ { kind: "turn_end", sessionId: this.threadId ?? undefined, turnOwner: this.turnReceipt(params.threadId, params.turn.id), outcome: "failed" },
];
}
return [{ kind: "turn_end", sessionId: this.threadId ?? undefined, turnOwner: this.turnReceipt(params.threadId, params.turn.id),
- ...(params.turn.status === "interrupted" ? { outcome: "interrupted" as const } : {}),
+ outcome: params.turn.status === "interrupted" ? "interrupted" : params.turn.status === "completed" ? "success" : "unknown",
}];
case "error":
@@ -484,6 +486,15 @@ export class CodexEventNormalizer {
return false;
}
+ private offRootActivity(method: string, params: any): AdapterEvent[] {
+ const attribution = { scope: "unknown" as const, agentId: params?.threadId, nativeTurnId: this.notificationTurnId(params) ?? undefined };
+ const events: AdapterEvent[] = method === "item/started" ? this.handleItemStarted(params)
+ : method === "item/completed" ? this.handleItemCompleted(params)
+ : method === "item/agentMessage/delta" ? [{ kind: "assistant_message_delta", text: params.delta ?? "" }]
+ : [{ kind: "internal_progress", source: "codex", itemType: method }];
+ return events.map(event => ({ ...event, attribution }));
+ }
+
private handleItemStarted(params: any): AdapterEvent[] {
const t = params?.item?.type ?? params?.type;
const callId = this.itemCallId(params);
@@ -512,21 +523,25 @@ export class CodexEventNormalizer {
const t = params?.item?.type ?? params?.type;
const callId = this.itemCallId(params);
const identity = callId ? { callId } : {};
+ const item = params?.item;
+ const outcome = item?.status === "failed" || item?.exitCode != null && item.exitCode !== 0 ? "failed"
+ : item?.status === "completed" || item?.exitCode === 0 ? "success" : "unknown";
+ const result = { outcome, output: item?.aggregatedOutput ?? item?.result ?? item?.output } as const;
switch (t) {
case "commandExecution":
- return [{ kind: "tool_output", ...identity, name: "shell" }];
+ return [{ kind: "tool_output", ...identity, ...result, name: "shell" }];
case "contextCompaction":
return [{ kind: "compaction_finished" }];
case "exitedReviewMode":
return [{ kind: "review_finished" }];
case "fileChange":
- return [{ kind: "tool_output", ...identity, name: "file_change" }];
+ return [{ kind: "tool_output", ...identity, ...result, name: "file_change" }];
case "mcpToolCall":
- return [{ kind: "tool_output", ...identity, name: `mcp_${params?.item?.tool ?? params?.item?.name ?? "tool"}` }];
+ return [{ kind: "tool_output", ...identity, ...result, name: `mcp_${params?.item?.tool ?? params?.item?.name ?? "tool"}` }];
case "webSearch":
- return [{ kind: "tool_output", ...identity, name: "web_search" }];
+ return [{ kind: "tool_output", ...identity, ...result, name: "web_search" }];
case "collabAgentToolCall":
- return [{ kind: "tool_output", ...identity, name: "collab_tool_call" }];
+ return [{ kind: "tool_output", ...identity, ...result, name: "collab_tool_call" }];
case "agentMessage":
return [{ kind: "assistant_message_completed", text: params?.item?.text ?? "" }];
case "reasoning": {
diff --git a/src/daemon/agent-driver/src/adapters/copilot/worker.ts b/src/daemon/agent-driver/src/adapters/copilot/worker.ts
new file mode 100644
index 000000000..6de8039e2
--- /dev/null
+++ b/src/daemon/agent-driver/src/adapters/copilot/worker.ts
@@ -0,0 +1,155 @@
+import type { SdkWorkerInit, SdkWorkerSession, SdkWorkerEvent } from "../../internal/sdk-worker-api.js";
+import type { LaneSendInput, ProbeResult } from "../../internal/adapter.js";
+
+export async function copilotWorker(init: SdkWorkerInit, emit: (event: SdkWorkerEvent) => void): Promise<SdkWorkerSession | ProbeResult> {
+ const load = new Function("specifier", "return import(specifier)") as (specifier: string) => Promise<any>;
+ const sdk = await load(init.moduleUrl);
+ if (typeof sdk.CopilotClient !== "function" || typeof sdk.RuntimeConnection?.forStdio !== "function") {
+ throw Object.assign(new Error("Copilot SDK lacks its owned stdio connection contract"), { code: "incompatible_configuration" });
+ }
+ const client = new sdk.CopilotClient({
+ connection: sdk.RuntimeConnection.forStdio({ ...(init.config.command ? { path: init.config.command } : {}) }),
+ workingDirectory: init.cwd,
+ });
+ let session: any;
+ let closed = false;
+ type Root = { owner: string; inFlight: number; pending: Set<string>; observed: Set<string>; inputs: Map<string, NonNullable<LaneSendInput["inputs"]>>; refusals: Map<string, { message: string; evidence: "explicitly_rejected" | "unknown" }>; rootInputId?: string; idle: boolean; failed: boolean; aborted: boolean };
+ let active: Root | undefined;
+ const tools = new Map<string, string>();
+ const close = async () => {
+ if (closed) return;
+ closed = true;
+ try { if (active && session) await session.abort(); }
+ finally { try { await session?.disconnect(); } finally { await client.stop(); } }
+ };
+ try {
+ await client.start();
+ if (init.probe) {
+ if (!init.probe.includeModels) { await close(); return { status: "healthy" }; }
+ const models = await client.listModels();
+ await close();
+ return { status: "healthy", reasoning: { updateMode: "unsupported", models: models.filter((model: any) => typeof model.id === "string").slice(0, 1024).map((model: any) => ({
+ id: model.id, displayName: model.name,
+ supportedReasoningEfforts: (model.supportedReasoningEfforts ?? []).map((value: string) => ({ value })),
+ ...(model.defaultReasoningEffort ? { defaultReasoningEffort: model.defaultReasoningEffort } : {}),
+ })) } };
+ }
+ const config = {
+ workingDirectory: init.cwd, streaming: true, onPermissionRequest: sdk.approveAll,
+ ...(init.instructions ? { systemMessage: { mode: "append", content: init.instructions } } : {}),
+ ...(init.config.model ? { model: init.config.model } : {}),
+ ...(init.config.reasoningEffort ? { reasoningEffort: init.config.reasoningEffort } : {}),
+ };
+ session = init.sessionId
+ ? await client.resumeSession(init.sessionId, { ...config, allowTranscriptRecovery: false, continuePendingWork: true })
+ : await client.createSession({ ...config, trustWorkingDirectory: "session" });
+ if (typeof session.sessionId !== "string" || (init.sessionId && session.sessionId !== init.sessionId)) {
+ throw Object.assign(new Error("Copilot did not restore the requested session"), { code: "reset_required" });
+ }
+ if (typeof session.send !== "function" || typeof session.on !== "function") throw new Error("Copilot SDK lacks persistent input observations");
+ } catch (error) {
+ await close();
+ if (init.sessionId && /(?:session|conversation|history).*(?:not found|missing|unknown)|(?:not found|missing|unknown).*(?:session|conversation|history)/i.test(String(error))) {
+ throw Object.assign(new Error("Copilot session history is missing"), { code: "reset_required" });
+ }
+ throw error;
+ }
+ const finish = (root: Root) => {
+ if (closed || active !== root || root.inFlight || !root.idle || root.pending.size || (!root.failed && !root.observed.size && !root.refusals.size)) return;
+ active = undefined;
+ for (const [callId, name] of tools) emit({ kind: "tool_output", callId, name });
+ tools.clear();
+ emit({ kind: "turn_end", sessionId: session.sessionId, turnOwner: root.owner, outcome: root.aborted ? "interrupted" : root.failed ? "failed" : "success" });
+ };
+ const refuseInput = (root: Root, id: string, message: string, evidence: "explicitly_rejected" | "unknown" = "explicitly_rejected") => {
+ root.refusals.set(id, { message, evidence });
+ root.pending.delete(id);
+ const inputs = root.inputs.get(id);
+ if (!inputs) return;
+ root.inputs.delete(id);
+ if (id === root.rootInputId) root.failed = true;
+ emit({ kind: "input_returned", inputs, evidence, reason: message, retryable: false });
+ };
+ session.on((event: any) => {
+ const root = active;
+ if (closed || !root) return;
+ if (event.agentId || event.data?.agentId || event.data?.parentToolCallId) {
+ emit({ kind: "internal_progress", source: "copilot", itemType: event.type, attribution: { scope: "child", agentId: event.agentId ?? event.data?.agentId, parentCallId: event.data?.parentToolCallId } });
+ return;
+ }
+ const data = event.data ?? {};
+ if (event.type === "session.model_change" && typeof data.newModel === "string") emit({ kind: "configuration_observed", observation: { evidence: "observed", effective: "current", model: data.newModel, ...(typeof data.reasoningEffort === "string" || data.reasoningEffort === null ? { reasoningEffort: data.reasoningEffort } : {}) } });
+ if (event.type === "user.message" && typeof data.messageId === "string") {
+ root.observed.add(data.messageId);
+ root.pending.delete(data.messageId);
+ const inputs = root.inputs.get(data.messageId);
+ if (inputs) emit({ kind: "input_observed", inputs, evidence: "user_message" });
+ } else if (event.type === "assistant.message_delta" && typeof data.deltaContent === "string") emit({ kind: "assistant_message_delta", text: data.deltaContent });
+ else if (event.type === "assistant.reasoning_delta" && typeof data.deltaContent === "string") emit({ kind: "assistant_reasoning_delta", text: data.deltaContent });
+ else if (event.type === "tool.execution_start" && typeof data.toolCallId === "string") {
+ const name = data.toolName ?? "unknown_tool";
+ tools.set(data.toolCallId, name);
+ emit({ kind: "tool_call", callId: data.toolCallId, name, input: data.arguments ?? {} });
+ } else if (event.type === "tool.execution_complete" && tools.has(data.toolCallId)) {
+ emit({ kind: "tool_output", callId: data.toolCallId, name: tools.get(data.toolCallId)!, outcome: data.success === true ? "success" : data.success === false ? "failed" : "unknown", output: data.result });
+ tools.delete(data.toolCallId);
+ } else if (event.type === "session.warning" && data.warningType === "policy_blocked" && typeof data.originatingMessageId === "string") {
+ refuseInput(root, data.originatingMessageId, data.message ?? "Copilot policy blocked an input");
+ } else if (event.type === "session.error" && data.eligibleForAutoSwitch === true) {
+ emit({ kind: "runtime_diagnostic", severity: "warning", source: "copilot", message: data.message ?? "Copilot is switching models after a rate limit" });
+ } else if (event.type === "session.error" && typeof data.originatingMessageId === "string") {
+ refuseInput(root, data.originatingMessageId, data.message ?? "Copilot reported an input error", "unknown");
+ } else if (event.type === "session.error") {
+ root.failed = true;
+ emit({ kind: "error", code: "copilot_run_failed", message: data.message ?? "Copilot reported an execution error" });
+ } else if (event.type === "assistant.turn_start" && typeof data.turnId === "string") emit({ kind: "turn_owner", receipt: root.owner, nativeTurnId: data.turnId });
+ else if (event.type === "session.idle" && data.mode !== "autopilot") {
+ root.idle = true;
+ root.aborted ||= data.aborted === true;
+ if (root.failed || root.aborted) {
+ for (const id of root.pending) {
+ const inputs = root.inputs.get(id);
+ if (inputs) emit({ kind: "input_returned", inputs, evidence: "unknown", reason: "Copilot ended before confirming input delivery", retryable: false });
+ }
+ root.pending.clear();
+ }
+ } else if (event.type === "assistant.usage") {
+ const metric = (value: unknown): number | null => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
+ emit({ kind: "telemetry", name: "token_usage", source: "copilot_assistant_usage", usage: {
+ input: metric(data.inputTokens), output: metric(data.outputTokens), cache: metric(data.cacheReadTokens) !== null && metric(data.cacheWriteTokens) !== null ? data.cacheReadTokens + data.cacheWriteTokens : null,
+ } });
+ }
+ finish(root);
+ });
+ return {
+ sessionId: session.sessionId,
+ acquisition: { status: init.sessionId ? "resumed" : "created", evidence: "native_api" },
+ async send(input: LaneSendInput) {
+ if (closed) return { ok: false, reason: "closed" };
+ if ((input.mode === "idle" && active) || (input.mode === "busy" && !active)) return { ok: false, reason: "runtime_busy" };
+ const root: Root = active ?? { owner: input.terminalOwner!, inFlight: 0, pending: new Set(), observed: new Set(), inputs: new Map(), refusals: new Map(), idle: false, failed: false, aborted: false };
+ if (!root.owner) return { ok: false, reason: "missing_terminal_owner" };
+ active = root;
+ root.inFlight++;
+ root.idle = false;
+ try {
+ const id = await session.send({ prompt: input.text, mode: input.mode === "busy" ? "immediate" : "enqueue" });
+ if (typeof id !== "string" || !id) throw new Error("Copilot did not return a native input identity");
+ if (input.mode === "idle") root.rootInputId = id;
+ root.inputs.set(id, input.inputs ?? []);
+ if (root.refusals.has(id)) {
+ const refusal = root.refusals.get(id)!;
+ refuseInput(root, id, refusal.message, refusal.evidence);
+ }
+ else if (root.observed.has(id)) emit({ kind: "input_observed", inputs: input.inputs ?? [], evidence: "user_message" });
+ else root.pending.add(id);
+ return { ok: true, acceptedAs: input.mode === "busy" ? "steer" : "prompt", receipt: root.owner };
+ } catch (error) {
+ if (input.mode === "idle" && active === root) active = undefined;
+ throw error;
+ } finally { root.inFlight--; finish(root); }
+ },
+ async interrupt() { if (!active) return false; active.aborted = true; await session.abort(); return true; },
+ close,
+ };
+}
diff --git a/src/daemon/agent-driver/src/adapters/cursor-sdk/worker.test.ts b/src/daemon/agent-driver/src/adapters/cursor-sdk/worker.test.ts
new file mode 100644
index 000000000..718702bee
--- /dev/null
+++ b/src/daemon/agent-driver/src/adapters/cursor-sdk/worker.test.ts
@@ -0,0 +1,158 @@
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, onTestFailed, vi } from "vitest";
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+import type { AgentEvent, BuiltinBackendSpecs, RawOutputEvent } from "../../contract.js";
+import { createAgentDriverSdkWithRegistry } from "../../sdk.js";
+import { capabilitiesFor, createAgentDriverRegistry } from "../../registry.js";
+import { createDefaultAgentDriverHost } from "../../host/default-host.js";
+import { buildSdkWorkerArtifact } from "../../testing/sdk-worker-artifact.spec.js";
+import { pathToFileURL } from "node:url";
+import { cursorSdkWorker } from "./worker.js";
+
+let artifact: Awaited<ReturnType<typeof buildSdkWorkerArtifact>>;
+beforeAll(async () => { artifact = await buildSdkWorkerArtifact(); });
+afterAll(() => artifact?.dispose());
+
+const roots: string[] = [];
+const ownedChildren = new Set<number>();
+afterEach(() => {
+ vi.restoreAllMocks();
+ for (const pid of ownedChildren) { try { process.kill(pid, "SIGKILL"); } catch { } }
+ ownedChildren.clear();
+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
+});
+
+function setup() {
+ const root = mkdtempSync(join(tmpdir(), "alook cursor sdk "));
+ roots.push(root);
+ const modulePath = join(root, "fixture.mjs");
+ writeFileSync(modulePath, readFileSync(new URL("../../testing/fixtures/sdk/cursor-sdk.mjs", import.meta.url)));
+ const registration = {
+ id: "cursor-sdk" as const, contractVersion: 2 as const, capabilities: capabilitiesFor("cursor-sdk"),
+ createAdapter: () => new artifact.OptionalSdkDriver("cursor-sdk", "fixture-sdk", artifact.cursorSdkWorker, () => ({ entry: modulePath, version: "fixture" })),
+ };
+ const rawOutput: RawOutputEvent[] = [];
+ const host = {
+ ...createDefaultAgentDriverHost({ onRawOutput: (event) => { rawOutput.push(event); } }),
+ rawOutput,
+ };
+ const sdk = createAgentDriverSdkWithRegistry<BuiltinBackendSpecs>({ host, registry: createAgentDriverRegistry([registration]) });
+ const open = (resumeSessionId?: string) => sdk.open({ backend: "cursor-sdk", config: { model: { kind: "named", name: "fixture-model" } }, launch: {
+ workingDirectory: root, instructions: { format: "markdown", content: "fixture instructions" }, launchId: "fixture", resumeSessionId,
+ } });
+ return { root, sdk, open, host };
+}
+
+async function waitUntil(predicate: () => boolean) {
+ for (let attempt = 0; attempt < 500; attempt++) {
+ if (predicate()) return;
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ }
+ throw new Error("Fixture did not reach the expected state");
+}
+
+describe("Cursor SDK public sessions through an owned worker", () => {
+ it("keeps one worker across turns and queues undelivered steering for the next turn", async () => {
+ const f = setup();
+ const opened = await f.open();
+ if (!opened.ok) throw new Error(opened.error.message);
+ const session = opened.session;
+ const events: AgentEvent<BuiltinBackendSpecs, "cursor-sdk">[] = [];
+ const collecting = (async () => { for await (const event of session.events) events.push(event); })();
+ let phase = "first admission";
+ let current = session;
+ const admissionTimings: Record<string, number> = {};
+ const firstStartedAt = Date.now();
+ let resumeStartedAt: number | undefined;
+ onTestFailed(() => {
+ const fixture = Object.fromEntries(["opens", "inputs", "steers", "fixture-history", "release"].map((name) => {
+ const path = join(f.root, name);
+ return [name, existsSync(path) ? readFileSync(path, "utf8") : null];
+ }));
+ console.error(JSON.stringify({ phase, admissionTimings, resumeWaitMs: resumeStartedAt === undefined ? null : Date.now() - resumeStartedAt,
+ snapshot: current.snapshot(), events: events.slice(-20), rawOutput: f.host.rawOutput, fixture }));
+ });
+ try {
+ const receipt = await session.start({ id: "root", kind: "user", text: "first" });
+ admissionTimings.firstMs = Date.now() - firstStartedAt;
+ expect(receipt, JSON.stringify({ receipt, rawOutput: f.host.rawOutput })).toMatchObject({ status: "accepted" });
+ phase = "busy steering refusal";
+ expect(await session.send({ id: "steer", kind: "user", text: "refuse" })).toMatchObject({ status: "queued", reason: "runtime_busy" });
+ writeFileSync(join(f.root, "release"), "go");
+ phase = "queued turn completion";
+ await waitUntil(() => events.some(event => event.type === "turn_completed" && event.commandIds.includes("steer")) && session.snapshot().state === "idle");
+ expect(events).toContainEqual(expect.objectContaining({ type: "turn_completed", result: expect.objectContaining({ outcome: "success" }) }));
+ phase = "next turn admission";
+ await session.send({ id: "next", kind: "user", text: "second" });
+ phase = "next turn completion";
+ await waitUntil(() => session.snapshot().state === "idle");
+ expect(readFileSync(join(f.root, "opens"), "utf8").trim().split("\n")).toHaveLength(1);
+ expect(readFileSync(join(f.root, "inputs"), "utf8")).toBe("first\nrefuse\nsecond\n");
+ } finally {
+ phase = `shutdown after ${phase}`;
+ await session.stop({ reason: "shutdown", forceAfterMs: 100 });
+ phase = "event stream shutdown";
+ await collecting;
+ }
+ phase = "resume open";
+ const resumed = await f.open("fixture-agent");
+ if (!resumed.ok) throw new Error(resumed.error.message);
+ current = resumed.session;
+ try {
+ phase = "resume admission";
+ resumeStartedAt = Date.now();
+ await resumed.session.start({ id: "resume", kind: "user", text: "third" });
+ admissionTimings.resumeMs = Date.now() - resumeStartedAt;
+ console.info(JSON.stringify({ cursorWorkerAdmissionTimings: admissionTimings }));
+ expect(resumed.session.snapshot().diagnostics.metrics.resumeOutcome).toBe("resumed");
+ } finally {
+ phase = `resume shutdown after ${phase}`;
+ await resumed.session.stop({ reason: "shutdown", forceAfterMs: 100 });
+ }
+ });
+
+ it.skipIf(process.platform === "win32")("stops a real detached tool descendant with its exact worker", async () => {
+ const f = setup();
+ const opened = await f.open();
+ if (!opened.ok) throw new Error(opened.error.message);
+ const session = opened.session;
+ try {
+ const receipt = await session.start({ id: "root", kind: "user", text: "spawn" });
+ expect(receipt, JSON.stringify(f.host.rawOutput)).toMatchObject({ status: "accepted" });
+ const pid = Number(readFileSync(join(f.root, "child-pid"), "utf8"));
+ ownedChildren.add(pid);
+ expect(() => process.kill(pid, 0)).not.toThrow();
+ await session.stop({ reason: "shutdown", forceAfterMs: 100 });
+ expect(() => process.kill(pid, 0)).toThrow();
+ ownedChildren.delete(pid);
+ } finally { await session.stop({ reason: "shutdown", forceAfterMs: 100 }); }
+ });
+
+ it("checks installation without opening a native session or reading the model catalog", async () => {
+ const f = setup();
+ expect(await f.sdk.probe({ backend: "cursor-sdk", includeModels: false })).toMatchObject({ status: "healthy", version: "fixture" });
+ expect(await f.sdk.probe({ backend: "cursor-sdk" })).toMatchObject({ status: "healthy", reasoning: { models: [{ id: "fixture-model" }] } });
+ expect(() => readFileSync(join(f.root, "opens"))).toThrow();
+ });
+});
+
+describe("Cursor SDK source probes", () => {
+ beforeEach(() => {
+ vi.spyOn(globalThis, "Function").mockImplementationOnce(function () {
+ return (url: string) => import(url);
+ } as unknown as FunctionConstructor);
+ });
+ it("reads the catalog without creating a native session", async () => {
+ const f = setup();
+ expect(await cursorSdkWorker({ moduleUrl: pathToFileURL(join(f.root, "fixture.mjs")).href, cwd: f.root, config: {}, probe: { includeModels: true } }, () => {})).toMatchObject({ status: "healthy", reasoning: { models: expect.arrayContaining([expect.objectContaining({ id: "fixture-model" })]) } });
+ expect(() => readFileSync(join(f.root, "opens"))).toThrow();
+ });
+
+ it("rejects an SDK missing the persistent local API", async () => {
+ const f = setup();
+ const modulePath = join(f.root, "incompatible.mjs");
+ writeFileSync(modulePath, "export const Agent = {};\n");
+ await expect(cursorSdkWorker({ moduleUrl: pathToFileURL(modulePath).href, cwd: f.root, config: {}, probe: { includeModels: false } }, () => {})).rejects.toMatchObject({ code: "incompatible_configuration" });
+ });
+});
diff --git a/src/daemon/agent-driver/src/adapters/cursor-sdk/worker.ts b/src/daemon/agent-driver/src/adapters/cursor-sdk/worker.ts
new file mode 100644
index 000000000..8d925809b
--- /dev/null
+++ b/src/daemon/agent-driver/src/adapters/cursor-sdk/worker.ts
@@ -0,0 +1,113 @@
+import type { SdkWorkerInit, SdkWorkerSession, SdkWorkerEvent as AdapterEvent } from "../../internal/sdk-worker-api.js";
+import type { LaneSendInput, ProbeResult } from "../../internal/adapter.js";
+
+export async function cursorSdkWorker(init: SdkWorkerInit, emit: (event: AdapterEvent) => void): Promise<SdkWorkerSession | ProbeResult> {
+ const load = new Function("specifier", "return import(specifier)") as (specifier: string) => Promise<any>;
+ const module = await load(init.moduleUrl);
+ const sdk = module.Agent ? module : module.default;
+ if (typeof sdk?.Agent?.create !== "function" || typeof sdk?.Agent?.resume !== "function" || typeof sdk?.Cursor?.models?.list !== "function" || typeof sdk?.JsonlLocalAgentStore !== "function") {
+ throw Object.assign(new Error("Cursor SDK lacks persistent local sessions or its JSONL store"), { code: "incompatible_configuration" });
+ }
+ const catalog = async () => {
+ const items = await sdk.Cursor.models.list();
+ return items.filter((model: any) => typeof model.id === "string").slice(0, 1024).map((model: any) => {
+ const parameter = model.parameters?.find((item: any) => /reason|effort|thinking/i.test(item.id));
+ return {
+ id: model.id, displayName: model.displayName,
+ supportedReasoningEfforts: parameter?.values?.map((item: any) => ({ value: item.value, ...(item.displayName ? { description: item.displayName } : {}) })) ?? [],
+ };
+ });
+ };
+ if (init.probe) return {
+ status: "healthy",
+ ...(init.probe.includeModels ? { reasoning: { updateMode: "unsupported", models: await catalog() } } : {}),
+ };
+ const { join } = await load("node:path");
+ if (!init.sessionId && !init.config.model) throw Object.assign(new Error("Cursor SDK requires an explicit local model selection"), { code: "incompatible_configuration" });
+ let model = init.config.model ? { id: init.config.model } as { id: string; params?: { id: string; value: string }[] } : undefined;
+ if (init.config.reasoningEffort) {
+ const native = (await sdk.Cursor.models.list()).find((entry: any) => entry.id === init.config.model);
+ const parameter = native?.parameters?.find((item: any) => /reason|effort|thinking/i.test(item.id));
+ if (!model || !parameter?.values?.some((item: any) => item.value === init.config.reasoningEffort)) {
+ throw Object.assign(new Error("Cursor SDK did not advertise the selected reasoning effort"), { code: "incompatible_configuration" });
+ }
+ model = { ...model, params: [{ id: parameter.id, value: init.config.reasoningEffort }] };
+ }
+ const options = {
+ ...(model ? { model } : {}),
+ local: { cwd: init.cwd, store: new sdk.JsonlLocalAgentStore(join(init.cwd, ".alook", "cursor-sdk")), settingSources: ["project"], sandboxOptions: { enabled: false } },
+ };
+ let agent: any;
+ try { agent = init.sessionId ? await sdk.Agent.resume(init.sessionId, options) : await sdk.Agent.create(options); }
+ catch (error) {
+ if (init.sessionId && (error as Error)?.name === "AgentNotFoundError") throw Object.assign(new Error("Cursor SDK session history is missing"), { code: "reset_required" });
+ throw error;
+ }
+ if (typeof agent.agentId !== "string" || (init.sessionId && agent.agentId !== init.sessionId)) {
+ await agent.close();
+ throw Object.assign(new Error("Cursor SDK did not restore the requested agent"), { code: "reset_required" });
+ }
+ if (typeof agent.model?.id === "string") emit({ kind: "configuration_observed", observation: { evidence: "observed", effective: "current", model: agent.model.id } });
+ let active: any;
+ let closed = false;
+ return {
+ sessionId: agent.agentId,
+ acquisition: { status: init.sessionId ? "resumed" : "created", evidence: "native_api" },
+ async send(input: LaneSendInput) {
+ if (closed) return { ok: false, reason: "closed" };
+ const receipt = input.terminalOwner ?? active?.id;
+ if (input.mode === "busy") {
+ if (!active || typeof active.steer !== "function") return { ok: false, reason: "runtime_busy" };
+ const outcome = await active.steer(input.text);
+ return outcome === "complete_delivered"
+ ? { ok: true, acceptedAs: "steer", receipt }
+ : { ok: false, reason: "runtime_busy", error: "Cursor SDK returned the input for follow-up delivery" };
+ }
+ if (active) return { ok: false, reason: "runtime_busy" };
+ let textSeen = false;
+ let terminal = false;
+ const tools = new Map<string, string>();
+ const run = await agent.send(input.text, { onDelta({ update }: { update: any }) {
+ if (closed || terminal) return;
+ if (update.type === "text-delta" && typeof update.text === "string") {
+ textSeen = true; emit({ kind: "assistant_message_delta", text: update.text });
+ } else if (update.type === "thinking-delta" && typeof update.text === "string") emit({ kind: "assistant_reasoning_delta", text: update.text });
+ else if (update.type === "tool-call-started" && typeof update.callId === "string") {
+ const name = update.toolCall?.type ?? "unknown_tool";
+ tools.set(update.callId, name);
+ emit({ kind: "tool_call", callId: update.callId, name, input: update.toolCall?.args ?? {} });
+ } else if (update.type === "tool-call-completed" && typeof update.callId === "string" && tools.has(update.callId)) {
+ emit({ kind: "tool_output", callId: update.callId, name: tools.get(update.callId)!, outcome: update.toolCall?.result?.status === "success" ? "success" : update.toolCall?.result?.status === "error" ? "failed" : "unknown", output: update.toolCall?.result });
+ tools.delete(update.callId);
+ }
+ } });
+ active = run;
+ const owner = input.terminalOwner ?? run.id;
+ emit({ kind: "turn_owner", receipt: owner, nativeTurnId: run.id });
+ void Promise.resolve().then(() => run.wait()).then(async (result: any) => {
+ if (closed || active !== run) return;
+ terminal = true; active = undefined;
+ if (!textSeen && typeof result.result === "string") emit({ kind: "assistant_message_completed", text: result.result });
+ if (result.usage) {
+ const metric = (value: unknown): number | null => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
+ const read = metric(result.usage.cacheReadTokens);
+ const write = metric(result.usage.cacheWriteTokens);
+ emit({ kind: "telemetry", name: "token_usage", source: "cursor_sdk_run", usage: {
+ input: metric(result.usage.inputTokens), output: metric(result.usage.outputTokens),
+ cache: read !== null && write !== null ? read + write : null,
+ } });
+ }
+ if (result.status === "error") emit({ kind: "error", code: "cursor_sdk_run_failed", message: result.error?.message ?? "Cursor SDK run failed" });
+ emit({ kind: "turn_end", sessionId: agent.agentId, turnOwner: owner, outcome: result.status === "cancelled" ? "interrupted" : result.status === "error" ? "failed" : result.status === "finished" ? "success" : "unknown" });
+ }).catch((error: unknown) => {
+ if (closed || active !== run) return;
+ terminal = true; active = undefined;
+ emit({ kind: "error", message: error instanceof Error ? error.message : "Cursor SDK run failed" });
+ emit({ kind: "turn_end", sessionId: agent.agentId, turnOwner: owner, outcome: "failed" });
+ });
+ return { ok: true, acceptedAs: "prompt", receipt: owner };
+ },
+ async interrupt() { if (!active) return false; await active.cancel(); return true; },
+ async close() { closed = true; if (active) await active.cancel(); await agent.close(); },
+ };
+}
diff --git a/src/daemon/agent-driver/src/adapters/cursor/acp-lane.ts b/src/daemon/agent-driver/src/adapters/cursor/acp-lane.ts
index ce3fd07f1..1e4236cfd 100644
--- a/src/daemon/agent-driver/src/adapters/cursor/acp-lane.ts
+++ b/src/daemon/agent-driver/src/adapters/cursor/acp-lane.ts
@@ -175,7 +175,7 @@ export class CursorAcpLane implements RuntimeLane {
if (!sessionId) throw new Error("Cursor ACP handshake completed without a session id");
this.processActivated = true;
this.ready = true;
- this.events.emit("runtime_event", { kind: "session_init", sessionId } satisfies AdapterEvent);
+ this.events.emit("runtime_event", { kind: "session_init", sessionId, acquisition: { status: input.sessionId ? "resumed" : "created", evidence: "native_api" } } satisfies AdapterEvent);
return this.admitPrompt(input.text);
} catch (error) {
// LogicalAgentSession owns failed-start settlement. Do not let the child
@@ -299,9 +299,12 @@ export class CursorAcpLane implements RuntimeLane {
private async configureModel(session: JsonRecord, ctx: AdapterLaunchContext): Promise<void> {
const requestedModel = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig).model;
- if (!requestedModel) return;
const configOptions = Array.isArray(session.configOptions) ? session.configOptions : [];
const modelConfig = configOptions.map(record).find((option) => option?.id === "model") ?? null;
+ if (!requestedModel) {
+ if (typeof modelConfig?.currentValue === "string") this.events.emit("runtime_event", { kind: "configuration_observed", observation: { evidence: "observed", effective: "current", model: modelConfig.currentValue } } satisfies AdapterEvent);
+ return;
+ }
if (!modelConfig) {
throw new CursorAcpIncompatibleError("Installed Cursor ACP does not support model configuration");
}
@@ -325,6 +328,7 @@ export class CursorAcpLane implements RuntimeLane {
if (confirmedModel?.currentValue !== match.value) {
throw new CursorAcpIncompatibleError("Cursor ACP did not confirm the exact configured model");
}
+ this.events.emit("runtime_event", { kind: "configuration_observed", observation: { evidence: "observed", effective: "current", model: confirmedModel.currentValue } } satisfies AdapterEvent);
}
private admitPrompt(text: string, delivery: "prompt" | "steer" = "prompt"): LaneAdmission {
@@ -385,7 +389,8 @@ export class CursorAcpLane implements RuntimeLane {
kind: "turn_end",
sessionId: this.sessionId ?? undefined,
turnOwner: terminalOwner,
- ...(result.stopReason === "cancelled" ? { outcome: "interrupted" as const } : {}),
+ outcome: result.stopReason === "cancelled" ? "interrupted" : result.stopReason === "end_turn" ? "success" : "failed",
+ stopReason: result.stopReason,
} satisfies AdapterEvent);
}
@@ -404,6 +409,7 @@ export class CursorAcpLane implements RuntimeLane {
kind: "turn_end",
sessionId: this.sessionId ?? undefined,
turnOwner: terminalOwner,
+ outcome: "failed",
} satisfies AdapterEvent);
}
@@ -674,6 +680,7 @@ export class CursorAcpLane implements RuntimeLane {
this.toolCalls.set(update.toolCallId, null);
this.events.emit("runtime_event", {
kind: "tool_output", callId: update.toolCallId, name: update.title,
+ outcome: update.status === "failed" ? "failed" : "success", output: update.rawOutput,
} satisfies AdapterEvent);
}
return;
@@ -689,6 +696,7 @@ export class CursorAcpLane implements RuntimeLane {
this.events.emit("runtime_event", {
kind: "tool_output",
callId: update.toolCallId,
+ outcome: update.status === "failed" ? "failed" : "success", output: update.rawOutput,
name: typeof update.title === "string" ? update.title : name,
} satisfies AdapterEvent);
}
diff --git a/src/daemon/agent-driver/src/adapters/cursor/index.test.ts b/src/daemon/agent-driver/src/adapters/cursor/index.test.ts
index a1eaed6c0..b04005e03 100644
--- a/src/daemon/agent-driver/src/adapters/cursor/index.test.ts
+++ b/src/daemon/agent-driver/src/adapters/cursor/index.test.ts
@@ -282,7 +282,7 @@ describe("CursorDriver persistent ACP transport", () => {
sessionId: "cursor-acp-session",
prompt: [{ type: "text", text: "busy" }],
});
- expect(events).toEqual([{ kind: "session_init", sessionId: "cursor-acp-session" }]);
+ expect(events).toEqual([{ kind: "session_init", sessionId: "cursor-acp-session", acquisition: { status: "created", evidence: "native_api" } }]);
});
it("keeps one root terminal owner across repeated steers and ignores every old response shape", async () => {
@@ -329,7 +329,7 @@ describe("CursorDriver persistent ACP transport", () => {
},
},
})}\n`);
- expect(events).toContainEqual({ kind: "tool_output", callId: "current-tool", name: "Current tool" });
+ expect(events).toContainEqual({ kind: "tool_output", callId: "current-tool", name: "Current tool", outcome: "success" });
completePrompt(process, server.prompts[3]!, "cancelled");
await settle();
@@ -338,6 +338,7 @@ describe("CursorDriver persistent ACP transport", () => {
sessionId: "cursor-acp-session",
turnOwner: "cursor:acp:4",
outcome: "interrupted",
+ stopReason: "cancelled",
}]);
completePrompt(process, server.prompts[0]!);
@@ -383,9 +384,9 @@ describe("CursorDriver persistent ACP transport", () => {
});
expect(events.filter((event) => event.kind === "turn_end")).toEqual([{
kind: "turn_end",
+ stopReason: "end_turn",
sessionId: "cursor-acp-session",
- turnOwner: "cursor:acp:4",
- }]);
+ turnOwner: "cursor:acp:4", outcome: "success" }]);
completePrompt(spawned[0]!, server.prompts[0]!);
await settle();
expect(events.filter((event) => event.kind === "turn_end")).toHaveLength(1);
@@ -424,15 +425,15 @@ describe("CursorDriver persistent ACP transport", () => {
},
},
})}\n`);
- expect(events).toContainEqual({ kind: "tool_output", callId: "root-tool", name: "Root tool" });
+ expect(events).toContainEqual({ kind: "tool_output", callId: "root-tool", name: "Root tool", outcome: "success" });
completePrompt(process, server.prompts[0]!);
await settle();
expect(events.filter((event) => event.kind === "turn_end")).toEqual([{
kind: "turn_end",
+ stopReason: "end_turn",
sessionId: "cursor-acp-session",
- turnOwner: "cursor:acp:4",
- }]);
+ turnOwner: "cursor:acp:4", outcome: "success" }]);
});
it("lets only the latest prompt RPC error fail the root turn", async () => {
@@ -453,8 +454,7 @@ describe("CursorDriver persistent ACP transport", () => {
expect(events.filter((event) => event.kind === "turn_end")).toEqual([{
kind: "turn_end",
sessionId: "cursor-acp-session",
- turnOwner: "cursor:acp:4",
- }]);
+ turnOwner: "cursor:acp:4", outcome: "failed" }]);
fail(process, server.prompts[0]!, "old failed later");
await settle();
@@ -1349,7 +1349,7 @@ describe("CursorDriver persistent ACP transport", () => {
expect(events).toContainEqual({ kind: "assistant_message_delta", text: "hello" });
expect(events).toContainEqual({ kind: "assistant_reasoning_delta", text: "thinking" });
expect(events).toContainEqual({ kind: "tool_call", callId: "tool-1", name: "Read", input: { path: "README.md" } });
- expect(events).toContainEqual({ kind: "tool_output", callId: "tool-1", name: "Read" });
+ expect(events).toContainEqual({ kind: "tool_output", callId: "tool-1", name: "Read", outcome: "success" });
expect(events).toContainEqual({ kind: "internal_progress", source: "cursor.acp", itemType: "plan" });
expect(events).toContainEqual(expect.objectContaining({
kind: "runtime_diagnostic",
diff --git a/src/daemon/agent-driver/src/adapters/grok/acp-lane.test.ts b/src/daemon/agent-driver/src/adapters/grok/acp-lane.test.ts
index 7c87b024b..fd4c49761 100644
--- a/src/daemon/agent-driver/src/adapters/grok/acp-lane.test.ts
+++ b/src/daemon/agent-driver/src/adapters/grok/acp-lane.test.ts
@@ -272,15 +272,15 @@ describe("Grok ACP persistent lane", () => {
{ kind: "assistant_message_delta", text: "answer" },
{ kind: "internal_progress", source: "grok.acp", itemType: "plan" },
{ kind: "tool_call", callId: "tool-1", name: "Read", input: { path: "README.md" } },
- { kind: "tool_output", callId: "tool-1", name: "Read" },
+ { kind: "tool_output", callId: "tool-1", name: "Read", outcome: "success" },
]));
respond(server.process, server.prompts[0]!, { stopReason: "end_turn" });
expect(events.filter((event) => event.kind === "turn_end")).toEqual([{
kind: "turn_end",
+ stopReason: "end_turn",
sessionId: "grok-session",
- turnOwner: "root-owner",
- }]);
+ turnOwner: "root-owner", outcome: "success" }]);
});
it("loads the exact session, gates replay, and only the matching prompt response terminates", async () => {
@@ -547,7 +547,7 @@ describe("Grok ACP persistent lane", () => {
status: "failed",
error: { code: "unsupported_reasoning_effort" },
});
- await expect(lane.updateSettings({ reasoningEffort: "low" })).resolves.toEqual({ status: "applied" });
+ await expect(lane.updateSettings({ reasoningEffort: "low" })).resolves.toEqual({ status: "acknowledged", effective: "next_turn" });
expect(server.messages.at(-1)).toMatchObject({
method: "session/set_model",
params: { sessionId: "grok-session", modelId: "grok-4.6", _meta: { reasoningEffort: "low" } },
@@ -818,7 +818,7 @@ describe("Grok ACP persistent lane", () => {
server.process.emit("error", new Error("duplicate"));
await vi.waitFor(() => expect(exits).toEqual([{ code: null, signal: null, reason: "runtime_exit" }]));
expect(errors).toEqual([new Error("EIO")]);
- expect(events).toContainEqual({ kind: "tool_output", callId: "open", name: "Open" });
+ expect(events).toContainEqual({ kind: "tool_output", callId: "open", name: "Open", outcome: "unknown" });
await vi.waitFor(() => expect(server.process.kill).toHaveBeenCalledOnce());
const startupMessages: RpcMessage[] = [];
@@ -852,7 +852,7 @@ describe("Grok ACP persistent lane", () => {
});
exited.process.emit("exit", 17, null);
expect(exitedSignals).toEqual([{ code: 17, signal: null, reason: "runtime_exit" }]);
- expect(exitedEvents).toContainEqual({ kind: "tool_output", callId: "exit-tool", name: "Exit" });
+ expect(exitedEvents).toContainEqual({ kind: "tool_output", callId: "exit-tool", name: "Exit", outcome: "unknown" });
});
it("covers stop races, protocol failures, close fallback, and detached cleanup", async () => {
diff --git a/src/daemon/agent-driver/src/adapters/grok/acp-lane.ts b/src/daemon/agent-driver/src/adapters/grok/acp-lane.ts
index be417a3fe..146b2e8cb 100644
--- a/src/daemon/agent-driver/src/adapters/grok/acp-lane.ts
+++ b/src/daemon/agent-driver/src/adapters/grok/acp-lane.ts
@@ -189,7 +189,7 @@ export class GrokAcpLane implements RuntimeLane {
if (!sessionId) throw new Error("Grok ACP handshake completed without a session id");
this.processActivated = true;
this.ready = true;
- this.events.emit("runtime_event", { kind: "session_init", sessionId } satisfies AdapterEvent);
+ this.events.emit("runtime_event", { kind: "session_init", sessionId, acquisition: { status: input.sessionId ? "resumed" : "created", evidence: "native_api" } } satisfies AdapterEvent);
return this.admitPrompt(input.text, input.terminalOwner);
} catch (error) {
this.suppressExit = true;
@@ -246,7 +246,7 @@ export class GrokAcpLane implements RuntimeLane {
try {
await this.setModel(modelId, input.reasoningEffort ?? undefined);
this.currentReasoningEffort = input.reasoningEffort ?? undefined;
- return { status: "applied" };
+ return { status: "acknowledged", effective: "next_turn" };
} catch {
return { status: "failed", error: settingsError("protocol", "settings_update_failed", "Grok rejected the settings update", true) };
}
@@ -451,7 +451,8 @@ export class GrokAcpLane implements RuntimeLane {
kind: "turn_end",
sessionId: this.sessionId ?? undefined,
turnOwner: terminalOwner,
- ...(result.stopReason === "cancelled" ? { outcome: "interrupted" as const } : {}),
+ outcome: result.stopReason === "cancelled" ? "interrupted" : result.stopReason === "end_turn" ? "success" : "failed",
+ stopReason: result.stopReason,
} satisfies AdapterEvent);
void this.refreshBilling();
}
@@ -471,6 +472,7 @@ export class GrokAcpLane implements RuntimeLane {
kind: "turn_end",
sessionId: this.sessionId ?? undefined,
turnOwner: terminalOwner,
+ outcome: "failed",
} satisfies AdapterEvent);
void this.refreshBilling();
}
@@ -735,6 +737,7 @@ export class GrokAcpLane implements RuntimeLane {
this.events.emit("runtime_event", {
kind: "tool_output",
callId: update.toolCallId,
+ outcome: update.status === "failed" ? "failed" : "success", output: update.rawOutput,
name: typeof update.title === "string" ? update.title : name,
} satisfies AdapterEvent);
}
@@ -815,7 +818,7 @@ export class GrokAcpLane implements RuntimeLane {
private finishOpenTools(): void {
for (const [callId, name] of this.openToolCalls) {
- this.events.emit("runtime_event", { kind: "tool_output", callId, name } satisfies AdapterEvent);
+ this.events.emit("runtime_event", { kind: "tool_output", callId, name, outcome: "unknown" } satisfies AdapterEvent);
}
this.openToolCalls.clear();
}
diff --git a/src/daemon/agent-driver/src/adapters/opencode/service-lane.test.ts b/src/daemon/agent-driver/src/adapters/opencode/service-lane.test.ts
index 6f1616c31..4fc1a1017 100644
--- a/src/daemon/agent-driver/src/adapters/opencode/service-lane.test.ts
+++ b/src/daemon/agent-driver/src/adapters/opencode/service-lane.test.ts
@@ -1158,9 +1158,9 @@ describe("OpenCodeServiceLane authenticated persistent protocol", () => {
await waitForTurn(runtime, 1);
expect(runtime).toContainEqual({ kind: "internal_progress", source: "opencode.service", itemType: "step_started" });
expect(runtime).toContainEqual({ kind: "assistant_reasoning_completed", text: "considering" });
- expect(runtime).toContainEqual({ kind: "tool_call", name: "Read", input: { path: "README.md" } });
- expect(runtime).toContainEqual({ kind: "tool_output", name: "Read" });
- expect(runtime).toContainEqual({ kind: "tool_output", name: "OpenCode tool" });
+ expect(runtime).toContainEqual({ kind: "tool_call", callId: "call_1", name: "Read", input: { path: "README.md" } });
+ expect(runtime).toContainEqual({ kind: "tool_output", callId: "call_1", name: "Read", outcome: "success" });
+ expect(runtime).toContainEqual({ kind: "tool_output", callId: "call_unknown", name: "OpenCode tool", outcome: "failed" });
expect(runtime).toContainEqual({ kind: "compaction_started" });
expect(runtime).toContainEqual({ kind: "compaction_finished" });
expect(runtime).toContainEqual({
diff --git a/src/daemon/agent-driver/src/adapters/opencode/service-lane.ts b/src/daemon/agent-driver/src/adapters/opencode/service-lane.ts
index 28f9acbfb..2d9d3a479 100644
--- a/src/daemon/agent-driver/src/adapters/opencode/service-lane.ts
+++ b/src/daemon/agent-driver/src/adapters/opencode/service-lane.ts
@@ -245,6 +245,7 @@ export class OpenCodeServiceLane implements RuntimeLane {
this.events.emit("runtime_event", {
kind: "session_init",
sessionId: this.sessionId,
+ acquisition: { status: input.sessionId ?? this.ctx.config.sessionId ? "resumed" : "created", evidence: "native_api" },
} satisfies AdapterEvent);
const admission = await this.beginRoot(input);
this.assertStartupIdentity(startupIdentity);
@@ -844,7 +845,7 @@ export class OpenCodeServiceLane implements RuntimeLane {
if (typeof data.callID === "string") {
const name = typeof data.tool === "string" ? data.tool : "OpenCode tool";
this.toolNames.set(data.callID, name);
- this.events.emit("runtime_event", { kind: "tool_call", name, input: data.input } satisfies AdapterEvent);
+ this.events.emit("runtime_event", { kind: "tool_call", callId: data.callID, name, input: data.input } satisfies AdapterEvent);
}
break;
case "session.next.tool.success":
@@ -852,7 +853,7 @@ export class OpenCodeServiceLane implements RuntimeLane {
if (typeof data.callID === "string") {
const name = this.toolNames.get(data.callID) ?? "OpenCode tool";
this.toolNames.delete(data.callID);
- this.events.emit("runtime_event", { kind: "tool_output", name } satisfies AdapterEvent);
+ this.events.emit("runtime_event", { kind: "tool_output", callId: data.callID, name, outcome: event.type === "session.next.tool.failed" ? "failed" : "success", output: data.output } satisfies AdapterEvent);
}
break;
case "session.next.compaction.started":
@@ -1190,6 +1191,7 @@ export class OpenCodeServiceLane implements RuntimeLane {
kind: "turn_end",
sessionId: this.sessionId ?? undefined,
turnOwner: root.receipt,
+ outcome: success ? "success" : "failed",
} satisfies AdapterEvent);
}
diff --git a/src/daemon/agent-driver/src/adapters/opencode/v2-service-lane.test.ts b/src/daemon/agent-driver/src/adapters/opencode/v2-service-lane.test.ts
index d6c820943..2e4fda073 100644
--- a/src/daemon/agent-driver/src/adapters/opencode/v2-service-lane.test.ts
+++ b/src/daemon/agent-driver/src/adapters/opencode/v2-service-lane.test.ts
@@ -267,7 +267,7 @@ describe("OpenCode CLI v2 persisted message authority", () => {
await new Promise((resolve) => setTimeout(resolve, 20));
expect(native.ends).toHaveLength(0);
native.finish();
- await vi.waitFor(() => expect(native.ends).toEqual([{ kind: "turn_end", sessionId: native.id, turnOwner: "msg_root" }]));
+ await vi.waitFor(() => expect(native.ends).toEqual([{ kind: "turn_end", sessionId: native.id, turnOwner: "msg_root" , outcome: "success" }]));
expect(native.errors).toHaveLength(0);
});
@@ -283,7 +283,7 @@ describe("OpenCode CLI v2 persisted message authority", () => {
{ type: "tool", id: "call_two", name: "bash", state: { status: "running", input: { command: "sleep 1" } } },
] });
await vi.waitFor(() => expect(native.events.filter(event => event.kind === "tool_call")).toHaveLength(2));
- expect(native.events.filter(event => event.kind === "tool_output")).toEqual([{ kind: "tool_output", callId: "msg_a:call_one", name: "bash" }]);
+ expect(native.events.filter(event => event.kind === "tool_output")).toEqual([{ kind: "tool_output", callId: "msg_a:call_one", name: "bash", outcome: "success" }]);
native.emit("session.tool.success", { assistantMessageID: "msg_a", id: "call_two", executed: true });
await vi.waitFor(() => expect(native.events.filter(event => event.kind === "tool_output")).toHaveLength(2));
native.finish(); await vi.waitFor(() => expect(native.ends).toHaveLength(1));
diff --git a/src/daemon/agent-driver/src/adapters/opencode/v2-service-lane.ts b/src/daemon/agent-driver/src/adapters/opencode/v2-service-lane.ts
index 3a9ba3ca2..d2bf152cd 100644
--- a/src/daemon/agent-driver/src/adapters/opencode/v2-service-lane.ts
+++ b/src/daemon/agent-driver/src/adapters/opencode/v2-service-lane.ts
@@ -118,7 +118,7 @@ export class OpenCodeV2ServiceLane extends OpenCodeServiceLane {
break;
case "session.tool.success":
case "session.tool.failed": {
- this.finishTool(this.toolKey(data.assistantMessageID, data.id));
+ this.finishTool(this.toolKey(data.assistantMessageID, data.id), event.type === "session.tool.failed" ? "failed" : "success", data.output);
break;
}
case "session.compaction.started":
@@ -298,7 +298,7 @@ export class OpenCodeV2ServiceLane extends OpenCodeServiceLane {
}
this.events.emit("runtime_event", {
kind: "turn_end", sessionId: this.sessionId!, turnOwner: root.receipt,
- ...(idle.outcome === "interrupted" ? { outcome: "interrupted" as const } : {}),
+ outcome: idle.outcome === "interrupted" ? "interrupted" : idle.outcome === "succeeded" ? "success" : "failed",
} satisfies AdapterEvent);
} catch (error) {
if (!current() || this.stopping) return;
@@ -322,13 +322,13 @@ export class OpenCodeV2ServiceLane extends OpenCodeServiceLane {
this.events.emit("runtime_event", { kind: "tool_call", callId: key, name: tool.name, input: data.input } satisfies AdapterEvent);
}
- private finishTool(key: string | undefined): void {
+ private finishTool(key: string | undefined, outcome: "success" | "failed", output?: unknown): void {
if (!key || this.settledTools.has(key)) return;
const tool = this.liveTools.get(key);
if (!tool?.called) return;
this.liveTools.delete(key);
this.settledTools.add(key);
- this.events.emit("runtime_event", { kind: "tool_output", callId: key, name: tool.name } satisfies AdapterEvent);
+ this.events.emit("runtime_event", { kind: "tool_output", callId: key, name: tool.name, outcome, output } satisfies AdapterEvent);
}
private projectTools(message: JsonRecord): void {
@@ -338,7 +338,7 @@ export class OpenCodeV2ServiceLane extends OpenCodeServiceLane {
const state = record(tool?.state);
if (tool?.type !== "tool" || !["running", "completed", "error"].includes(String(state?.status))) continue;
this.projectTool({ assistantMessageID: message.id, id: tool.id, name: tool.name, input: state?.input });
- if (state?.status !== "running") this.finishTool(this.toolKey(message.id, tool.id));
+ if (state?.status !== "running") this.finishTool(this.toolKey(message.id, tool.id), state?.status === "error" ? "failed" : "success", state?.output);
}
}
diff --git a/src/daemon/agent-driver/src/adapters/pi-durable/worker.ts b/src/daemon/agent-driver/src/adapters/pi-durable/worker.ts
new file mode 100644
index 000000000..16e561921
--- /dev/null
+++ b/src/daemon/agent-driver/src/adapters/pi-durable/worker.ts
@@ -0,0 +1,201 @@
+import type { SdkWorkerInit, SdkWorkerSession, SdkWorkerEvent as AdapterEvent } from "../../internal/sdk-worker-api.js";
+import type { LaneSendInput, ProbeResult } from "../../internal/adapter.js";
+
+export async function piDurableWorker(init: SdkWorkerInit, emit: (event: AdapterEvent) => void): Promise<SdkWorkerSession | ProbeResult> {
+ const load = new Function("specifier", "return import(specifier)") as (specifier: string) => Promise<any>;
+ const sdk = await load(init.moduleUrl);
+ if (typeof sdk.Harness?.open !== "function" || typeof sdk.createRegistry !== "function") throw Object.assign(new Error("Pi Durable lacks its Harness contract"), { code: "incompatible_configuration" });
+ const resolver = await load("data:text/javascript,export const resolve = (s,p) => import.meta.resolve(s,p)");
+ const peer = (name: string) => load(resolver.resolve(name, init.moduleUrl));
+ const { DatabaseSync } = await load("node:sqlite");
+ const { getSupportedThinkingLevels } = await peer("@earendil-works/pi-ai/models");
+ const { builtinModels } = await peer("@earendil-works/pi-ai/providers/all");
+ const { InMemoryCredentialStore } = await peer("@earendil-works/pi-ai");
+ const credential = init.config.provider;
+ const credentials = new InMemoryCredentialStore();
+ if (credential?.kind === "builtin" && credential.providerId && credential.apiKey) {
+ await credentials.modify(credential.providerId, async () => ({ type: "api_key", key: credential.apiKey }));
+ }
+ const models = builtinModels({ credentials });
+ if (credential?.kind === "builtin" && !models.getProvider(credential.providerId)) throw Object.assign(new Error("Pi Durable provider is not configured by this adapter"), { code: "incompatible_configuration" });
+ if (init.probe) return { status: "healthy", ...(init.probe.includeModels ? { reasoning: {
+ updateMode: "unsupported", models: models.getModels().slice(0, 1024).map((model: any) => ({
+ id: `${model.provider}/${model.id}`, displayName: model.name,
+ supportedReasoningEfforts: getSupportedThinkingLevels(model).map((value: string) => ({ value })),
+ })),
+ } } : {}) };
+ const { mkdirSync } = await load("node:fs");
+ const { join } = await load("node:path");
+ const directory = join(init.cwd, ".alook", "pi-durable");
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
+ const owner = new DatabaseSync(join(directory, "owner.sqlite"));
+ try { owner.exec("BEGIN EXCLUSIVE"); }
+ catch { owner.close(); throw Object.assign(new Error("Pi Durable storage already has a live driver"), { code: "runtime_busy" }); }
+ const { BACKGROUND_CONTEXT: context } = await peer("@earendil-works/chord/context");
+ const { openNodeSqliteStorage } = await peer("@earendil-works/pi-durable/storage/sqlite/node");
+ const { NodeExecutionEnv } = await peer("@earendil-works/pi-durable/env/node");
+ const { CodingTools } = await peer("@earendil-works/pi-durable/tools");
+ const registry = sdk.createRegistry();
+ registry.install(CodingTools);
+ let harness: any;
+ let conversation: any;
+ let watch: any;
+ let closed = false;
+ let active: { owner: string; root: string; pending: Set<string>; rootResult?: any; interrupted: boolean } | undefined;
+ let view: any;
+ let settling = false;
+ const seenEntries = new Set<number>();
+ const tools = new Map<string, string>();
+ let partialKey = "";
+ let partialText = "";
+ let partialReasoning = "";
+ let compacting = false;
+ const metric = (value: unknown): number | null => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
+ const entry = (value: any) => {
+ if (seenEntries.has(value.id)) return;
+ seenEntries.add(value.id);
+ if (!active) return;
+ for (const message of value.model ?? []) {
+ if (message.role === "assistant") {
+ const text = (message.content ?? []).filter((block: any) => block.type === "text").map((block: any) => block.text).join("");
+ const reasoning = (message.content ?? []).filter((block: any) => block.type === "thinking").map((block: any) => block.thinking).join("");
+ if (text) emit({ kind: "assistant_message_completed", text });
+ if (reasoning) emit({ kind: "assistant_reasoning_completed", text: reasoning });
+ partialText = ""; partialReasoning = "";
+ for (const block of message.content ?? []) {
+ if (block.type === "toolCall" && !tools.has(block.id)) {
+ tools.set(block.id, block.name);
+ emit({ kind: "tool_call", callId: block.id, name: block.name, input: block.arguments });
+ }
+ }
+ if (message.usage) emit({ kind: "telemetry", name: "token_usage", source: "pi_durable_assistant_entry", usage: {
+ input: metric(message.usage.input), output: metric(message.usage.output),
+ cache: metric(message.usage.cacheRead) !== null && metric(message.usage.cacheWrite) !== null ? message.usage.cacheRead + message.usage.cacheWrite : null,
+ } });
+ } else if (message.role === "toolResult" && tools.has(message.toolCallId)) {
+ emit({ kind: "tool_output", callId: message.toolCallId, name: tools.get(message.toolCallId)!, outcome: message.isError ? "failed" : "success", output: message.content });
+ tools.delete(message.toolCallId);
+ }
+ }
+ };
+ const project = (next: any) => {
+ view = next;
+ for (const value of next.entries ?? []) entry(value);
+ if (!active) return;
+ const live = next.docs?.["pi.live"] ?? {};
+ const key = `${live.run?.taskId ?? ""}:${live.generation?.attempt ?? ""}`;
+ if (key !== partialKey) { partialKey = key; partialText = ""; partialReasoning = ""; }
+ const blocks = live.generation?.message?.content ?? [];
+ const text = blocks.filter((block: any) => block.type === "text").map((block: any) => block.text).join("");
+ const reasoning = blocks.filter((block: any) => block.type === "thinking").map((block: any) => block.thinking).join("");
+ if (text.startsWith(partialText) && text.length > partialText.length) emit({ kind: "assistant_message_delta", text: text.slice(partialText.length) });
+ if (reasoning.startsWith(partialReasoning) && reasoning.length > partialReasoning.length) emit({ kind: "assistant_reasoning_delta", text: reasoning.slice(partialReasoning.length) });
+ partialText = text; partialReasoning = reasoning;
+ for (const slot of live.tools ?? []) {
+ if (slot.status !== "running" || tools.has(slot.callId)) continue;
+ tools.set(slot.callId, slot.name);
+ emit({ kind: "tool_call", callId: slot.callId, name: slot.name, input: null });
+ }
+ const nowCompacting = (live.compactions ?? []).some((item: any) => item.blocking);
+ if (nowCompacting !== compacting) { compacting = nowCompacting; emit({ kind: nowCompacting ? "compaction_started" : "compaction_finished" }); }
+ const visible = new Set<number>((next.entries ?? []).map((item: any) => item.id));
+ for (const id of seenEntries) if (!visible.has(id)) seenEntries.delete(id);
+ };
+ const close = async () => {
+ if (closed) return;
+ closed = true;
+ try {
+ await watch?.stop();
+ await harness?.close(context);
+ } finally { try { owner.exec("ROLLBACK"); } finally { owner.close(); } }
+ };
+ try {
+ const storage = await openNodeSqliteStorage(join(directory, "state.sqlite"));
+ harness = await sdk.Harness.open(storage, { models, registry, env: ({ cwd }: { cwd?: string }) => new NodeExecutionEnv({ cwd: cwd ?? init.cwd, shellEnv: process.env }),
+ onReport: (report: any) => { if (!closed) emit({ kind: "runtime_diagnostic", severity: "warning", source: "pi-durable", message: report?.message ?? report?.error?.message ?? "Pi Durable reported a task condition" }); },
+ }, context);
+ if (init.sessionId) {
+ const id = /^[1-9]\d*$/.test(init.sessionId) ? Number(init.sessionId) : NaN;
+ if (!Number.isSafeInteger(id)) throw Object.assign(new Error("Pi Durable conversation id is invalid"), { code: "reset_required" });
+ conversation = await harness.conversation(id, context);
+ if (!conversation) throw Object.assign(new Error("Pi Durable conversation history is missing"), { code: "reset_required" });
+ }
+ const selected = init.config.model;
+ let modelRef: { provider: string; modelId: string } | undefined;
+ if (selected) {
+ const slash = selected.indexOf("/");
+ if (slash < 1) throw Object.assign(new Error("Pi Durable models use provider/model format"), { code: "incompatible_configuration" });
+ modelRef = { provider: selected.slice(0, slash), modelId: selected.slice(slash + 1) };
+ const nativeModel = models.getModel(modelRef.provider, modelRef.modelId);
+ if (!nativeModel || (init.config.reasoningEffort && !getSupportedThinkingLevels(nativeModel).includes(init.config.reasoningEffort))) throw Object.assign(new Error("Pi Durable did not advertise the selected model or effort"), { code: "incompatible_configuration" });
+ } else if (!conversation) throw Object.assign(new Error("Pi Durable requires an explicit model selection"), { code: "incompatible_configuration" });
+ const agent = { cwd: init.cwd, instructions: init.instructions ?? "", ...(modelRef ? { model: modelRef } : {}), ...(init.config.reasoningEffort ? { thinkingLevel: init.config.reasoningEffort } : {}) };
+ if (!conversation) conversation = await harness.createConversation({ ownership: { kind: "ownerless" }, agent }, context);
+ else {
+ const existing = await conversation.agent(context);
+ const snapshot = await conversation.watch(context);
+ const busy = Boolean(snapshot.value.docs?.["pi.live"]?.run);
+ await snapshot.stop();
+ if (busy && (existing.cwd !== agent.cwd || existing.instructions !== agent.instructions || (modelRef && JSON.stringify(existing.model) !== JSON.stringify(modelRef)) || (init.config.reasoningEffort && existing.thinkingLevel !== init.config.reasoningEffort))) {
+ throw Object.assign(new Error("Pi Durable cannot change saved settings while adopting an active run"), { code: "incompatible_configuration" });
+ }
+ if (!busy) await conversation.configure(agent, context);
+ }
+ watch = await conversation.watch(context);
+ view = watch.value;
+ for (const value of view.entries ?? []) seenEntries.add(value.id);
+ watch.start(async (call: any) => { if (call.kind === "value") project(call.value); else emit({ kind: "runtime_diagnostic", severity: "warning", source: "pi-durable", message: "Pi Durable state observation temporarily failed" }); });
+ void watch.closed.then((end: any) => { if (!closed) emit({ kind: "worker_error", code: "pi_durable_watch_ended", message: end?.error?.message ?? "Pi Durable observation ended" }); });
+ harness.resume();
+ } catch (error) { await close(); throw error; }
+ const settleRoot = async () => {
+ if (settling || !active || active.pending.size || !active.rootResult) return;
+ settling = true;
+ const root = active;
+ try {
+ await conversation.waitForIdle(context);
+ if (closed || active !== root || root.pending.size) return;
+ active = undefined;
+ const result = root.rootResult;
+ for (const [callId, name] of tools) emit({ kind: "tool_output", callId, name });
+ tools.clear();
+ const interrupted = root.interrupted || /abort|interrupt/.test(result.reason ?? "");
+ if (result.status !== "done" && !interrupted) emit({ kind: "error", code: "pi_durable_unanswered", message: `Pi Durable could not answer the root input: ${String(result.reason ?? "unknown")}` });
+ emit({ kind: "turn_end", sessionId: String(conversation.id), turnOwner: root.owner, outcome: interrupted ? "interrupted" : result.status === "done" ? "success" : "failed" });
+ } catch (error) { if (!closed) emit({ kind: "worker_error", code: "pi_durable_settlement_failed", message: error instanceof Error ? error.message : "Pi Durable settlement failed" }); }
+ finally { settling = false; }
+ };
+ return {
+ sessionId: String(conversation.id),
+ acquisition: { status: init.sessionId ? "resumed" : "created", evidence: "native_api" },
+ async send(input: LaneSendInput) {
+ if (closed) return { ok: false, reason: "closed" };
+ if (input.mode === "busy" && !active) return { ok: false, reason: "runtime_busy" };
+ if (input.mode === "idle" && active) return { ok: false, reason: "runtime_busy" };
+ const { randomUUID } = await load("node:crypto");
+ const requestId = `alook:${randomUUID()}`;
+ const root: NonNullable<typeof active> = active ?? { owner: input.terminalOwner ?? requestId, root: requestId, pending: new Set<string>(), interrupted: false };
+ root.pending.add(requestId);
+ active = root;
+ let submission: any;
+ try { submission = await conversation.submit({ type: "input", content: input.text, requestId, whenBusy: "steer", ...(input.mode === "busy" ? { whenIdle: "reject" } : {}) }, context); }
+ catch (error) {
+ root.pending.delete(requestId);
+ if (root.root === requestId) active = undefined;
+ if (/ConversationBusy|ConversationIdle/.test((error as Error)?.name ?? "")) return { ok: false, reason: "runtime_busy" };
+ throw error;
+ }
+ project(view);
+ void submission.wait(context).then((result: any) => {
+ if (closed || active !== root) return;
+ root.pending.delete(requestId);
+ if (requestId === root.root) root.rootResult = result;
+ if (result.status === "unanswered") emit({ kind: "input_returned", inputs: input.inputs ?? [], evidence: "unknown", reason: `Pi Durable returned an unanswered input: ${String(result.reason)}`, retryable: false });
+ void settleRoot();
+ }).catch((error: unknown) => { if (!closed) emit({ kind: "worker_error", code: "pi_durable_submission_failed", message: error instanceof Error ? error.message : "Pi Durable submission status failed" }); });
+ return { ok: true, acceptedAs: input.mode === "busy" ? "steer" : "prompt", receipt: root.owner };
+ },
+ async interrupt() { if (!active) return false; active.interrupted = true; await conversation.abort(context, { background: true }); return true; },
+ close,
+ };
+}
diff --git a/src/daemon/agent-driver/src/adapters/pi/index.test.ts b/src/daemon/agent-driver/src/adapters/pi/index.test.ts
index fde79ff94..ec95ad4d3 100644
--- a/src/daemon/agent-driver/src/adapters/pi/index.test.ts
+++ b/src/daemon/agent-driver/src/adapters/pi/index.test.ts
@@ -268,7 +268,7 @@ describe("PiDriver.openLane — does not fire the initial prompt itself", () =>
subscribeCb({ type: "message_update", assistantMessageEvent: { type: "text_delta", delta: "hi" } });
expect(received).toEqual([
- { kind: "session_init", sessionId: "sess_1" },
+ { kind: "session_init", sessionId: "sess_1", acquisition: { status: "created", evidence: "native_api" } },
{ kind: "assistant_message_delta", text: "hi" },
]);
});
@@ -321,7 +321,7 @@ describe("PiDriver persistent RuntimeLane contract", () => {
const beginTurn = vi.spyOn(driver, "beginTurn");
const registry = createAgentDriverRegistry<BuiltinBackendSpecs>([{
id: "pi",
- contractVersion: 1,
+ contractVersion: 2,
capabilities: capabilitiesFor("pi"),
createAdapter: () => driver,
}]);
diff --git a/src/daemon/agent-driver/src/adapters/pi/index.ts b/src/daemon/agent-driver/src/adapters/pi/index.ts
index 8bea7f3e9..400814e13 100644
--- a/src/daemon/agent-driver/src/adapters/pi/index.ts
+++ b/src/daemon/agent-driver/src/adapters/pi/index.ts
@@ -235,9 +235,9 @@ export function mapPiSdkEvent(event: any, sessionId: string, state: PiEventState
case "auto_retry_end":
return [{ kind: "runtime_recovery", stage: "recovered", source: "pi_auto_retry" }];
case "tool_execution_start":
- return [{ kind: "tool_call", name: event.toolName ?? "unknown_tool", input: event.args ?? {} }];
+ return [{ kind: "tool_call", callId: event.toolCallId, name: event.toolName ?? "unknown_tool", input: event.args ?? {} }];
case "tool_execution_end":
- return [{ kind: "tool_output", name: event.toolName ?? "unknown_tool" }];
+ return [{ kind: "tool_output", callId: event.toolCallId, name: event.toolName ?? "unknown_tool", outcome: event.isError === true ? "failed" : event.isError === false ? "success" : "unknown", output: event.result }];
case "compaction_start":
return [{ kind: "compaction_started" }];
case "compaction_end":
@@ -341,7 +341,7 @@ export class PiDriver implements BackendAdapter {
return session.isStreaming;
},
};
- const runtimeSession = new SdkLane(handle, this.sessionId!, { terminalOnPromptSettled: true });
+ const runtimeSession = new SdkLane(handle, this.sessionId!, { terminalOnPromptSettled: true, acquisition: { status: ctx.config.sessionId ? "resumed" : "created", evidence: "native_api" } });
session.subscribe((event: unknown) => {
runtimeSession.emitEvents(mapPiSdkEvent(event, this.sessionId!, state));
});
diff --git a/src/daemon/agent-driver/src/adapters/pi/sessionDeps.test.ts b/src/daemon/agent-driver/src/adapters/pi/sessionDeps.test.ts
index 3c6e0777f..0ee47037a 100644
--- a/src/daemon/agent-driver/src/adapters/pi/sessionDeps.test.ts
+++ b/src/daemon/agent-driver/src/adapters/pi/sessionDeps.test.ts
@@ -273,35 +273,14 @@ describe("createPiSessionDependencies — createAgentSession", () => {
expect(fake.sessionManagerContinueRecent).not.toHaveBeenCalled();
});
- it("no matching file: sessionId + empty session dir → create(cwd, sessionDir, { id })", async () => {
- const sessionDir = mkTmp();
- const fake = fakeSdk({ sessionDir });
+ it.each([false, true])("refuses missing history without creating an empty same-ID session (omitHelper=%s)", async (omitGetDefaultSessionDir) => {
+ const fake = fakeSdk({ sessionDir: mkTmp(), omitGetDefaultSessionDir, agentDir: mkTmp() });
const ctx = baseCtx();
const deps = createPiSessionDependencies(ctx, fake.loader);
-
- await deps.createAgentSession({ cwd: ctx.workingDirectory, sessionId: "brand-new-id", spawnEnv: {} });
-
- expect(fake.sessionManagerCreate).toHaveBeenCalledWith(ctx.workingDirectory, sessionDir, { id: "brand-new-id" });
+ await expect(deps.createAgentSession({ cwd: ctx.workingDirectory, sessionId: "missing", spawnEnv: {} })).rejects.toMatchObject({ code: "reset_required" });
+ expect(fake.sessionManagerCreate).not.toHaveBeenCalled();
expect(fake.sessionManagerOpen).not.toHaveBeenCalled();
- expect(fake.sessionManagerContinueRecent).not.toHaveBeenCalled();
- });
-
- it("resumes without throwing when the SDK barrel omits getDefaultSessionDir (the real vendor shape)", async () => {
- // The vendor package's top-level entry re-exports only `SessionManager`
- // from core/session-manager.js — `getDefaultSessionDir` is NOT exported.
- // Calling it unconditionally threw "is not a function" and broke every
- // Pi resume, so the deps must fall back to deriving the dir themselves.
- const agentDir = mkTmp();
- const fake = fakeSdk({ omitGetDefaultSessionDir: true, agentDir });
- const ctx = baseCtx();
- const deps = createPiSessionDependencies(ctx, fake.loader);
-
- await deps.createAgentSession({ cwd: ctx.workingDirectory, sessionId: "resume-me", spawnEnv: {} });
-
- const encoded = `--${path.resolve(ctx.workingDirectory).replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
- const expectedDir = path.join(agentDir, "sessions", encoded);
- // No rollout file exists there, so it pins the id on a fresh session.
- expect(fake.sessionManagerCreate).toHaveBeenCalledWith(ctx.workingDirectory, expectedDir, { id: "resume-me" });
+ expect(fake.createAgentSession).not.toHaveBeenCalled();
});
it("no sessionId: uses SessionManager.create(cwd) — a fresh session, unchanged from prior behavior", async () => {
diff --git a/src/daemon/agent-driver/src/adapters/pi/sessionDeps.ts b/src/daemon/agent-driver/src/adapters/pi/sessionDeps.ts
index fbd8b4f97..ddd442275 100644
--- a/src/daemon/agent-driver/src/adapters/pi/sessionDeps.ts
+++ b/src/daemon/agent-driver/src/adapters/pi/sessionDeps.ts
@@ -202,9 +202,8 @@ export function createPiSessionDependencies(
if (requestedSessionId) {
const sessionDir = resolvePiSessionDir(sdk, cwd);
const existingFile = findPiSessionFile(sessionDir, requestedSessionId);
- sessionManager = existingFile
- ? sdk.SessionManager.open(existingFile, sessionDir, cwd)
- : sdk.SessionManager.create(cwd, sessionDir, { id: requestedSessionId });
+ if (!existingFile) throw Object.assign(new Error("Pi session history is missing"), { code: "reset_required" });
+ sessionManager = sdk.SessionManager.open(existingFile, sessionDir, cwd);
} else {
sessionManager = sdk.SessionManager.create(cwd);
}
diff --git a/src/daemon/agent-driver/src/adapters/qoder/worker.ts b/src/daemon/agent-driver/src/adapters/qoder/worker.ts
new file mode 100644
index 000000000..a96aae088
--- /dev/null
+++ b/src/daemon/agent-driver/src/adapters/qoder/worker.ts
@@ -0,0 +1,175 @@
+import type { SdkWorkerInit, SdkWorkerSession, SdkWorkerEvent as AdapterEvent } from "../../internal/sdk-worker-api.js";
+import type { LaneSendInput, ProbeResult } from "../../internal/adapter.js";
+
+export async function qoderWorker(init: SdkWorkerInit, emit: (event: AdapterEvent) => void): Promise<SdkWorkerSession | ProbeResult> {
+ const load = new Function("specifier", "return import(specifier)") as (specifier: string) => Promise<any>;
+ const sdk = await load(init.moduleUrl);
+ if (typeof sdk.query !== "function" || typeof sdk.qodercliAuth !== "function" || typeof sdk.shutdownDaemon !== "function" || typeof sdk.startDaemon !== "function") {
+ throw Object.assign(new Error("Qoder SDK lacks its persistent daemon contract"), { code: "incompatible_configuration" });
+ }
+ const { randomUUID } = await load("node:crypto");
+ const sessionId = init.sessionId ?? randomUUID();
+ const queue: any[] = [];
+ let wake: (() => void) | undefined;
+ let closed = false;
+ const stream = async function* () {
+ while (!closed) {
+ const item = queue.shift();
+ if (item) { yield item; continue; }
+ await new Promise<void>((resolve) => { wake = resolve; });
+ }
+ };
+ const token = process.env.QODER_PERSONAL_ACCESS_TOKEN;
+ const service = process.env.QODER_SERVICE_ACCOUNT_KEY;
+ if (service && token) throw Object.assign(new Error("Qoder credentials select two authentication methods"), { code: "incompatible_configuration" });
+ const auth = service ? sdk.serviceAccount(service) : token ? sdk.accessToken(token) : sdk.qodercliAuth();
+ const options: any = {
+ cwd: init.cwd, env: { ...process.env, QODER_EXPOSE_TOKEN_USAGE: "1" }, auth,
+ permissionMode: "bypassPermissions", includePartialMessages: true,
+ ...(init.instructions ? { systemPrompt: { type: "preset", preset: "qodercli", append: init.instructions } } : {}),
+ ...(init.sessionId ? { resume: init.sessionId } : { sessionId }),
+ ...(init.config.model ? { model: init.config.model } : {}),
+ ...(init.config.reasoningEffort ? { extraArgs: { "reasoning-effort": init.config.reasoningEffort } } : {}),
+ ...(init.config.command ? { pathToQoderCLIExecutable: init.config.command, transport: sdk.ProcessTransport.default } : {}),
+ };
+ if (init.probe) {
+ const daemon = await sdk.startDaemon({ auth, env: options.env, ...(init.config.command ? { pathToQoderCLIExecutable: init.config.command, launchMode: "process" } : {}) });
+ try {
+ if (!init.probe.includeModels) return { status: "healthy" };
+ const models = await daemon.getModels();
+ const nativeDefault = models.find((model: any) => model.isDefault === true && typeof model.value === "string");
+ return { status: "healthy", reasoning: { updateMode: "unsupported", ...(nativeDefault ? { defaultModelId: nativeDefault.value } : {}), models: models.filter((model: any) => typeof model.value === "string").slice(0, 1024).map((model: any) => ({
+ id: model.value, displayName: model.displayName,
+ supportedReasoningEfforts: (model.efforts ?? []).map((value: string) => ({ value })),
+ ...(typeof model.defaultEffort === "string" ? { defaultReasoningEffort: model.defaultEffort } : {}),
+ })) } };
+ } finally { await daemon.stop(); }
+ }
+ const query = sdk.query({ prompt: stream(), options });
+ let resolveInit!: () => void;
+ let rejectInit!: (error: unknown) => void;
+ const nativeInit = new Promise<void>((resolve, reject) => { resolveInit = resolve; rejectInit = reject; });
+ void nativeInit.catch(() => {});
+ let active: { owner: string; root: string; pending: Set<string>; inputs: Map<string, { started: boolean; references: NonNullable<LaneSendInput["inputs"]> }>; result?: any } | undefined;
+ let streamed = false;
+ let ready = false;
+ const tools = new Map<string, string>();
+ const metric = (value: unknown): number | null => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
+ const finish = () => {
+ if (!active?.result || active.pending.size) return;
+ const root = active;
+ active = undefined;
+ const result = root.result;
+ if (result.is_error) emit({ kind: "error", code: "qoder_turn_failed", message: result.errors?.join("\n") || result.error_message || "Qoder execution failed" });
+ const usage = result.usage;
+ if (usage) {
+ const read = metric(usage.cache_read_input_tokens);
+ const write = metric(usage.cache_creation_input_tokens);
+ emit({ kind: "telemetry", name: "token_usage", source: "qoder_result", usage: {
+ input: metric(usage.input_tokens), output: metric(usage.output_tokens), cache: read !== null && write !== null ? read + write : null,
+ } });
+ }
+ for (const [callId, name] of tools) emit({ kind: "tool_output", callId, name });
+ tools.clear();
+ emit({ kind: "turn_end", sessionId, turnOwner: root.owner,
+ outcome: /^aborted_/.test(result.terminal_reason ?? "") ? "interrupted" : result.is_error ? "failed" : "success" });
+ };
+ const consuming = (async () => {
+ for await (const frame of query) {
+ if (closed) return;
+ if (frame.parent_tool_use_id) {
+ emit({ kind: "internal_progress", source: "qoder", itemType: frame.type, attribution: { scope: "child", parentCallId: frame.parent_tool_use_id } });
+ continue;
+ }
+ if (frame.session_id && frame.session_id !== sessionId) throw new Error("Qoder reported another session identity");
+ if (frame.type === "system" && frame.subtype === "init") {
+ if (typeof frame.model === "string") emit({ kind: "configuration_observed", observation: { evidence: "observed", effective: "current", model: frame.model } });
+ resolveInit(); continue;
+ }
+ if (!active) continue;
+ if (frame.type === "command_lifecycle") {
+ const input = active.inputs.get(frame.command_uuid);
+ if (!input) continue;
+ if (frame.state === "started") {
+ input.started = true;
+ active.result = undefined;
+ emit({ kind: "input_observed", inputs: input.references, evidence: "native_ack" });
+ } else if (frame.state === "completed" || frame.state === "cancelled" || frame.state === "discarded") {
+ active.pending.delete(frame.command_uuid);
+ if (frame.state !== "completed") {
+ emit({ kind: "input_returned", inputs: input.references, evidence: input.started ? "unknown" : "explicitly_rejected", reason: "Qoder cancelled or discarded an owned input", retryable: !input.started });
+ if (!input.started && !active.pending.size && !active.result) active.result = { terminal_reason: "aborted_queued", is_error: false };
+ }
+ finish();
+ }
+ } else if (frame.type === "stream_event") {
+ const event = frame.event;
+ if (event?.type === "message_start") streamed = false;
+ if (event?.type === "content_block_delta") {
+ if (event.delta?.type === "text_delta") { streamed = true; emit({ kind: "assistant_message_delta", text: event.delta.text }); }
+ else if (event.delta?.type === "thinking_delta") emit({ kind: "assistant_reasoning_delta", text: event.delta.thinking });
+ }
+ } else if (frame.type === "assistant") {
+ for (const block of frame.message?.content ?? []) {
+ if (block.type === "text" && !streamed) emit({ kind: "assistant_message_completed", text: block.text });
+ else if (block.type === "tool_use" && typeof block.id === "string" && !tools.has(block.id)) {
+ tools.set(block.id, block.name);
+ emit({ kind: "tool_call", callId: block.id, name: block.name, input: block.input });
+ }
+ }
+ } else if (frame.type === "user") {
+ for (const block of frame.message?.content ?? []) {
+ if (block.type !== "tool_result" || !tools.has(block.tool_use_id)) continue;
+ emit({ kind: "tool_output", callId: block.tool_use_id, name: tools.get(block.tool_use_id)!, outcome: block.is_error ? "failed" : "success", output: block.content });
+ tools.delete(block.tool_use_id);
+ }
+ } else if (frame.type === "result") {
+ active.result = frame;
+ finish();
+ } else if (frame.type === "system" && frame.subtype === "status" && frame.status === "compacting") emit({ kind: "compaction_started" });
+ }
+ if (!closed) throw new Error("Qoder SDK ended its persistent stream");
+ })();
+ void consuming.catch((error: unknown) => {
+ rejectInit(error);
+ if (!closed && ready) emit({ kind: "worker_error", code: "qoder_stream_failed", message: error instanceof Error ? error.message : "Qoder stream failed" });
+ });
+ const close = async () => {
+ closed = true; wake?.();
+ try { await query.close(); } finally { await sdk.shutdownDaemon(); }
+ };
+ try {
+ await query.initializationResult();
+ await nativeInit;
+ ready = true;
+ } catch (error) {
+ await close();
+ if (init.sessionId && /(?:session|conversation|history).*(?:not found|missing|unknown)|(?:not found|missing|unknown).*(?:session|conversation|history)/i.test(String(error))) {
+ throw Object.assign(new Error("Qoder session history is missing"), { code: "reset_required" });
+ }
+ throw error;
+ }
+ return {
+ sessionId,
+ acquisition: { status: init.sessionId ? "resumed" : "created", evidence: "native_api" },
+ async send(input: LaneSendInput) {
+ if (closed) return { ok: false, reason: "closed" };
+ if (input.mode === "idle" && active) return { ok: false, reason: "runtime_busy" };
+ if (input.mode === "busy" && !active) return { ok: false, reason: "runtime_busy" };
+ const uuid = randomUUID();
+ const owner = input.terminalOwner ?? active?.owner ?? uuid;
+ if (!active) {
+ active = { owner, root: uuid, pending: new Set(), inputs: new Map() };
+ streamed = false;
+ }
+ active.pending.add(uuid);
+ active.inputs.set(uuid, { started: false, references: input.inputs ?? [] });
+ queue.push({ type: "user", uuid, session_id: sessionId, priority: "next", parent_tool_use_id: null,
+ message: { role: "user", content: [{ type: "text", text: input.text }] } });
+ wake?.(); wake = undefined;
+ return { ok: true, acceptedAs: input.mode === "busy" ? "steer" : "prompt", receipt: owner };
+ },
+ async interrupt() { if (!active) return false; await query.interrupt(); return true; },
+ close,
+ };
+}
diff --git a/src/daemon/agent-driver/src/adapters/sdk-workers.native.test.ts b/src/daemon/agent-driver/src/adapters/sdk-workers.native.test.ts
new file mode 100644
index 000000000..7f366b194
--- /dev/null
+++ b/src/daemon/agent-driver/src/adapters/sdk-workers.native.test.ts
@@ -0,0 +1,184 @@
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { createRequire } from "node:module";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
+import type { AgentEvent, AgentSession, BuiltinBackendId, BuiltinBackendSpecs } from "../contract.js";
+import { createAgentDriverSdkWithRegistry } from "../sdk.js";
+import { capabilitiesFor, createAgentDriverRegistry, type AgentBackendRegistrationOf } from "../registry.js";
+import { createFakeAgentDriverHost } from "../testing/fake-host.js";
+import type { SdkWorkerFactory } from "../internal/sdk-worker-api.js";
+
+import { buildSdkWorkerArtifact } from "../testing/sdk-worker-artifact.spec.js";
+
+const nativeRoot = process.env.ALOOK_NATIVE_SDK_ROOT;
+let artifact: Awaited<ReturnType<typeof buildSdkWorkerArtifact>>;
+beforeAll(async () => { if (nativeRoot) artifact = await buildSdkWorkerArtifact(); });
+afterAll(() => artifact?.dispose());
+const roots: string[] = [];
+const sessions: AgentSession<BuiltinBackendSpecs, BuiltinBackendId>[] = [];
+afterEach(async () => {
+ for (const session of sessions.splice(0)) await session.stop({ reason: "shutdown", forceAfterMs: 300 });
+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
+});
+
+async function waitUntil(predicate: () => boolean, label: string): Promise<void> {
+ for (let attempt = 0; attempt < 1000; attempt++) {
+ if (predicate()) return;
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ }
+ throw new Error(`Native SDK fixture timed out: ${label}`);
+}
+
+const entries = [
+ { id: "qoder", packageName: "@qoder-ai/qoder-agent-sdk", factory: "qoderWorker", commandFixture: "qoder-cli.mjs", model: "native-fixture", inputFile: "qoder-inputs" },
+ { id: "copilot", packageName: "@github/copilot-sdk", factory: "copilotWorker", commandFixture: "copilot-cli.mjs", model: "native-fixture", inputFile: "copilot-inputs" },
+ { id: "pi-durable", packageName: "@earendil-works/pi-durable", factory: "piDurableWorker", model: "faux/faux-1", inputFile: "native-requests" },
+] as const;
+
+function setup(entry: (typeof entries)[number]) {
+ if (!nativeRoot) throw new Error("ALOOK_NATIVE_SDK_ROOT must point to the isolated npm prefix");
+ const root = mkdtempSync(join(tmpdir(), `alook-native-${entry.id}-`));
+ roots.push(root);
+ const require = createRequire(join(resolve(nativeRoot), "fixture.cjs"));
+ let modulePath = require.resolve(entry.packageName);
+ let command: string | undefined;
+ if ("commandFixture" in entry) {
+ command = join(root, entry.commandFixture);
+ const source = readFileSync(new URL(`../testing/fixtures/sdk/${entry.commandFixture}`, import.meta.url), "utf8");
+ writeFileSync(command, source.replace("#!/usr/bin/env node", `#!${process.execPath}`), { mode: 0o700 });
+ } else {
+ const directory = mkdtempSync(join(resolve(nativeRoot), "alook-native-model-"));
+ roots.push(directory);
+ modulePath = join(directory, "fixture.mjs");
+ writeFileSync(modulePath, readFileSync(new URL("../testing/fixtures/sdk/pi-harness.mjs", import.meta.url)));
+ }
+ const host = createFakeAgentDriverHost();
+ const factory: SdkWorkerFactory = artifact[entry.factory];
+ const sdk = createAgentDriverSdkWithRegistry<BuiltinBackendSpecs>({ host, registry: createAgentDriverRegistry([{
+ id: entry.id,
+ contractVersion: 2,
+ capabilities: capabilitiesFor(entry.id),
+ createAdapter: () => new artifact.OptionalSdkDriver(entry.id, entry.packageName, factory, () => ({ entry: modulePath }), { kind: "native" }),
+ } as AgentBackendRegistrationOf<BuiltinBackendSpecs>]) });
+ const open = async (resumeSessionId?: string) => {
+ const opened = await sdk.open({ backend: entry.id, config: {
+ model: { kind: "named", name: entry.model },
+ command,
+ provider: { kind: "default" },
+ environment: { QODER_PERSONAL_ACCESS_TOKEN: "fixture-local-token" },
+ }, launch: { workingDirectory: root, instructions: { format: "markdown", content: "Native fixture instructions" }, launchId: "native-test", resumeSessionId } });
+ if (!opened.ok) throw new Error(opened.error.message);
+ sessions.push(opened.session);
+ const events: AgentEvent<BuiltinBackendSpecs, BuiltinBackendId>[] = [];
+ void (async () => { for await (const event of opened.session.events) events.push(event); })();
+ return { session: opened.session, events };
+ };
+ return { root, modulePath, command, open };
+}
+
+describe.skipIf(!nativeRoot || process.platform === "win32").each(entries)("$id with the installed official SDK and a local runtime", (entry) => {
+ it("reuses a persistent context, delivers busy input, resumes and refuses missing history", { timeout: 25_000 }, async () => {
+ const f = setup(entry);
+ const { session, events } = await f.open();
+ expect(await session.start({ id: "first", kind: "user", text: "hold first" })).toMatchObject({ status: "accepted" });
+ const id = session.snapshot().backendSessionId;
+ expect(typeof id).toBe("string");
+ expect(await session.send({ id: "second", kind: "user", text: "second" })).toMatchObject({ status: "accepted", delivery: "steer" });
+ writeFileSync(join(f.root, "release"), "go");
+ await waitUntil(() => session.snapshot().state === "idle", "busy completion");
+ expect(events.filter((event) => event.type === "turn_completed")).toEqual([
+ expect.objectContaining({ commandIds: ["first", "second"], result: expect.objectContaining({ outcome: "success" }) }),
+ ]);
+ const inputs = readFileSync(join(f.root, entry.inputFile), "utf8");
+ expect(inputs.indexOf("hold first")).toBeLessThan(inputs.indexOf("second"));
+ if (entry.id === "copilot") expect(inputs).toContain('"mode":"immediate"');
+ expect(await session.send({ id: "third", kind: "user", text: "third" })).toMatchObject({ status: "accepted" });
+ await waitUntil(() => session.snapshot().state === "idle", "reuse completion");
+ expect(session.snapshot().diagnostics.metrics.physicalOpenCount).toBe(1);
+ await session.stop({ reason: "shutdown", forceAfterMs: 300 });
+ const resumed = await f.open(id);
+ expect(await resumed.session.start({ id: "resume", kind: "user", text: "resumed" })).toMatchObject({ status: "accepted" });
+ await waitUntil(() => resumed.session.snapshot().state === "idle", "resume completion");
+ expect(resumed.session.snapshot().diagnostics.metrics.resumeOutcome).toBe("resumed");
+ await resumed.session.stop({ reason: "shutdown", forceAfterMs: 300 });
+ const missing = await f.open("999999");
+ expect(await missing.session.start({ id: "missing", kind: "user", text: "never sent" })).toMatchObject({ status: "rejected", error: { code: "reset_required" } });
+ expect(readFileSync(join(f.root, entry.inputFile), "utf8")).not.toContain("never sent");
+ });
+
+ it("correlates interruption to the root and keeps the session reusable", { timeout: 20_000 }, async () => {
+ const f = setup(entry);
+ const { session, events } = await f.open();
+ expect(await session.start({ id: "first", kind: "user", text: "hold interrupted" })).toMatchObject({ status: "accepted" });
+ expect(await session.interrupt({ requestId: "interrupt", reason: "fixture" })).toMatchObject({ status: "accepted" });
+ await waitUntil(() => session.snapshot().state === "idle", "interrupted root");
+ expect(events).toContainEqual(expect.objectContaining({ type: "turn_completed", result: expect.objectContaining({ outcome: "interrupted" }) }));
+ writeFileSync(join(f.root, "release"), "go");
+ expect(await session.send({ id: "after", kind: "user", text: "after interrupt" })).toMatchObject({ status: "accepted" });
+ await waitUntil(() => session.snapshot().state === "idle", "next root");
+ expect(events.at(-1)).toMatchObject({ type: "turn_completed", result: { outcome: "success" } });
+ });
+
+ it("reads the native model catalog through the owned protocol worker", { timeout: 15_000 }, async () => {
+ const f = setup(entry);
+ const lane = new artifact.SdkWorkerLane(artifact[entry.factory], { cwd: f.root, modulePath: f.modulePath, config: { command: f.command }, probe: { includeModels: true } }, { ...process.env, QODER_PERSONAL_ACCESS_TOKEN: "fixture-local-token" });
+ try {
+ expect(await lane.probe()).toMatchObject({ status: "healthy", reasoning: { models: expect.arrayContaining([expect.objectContaining({ id: entry.id === "pi-durable" ? expect.any(String) : "native-fixture" })]) } });
+ } finally { await lane.stop({ forceAfterMs: 300 }); }
+ });
+});
+
+
+describe.skipIf(!nativeRoot || process.platform === "win32")("installed Copilot SDK request endings", () => {
+ it("finishes a policy-blocked input without waiting for a user echo, then reuses the session", async () => {
+ const f = setup(entries[1]);
+ const { session, events } = await f.open();
+ expect(await session.start({ id: "blocked", kind: "user", text: "policy blocked" })).toMatchObject({ status: "accepted" });
+ await waitUntil(() => session.snapshot().state === "idle", "policy refusal");
+ expect(events).toContainEqual(expect.objectContaining({ type: "turn_completed", result: expect.objectContaining({ outcome: "failed" }) }));
+ expect(await session.send({ id: "next", kind: "user", text: "allowed" })).toMatchObject({ status: "accepted" });
+ await waitUntil(() => session.snapshot().state === "idle", "after policy refusal");
+ expect(events.at(-1)).toMatchObject({ type: "turn_completed", result: { outcome: "success" } });
+ expect(session.snapshot().diagnostics.metrics.physicalOpenCount).toBe(1);
+ });
+
+ it.each(["blocked extra", "error extra"])("keeps the root healthy when %s arrives before its native send reply", async (text) => {
+ const f = setup(entries[1]);
+ const { session, events } = await f.open();
+ await session.start({ id: "A", kind: "user", text: "hold root" });
+ expect(await session.send({ id: "B", attemptId: "B-1", kind: "user", text })).toMatchObject({ status: "accepted", delivery: "steer" });
+ await waitUntil(() => events.some(event => event.type === "command_returned" && event.input.commandId === "B"), "correlated refusal");
+ expect(session.snapshot().state).toBe("working");
+ expect(events).toContainEqual(expect.objectContaining({ type: "command_returned", input: { commandId: "B", attemptId: "B-1" }, evidence: text === "blocked extra" ? "explicitly_rejected" : "unknown", retryable: false }));
+ writeFileSync(join(f.root, "release"), "go");
+ await waitUntil(() => session.snapshot().state === "idle", "healthy root completion");
+ expect(events).toContainEqual(expect.objectContaining({ type: "turn_completed", commandIds: ["A"], result: expect.objectContaining({ outcome: "success" }) }));
+ });
+
+ it("keeps a recoverable model switch active until native idle and does not fail on unrelated warnings", async () => {
+ const f = setup(entries[1]);
+ const { session, events } = await f.open();
+ expect(await session.start({ id: "switch", kind: "user", text: "hold auto switch" })).toMatchObject({ status: "accepted" });
+ await waitUntil(() => events.some((event) => event.type === "diagnostic" && event.message === "Fixture model switching"), "model-switch diagnostic");
+ expect(session.snapshot().state).toBe("working");
+ expect(events.filter((event) => event.type === "turn_completed")).toEqual([]);
+ writeFileSync(join(f.root, "release"), "go");
+ await waitUntil(() => session.snapshot().state === "idle", "model-switch completion");
+ expect(events.filter((event) => event.type === "turn_completed")).toEqual([
+ expect.objectContaining({ commandIds: ["switch"], result: expect.objectContaining({ outcome: "success" }) }),
+ ]);
+ });
+});
+
+describe.skipIf(!nativeRoot)("installed Cursor SDK API", () => {
+ it("loads persistent local agent APIs without opening a paid native run", async () => {
+ const prefix = resolve(nativeRoot!);
+ const require = createRequire(join(prefix, "fixture.cjs"));
+ const lane = new artifact.SdkWorkerLane(artifact.cursorSdkWorker, {
+ cwd: prefix, modulePath: require.resolve("@cursor/sdk"), config: {}, probe: { includeModels: false },
+ }, { ...process.env });
+ try { expect(await lane.probe()).toEqual({ status: "healthy" }); }
+ finally { await lane.stop({ forceAfterMs: 300 }); }
+ });
+});
diff --git a/src/daemon/agent-driver/src/builtin-config.ts b/src/daemon/agent-driver/src/builtin-config.ts
index 1f033f0be..a8c054c39 100644
--- a/src/daemon/agent-driver/src/builtin-config.ts
+++ b/src/daemon/agent-driver/src/builtin-config.ts
@@ -50,6 +50,12 @@ export function toBuiltinBackendSelection(config: BuiltinRuntimeConfigInput): Bu
};
case "agy":
return { backend: "agy", config: { ...base, reasoningEffort: config.reasoningEffort } };
+ case "qoder":
+ return { backend: "qoder", config: { ...base, reasoningEffort: config.reasoningEffort } };
+ case "copilot":
+ return { backend: "copilot", config: { ...base, reasoningEffort: config.reasoningEffort } };
+ case "cursor-sdk":
+ return { backend: "cursor-sdk", config: { model: config.model, environment: config.envVars, reasoningEffort: config.reasoningEffort } };
case "antigravity":
return { backend: "antigravity", config: { ...base, reasoningEffort: config.reasoningEffort } };
case "cursor":
@@ -59,8 +65,9 @@ export function toBuiltinBackendSelection(config: BuiltinRuntimeConfigInput): Bu
case "opencode":
return { backend: "opencode", config: base };
case "pi":
+ case "pi-durable":
return {
- backend: "pi",
+ backend: config.runtime,
config: {
model: config.model,
environment: config.envVars,
diff --git a/src/daemon/agent-driver/src/contract.ts b/src/daemon/agent-driver/src/contract.ts
index 93e11013c..e9f12da90 100644
--- a/src/daemon/agent-driver/src/contract.ts
+++ b/src/daemon/agent-driver/src/contract.ts
@@ -2,7 +2,7 @@ export type JsonPrimitive = string | number | boolean | null;
export type JsonValue = JsonPrimitive | JsonObject | readonly JsonValue[];
export type JsonObject = { readonly [key: string]: JsonValue };
-export type BuiltinBackendId = "claude" | "codex" | "cursor" | "grok" | "opencode" | "pi" | "antigravity" | "agy";
+export type BuiltinBackendId = "claude" | "codex" | "cursor" | "grok" | "opencode" | "pi" | "antigravity" | "agy" | "qoder" | "copilot" | "cursor-sdk" | "pi-durable";
export type ReasoningEffort =
| "minimal"
| "low"
@@ -18,7 +18,8 @@ export type RuntimeSettingsUpdate = {
};
export type RuntimeSettingsUpdateResult =
- | { readonly status: "applied" }
+ | { readonly status: "applied"; readonly observed: RuntimeSettingsUpdate }
+ | { readonly status: "acknowledged"; readonly effective: "current" | "next_turn" | "unknown" }
| { readonly status: "unsupported"; readonly error?: AgentDriverError }
| { readonly status: "failed"; readonly error: AgentDriverError };
@@ -86,12 +87,16 @@ export interface GrokConfig extends ModelBackendConfig {
readonly reasoningEffort?: ReasoningEffort;
}
export type OpenCodeConfig = ModelBackendConfig;
+export interface QoderConfig extends ModelBackendConfig { readonly reasoningEffort?: ReasoningEffort }
+export interface CopilotConfig extends ModelBackendConfig { readonly reasoningEffort?: ReasoningEffort }
+export interface CursorSdkConfig extends Omit<ModelBackendConfig, "command"> { readonly reasoningEffort?: ReasoningEffort }
export interface PiConfig extends Omit<BaseBackendConfig, "command"> {
readonly model: ModelSelection;
readonly provider: PiProvider;
readonly reasoningEffort?: ReasoningEffort;
}
+export type PiDurableConfig = PiConfig;
export interface BackendCapabilities {
readonly modelSelection: "launchable" | "suggestion_only" | "unsupported";
@@ -129,12 +134,16 @@ export type FixedCapabilities<
export type AntigravityCapabilities = FixedCapabilities<false, true, false, false, true, "next_turn_queue", "persistent">;
export type AgyCapabilities = Omit<AntigravityCapabilities, "interrupt"> & { readonly interrupt: false };
-export type ClaudeCapabilities = FixedCapabilities<true, true, true, true, true, "safe_boundary_queue", "persistent">;
-export type CodexCapabilities = FixedCapabilities<false, true, true, false, true, "safe_boundary_queue", "persistent">;
+export type ClaudeCapabilities = FixedCapabilities<true, true, true, true, true, "steer", "persistent">;
+export type CodexCapabilities = FixedCapabilities<false, true, true, false, true, "steer", "persistent">;
export type CursorCapabilities = FixedCapabilities<false, false, false, false, true, "steer", "persistent">;
export type GrokCapabilities = FixedCapabilities<false, true, false, false, true, "safe_boundary_queue", "persistent">;
export type OpenCodeCapabilities = FixedCapabilities<false, false, false, false, true, "steer", "persistent">;
export type PiCapabilities = FixedCapabilities<true, true, false, false, false, "steer", "persistent">;
+export type QoderCapabilities = FixedCapabilities<false, true, false, false, true, "steer", "persistent">;
+export type CopilotCapabilities = FixedCapabilities<false, true, false, false, true, "steer", "persistent">;
+export type CursorSdkCapabilities = FixedCapabilities<false, true, false, false, false, "steer", "persistent">;
+export type PiDurableCapabilities = PiCapabilities;
export interface BackendExtensionSpec<Input, Output> {
readonly input: Input;
@@ -149,6 +158,10 @@ export interface BackendTypeSpec<Config, Capabilities, Extensions, ExtraEvent> {
}
export interface BuiltinBackendSpecs {
+ readonly qoder: BackendTypeSpec<QoderConfig, QoderCapabilities, {}, never>;
+ readonly copilot: BackendTypeSpec<CopilotConfig, CopilotCapabilities, {}, never>;
+ readonly "cursor-sdk": BackendTypeSpec<CursorSdkConfig, CursorSdkCapabilities, {}, never>;
+ readonly "pi-durable": BackendTypeSpec<PiDurableConfig, PiDurableCapabilities, {}, never>;
readonly antigravity: BackendTypeSpec<AntigravityConfig, AntigravityCapabilities, {}, never>;
readonly agy: BackendTypeSpec<AgyConfig, AgyCapabilities, {}, never>;
readonly claude: BackendTypeSpec<ClaudeConfig, ClaudeCapabilities, {}, never>;
@@ -189,11 +202,39 @@ export interface AgentLaunchContext {
readonly launchId: string;
}
+export interface InputReference {
+ readonly commandId: string;
+ readonly attemptId: string;
+}
+
+export type InputReturnEvidence = "not_submitted" | "explicitly_rejected" | "unknown";
+export type ExecutionOutcome = "success" | "failed" | "interrupted" | "unknown";
+export interface EventAttribution {
+ readonly scope: "root" | "child" | "unknown";
+ readonly agentId?: string;
+ readonly parentCallId?: string;
+ readonly nativeTurnId?: string;
+}
+
+export interface SessionAcquisition {
+ readonly status: "created" | "resumed" | "unverified";
+ readonly evidence: "native_api" | "native_protocol" | "history" | "none";
+}
+
+export interface RuntimeConfigurationObservation {
+ readonly evidence: "observed" | "acknowledged" | "unverified" | "unsupported" | "refused";
+ readonly effective: "current" | "next_turn" | "after_resume" | "unknown";
+ readonly model?: string;
+ readonly reasoningEffort?: ReasoningEffort | null;
+}
+
export interface AgentMessage {
readonly id: string;
readonly kind: "user" | "system" | "recovery";
readonly text: string;
readonly sequence?: number;
+ readonly attemptId?: string;
+ readonly delivery?: "auto" | "next_turn";
}
export interface AgentDriverError {
@@ -303,10 +344,12 @@ export type AgentSessionResult =
readonly cleanup: HostCleanupResult;
};
-export type AgentTurnResult =
+export type AgentTurnResult = { readonly stopReason?: string } & (
| { readonly outcome: "success"; readonly backendSessionId: string }
| { readonly outcome: "interrupted"; readonly backendSessionId?: string }
- | { readonly outcome: "failed"; readonly backendSessionId?: string; readonly error: AgentDriverError };
+ | { readonly outcome: "failed"; readonly backendSessionId?: string; readonly error: AgentDriverError }
+ | { readonly outcome: "unknown"; readonly backendSessionId?: string }
+);
export type TokenUsageIdentity = { readonly source: string; readonly index: number; readonly occurredAt: string };
@@ -371,6 +414,11 @@ export type ProviderQuotaObservation =
};
export type CoreAgentEventPayload =
+ | { readonly type: "session_acquired"; readonly backendSessionId: string; readonly acquisition: SessionAcquisition }
+ | { readonly type: "configuration_observed"; readonly observation: RuntimeConfigurationObservation }
+ | { readonly type: "input_observed"; readonly input: InputReference; readonly evidence: "native_ack" | "user_message" | "conversation" }
+ | { readonly type: "command_returned"; readonly input: InputReference; readonly message: AgentMessage; readonly ordinal: number; readonly evidence: InputReturnEvidence; readonly reason: string; readonly retryable: boolean }
+ | { readonly type: "activity"; readonly attribution: EventAttribution; readonly kind: string; readonly text?: string; readonly callId?: string; readonly name?: string; readonly outcome?: ExecutionOutcome; readonly output?: JsonValue }
| { readonly type: "session_started"; readonly backendSessionId: string }
| {
readonly type: "command_queued";
@@ -385,6 +433,7 @@ export type CoreAgentEventPayload =
}
| {
readonly type: "command_failed";
+ readonly scope?: "input" | "turn";
readonly commandId: string;
readonly turnId?: string;
readonly error: AgentDriverError;
@@ -417,6 +466,7 @@ export type CoreAgentEventPayload =
readonly callId?: string;
readonly name: string;
readonly output?: JsonValue;
+ readonly outcome?: ExecutionOutcome;
}
| { readonly type: "compaction_started"; readonly turnId: string }
| { readonly type: "compaction_finished"; readonly turnId: string }
@@ -480,6 +530,8 @@ export type AgentEvent<Specs, Id extends BackendId<Specs>> =
AgentEventEnvelope & (CoreAgentEventPayload | ExtraEventOf<Specs, Id>);
export interface AgentSessionSnapshot {
+ readonly acquisition?: SessionAcquisition;
+ readonly configuration?: RuntimeConfigurationObservation;
readonly sessionInstanceId: string;
readonly state:
| "new"
@@ -527,7 +579,7 @@ export interface AgentSessionSnapshot {
readonly anonymousOutstandingToolUses?: number;
/** Duplicate starts, unmatched finishes, or unattributable lifecycle events. */
readonly toolLifecycleMismatchCount?: number;
- readonly resumeOutcome: "not_requested" | "pending" | "resumed" | "reset_required" | "failed";
+ readonly resumeOutcome: "not_requested" | "pending" | "resumed" | "unverified" | "reset_required" | "failed";
readonly terminalOwnerKind:
| "transport_request"
| "vendor_message"
diff --git a/src/daemon/agent-driver/src/controller/logical-session.test.ts b/src/daemon/agent-driver/src/controller/logical-session.test.ts
index 337c1a2ee..f9e6babd1 100644
--- a/src/daemon/agent-driver/src/controller/logical-session.test.ts
+++ b/src/daemon/agent-driver/src/controller/logical-session.test.ts
@@ -29,6 +29,10 @@ import { SdkLane } from "./sdk-host.js";
import { capabilitiesFor } from "../registry.js";
const configs: Record<BuiltinBackendId, unknown> = {
+ qoder: { model: { kind: "default" } },
+ copilot: { model: { kind: "default" } },
+ "cursor-sdk": { model: { kind: "named", name: "fixture" } },
+ "pi-durable": { model: { kind: "named", name: "openai/fixture" }, provider: { kind: "default" } },
claude: { model: { kind: "default" }, provider: { kind: "default" }, mode: "default" },
codex: { model: { kind: "default" }, mode: "default" },
cursor: { model: { kind: "default" } },
@@ -120,7 +124,7 @@ class FakeDriver implements BackendAdapter {
this.lane = new SdkLane(handle, "sdk-session");
return this.lane;
}
- normalizeLine(line: string): AdapterEvent[] { return [JSON.parse(line) as AdapterEvent]; }
+ normalizeLine(line: string): AdapterEvent[] { const event = JSON.parse(line) as AdapterEvent; return [event.kind === "turn_end" ? { outcome: "success", ...event } : event]; }
async interrupt(_input: LaneInterruptInput, process: SpawnedProcessHandle): Promise<boolean> {
return process.kill("SIGINT");
}
@@ -189,8 +193,8 @@ describe("LogicalAgentSession reasoning settings boundary", () => {
});
expect(sent).toHaveBeenCalledTimes(0);
- update.resolve({ status: "applied" });
- await expect(settings).resolves.toEqual({ status: "applied" });
+ update.resolve({ status: "acknowledged", effective: "next_turn" });
+ await expect(settings).resolves.toEqual({ status: "acknowledged", effective: "next_turn" });
await vi.waitFor(() => expect(sent).toHaveBeenCalledTimes(1));
});
@@ -329,6 +333,10 @@ function makeSession<Id extends BuiltinBackendId>(
return { session, driver, host };
}
+function makeSafeBoundarySession<Id extends BuiltinBackendId>(backend: Id, options: Parameters<typeof makeSession<Id>>[1] = {}) {
+ return makeSession(backend, { ...options, capabilities: { ...(capabilitiesFor(backend) as BackendCapabilities), midTurnDelivery: "safe_boundary_queue" } as BackendCapabilities });
+}
+
async function emit(driver: FakeDriver, event: AdapterEvent): Promise<void> {
emitNow(driver, event);
await Promise.resolve();
@@ -342,6 +350,96 @@ function emitNow(driver: FakeDriver, event: AdapterEvent): void {
else driver.processes.at(-1)!.stdout.write(`${JSON.stringify(ownedEvent)}\n`);
}
+describe("shared input responsibility and evidence", () => {
+ it("preserves merged members, rejects overlapping attempts, and fences a returned input's old attempt", async () => {
+ const lane = new ControlledRuntimeLane();
+ lane.startAdmission = { ok: true, acceptedAs: "prompt", receipt: "codex:test:1" };
+ lane.sendAdmission = { ok: true, acceptedAs: "steer", receipt: "codex:test:1" };
+ const starts: LaneStartInput[] = [];
+ const sends: LaneSendInput[] = [];
+ lane.onStart = (input) => starts.push(input);
+ lane.onSend = (input) => sends.push(input);
+ const { session } = makeSession("codex", { lane, capabilities: { ...capabilitiesFor("codex"), midTurnDelivery: "steer" } });
+ const observed: AgentEvent<BuiltinBackendSpecs, BuiltinBackendId>[] = [];
+ const collecting = (async () => { for await (const event of session.events) observed.push(event); })();
+ try {
+ await session.start({ id: "A", kind: "user", text: "root" });
+ const accepted = await session.send({ id: "B", kind: "user", text: "extra" });
+ expect(await session.send({ text: "extra", kind: "user", id: "B", attemptId: "B" })).toEqual(accepted);
+ expect(starts[0]!.inputs).toEqual([{ commandId: "A", attemptId: "A" }]);
+ expect(sends[0]!.inputs).toEqual([{ commandId: "B", attemptId: "B" }]);
+ expect(await session.send({ id: "B", attemptId: "B2", kind: "user", text: "extra" })).toMatchObject({ status: "rejected", reason: "duplicate_conflict" });
+ lane.emit({ kind: "input_returned", inputs: [{ commandId: "B", attemptId: "B" }], evidence: "explicitly_rejected", reason: "native_busy", retryable: true });
+ expect(await session.send({ id: "B", attemptId: "B2", kind: "user", text: "changed" })).toMatchObject({ status: "rejected", reason: "duplicate_conflict" });
+ expect(await session.send({ id: "B", attemptId: "B2", kind: "user", text: "extra" })).toMatchObject({ status: "accepted" });
+ lane.emit({ kind: "input_returned", inputs: [{ commandId: "B", attemptId: "B" }], evidence: "unknown", reason: "late" });
+ lane.emit({ kind: "error", scope: "input", message: "extra input refused" });
+ lane.emit({ kind: "turn_end", turnOwner: "codex:test:1", outcome: "success" });
+ } finally { await session.stop({ reason: "shutdown", forceAfterMs: 10 }); await collecting; }
+ expect(observed.filter((event) => event.type === "command_returned")).toEqual([
+ expect.objectContaining({ input: { commandId: "B", attemptId: "B" }, ordinal: 2, evidence: "explicitly_rejected", message: expect.objectContaining({ text: "extra" }) }),
+ ]);
+ expect(observed).toContainEqual(expect.objectContaining({ type: "turn_completed", result: { outcome: "success", backendSessionId: "" } }));
+ });
+
+ it("scopes an immediate steering refusal to B while root A succeeds", async () => {
+ const lane = new ControlledRuntimeLane();
+ lane.startAdmission = { ok: true, acceptedAs: "prompt", receipt: "codex:test:1" };
+ lane.sendAdmission = { ok: false, reason: "input_rejected", error: "extra input refused" };
+ const { session } = makeSession("codex", { lane });
+ const events: AgentEvent<BuiltinBackendSpecs, BuiltinBackendId>[] = [];
+ const collecting = (async () => { for await (const event of session.events) events.push(event); })();
+ await session.start({ id: "A", kind: "user", text: "root" });
+ expect(await session.send({ id: "B", kind: "user", text: "extra" })).toMatchObject({ status: "rejected" });
+ expect(session.snapshot().activeTurn?.commandIds).toEqual(["A"]);
+ lane.emit({ kind: "turn_end", turnOwner: "codex:test:1", outcome: "success" });
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ await collecting;
+ expect(events).toContainEqual(expect.objectContaining({ type: "command_failed", scope: "input", commandId: "B" }));
+ expect(events).toContainEqual(expect.objectContaining({ type: "turn_completed", commandIds: ["A"], result: expect.objectContaining({ outcome: "success" }) }));
+ });
+
+ it("keeps child tools, text, errors and terminals outside root authority", async () => {
+ const lane = new ControlledRuntimeLane();
+ lane.startAdmission = { ok: true, acceptedAs: "prompt", receipt: "codex:test:1" };
+ const { session } = makeSession("codex", { lane });
+ const observed: AgentEvent<BuiltinBackendSpecs, BuiltinBackendId>[] = [];
+ const collecting = (async () => { for await (const event of session.events) observed.push(event); })();
+ try {
+ await session.start({ id: "A", kind: "user", text: "root" });
+ lane.emit({ kind: "tool_call", callId: "1", name: "root tool", input: {} });
+ const attribution = { scope: "child", agentId: "child-A" } as const;
+ lane.emit({ kind: "tool_call", callId: "1", name: "child tool", input: {}, attribution });
+ lane.emit({ kind: "tool_output", callId: "1", name: "child tool", outcome: "failed", attribution });
+ lane.emit({ kind: "assistant_message_completed", text: "child text", attribution });
+ lane.emit({ kind: "error", message: "child failed", attribution });
+ lane.emit({ kind: "turn_end", turnOwner: "codex:test:1", outcome: "failed", attribution });
+ expect(session.snapshot().diagnostics.metrics.outstandingToolUses).toBe(1);
+ expect(session.snapshot().state).toBe("working");
+ lane.emit({ kind: "turn_end", turnOwner: "codex:test:1", outcome: "success" });
+ } finally { await session.stop({ reason: "shutdown", forceAfterMs: 10 }); await collecting; }
+ expect(observed.filter((event) => event.type === "activity")).toHaveLength(5);
+ expect(observed.filter((event) => event.type === "assistant_message_completed")).toEqual([]);
+ expect(observed.filter((event) => event.type === "turn_completed")).toEqual([expect.objectContaining({ result: { outcome: "success", backendSessionId: "" } })]);
+ });
+
+ it("reports same-ID recovery and absent terminal evidence as unverified and unknown", async () => {
+ const lane = new ControlledRuntimeLane();
+ lane.startAdmission = { ok: true, acceptedAs: "prompt", receipt: "codex:test:1" };
+ lane.onStart = () => lane.emit({ kind: "session_init", sessionId: "saved" });
+ const { session } = makeSession("codex", { lane, resumeSessionId: "saved" });
+ const observed: AgentEvent<BuiltinBackendSpecs, BuiltinBackendId>[] = [];
+ const collecting = (async () => { for await (const event of session.events) observed.push(event); })();
+ try {
+ await session.start({ id: "A", kind: "user", text: "root" });
+ expect(session.snapshot().diagnostics.metrics.resumeOutcome).toBe("unverified");
+ lane.emit({ kind: "turn_end", turnOwner: "codex:test:1" });
+ } finally { await session.stop({ reason: "shutdown", forceAfterMs: 10 }); await collecting; }
+ expect(observed).toContainEqual(expect.objectContaining({ type: "session_acquired", acquisition: { status: "unverified", evidence: "none" } }));
+ expect(observed).toContainEqual(expect.objectContaining({ type: "turn_completed", result: { outcome: "unknown", backendSessionId: "saved" } }));
+ });
+});
+
async function take(
iterator: AsyncIterator<AgentEvent<BuiltinBackendSpecs, BuiltinBackendId>>,
count: number,
@@ -350,7 +448,7 @@ async function take(
while (events.length < count) {
const next = await iterator.next();
if (next.done) break;
- events.push(next.value);
+ if (next.value.type !== "session_acquired" && next.value.type !== "configuration_observed") events.push(next.value);
}
return events;
}
@@ -532,7 +630,7 @@ describe("root-turn text assembly", () => {
lane.emit({ kind: "turn_end", turnOwner: "stale-owner", pendingContent, outcome: "interrupted" });
lane.emit({ kind: "assistant_message_delta", text: "working" });
lane.emit({ kind: "assistant_reasoning_delta", text: "now" });
- lane.emit({ kind: "turn_end", turnOwner: "claude:test:1" });
+ lane.emit({ kind: "turn_end", turnOwner: "claude:test:1", outcome: "success" });
await session.stop({ reason: "shutdown", forceAfterMs: 10 });
await collecting;
expect(observed.filter((event) => event.type === "assistant_message_completed"))
@@ -546,7 +644,7 @@ describe("root-turn text assembly", () => {
it("preserves an owned native interruption and drains the next queued command", async () => {
const lane = new ControlledRuntimeLane();
- const { session } = makeSession("claude", { lane });
+ const { session } = makeSafeBoundarySession("claude", { lane });
const observed: Array<AgentEvent<BuiltinBackendSpecs, BuiltinBackendId>> = [];
const collecting = (async () => { for await (const event of session.events) observed.push(event); })();
await session.start({ id: "one", kind: "user", text: "start" });
@@ -558,7 +656,7 @@ describe("root-turn text assembly", () => {
lane.emit({ kind: "assistant_reasoning_delta", text: "new reasoning" });
lane.emit({ kind: "turn_end", turnOwner: "claude:test:1", outcome: "interrupted", pendingContent: "discard" });
expect(session.snapshot().activeTurn?.commandIds).toEqual(["two"]);
- lane.emit({ kind: "turn_end", turnOwner: "claude:test:2" });
+ lane.emit({ kind: "turn_end", turnOwner: "claude:test:2", outcome: "success" });
await session.stop({ reason: "shutdown", forceAfterMs: 10 });
await collecting;
expect(observed.filter((event) => event.type === "turn_completed"))
@@ -953,7 +1051,7 @@ describe("logical delivery diagnostics", () => {
const lane = new ControlledRuntimeLane();
const startGate = deferredValue<LaneAdmission>();
lane.startPromise = startGate.promise;
- const { session } = makeSession("claude", { lane, now: () => now });
+ const { session } = makeSafeBoundarySession("claude", { lane, now: () => now });
expect(session.snapshot().diagnostics).toEqual({
deliveryPhase: "idle",
@@ -1068,7 +1166,7 @@ describe("logical delivery diagnostics", () => {
it("reports exact resume outcomes without exposing vendor payloads", async () => {
const lane = new ControlledRuntimeLane();
lane.startAdmission = { ok: true, acceptedAs: "prompt", receipt: "codex:test:1" };
- lane.onStart = () => lane.emit({ kind: "session_init", sessionId: "resume-exact" });
+ lane.onStart = () => lane.emit({ kind: "session_init", sessionId: "resume-exact", acquisition: { status: "resumed", evidence: "native_api" } });
const { session } = makeSession("codex", { lane, resumeSessionId: "resume-exact" });
expect(session.snapshot().diagnostics.metrics.resumeOutcome).toBe("pending");
await session.start({ id: "one", kind: "user", text: "resume" });
@@ -1163,7 +1261,7 @@ describe("logical delivery diagnostics", () => {
describe("closed physical-lane tombstone", () => {
it("drops every closed per-turn lane tail before it can poison the next turn boundary", async () => {
- const { session, driver } = makeSession("claude", {
+ const { session, driver } = makeSafeBoundarySession("claude", {
execution: {
lifetime: "turn",
transport: { kind: "one_shot_cli", protocol: "test.one-shot.v1" },
@@ -1330,7 +1428,7 @@ describe("backend-owned delivery behavior", () => {
});
it.each(["claude", "codex"] as const)("%s queues mid-turn and flushes at a safe boundary", async (backend) => {
- const { session, driver } = makeSession(backend);
+ const { session, driver } = makeSafeBoundarySession(backend);
await session.start({ id: "one", kind: "user", text: "start" });
await emit(driver, { kind: "compaction_started" });
expect(await session.send({ id: "two", kind: "user", text: "follow" })).toEqual({ status: "queued", reason: "unsafe_boundary", commandId: "two" });
@@ -1342,7 +1440,7 @@ describe("backend-owned delivery behavior", () => {
});
it.each(["claude", "codex"] as const)("%s preserves FIFO and distinct ids for identical queued text", async (backend) => {
- const { session, driver } = makeSession(backend);
+ const { session, driver } = makeSafeBoundarySession(backend);
const iterator = session.events[Symbol.asyncIterator]();
await session.start({ id: "one", kind: "user", text: "start" });
await emit(driver, { kind: "compaction_started" });
@@ -1363,7 +1461,7 @@ describe("backend-owned delivery behavior", () => {
});
it.each(["claude", "codex"] as const)("%s flushes a message that arrives at an already-safe boundary", async (backend) => {
- const { session, driver } = makeSession(backend);
+ const { session, driver } = makeSafeBoundarySession(backend);
const iterator = session.events[Symbol.asyncIterator]();
await session.start({ id: "one", kind: "user", text: "start" });
@@ -1411,7 +1509,7 @@ describe("backend-owned delivery behavior", () => {
});
it("flushes a safe-boundary message queued while the persistent lane is still starting", async () => {
- const { session, driver } = makeSession("claude");
+ const { session, driver } = makeSafeBoundarySession("claude");
const gate = deferred();
driver.spawnGate = gate.promise;
const starting = session.start({ id: "one", kind: "user", text: "start" });
@@ -1561,7 +1659,7 @@ describe("backend-owned delivery behavior", () => {
});
it("fails every still-queued command when the session stops", async () => {
- const { session, driver } = makeSession("claude");
+ const { session, driver } = makeSafeBoundarySession("claude");
const iterator = session.events[Symbol.asyncIterator]();
await session.start({ id: "one", kind: "user", text: "start" });
await emit(driver, { kind: "compaction_started" });
@@ -1574,7 +1672,7 @@ describe("backend-owned delivery behavior", () => {
});
it("emits command_failed for every safe-boundary delivery rejection", async () => {
- const { session, driver } = makeSession("claude");
+ const { session, driver } = makeSafeBoundarySession("claude");
const iterator = session.events[Symbol.asyncIterator]();
await session.start({ id: "one", kind: "user", text: "start" });
await emit(driver, { kind: "compaction_started" });
@@ -1590,7 +1688,7 @@ describe("backend-owned delivery behavior", () => {
});
it("single-flights same-tick safe boundaries and delivers queued commands exactly once in FIFO order", async () => {
- const { session, driver } = makeSession("claude");
+ const { session, driver } = makeSafeBoundarySession("claude");
const iterator = session.events[Symbol.asyncIterator]();
await session.start({ id: "one", kind: "user", text: "start" });
await emit(driver, { kind: "compaction_started" });
@@ -1610,7 +1708,7 @@ describe("backend-owned delivery behavior", () => {
});
it("single-flights same-tick rejected safe boundaries and fails each queued command exactly once", async () => {
- const { session, driver } = makeSession("claude");
+ const { session, driver } = makeSafeBoundarySession("claude");
const iterator = session.events[Symbol.asyncIterator]();
await session.start({ id: "one", kind: "user", text: "start" });
await emit(driver, { kind: "compaction_started" });
@@ -1631,7 +1729,7 @@ describe("backend-owned delivery behavior", () => {
});
it("cancels an in-flight safe-boundary admission once before a same-tick terminal stop", async () => {
- const { session, driver } = makeSession("claude");
+ const { session, driver } = makeSafeBoundarySession("claude");
const iterator = session.events[Symbol.asyncIterator]();
await session.start({ id: "one", kind: "user", text: "start" });
await emit(driver, { kind: "compaction_started" });
@@ -1670,7 +1768,7 @@ describe("backend-owned delivery behavior", () => {
});
it("fails an in-flight boundary command before a same-tick turn completion", async () => {
- const { session, driver } = makeSession("claude");
+ const { session, driver } = makeSafeBoundarySession("claude");
const iterator = session.events[Symbol.asyncIterator]();
await session.start({ id: "one", kind: "user", text: "start" });
await emit(driver, { kind: "compaction_started" });
@@ -1694,7 +1792,7 @@ describe("backend-owned delivery behavior", () => {
});
it("settles a rejected in-flight boundary command once before same-tick turn completion", async () => {
- const { session, driver } = makeSession("claude");
+ const { session, driver } = makeSafeBoundarySession("claude");
const iterator = session.events[Symbol.asyncIterator]();
await session.start({ id: "one", kind: "user", text: "start" });
await emit(driver, { kind: "compaction_started" });
@@ -1721,7 +1819,7 @@ describe("backend-owned delivery behavior", () => {
});
it("does not start the next turn while a cancelled boundary send is still physically in flight", async () => {
- const { session, driver } = makeSession("claude");
+ const { session, driver } = makeSafeBoundarySession("claude");
await session.start({ id: "one", kind: "user", text: "start" });
await emit(driver, { kind: "compaction_started" });
const internals = session as unknown as {
@@ -1756,7 +1854,7 @@ describe("backend-owned delivery behavior", () => {
it.each(["claude", "codex"] as const)(
"%s flushes at the first valid tool output while another tool remains active",
async (backend) => {
- const { session, driver } = makeSession(backend);
+ const { session, driver } = makeSafeBoundarySession(backend);
await session.start({ id: "one", kind: "user", text: "start" });
await emit(driver, { kind: "tool_call", callId: "tool-one", name: "one", input: {} });
await emit(driver, { kind: "tool_call", callId: "tool-two", name: "two", input: {} });
@@ -1771,7 +1869,7 @@ describe("backend-owned delivery behavior", () => {
);
it("closes the boundary latch again when a later tool starts", async () => {
- const { session, driver } = makeSession("codex");
+ const { session, driver } = makeSafeBoundarySession("codex");
await session.start({ id: "one", kind: "user", text: "start" });
await emit(driver, { kind: "tool_call", callId: "tool-one", name: "one", input: {} });
await session.send({ id: "two", kind: "user", text: "first follow" });
@@ -1787,7 +1885,7 @@ describe("backend-owned delivery behavior", () => {
});
it("deduplicates replayed identified tool starts and ignores unmatched finishes", async () => {
- const { session, driver } = makeSession("claude");
+ const { session, driver } = makeSafeBoundarySession("claude");
const observed: Array<AgentEvent<BuiltinBackendSpecs, BuiltinBackendId>> = [];
const collecting = (async () => { for await (const event of session.events) observed.push(event); })();
await session.start({ id: "one", kind: "user", text: "start" });
@@ -1844,7 +1942,7 @@ describe("backend-owned delivery behavior", () => {
});
it("flushes after review finishes but not while review is active", async () => {
- const { session, driver } = makeSession("codex");
+ const { session, driver } = makeSafeBoundarySession("codex");
await session.start({ id: "one", kind: "user", text: "start" });
await emit(driver, { kind: "review_started" });
await session.send({ id: "two", kind: "user", text: "follow" });
@@ -1879,7 +1977,7 @@ describe("backend-owned delivery behavior", () => {
});
it("does not tool-boundary flush after an error in the same turn", async () => {
- const { session, driver } = makeSession("claude");
+ const { session, driver } = makeSafeBoundarySession("claude");
await session.start({ id: "one", kind: "user", text: "start" });
await emit(driver, { kind: "tool_call", name: "one", input: {} });
await session.send({ id: "two", kind: "user", text: "follow" });
diff --git a/src/daemon/agent-driver/src/controller/logical-session.ts b/src/daemon/agent-driver/src/controller/logical-session.ts
index 8de04ba34..19f6379aa 100644
--- a/src/daemon/agent-driver/src/controller/logical-session.ts
+++ b/src/daemon/agent-driver/src/controller/logical-session.ts
@@ -4,6 +4,7 @@ import type {
AgentMessage,
AgentSession,
AgentSessionResult,
+ AgentTurnResult,
AgentSessionSnapshot,
BackendId,
CapabilitiesOf,
@@ -19,6 +20,11 @@ import type {
StopReceipt,
RuntimeSettingsUpdate,
RuntimeSettingsUpdateResult,
+ InputReference,
+ InputReturnEvidence,
+ ExecutionOutcome,
+ SessionAcquisition,
+ RuntimeConfigurationObservation,
} from "../contract.js";
import type { AgentDriverHost } from "../contract.js";
import type {
@@ -51,6 +57,13 @@ interface CommandRecord {
method: "start" | "send";
canonical: string;
promise: Promise<DeliveryReceipt>;
+ message: AgentMessage;
+ attemptId: string;
+ ordinal: number;
+ admitted: boolean;
+ returned: boolean;
+ pendingReturn?: { evidence: InputReturnEvidence; reason: string; retryable: boolean };
+ observations: Set<"native_ack" | "user_message" | "conversation">;
}
interface SafeBoundaryDelivery {
@@ -88,6 +101,8 @@ interface ActiveTurn {
pendingMessage: SemanticAssembler;
pendingReasoning: SemanticAssembler;
lastWorkHeartbeatAt: number | null;
+ outcome?: ExecutionOutcome;
+ stopReason?: string;
}
interface SemanticAssembler {
@@ -196,10 +211,14 @@ implements AgentSession<Specs, Id> {
private state: SessionState = "new";
private backendSessionId?: string;
+ private acquisition?: SessionAcquisition;
+ private configuration?: RuntimeConfigurationObservation;
private lane: RuntimeLane | null = null;
private activeTurn?: ActiveTurn;
private readonly queued: QueuedCommand[] = [];
private readonly commands = new Map<string, CommandRecord>();
+ private readonly latestCommands = new Map<string, CommandRecord>();
+ private commandOrdinal = 0;
private readonly commandAdmittedAt = new Map<string, number>();
private startedAdmitted = false;
private eventSequence = 0;
@@ -307,7 +326,14 @@ implements AgentSession<Specs, Id> {
const operation = this.settingsUpdateTail.then(async (): Promise<RuntimeSettingsUpdateResult> => {
if (!this.lane?.updateSettings) return { status: "unsupported" };
try {
- return await this.lane.updateSettings(input);
+ const result = await this.lane.updateSettings(input);
+ const observation = result.status === "applied" && result.observed
+ ? { evidence: "observed" as const, effective: "next_turn" as const, reasoningEffort: result.observed.reasoningEffort }
+ : result.status === "applied" || result.status === "acknowledged"
+ ? { evidence: "acknowledged" as const, effective: result.status === "acknowledged" ? result.effective : "unknown" as const }
+ : { evidence: result.status === "unsupported" ? "unsupported" as const : "refused" as const, effective: "unknown" as const };
+ this.emit({ type: "configuration_observed", observation });
+ return result.status === "applied" && !result.observed ? { status: "acknowledged", effective: "unknown" } : result;
} catch (error) {
return {
status: "failed",
@@ -316,7 +342,7 @@ implements AgentSession<Specs, Id> {
}
});
this.settingsUpdateTail = operation.then((result) => {
- if (result.status === "applied") {
+ if (result.status === "applied" || result.status === "acknowledged") {
this.settingsUpdatePending = false;
return;
}
@@ -410,6 +436,8 @@ implements AgentSession<Specs, Id> {
snapshot(): AgentSessionSnapshot {
return {
+ ...(this.acquisition ? { acquisition: this.acquisition } : {}),
+ ...(this.configuration ? { configuration: this.configuration } : {}),
sessionInstanceId: this.sessionInstanceId,
state: this.state,
backendSessionId: this.backendSessionId,
@@ -450,18 +478,33 @@ implements AgentSession<Specs, Id> {
}
private admit(method: "start" | "send", message: AgentMessage): Promise<DeliveryReceipt> {
- const canonical = JSON.stringify(message);
- const existing = this.commands.get(message.id);
+ const attemptId = message.attemptId ?? message.id;
+ const key = JSON.stringify([message.id, attemptId]);
+ const canonical = JSON.stringify([message.id, attemptId, message.kind, message.text, message.sequence ?? null, message.delivery ?? "auto"]);
+ const existing = this.commands.get(key);
if (existing) {
if (existing.method === method && existing.canonical === canonical) return existing.promise;
return Promise.resolve({ status: "rejected", reason: "duplicate_conflict" });
}
+ const previous = this.latestCommands.get(message.id);
+ if (previous && (!previous.returned || JSON.stringify([previous.message.kind, previous.message.text, previous.message.sequence]) !== JSON.stringify([message.kind, message.text, message.sequence]))) {
+ return Promise.resolve({ status: "rejected", reason: "duplicate_conflict" });
+ }
+ let resolve!: (receipt: DeliveryReceipt) => void;
+ let reject!: (error: unknown) => void;
+ const promise = new Promise<DeliveryReceipt>((yes, no) => { resolve = yes; reject = no; });
+ const record: CommandRecord = {
+ method, canonical, promise, message: { ...message }, attemptId,
+ ordinal: previous?.ordinal ?? ++this.commandOrdinal, admitted: false, returned: false,
+ observations: new Set(),
+ };
+ this.commands.set(key, record);
+ this.latestCommands.set(message.id, record);
this.commandAdmittedAt.set(message.id, this.metricNow());
- const promise = this.admitFresh(method, message).then((receipt) => {
+ void this.admitFresh(method, message).then((receipt) => {
if (receipt.status === "rejected") this.commandAdmittedAt.delete(message.id);
- return receipt;
- });
- this.commands.set(message.id, { method, canonical, promise });
+ resolve(receipt);
+ }, reject);
return promise;
}
@@ -495,6 +538,7 @@ implements AgentSession<Specs, Id> {
return this.startTurn([...prefix, message], "prompt");
}
if (this.state === "working" || this.state === "starting") {
+ if (message.delivery === "next_turn") return this.queue(message, "runtime_busy");
if (this.behavior.midTurnDelivery === "steer" && this.activeTurn && this.lane) {
return this.deliverSteer(message, this.activeTurn);
}
@@ -575,7 +619,7 @@ implements AgentSession<Specs, Id> {
try {
let laneAdmission: LaneAdmission;
if (reuseExistingLane) {
- laneAdmission = await this.sendLane(text, "idle");
+ laneAdmission = await this.sendLane(text, "idle", messages);
} else {
const opened = await this.openLane(text, generation);
if (!opened) {
@@ -636,6 +680,7 @@ implements AgentSession<Specs, Id> {
workingDirectory: this.launch.workingDirectory,
standingPrompt: this.launch.instructions,
prompt,
+ inputs: this.inputReferences(this.turnAdmission?.messages ?? []),
prepared: this.prepared,
config: {
sessionId: this.backendSessionId ?? this.launch.resumeSessionId,
@@ -681,6 +726,7 @@ implements AgentSession<Specs, Id> {
text: prompt,
sessionId: ctx.config.sessionId,
terminalOwner: this.activeTurn?.terminalOwner,
+ inputs: this.inputReferences(this.turnAdmission?.messages ?? []),
});
if (!admission.ok) {
if (admission.reason === "reset_required" || admission.reason === "incompatible_configuration") {
@@ -741,15 +787,42 @@ implements AgentSession<Specs, Id> {
): void {
if (this.state === "closed" || this.state === "stopping" || this.finishing) return;
if (this.isClosedPerTurnLaneTail(physicalOwner, generation)) return;
+ if (event.attribution?.scope === "child" || event.attribution?.scope === "unknown") {
+ this.emit({
+ type: "activity", attribution: event.attribution, kind: event.kind === "internal_progress" ? event.itemType ?? event.kind : event.kind,
+ ...("text" in event ? { text: boundedSemanticCompletion(event.text).text } : {}),
+ ...("callId" in event ? { callId: event.callId } : {}),
+ ...("name" in event ? { name: event.name } : {}),
+ ...("outcome" in event ? { outcome: event.outcome } : {}),
+ ...("output" in event ? { output: jsonValue(event.output) } : {}),
+ });
+ return;
+ }
const turnId = this.activeTurn?.turnId ?? this.reopenClosedLaneForWork(event, physicalOwner, generation);
switch (event.kind) {
+ case "input_returned":
+ for (const input of event.inputs) this.returnInput(input, event.evidence, event.reason, event.retryable === true);
+ return;
+ case "input_observed":
+ for (const input of event.inputs) {
+ const record = this.commands.get(JSON.stringify([input.commandId, input.attemptId]));
+ if (!record || record.returned || record.observations.has(event.evidence)) continue;
+ record.observations.add(event.evidence);
+ if (record.admitted) this.emit({ type: "input_observed", input, evidence: event.evidence });
+ }
+ return;
+ case "configuration_observed":
+ this.emit({ type: "configuration_observed", observation: event.observation });
+ return;
case "session_init":
if (this.launch.resumeSessionId && this.resumeOutcome === "pending") {
- this.resumeOutcome = event.sessionId === this.launch.resumeSessionId ? "resumed" : "failed";
+ this.resumeOutcome = event.acquisition?.status === "resumed" && event.sessionId === this.launch.resumeSessionId ? "resumed" : event.sessionId !== this.launch.resumeSessionId ? "failed" : "unverified";
}
if (this.backendSessionId !== event.sessionId) {
this.backendSessionId = event.sessionId;
this.emit({ type: "session_started", backendSessionId: event.sessionId });
+ this.emit({ type: "session_acquired", backendSessionId: event.sessionId, acquisition: event.acquisition ?? { status: "unverified", evidence: "none" } });
+ if (!this.configuration) this.emit({ type: "configuration_observed", observation: { evidence: "unverified", effective: "unknown" } });
}
return;
case "turn_owner":
@@ -838,6 +911,8 @@ implements AgentSession<Specs, Id> {
turnId,
...(finishedCallId ? { callId: finishedCallId } : {}),
name: event.name,
+ outcome: event.outcome ?? "unknown",
+ ...("output" in event ? { output: jsonValue(event.output) } : {}),
});
if (!this.toolBoundaryFlushDisabled) void this.flushSafeBoundaryQueue();
return;
@@ -891,6 +966,10 @@ implements AgentSession<Specs, Id> {
return;
}
case "error":
+ if (event.scope === "input" || event.scope === "operation" || event.scope === "diagnostic") {
+ this.emit({ type: "diagnostic", turnId, severity: "warning", source: this.backend, message: scrubDriverErrorMessage(event.message) });
+ return;
+ }
this.toolBoundaryFlushDisabled = true;
this.turnError = driverError(
"process",
@@ -909,6 +988,8 @@ implements AgentSession<Specs, Id> {
case "turn_end":
if (!this.activeTurn?.terminalOwner || event.turnOwner !== this.activeTurn.terminalOwner) return;
if (event.outcome === "interrupted") this.interruptedTurnId = this.activeTurn.turnId;
+ this.activeTurn.outcome = event.outcome ?? "unknown";
+ this.activeTurn.stopReason = event.stopReason;
if (event.pendingContent === "discard") {
this.activeTurn.pendingReasoning = emptySemanticAssembler();
this.activeTurn.pendingMessage = emptySemanticAssembler();
@@ -1010,15 +1091,20 @@ implements AgentSession<Specs, Id> {
this.backendSessionId = sessionId;
this.emit({ type: "session_started", backendSessionId: sessionId });
}
+ const result: AgentTurnResult = this.interruptedTurnId === active.turnId
+ ? { outcome: "interrupted", backendSessionId: this.backendSessionId }
+ : this.turnError
+ ? { outcome: "failed", backendSessionId: this.backendSessionId, error: this.turnError }
+ : active.outcome === "success"
+ ? { outcome: "success", backendSessionId: this.backendSessionId ?? "" }
+ : active.outcome === "failed"
+ ? { outcome: "failed", backendSessionId: this.backendSessionId, error: driverError("process", active.stopReason ? `native_${active.stopReason}` : "native_execution_failed", active.stopReason ? `Native execution stopped (${active.stopReason})` : "Native execution failed") }
+ : { outcome: "unknown", backendSessionId: this.backendSessionId };
this.emit({
type: "turn_completed",
turnId: active.turnId,
commandIds: active.commandIds,
- result: this.interruptedTurnId === active.turnId
- ? { outcome: "interrupted", backendSessionId: this.backendSessionId }
- : this.turnError
- ? { outcome: "failed", backendSessionId: this.backendSessionId, error: this.turnError }
- : { outcome: "success", backendSessionId: this.backendSessionId ?? "" },
+ result: { ...result, ...(active.stopReason ? { stopReason: active.stopReason } : {}) },
});
if (physicalOwner) {
this.closedLaneTombstone = {
@@ -1069,7 +1155,8 @@ implements AgentSession<Specs, Id> {
&& !this.reviewing
&& this.activeTurn !== undefined
&& this.lane !== null
- && this.queued.length > 0;
+ && this.queued.length > 0
+ && this.queued[0]!.message.delivery !== "next_turn";
}
private async drainSafeBoundaryQueue(): Promise<void> {
@@ -1079,7 +1166,7 @@ implements AgentSession<Specs, Id> {
const delivery: SafeBoundaryDelivery = { item, activeTurn, finalized: false };
this.safeBoundaryDelivery = delivery;
try {
- await this.sendLane(item.message.text, "busy");
+ await this.sendLane(item.message.text, "busy", [item.message]);
} catch (error) {
if (error instanceof StructuredLaneAdmissionError && error.code === "runtime_busy") {
this.queued.unshift(item);
@@ -1091,6 +1178,7 @@ implements AgentSession<Specs, Id> {
delivery.finalized = true;
this.emit({
type: "command_failed",
+ scope: "input",
commandId: item.message.id,
turnId: activeTurn.turnId,
error: driverError("process", "delivery_failed", String(error), true),
@@ -1123,6 +1211,7 @@ implements AgentSession<Specs, Id> {
delivery.finalized = true;
this.emit({
type: "command_failed",
+ scope: "input",
commandId: delivery.item.message.id,
turnId: delivery.activeTurn.turnId,
error: driverError(category, code, message),
@@ -1144,7 +1233,7 @@ implements AgentSession<Specs, Id> {
admission.pendingEvents.length = 0;
if (this.turnAdmission === admission) this.turnAdmission = undefined;
for (const message of admission.messages) {
- this.emit({ type: "command_failed", commandId: message.id, turnId: admission.turnId, error });
+ this.emit({ type: "command_failed", scope: "turn", commandId: message.id, turnId: admission.turnId, error });
}
}
@@ -1230,6 +1319,8 @@ implements AgentSession<Specs, Id> {
}
private emit(payload: CoreAgentEventPayload): void {
+ if (payload.type === "session_acquired") this.acquisition = payload.acquisition;
+ if (payload.type === "configuration_observed") this.configuration = payload.observation;
const at = this.metricNow();
if (payload.type === "command_accepted" || payload.type === "command_failed") {
const admittedAt = this.commandAdmittedAt.get(payload.commandId);
@@ -1246,13 +1337,35 @@ implements AgentSession<Specs, Id> {
at,
} as AgentEvent<Specs, Id>;
this.eventQueue.push(event, payload.type === "session_closed");
+ if (payload.type === "command_accepted") {
+ const record = this.latestCommands.get(payload.commandId);
+ if (record) {
+ record.admitted = true;
+ for (const evidence of record.observations) this.emit({ type: "input_observed", input: { commandId: payload.commandId, attemptId: record.attemptId }, evidence });
+ if (record.pendingReturn) this.returnInput({ commandId: payload.commandId, attemptId: record.attemptId }, record.pendingReturn.evidence, record.pendingReturn.reason, record.pendingReturn.retryable);
+ }
+ }
+ }
+
+ private inputReferences(messages: readonly AgentMessage[]): InputReference[] {
+ return messages.map((message) => ({ commandId: message.id, attemptId: message.attemptId ?? message.id }));
+ }
+
+ private returnInput(input: InputReference, evidence: InputReturnEvidence, reason: string, retryable: boolean): void {
+ const record = this.commands.get(JSON.stringify([input.commandId, input.attemptId]));
+ if (!record || record.returned || this.latestCommands.get(input.commandId) !== record) return;
+ if (!record.admitted) { record.pendingReturn = { evidence, reason, retryable }; return; }
+ record.returned = true;
+ record.pendingReturn = undefined;
+ if (this.activeTurn) this.activeTurn.commandIds = this.activeTurn.commandIds.filter((id) => id !== input.commandId);
+ this.emit({ type: "command_returned", input, message: record.message, ordinal: record.ordinal, evidence, reason: scrubDriverErrorMessage(reason), retryable });
}
private failQueued(category: AgentDriverError["category"], code: string, message: string): void {
const error = driverError(category, code, message);
for (const item of this.queued.splice(0)) {
this.recordQueueDwell(item);
- this.emit({ type: "command_failed", commandId: item.message.id, error });
+ this.emit({ type: "command_failed", scope: "turn", commandId: item.message.id, error });
}
}
@@ -1372,7 +1485,7 @@ implements AgentSession<Specs, Id> {
"Turn closed before command acceptance",
);
}
- await this.sendLane(message.text, "busy");
+ await this.sendLane(message.text, "busy", [message]);
if (delivery.finalized || this.activeTurn !== activeTurn) {
throw delivery.failure ?? driverError(
"cancelled",
@@ -1385,12 +1498,16 @@ implements AgentSession<Specs, Id> {
this.emit({ type: "command_accepted", commandId: message.id, turnId: activeTurn.turnId, delivery: "steer" });
return { status: "accepted", delivery: "steer", commandId: message.id, turnId: activeTurn.turnId };
} catch (error) {
+ if (!delivery.finalized && this.activeTurn === activeTurn && error instanceof StructuredLaneAdmissionError && error.code === "runtime_busy") {
+ delivery.finalized = true;
+ return this.queue(message, "runtime_busy");
+ }
const failure = delivery.failure ?? (typeof error === "object" && error !== null && "category" in error
? error as AgentDriverError
: driverError("process", "delivery_failed", String(error), true));
if (!delivery.finalized) {
delivery.finalized = true;
- this.emit({ type: "command_failed", commandId: message.id, turnId: activeTurn.turnId, error: failure });
+ this.emit({ type: "command_failed", scope: "input", commandId: message.id, turnId: activeTurn.turnId, error: failure });
}
return { status: "rejected", reason: "runtime_unavailable", error: failure };
}
@@ -1403,7 +1520,7 @@ implements AgentSession<Specs, Id> {
: driverError("process", "delivery_failed", String(error), true));
if (!delivery.finalized) {
delivery.finalized = true;
- this.emit({ type: "command_failed", commandId: message.id, turnId: activeTurn.turnId, error: failure });
+ this.emit({ type: "command_failed", scope: "input", commandId: message.id, turnId: activeTurn.turnId, error: failure });
}
return { status: "rejected", reason: "runtime_unavailable", error: failure };
} finally {
@@ -1425,6 +1542,7 @@ implements AgentSession<Specs, Id> {
delivery.failure = error;
this.emit({
type: "command_failed",
+ scope: "input",
commandId: delivery.message.id,
turnId: delivery.activeTurn.turnId,
error,
@@ -1564,13 +1682,14 @@ implements AgentSession<Specs, Id> {
await this.stopWithRelease({ reason: "shutdown", forceAfterMs: 5_000 }, "consumer_closed");
}
- private sendLane(text: string, mode: "busy" | "idle"): Promise<LaneAdmission> {
+ private sendLane(text: string, mode: "busy" | "idle", messages: readonly AgentMessage[] = []): Promise<LaneAdmission> {
if (!this.lane) return Promise.reject(new Error("runtime lane is not open"));
return this.lane.send({
text,
mode,
sessionId: this.backendSessionId ?? this.launch.resumeSessionId,
terminalOwner: mode === "idle" ? this.activeTurn?.terminalOwner : undefined,
+ inputs: this.inputReferences(messages),
})
.then((result) => {
if (!result.ok) {
diff --git a/src/daemon/agent-driver/src/controller/process-host.test.ts b/src/daemon/agent-driver/src/controller/process-host.test.ts
index 205117eae..462e25bf7 100644
--- a/src/daemon/agent-driver/src/controller/process-host.test.ts
+++ b/src/daemon/agent-driver/src/controller/process-host.test.ts
@@ -472,12 +472,13 @@ describe("ProcessLane interrupt", () => {
describe("ProcessLane settings updates", () => {
it("delegates to an adapter-provided settings method", async () => {
const { driver } = controllableDriver(() => []);
- const updateSettings = vi.fn(async () => ({ status: "applied" as const }));
+ const updateSettings = vi.fn(async () => ({ status: "acknowledged" as const, effective: "next_turn" as const }));
driver.updateSettings = updateSettings;
const session = new ProcessLane(driver, minimalCtx());
await expect(session.updateSettings({ reasoningEffort: "high" })).resolves.toEqual({
- status: "applied",
+ status: "acknowledged",
+ effective: "next_turn",
});
expect(updateSettings).toHaveBeenCalledWith({ reasoningEffort: "high" });
});
diff --git a/src/daemon/agent-driver/src/controller/process-host.ts b/src/daemon/agent-driver/src/controller/process-host.ts
index 27e6e99e6..8fd84e867 100644
--- a/src/daemon/agent-driver/src/controller/process-host.ts
+++ b/src/daemon/agent-driver/src/controller/process-host.ts
@@ -153,7 +153,7 @@ export class ProcessLane<Id extends string = BuiltinBackendId, Config = BackendC
if (input.mode === "idle" && this.pendingPromptAdmission) {
return { ok: false, reason: "runtime_busy", error: "prompt admission is already pending" };
}
- const encoded = this.driver.encodeMessage(input.text, input.sessionId ?? null, { mode: input.mode });
+ const encoded = this.driver.encodeMessage(input.text, input.sessionId ?? null, { mode: input.mode, inputs: input.inputs });
if (!encoded) return { ok: false, reason: "unsupported" };
if (input.mode === "idle") {
const admission = this.admitPrompt(input.terminalOwner, `${this.driver.id}:send:${++this.admissionSequence}`);
@@ -306,8 +306,8 @@ export class ProcessLane<Id extends string = BuiltinBackendId, Config = BackendC
for (const event of this.driver.normalizeLine(line)) {
if (event.kind === "turn_owner" && event.receipt.trim()) {
this.settlePendingPrompt({ ok: true, acceptedAs: "prompt", receipt: event.receipt });
- } else if (event.kind === "error" && this.pendingPromptAdmission) {
- this.settlePendingPrompt({ ok: false, reason: "runtime_error", error: event.message });
+ } else if (event.kind === "error" && event.scope !== "input" && event.scope !== "operation" && event.scope !== "diagnostic" && this.pendingPromptAdmission) {
+ this.settlePendingPrompt({ ok: false, reason: event.code === "reset_required" ? "reset_required" : "runtime_error", error: event.message });
}
const ownedEvent = event.kind === "turn_end" && !event.turnOwner && this.activeTerminalReceipt
? { ...event, turnOwner: this.activeTerminalReceipt }
diff --git a/src/daemon/agent-driver/src/controller/sdk-host.test.ts b/src/daemon/agent-driver/src/controller/sdk-host.test.ts
index 0cd5f69d0..42d63e3ce 100644
--- a/src/daemon/agent-driver/src/controller/sdk-host.test.ts
+++ b/src/daemon/agent-driver/src/controller/sdk-host.test.ts
@@ -54,14 +54,14 @@ describe("SdkLane.send", () => {
await Promise.resolve();
expect(received).toEqual([
{ kind: "session_init", sessionId: "s1" },
- { kind: "turn_end", sessionId: "s1", turnOwner: "pi:1" },
+ { kind: "turn_end", sessionId: "s1", turnOwner: "pi:1" , outcome: "success" },
]);
await session.send({ text: "same", mode: "idle", terminalOwner: "pi:2" });
pending[1]!.resolve();
await pending[1]!.promise;
await Promise.resolve();
- expect(received.at(-1)).toEqual({ kind: "turn_end", sessionId: "s1", turnOwner: "pi:2" });
+ expect(received.at(-1)).toEqual({ kind: "turn_end", sessionId: "s1", turnOwner: "pi:2" , outcome: "success" });
});
it("idle send while not streaming calls prompt() directly, no wait", async () => {
@@ -139,7 +139,7 @@ describe("SdkLane.send", () => {
expect(received).toEqual([
{ kind: "session_init", sessionId: "s1" },
{ kind: "error", message: "SDK remained busy before the next owned prompt" },
- { kind: "turn_end", sessionId: "s1", turnOwner: "pi:2" },
+ { kind: "turn_end", sessionId: "s1", turnOwner: "pi:2" , outcome: "failed" },
]);
} finally {
vi.useRealTimers();
@@ -186,11 +186,11 @@ describe("SdkLane.send", () => {
expect(received).toEqual([
{ kind: "session_init", sessionId: "s1" },
{ kind: "error", message: "boom" },
- { kind: "turn_end", sessionId: "s1", turnOwner: "s1:sdk:1" },
+ { kind: "turn_end", sessionId: "s1", turnOwner: "s1:sdk:1" , outcome: "failed" },
]);
});
- it("a thrown steer() surfaces as a runtime_event error instead of rejecting send()", async () => {
+ it("a thrown steer() returns the exact input with unknown delivery without failing the root", async () => {
const handle = fakeHandle(false);
handle.steer.mockRejectedValue(new Error("nope"));
const session = new SdkLane(handle, "s1");
@@ -199,7 +199,7 @@ describe("SdkLane.send", () => {
await expect(session.send({ text: "hi", mode: "busy" })).resolves.toMatchObject({ ok: true });
- expect(received).toContainEqual({ kind: "error", message: "nope" });
+ expect(received).toContainEqual({ kind: "input_returned", inputs: [], evidence: "unknown", reason: "nope", retryable: false });
});
// A failed steer() (mode "busy") does NOT mean the turn it was steering
@@ -233,7 +233,7 @@ describe("SdkLane.send", () => {
await vi.advanceTimersByTimeAsync(1100);
await pending;
- expect(received).toContainEqual({ kind: "error", message: "nope" });
+ expect(received).toContainEqual({ kind: "input_returned", inputs: [], evidence: "unknown", reason: "nope", retryable: false });
expect(received).not.toContainEqual(expect.objectContaining({ kind: "turn_end" }));
} finally {
vi.useRealTimers();
diff --git a/src/daemon/agent-driver/src/controller/sdk-host.ts b/src/daemon/agent-driver/src/controller/sdk-host.ts
index b606f636b..a8ff8275e 100644
--- a/src/daemon/agent-driver/src/controller/sdk-host.ts
+++ b/src/daemon/agent-driver/src/controller/sdk-host.ts
@@ -10,6 +10,7 @@ import type {
RuntimeLaneEventMap,
VendorSessionHandle,
} from "../internal/adapter.js";
+import type { InputReference, SessionAcquisition } from "../contract.js";
/** Poll briefly before degrading an idle prompt to a safe steer. */
const IDLE_PROMPT_RETRY_MS = 25;
@@ -31,7 +32,7 @@ export class SdkLane implements RuntimeLane {
constructor(
private readonly handle: VendorSessionHandle,
private readonly sessionId: string,
- private readonly options: { terminalOnPromptSettled?: boolean } = {},
+ private readonly options: { terminalOnPromptSettled?: boolean; acquisition?: SessionAcquisition } = {},
) {}
on<K extends keyof RuntimeLaneEventMap>(
@@ -52,7 +53,7 @@ export class SdkLane implements RuntimeLane {
emitEvents(events: AdapterEvent[]): void {
if (!this.sentInit && events.length > 0) {
this.sentInit = true;
- this.events.emit("runtime_event", { kind: "session_init", sessionId: this.sessionId } as AdapterEvent);
+ this.events.emit("runtime_event", { kind: "session_init", sessionId: this.sessionId, ...(this.options.acquisition ? { acquisition: this.options.acquisition } : {}) } as AdapterEvent);
}
for (const e of events) this.events.emit("runtime_event", e);
}
@@ -64,7 +65,7 @@ export class SdkLane implements RuntimeLane {
/** Delivers immediately; failures return through normalized events. */
send(input: LaneSendInput): Promise<LaneAdmission> {
const receipt = input.terminalOwner ?? `${this.sessionId}:sdk:${++this.admissionSequence}`;
- void this.deliver(input.text, input.mode, receipt);
+ void this.deliver(input.text, input.mode, receipt, input.inputs ?? []);
return Promise.resolve({
ok: true,
acceptedAs: input.mode === "busy" ? "steer" : "prompt",
@@ -72,9 +73,11 @@ export class SdkLane implements RuntimeLane {
});
}
- private async deliver(text: string, mode: InputMode, terminalOwner?: string): Promise<void> {
+ private async deliver(text: string, mode: InputMode, terminalOwner?: string, inputs: readonly InputReference[] = []): Promise<void> {
+ let steering = mode === "busy";
try {
if (mode === "busy") {
+ steering = true;
await this.handle.steer(text);
return;
}
@@ -83,26 +86,29 @@ export class SdkLane implements RuntimeLane {
if (this.options.terminalOnPromptSettled) {
this.emitEvents([
{ kind: "error", message: "SDK remained busy before the next owned prompt" },
- { kind: "turn_end", sessionId: this.sessionId, turnOwner: terminalOwner },
+ { kind: "turn_end", sessionId: this.sessionId, turnOwner: terminalOwner, outcome: "failed" },
]);
return;
}
+ steering = true;
await this.handle.steer(text);
return;
}
try {
await this.handle.prompt(text);
if (this.options.terminalOnPromptSettled) {
- this.emitEvents([{ kind: "turn_end", sessionId: this.sessionId, turnOwner: terminalOwner }]);
+ this.emitEvents([{ kind: "turn_end", sessionId: this.sessionId, turnOwner: terminalOwner, outcome: "success" }]);
}
} catch (err) {
this.emitEvents([
{ kind: "error", message: errorMessage(err) },
- { kind: "turn_end", sessionId: this.sessionId, turnOwner: terminalOwner },
+ { kind: "turn_end", sessionId: this.sessionId, turnOwner: terminalOwner, outcome: "failed" },
]);
}
} catch (err) {
- this.emitEvents([{ kind: "error", message: errorMessage(err) }]);
+ this.emitEvents(steering
+ ? [{ kind: "input_returned", inputs, evidence: "unknown", reason: errorMessage(err), retryable: false }]
+ : [{ kind: "error", message: errorMessage(err), scope: "turn" }]);
}
}
diff --git a/src/daemon/agent-driver/src/internal/adapter.ts b/src/daemon/agent-driver/src/internal/adapter.ts
index 1f321dd32..b2a0d0058 100644
--- a/src/daemon/agent-driver/src/internal/adapter.ts
+++ b/src/daemon/agent-driver/src/internal/adapter.ts
@@ -6,6 +6,8 @@ import type {
GrokConfig,
OpenCodeConfig,
PiConfig,
+ QoderConfig, CopilotConfig, CursorSdkConfig, PiDurableConfig,
+ InputReference, InputReturnEvidence, ExecutionOutcome, EventAttribution, SessionAcquisition, RuntimeConfigurationObservation,
PreparedExecutionResource,
JsonValue,
RuntimeReasoningCatalog,
@@ -16,7 +18,7 @@ import type {
} from "../contract.js";
import type { ProviderQuotaObservation, TokenUsageDelta, TokenUsageIdentity } from "../contract.js";
-export type BackendConfig = ClaudeConfig | CodexConfig | CursorConfig | GrokConfig | OpenCodeConfig | PiConfig;
+export type BackendConfig = ClaudeConfig | CodexConfig | CursorConfig | GrokConfig | OpenCodeConfig | PiConfig | QoderConfig | CopilotConfig | CursorSdkConfig | PiDurableConfig;
export type WellKnownTransportKind =
| "stdio_stream"
@@ -56,16 +58,20 @@ export const DEFAULT_RECOVERY_GRACE_MS = 60_000;
export const DEFAULT_MAX_RECOVERY_EXTENSIONS = 1;
export type InputMode = "busy" | "idle";
-export interface EncodeMessageOptions { mode?: InputMode }
-
-export type AdapterEvent =
- | { kind: "session_init"; sessionId: string }
+export interface EncodeMessageOptions { mode?: InputMode; inputs?: readonly InputReference[] }
+
+export type AdapterEvent = AdapterEventPayload & { readonly attribution?: EventAttribution };
+type AdapterEventPayload =
+ | { kind: "session_init"; sessionId: string; acquisition?: SessionAcquisition }
+ | { kind: "configuration_observed"; observation: RuntimeConfigurationObservation }
+ | { kind: "input_observed"; inputs: readonly InputReference[]; evidence: "native_ack" | "user_message" | "conversation" }
+ | { kind: "input_returned"; inputs: readonly InputReference[]; evidence: InputReturnEvidence; reason: string; retryable?: boolean }
| { kind: "assistant_reasoning_delta"; text: string }
| { kind: "assistant_reasoning_completed"; text: string }
| { kind: "assistant_message_delta"; text: string }
| { kind: "assistant_message_completed"; text: string }
| { kind: "tool_call"; callId?: string; name: string; input: unknown }
- | { kind: "tool_output"; callId?: string; name: string }
+ | { kind: "tool_output"; callId?: string; name: string; outcome?: ExecutionOutcome; output?: unknown }
| { kind: "compaction_started" }
| { kind: "compaction_finished" }
| { kind: "review_started" }
@@ -75,8 +81,8 @@ export type AdapterEvent =
| { kind: "runtime_recovery"; stage: "retrying" | "recovered"; source?: string }
| { kind: "runtime_metric"; name: "sse_reconnect"; increment: 1 }
| { kind: "turn_owner"; receipt: string; nativeTurnId?: string }
- | { kind: "turn_end"; sessionId?: string; turnOwner?: string; pendingContent?: "discard"; outcome?: "interrupted" }
- | { kind: "error"; code?: string; message: string }
+ | { kind: "turn_end"; sessionId?: string; turnOwner?: string; pendingContent?: "discard"; outcome?: ExecutionOutcome; stopReason?: string }
+ | { kind: "error"; code?: string; message: string; scope?: "input" | "operation" | "turn" | "session" | "diagnostic"; inputs?: readonly InputReference[] }
| { kind: "telemetry"; name: "token_usage"; source: string; usage: TokenUsageDelta; identity?: TokenUsageIdentity }
| { kind: "telemetry"; name: "token_usage_status"; source: string; status: "available" | "unavailable" }
| { kind: "telemetry"; name: "rate_limits"; source: string; quota: ProviderQuotaObservation };
@@ -85,6 +91,7 @@ export interface LaneStartInput {
readonly text: string;
readonly sessionId?: string;
readonly terminalOwner?: string;
+ readonly inputs?: readonly InputReference[];
}
export interface LaneSendInput extends LaneStartInput {
@@ -159,6 +166,7 @@ export interface AdapterLaunchConfig<Config = BackendConfig> {
}
export interface AdapterLaunchContext<Id extends string = BuiltinBackendId, Config = BackendConfig> {
+ inputs?: readonly InputReference[];
backend: Id;
agentId: string;
launchId: string;
diff --git a/src/daemon/agent-driver/src/internal/killTree.test.ts b/src/daemon/agent-driver/src/internal/killTree.test.ts
index 89fcd1722..d7ab306df 100644
--- a/src/daemon/agent-driver/src/internal/killTree.test.ts
+++ b/src/daemon/agent-driver/src/internal/killTree.test.ts
@@ -401,6 +401,30 @@ describe("spawnAgentProcess", () => {
});
});
+ it("starts an owned native process with an isolated PATH and preserves raw Unicode output", async () => {
+ const cwd = mkdtempSync(join(tmpdir(), "agent-driver-isolated-env-"));
+ tempDirs.push(cwd);
+ const proc = spawnAgentProcess(process.execPath, ["-e", `
+ const { writeSync } = require("node:fs");
+ writeSync(1, Buffer.from("你好😀"));
+ writeSync(2, Buffer.from("日志😀"));
+ `], { cwd, env: { PATH: cwd }, stdin: "ignore" });
+ spawned.push(proc);
+ const stdout: Buffer[] = [];
+ const stderr: Buffer[] = [];
+ proc.stdout!.on("data", (chunk: Buffer) => stdout.push(chunk));
+ proc.stderr!.on("data", (chunk: Buffer) => stderr.push(chunk));
+ await new Promise<void>((resolve, reject) => {
+ proc.once("error", reject);
+ proc.once("close", (code, signal) => {
+ if (code === 0 && signal === null) resolve();
+ else reject(new Error(`Isolated process exited: code=${code}, signal=${signal}, stderr=${Buffer.concat(stderr).toString("utf8")}`));
+ });
+ });
+ expect(Buffer.concat(stdout).toString("utf8")).toBe("你好😀");
+ expect(Buffer.concat(stderr).toString("utf8")).toBe("日志😀");
+ });
+
it("preserves persistent Windows stdin/stdout, cwd/env, and the exact inner exit code", async () => {
if (process.platform !== "win32") return;
const base = mkdtempSync(join(tmpdir(), "agent-driver-job-stdio-"));
diff --git a/src/daemon/agent-driver/src/internal/killTree.ts b/src/daemon/agent-driver/src/internal/killTree.ts
index 0bc842456..f9b3edaee 100644
--- a/src/daemon/agent-driver/src/internal/killTree.ts
+++ b/src/daemon/agent-driver/src/internal/killTree.ts
@@ -22,6 +22,7 @@ import { execFileSync, spawn, type ChildProcess } from "child_process";
import { randomUUID } from "node:crypto";
import { createServer, type Socket } from "node:net";
import { PassThrough } from "node:stream";
+import { win32 } from "node:path";
import { quoteWindowsShimCommand } from "./probe.js";
const POLL_MS = 100;
@@ -58,7 +59,7 @@ const WINDOWS_JOB_STDIN_PIPE_ENV = "ALOOK_WINDOWS_JOB_STDIN_PIPE";
// resumes it. Every descendant inherits the job, so the kernel retains tree
// authority after a `.cmd` shell or runtime root exits. Persistent protocol
// stdin uses a dedicated named pipe: PowerShell must not own that pipe because
-// its host can block while probing stdin before it runs the encoded bootstrap.
+// its host can block while probing stdin before it runs the bootstrap.
const WINDOWS_JOB_RUNNER = "const{spawn}=require('node:child_process');const{connect}=require('node:net');const p=JSON.parse(Buffer.from(process.env.ALOOK_WINDOWS_JOB_PAYLOAD,'base64').toString('utf8'));const pipe=process.env.ALOOK_WINDOWS_JOB_STDIN_PIPE;delete process.env.ALOOK_WINDOWS_JOB_NODE;delete process.env.ALOOK_WINDOWS_JOB_PAYLOAD;delete process.env.ALOOK_WINDOWS_JOB_RUNNER;delete process.env.ALOOK_WINDOWS_JOB_STDIN_PIPE;const run=stdin=>{const c=spawn(p.command,p.args,{cwd:p.cwd,env:process.env,shell:p.shell,stdio:[stdin,'inherit','inherit'],windowsHide:true});c.once('spawn',()=>{if(stdin!=='ignore')stdin.unref()});c.once('error',e=>{console.error(e);process.exitCode=1});c.once('exit',(code,signal)=>{process.exitCode=signal?1:(code??1)})};if(pipe){const input=connect(pipe);input.once('connect',()=>run(input));input.once('error',e=>{console.error(e);process.exitCode=1})}else run('ignore')";
const WINDOWS_JOB_BOOTSTRAP = String.raw`
@@ -371,8 +372,6 @@ $exitCode = [AlookAgentJob]::RunNode($env:ALOOK_WINDOWS_JOB_NODE, $env:ALOOK_WIN
exit $exitCode
`;
-const WINDOWS_JOB_ENCODED_COMMAND = Buffer.from(WINDOWS_JOB_BOOTSTRAP, "utf16le").toString("base64");
-
interface AgentSpawnOptions {
cwd: string;
env: NodeJS.ProcessEnv;
@@ -427,7 +426,9 @@ export function spawnAgentProcess(command: string, args: string[], opts: AgentSp
};
let proc: ChildProcess;
try {
- proc = spawn("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", WINDOWS_JOB_ENCODED_COMMAND], {
+ const systemRoot = process.env.SystemRoot ?? process.env.WINDIR;
+ const powershell = systemRoot ? win32.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe") : "powershell.exe";
+ proc = spawn(powershell, ["-NoLogo", "-NoProfile", "-NonInteractive", "-OutputFormat", "Text", "-Command", WINDOWS_JOB_BOOTSTRAP], {
cwd: opts.cwd,
// PowerShell receives NUL for stdin so its host cannot consume or
// block the persistent protocol pipe before running the bootstrap.
diff --git a/src/daemon/agent-driver/src/internal/optional-package.test.ts b/src/daemon/agent-driver/src/internal/optional-package.test.ts
new file mode 100644
index 000000000..f830646c1
--- /dev/null
+++ b/src/daemon/agent-driver/src/internal/optional-package.test.ts
@@ -0,0 +1,51 @@
+import { mkdtempSync, mkdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+import { resolveOptionalPackage } from "./optional-package.js";
+
+const roots: string[] = [];
+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
+
+function installation() {
+ const root = mkdtempSync(join(tmpdir(), "alook-optional-sdk-"));
+ roots.push(root);
+ return root;
+}
+
+function sdk(root: string, version: string): string {
+ const directory = join(root, "node_modules", "@fixture", "sdk");
+ mkdirSync(join(directory, "dist", "nested"), { recursive: true });
+ writeFileSync(join(directory, "package.json"), JSON.stringify({ name: "@fixture/sdk", version, main: "./dist/nested/index.js" }));
+ const entry = join(directory, "dist", "nested", "index.js");
+ writeFileSync(entry, "exports.available = true;\n");
+ return realpathSync(entry);
+}
+
+describe("optional SDK installation discovery", () => {
+ it("prefers the local installation over the explicit global npm prefix", () => {
+ const local = installation();
+ const global = installation();
+ const entry = sdk(local, "local");
+ sdk(join(global, "lib"), "global");
+ expect(resolveOptionalPackage("@fixture/sdk", [join(local, "loader.cjs"), join(global, "lib", "loader.cjs")])).toEqual({ entry, version: "local" });
+ });
+
+ it("resolves a global SDK through the installed npm entry", () => {
+ const root = installation();
+ const lib = join(root, "lib");
+ const entry = sdk(lib, "global");
+ const npm = join(lib, "node_modules", "npm", "bin", "npm-cli.js");
+ mkdirSync(join(lib, "node_modules", "npm", "bin"), { recursive: true });
+ writeFileSync(npm, "");
+ expect(resolveOptionalPackage("@fixture/sdk", [npm])).toEqual({ entry, version: "global" });
+ });
+
+ it("returns unavailable for an absent or invalid installation", () => {
+ const root = installation();
+ expect(resolveOptionalPackage("@fixture/sdk", [join(root, "loader.cjs")])).toBeUndefined();
+ sdk(root, "broken");
+ rmSync(join(root, "node_modules", "@fixture", "sdk", "dist"), { recursive: true });
+ expect(resolveOptionalPackage("@fixture/sdk", [join(root, "loader.cjs")])).toBeUndefined();
+ });
+});
diff --git a/src/daemon/agent-driver/src/internal/optional-package.ts b/src/daemon/agent-driver/src/internal/optional-package.ts
new file mode 100644
index 000000000..13056e810
--- /dev/null
+++ b/src/daemon/agent-driver/src/internal/optional-package.ts
@@ -0,0 +1,45 @@
+import { createRequire } from "node:module";
+import { realpathSync, readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { resolveCommandOnPath } from "./probe.js";
+
+function installationLocations(): readonly string[] {
+ const bases = [import.meta.url, join(process.cwd(), "__alook_sdk_loader__.cjs")];
+ for (const binary of [process.execPath, resolveCommandOnPath("npm")]) {
+ if (!binary) continue;
+ bases.push(binary);
+ try {
+ bases.push(realpathSync(binary));
+ } catch { continue; }
+ }
+ for (const executable of [process.execPath, realpathSync(process.execPath)]) {
+ const directory = dirname(executable);
+ bases.push(join(directory, "__alook_sdk_loader__.cjs"), join(directory, "..", "lib", "__alook_sdk_loader__.cjs"));
+ }
+ const prefix = process.env.npm_config_prefix ?? process.env.NPM_CONFIG_PREFIX;
+ if (prefix) bases.push(join(prefix, "__alook_sdk_loader__.cjs"), join(prefix, "lib", "__alook_sdk_loader__.cjs"));
+ return [...new Set(bases)];
+}
+
+export function resolveOptionalPackage(
+ name: string,
+ locations: readonly string[] = installationLocations(),
+): { entry: string; version?: string } | undefined {
+ for (const base of locations) {
+ try {
+ const entry = createRequire(base).resolve(name);
+ let directory = dirname(entry);
+ while (true) {
+ try {
+ const manifest = JSON.parse(readFileSync(join(directory, "package.json"), "utf8")) as { name?: string; version?: string };
+ if (manifest.name === name) return { entry, version: manifest.version };
+ } catch { }
+ const parent = dirname(directory);
+ if (parent === directory) break;
+ directory = parent;
+ }
+ return { entry };
+ } catch { continue; }
+ }
+ return undefined;
+}
diff --git a/src/daemon/agent-driver/src/internal/optional-sdk-driver.ts b/src/daemon/agent-driver/src/internal/optional-sdk-driver.ts
new file mode 100644
index 000000000..7fd0796e1
--- /dev/null
+++ b/src/daemon/agent-driver/src/internal/optional-sdk-driver.ts
@@ -0,0 +1,56 @@
+import { randomUUID } from "node:crypto";
+import type { BuiltinBackendId, BuiltinBackendSpecs } from "../contract.js";
+import type { AdapterLaunchContext, BackendAdapter, ProbeResult } from "./adapter.js";
+import type { SdkWorkerFactory } from "./sdk-worker-api.js";
+import { prepareCliTransport } from "./cliTransport.js";
+import { resolveLaunchFieldsOrDefault } from "./config.js";
+import { resolveOptionalPackage } from "./optional-package.js";
+import { SdkWorkerLane } from "./sdk-worker-lane.js";
+
+export class OptionalSdkDriver<Id extends BuiltinBackendId> implements BackendAdapter<Id, BuiltinBackendSpecs[Id]["config"]> {
+ readonly modelCatalogOrigin = "native_report" as const;
+ readonly execution;
+
+ constructor(
+ readonly id: Id,
+ private readonly packageName: string,
+ private readonly factory: SdkWorkerFactory,
+ private readonly resolvePackage = resolveOptionalPackage,
+ readonly instructionDelivery: BackendAdapter["instructionDelivery"] = { kind: "workspace_file", canonical: "AGENTS.md", aliases: ["CLAUDE.md"] },
+ ) {
+ this.execution = {
+ lifetime: "session", transport: { kind: "stdio_rpc", protocol: `${id}.sdk-worker.v1` },
+ wakeStart: "immediate", terminalOwnership: "prompt_invocation",
+ } as const;
+ }
+
+ beginTurn(): string { return `${this.id}:${randomUUID()}`; }
+
+ async probe(command?: string, includeModels = true): Promise<ProbeResult> {
+ const installed = this.resolvePackage(this.packageName);
+ if (!installed) return { status: "unhealthy", lastError: "sdk_not_installed" };
+ const lane = new SdkWorkerLane(this.factory, {
+ modulePath: installed.entry, cwd: process.cwd(), config: { command }, probe: { includeModels },
+ }, { ...process.env, CI: "1" });
+ try {
+ const result = await lane.probe() as ProbeResult;
+ if (result?.status !== "healthy" && result?.status !== "unhealthy") return { status: "unhealthy", lastError: "sdk_probe_invalid" };
+ return { ...result, version: installed.version };
+ } catch { return { status: "unhealthy", lastError: "sdk_probe_failed" }; }
+ finally { await lane.stop({ reason: "probe_complete", forceAfterMs: 250 }); }
+ }
+
+ async openLane(ctx: AdapterLaunchContext<Id, BuiltinBackendSpecs[Id]["config"]>): Promise<SdkWorkerLane> {
+ const installed = this.resolvePackage(this.packageName);
+ if (!installed) throw new Error(`${this.packageName} is not installed`);
+ const { spawnEnv } = await prepareCliTransport(ctx);
+ const fields = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig);
+ const provider = ctx.config.runtimeConfig && "provider" in ctx.config.runtimeConfig ? ctx.config.runtimeConfig.provider : undefined;
+ return new SdkWorkerLane(this.factory, {
+ modulePath: installed.entry, cwd: ctx.workingDirectory, sessionId: ctx.config.sessionId, instructions: ctx.standingPrompt,
+ config: { model: fields.model, command: fields.command, reasoningEffort: fields.reasoningEffort,
+ ...(provider && "providerId" in provider ? { provider: { kind: provider.kind, providerId: provider.providerId, apiKey: provider.apiKey } } : {}),
+ },
+ }, spawnEnv);
+ }
+}
diff --git a/src/daemon/agent-driver/src/internal/sdk-worker-api.ts b/src/daemon/agent-driver/src/internal/sdk-worker-api.ts
new file mode 100644
index 000000000..915b9da81
--- /dev/null
+++ b/src/daemon/agent-driver/src/internal/sdk-worker-api.ts
@@ -0,0 +1,97 @@
+import type { AdapterEvent, LaneAdmission, LaneSendInput, ProbeResult } from "./adapter.js";
+import type { SessionAcquisition } from "../contract.js";
+
+export type SdkWorkerEvent = AdapterEvent | { readonly kind: "worker_error"; readonly code: string; readonly message: string };
+
+export interface SdkWorkerInit {
+ readonly moduleUrl: string;
+ readonly cwd: string;
+ readonly sessionId?: string;
+ readonly instructions?: string;
+ readonly config: {
+ readonly model?: string;
+ readonly command?: string;
+ readonly reasoningEffort?: string;
+ readonly provider?: { readonly kind: string; readonly providerId?: string; readonly apiKey?: string };
+ };
+ readonly probe?: { readonly includeModels: boolean };
+}
+
+export interface SdkWorkerSession {
+ readonly sessionId: string;
+ readonly acquisition?: SessionAcquisition;
+ send(input: LaneSendInput): Promise<LaneAdmission>;
+ interrupt(): Promise<boolean>;
+ close(): Promise<void>;
+}
+
+export type SdkWorkerFactory = (
+ init: SdkWorkerInit,
+ emit: (event: SdkWorkerEvent) => void,
+) => Promise<SdkWorkerSession | ProbeResult>;
+
+export async function sdkWorkerMain(factory: SdkWorkerFactory): Promise<void> {
+ const load = new Function("specifier", "return import(specifier)") as (specifier: string) => Promise<typeof import("node:readline")>;
+ const { createInterface } = await load("node:readline");
+ const write = process.stdout.write.bind(process.stdout);
+ process.stdout.write = process.stderr.write.bind(process.stderr);
+ const send = (message: unknown): void => { write(`${JSON.stringify(message)}\n`); };
+ let session: SdkWorkerSession | undefined;
+ let closing = false;
+ let opening: Promise<void> | undefined;
+ const close = async (): Promise<void> => {
+ if (closing) return;
+ closing = true;
+ await opening?.catch(() => {});
+ await session?.close();
+ };
+ const fail = (id: number, error: unknown): void => {
+ const value = error as { code?: unknown; message?: unknown } | undefined;
+ send({ id, error: {
+ code: typeof value?.code === "string" ? value.code : "sdk_request_failed",
+ message: error instanceof Error ? error.message : "SDK request failed",
+ } });
+ };
+ const request = async (frame: { id: number; method: string; params: unknown }): Promise<void> => {
+ try {
+ if (frame.method === "open") {
+ if (opening || session || closing) throw new Error("SDK worker was already opened or stopped");
+ opening = (async () => {
+ const init = frame.params as SdkWorkerInit;
+ const result = await factory(init, (event) => send({ event }));
+ if ("status" in result) {
+ send({ id: frame.id, result });
+ return;
+ }
+ session = result;
+ send({ event: { kind: "session_init", sessionId: result.sessionId, acquisition: result.acquisition } });
+ send({ id: frame.id, result: { sessionId: result.sessionId } });
+ })();
+ await opening;
+ return;
+ }
+ if (frame.method === "close") {
+ await close();
+ send({ id: frame.id, result: null });
+ return;
+ }
+ if (closing || !session) throw new Error("SDK worker is not open");
+ if (frame.method === "send") send({ id: frame.id, result: await session.send(frame.params as LaneSendInput) });
+ else if (frame.method === "interrupt") send({ id: frame.id, result: await session.interrupt() });
+ else throw new Error("Unknown SDK worker request");
+ } catch (error) { fail(frame.id, error); }
+ };
+ const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
+ lines.on("line", (line: string) => {
+ if (Buffer.byteLength(line) > 8 * 1024 * 1024) { process.exitCode = 1; lines.close(); return; }
+ try {
+ const frame = JSON.parse(line) as { id: number; method: string; params: unknown };
+ if (!Number.isSafeInteger(frame.id) || typeof frame.method !== "string") throw new Error("Invalid request");
+ void request(frame);
+ } catch { process.exitCode = 1; lines.close(); }
+ });
+ lines.on("close", () => { void close().finally(() => process.exit(process.exitCode ?? 0)); });
+ for (const signal of ["SIGTERM", "SIGINT"] as const) {
+ process.on(signal, () => { void close().finally(() => process.exit(0)); });
+ }
+}
diff --git a/src/daemon/agent-driver/src/internal/sdk-worker-lane.test.ts b/src/daemon/agent-driver/src/internal/sdk-worker-lane.test.ts
new file mode 100644
index 000000000..53863576b
--- /dev/null
+++ b/src/daemon/agent-driver/src/internal/sdk-worker-lane.test.ts
@@ -0,0 +1,97 @@
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
+import type { SdkWorkerLane } from "./sdk-worker-lane.js";
+import type { SdkWorkerFactory } from "./sdk-worker-api.js";
+import type { AdapterEvent } from "./adapter.js";
+
+import { buildSdkWorkerArtifact } from "../testing/sdk-worker-artifact.spec.js";
+
+let artifact: Awaited<ReturnType<typeof buildSdkWorkerArtifact>>;
+beforeAll(async () => { artifact = await buildSdkWorkerArtifact(); });
+afterAll(() => artifact?.dispose());
+
+const roots: string[] = [];
+const lanes: SdkWorkerLane[] = [];
+afterEach(async () => {
+ for (const lane of lanes.splice(0)) await lane.stop({ forceAfterMs: 100 });
+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
+});
+
+function worker(factory: SdkWorkerFactory): SdkWorkerLane {
+ const cwd = mkdtempSync(join(tmpdir(), "alook-worker-protocol-"));
+ roots.push(cwd);
+ const lane = new artifact.SdkWorkerLane(factory, { modulePath: "unused", cwd, config: {}, probe: { includeModels: false } }, { ...process.env });
+ lanes.push(lane);
+ return lane;
+}
+
+describe("owned SDK worker transport", () => {
+ it("imports a native filesystem entry with spaces, Unicode, percent and fragment characters", async () => {
+ const cwd = mkdtempSync(join(tmpdir(), "alook SDK 你好 #%-"));
+ roots.push(cwd);
+ const modulePath = join(cwd, "sdk #%.mjs");
+ writeFileSync(modulePath, "export const status = 'healthy';\n");
+ const lane = new artifact.SdkWorkerLane(async (init) => {
+ if (!init.moduleUrl.startsWith("file:")) throw new Error("Expected a file URL");
+ const load = new Function("specifier", "return import(specifier)") as (specifier: string) => Promise<any>;
+ return { status: (await load(init.moduleUrl)).status };
+ }, { modulePath, cwd, config: {}, probe: { includeModels: false } }, { ...process.env });
+ lanes.push(lane);
+ expect(await lane.probe()).toEqual({ status: "healthy" });
+ });
+
+ it("preserves UTF-8 text and stderr across individual byte boundaries", async () => {
+ const lane = worker(async () => {
+ const load = new Function("specifier", "return import(specifier)") as (specifier: string) => Promise<any>;
+ const { writeSync } = await load("node:fs");
+ const line = Buffer.from(`${JSON.stringify({ event: { kind: "assistant_message_delta", text: "你好😀" } })}\n`);
+ for (const byte of line) {
+ writeSync(1, Buffer.from([byte]));
+ await new Promise((resolve) => setTimeout(resolve, 1));
+ }
+ for (const byte of Buffer.from("日志😀")) {
+ writeSync(2, Buffer.from([byte]));
+ await new Promise((resolve) => setTimeout(resolve, 1));
+ }
+ return { status: "healthy" };
+ });
+ const events: AdapterEvent[] = [];
+ let stderr = "";
+ lane.on("runtime_event", (event) => events.push(event));
+ const stderrComplete = new Promise<void>((resolve) => {
+ lane.on("stderr", (text) => {
+ stderr += text;
+ if (Buffer.byteLength(stderr) >= Buffer.byteLength("日志😀")) resolve();
+ });
+ });
+ expect(await lane.probe()).toEqual({ status: "healthy" });
+ await stderrComplete;
+ expect(events).toEqual([{ kind: "assistant_message_delta", text: "你好😀" }]);
+ expect(stderr).toBe("日志😀");
+ });
+
+ it("preserves stdout write encoding, callbacks and backpressure return type", async () => {
+ const lane = worker(async () => {
+ await new Promise<void>((resolve, reject) => {
+ const writable = process.stdout.write("带编码😀", "utf8", (error) => error ? reject(error) : resolve());
+ if (typeof writable !== "boolean") reject(new Error("Lost native write return value"));
+ });
+ await new Promise<void>((resolve, reject) => {
+ process.stdout.write("带回调", (error) => error ? reject(error) : resolve());
+ });
+ return { status: "healthy" };
+ });
+ let stderr = "";
+ const stderrComplete = new Promise<void>((resolve) => {
+ lane.on("stderr", (text) => {
+ stderr += text;
+ if (Buffer.byteLength(stderr) >= Buffer.byteLength("带编码😀带回调")) resolve();
+ });
+ });
+ expect(await lane.probe()).toEqual({ status: "healthy" });
+ await stderrComplete;
+ expect(stderr).toBe("带编码😀带回调");
+ });
+});
diff --git a/src/daemon/agent-driver/src/internal/sdk-worker-lane.ts b/src/daemon/agent-driver/src/internal/sdk-worker-lane.ts
new file mode 100644
index 000000000..34bfc7216
--- /dev/null
+++ b/src/daemon/agent-driver/src/internal/sdk-worker-lane.ts
@@ -0,0 +1,179 @@
+import { EventEmitter } from "node:events";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { StringDecoder } from "node:string_decoder";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { pathToFileURL } from "node:url";
+import type {
+ LaneAdmission, LaneSendInput, LaneStartInput, LaneStopInput,
+ RuntimeLane, RuntimeLaneEventMap, SpawnedProcessHandle,
+} from "./adapter.js";
+import { killProcessTree, spawnAgentProcess, SESSION_STOP_GRACE_MS } from "./killTree.js";
+import { scrubDriverErrorMessage } from "./errors.js";
+import { sdkWorkerMain, type SdkWorkerFactory, type SdkWorkerInit, type SdkWorkerEvent } from "./sdk-worker-api.js";
+
+class SdkRequestError extends Error {
+ constructor(readonly code: string, message: string) { super(message); }
+}
+
+const MAX_LINE_BYTES = 8 * 1024 * 1024;
+
+export class SdkWorkerLane implements RuntimeLane {
+ private readonly events = new EventEmitter();
+ private readonly pending = new Map<number, { resolve(value: unknown): void; reject(error: unknown): void; timer: ReturnType<typeof setTimeout> }>();
+ private readonly child: SpawnedProcessHandle;
+ private readonly directory: string;
+ private readonly init: SdkWorkerInit;
+ private sequence = 0;
+ private sessionId: string | null = null;
+ private buffer = "";
+ private readonly stdoutDecoder = new StringDecoder("utf8");
+ private readonly stderrDecoder = new StringDecoder("utf8");
+ private started = false;
+ private stopping = false;
+ private exited = false;
+ private stopPromise?: Promise<void>;
+
+ constructor(
+ factory: SdkWorkerFactory,
+ init: Omit<SdkWorkerInit, "moduleUrl"> & { readonly modulePath: string },
+ environment: NodeJS.ProcessEnv,
+ ) {
+ const { modulePath, ...options } = init;
+ this.init = { ...options, moduleUrl: pathToFileURL(modulePath).href };
+ const source = `void (${sdkWorkerMain.toString()})(${factory.toString()});`;
+ this.directory = mkdtempSync(join(tmpdir(), "alook-sdk-worker-"));
+ this.events.on("error", () => {});
+ const entry = join(this.directory, "worker.mjs");
+ try {
+ writeFileSync(entry, source, { mode: 0o600 });
+ this.child = spawnAgentProcess(process.execPath, ["--experimental-import-meta-resolve", entry], { cwd: init.cwd, env: environment, shell: false });
+ } catch (error) { rmSync(this.directory, { recursive: true, force: true }); throw error; }
+ this.child.stdout?.on("data", (chunk) => this.read(this.stdoutDecoder.write(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk.toString()))));
+ this.child.stderr?.on("data", (chunk) => {
+ const text = this.stderrDecoder.write(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk.toString()));
+ if (text) this.events.emit("stderr", scrubDriverErrorMessage(text));
+ });
+ this.child.on("error", (error) => {
+ this.rejectPending(error);
+ this.events.emit("error", error);
+ });
+ this.child.on("exit", (code, signal) => {
+ this.exited = true;
+ this.rejectPending(new Error("SDK worker exited"));
+ this.events.emit("exit", { code, signal, reason: this.stopping ? "requested" : "runtime_exit" });
+ });
+ }
+
+ get currentSessionId(): string | null { return this.sessionId; }
+
+ on<K extends keyof RuntimeLaneEventMap>(event: K, listener: (value: RuntimeLaneEventMap[K]) => void): void {
+ this.events.on(event, listener);
+ }
+
+ async start(input: LaneStartInput): Promise<LaneAdmission> {
+ if (this.started || this.stopping) return { ok: false, reason: "closed" };
+ this.started = true;
+ try {
+ await this.request("open", this.init);
+ return await this.send({ ...input, mode: "idle" });
+ } catch (error) {
+ if (error instanceof SdkRequestError) return { ok: false, reason: error.code === "authentication_required" ? "authentication" : error.code, error: error.message };
+ throw error;
+ }
+ }
+
+ async probe(): Promise<unknown> { return this.request("open", this.init, this.init.probe?.includeModels ? 10_000 : 5_000); }
+
+ async send(input: LaneSendInput): Promise<LaneAdmission> {
+ if (this.stopping || this.exited) return { ok: false, reason: "closed" };
+ return await this.request("send", input) as LaneAdmission;
+ }
+
+ async interrupt(): Promise<boolean> {
+ if (this.stopping || this.exited) return false;
+ return await this.request("interrupt", {}) === true;
+ }
+
+ stop(input: LaneStopInput = {}): Promise<void> {
+ this.stopPromise ??= this.stopOnce(input);
+ return this.stopPromise;
+ }
+
+ private async stopOnce(input: LaneStopInput): Promise<void> {
+ this.stopping = true;
+ this.rejectPending(new Error("SDK worker is stopping"));
+ try {
+ if (this.child.pid) await killProcessTree(this.child.pid, { graceMs: input.forceAfterMs ?? SESSION_STOP_GRACE_MS });
+ else if (!this.exited) this.child.kill("SIGTERM");
+ } finally { rmSync(this.directory, { recursive: true, force: true }); }
+ }
+
+ private request(method: string, params: unknown, timeoutMs = 60_000): Promise<unknown> {
+ if (this.exited || !this.child.stdin || this.child.stdin.destroyed || this.child.stdin.writableEnded || this.child.stdin.writable === false) {
+ return Promise.reject(new Error("SDK worker stdin is unavailable"));
+ }
+ const id = ++this.sequence;
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ if (!this.pending.delete(id)) return;
+ reject(new Error(`SDK ${method} did not acknowledge before its deadline`));
+ }, timeoutMs);
+ timer.unref?.();
+ this.pending.set(id, { resolve, reject, timer });
+ try {
+ const line = JSON.stringify({ id, method, params });
+ if (Buffer.byteLength(line) > MAX_LINE_BYTES) throw new Error("SDK worker input exceeds its protocol limit");
+ this.child.stdin!.write(`${line}\n`);
+ } catch (error) {
+ clearTimeout(timer);
+ this.pending.delete(id);
+ reject(error);
+ }
+ });
+ }
+
+ private read(chunk: string): void {
+ this.buffer += chunk;
+ let end: number;
+ while ((end = this.buffer.indexOf("\n")) !== -1) {
+ const line = this.buffer.slice(0, end);
+ this.buffer = this.buffer.slice(end + 1);
+ if (Buffer.byteLength(line) > MAX_LINE_BYTES) { this.protocolFailure(); return; }
+ try {
+ const frame = JSON.parse(line) as { id?: number; result?: unknown; error?: { code?: string; message?: string }; event?: SdkWorkerEvent };
+ if (typeof frame.id === "number") {
+ const pending = this.pending.get(frame.id);
+ if (!pending) continue;
+ clearTimeout(pending.timer);
+ this.pending.delete(frame.id);
+ if (frame.error) {
+ const code = frame.error.code;
+ const message = scrubDriverErrorMessage(frame.error.message);
+ pending.reject(code === "reset_required" || code === "incompatible_configuration" || code === "authentication_required" || code === "runtime_busy"
+ ? new SdkRequestError(code, message) : new Error(message));
+ } else pending.resolve(frame.result);
+ } else if (frame.event && typeof frame.event.kind === "string") {
+ if (frame.event.kind === "worker_error") { this.protocolFailure(frame.event.message); return; }
+ if (frame.event.kind === "session_init") this.sessionId = frame.event.sessionId;
+ if (frame.event.kind === "error" || frame.event.kind === "runtime_diagnostic") frame.event.message = scrubDriverErrorMessage(frame.event.message);
+ this.events.emit("runtime_event", frame.event);
+ }
+ } catch { this.protocolFailure(); return; }
+ }
+ if (Buffer.byteLength(this.buffer) > MAX_LINE_BYTES) this.protocolFailure();
+ }
+
+ private protocolFailure(message = "SDK worker emitted an invalid or oversized protocol frame"): void {
+ this.buffer = "";
+ const error = new Error(scrubDriverErrorMessage(message));
+ this.rejectPending(error);
+ this.events.emit("error", error);
+ void this.stop({ reason: "protocol_error", forceAfterMs: 0 }).catch(() => {});
+ }
+
+ private rejectPending(error: unknown): void {
+ for (const item of this.pending.values()) { clearTimeout(item.timer); item.reject(error); }
+ this.pending.clear();
+ }
+}
diff --git a/src/daemon/agent-driver/src/public-contract.ts b/src/daemon/agent-driver/src/public-contract.ts
index 326d374d9..7e3190043 100644
--- a/src/daemon/agent-driver/src/public-contract.ts
+++ b/src/daemon/agent-driver/src/public-contract.ts
@@ -4,10 +4,12 @@ import { SESSION_FILE_DISCOVERY_CAPABILITIES as sessionFileDiscoveryCapabilities
export const SESSION_FILE_DISCOVERY_CAPABILITIES = sessionFileDiscoveryCapabilities;
export type {
+ InputReference, InputReturnEvidence, ExecutionOutcome, EventAttribution, SessionAcquisition, RuntimeConfigurationObservation,
JsonPrimitive, JsonValue, JsonObject, BuiltinBackendId, ReasoningEffort, RuntimeReasoningCatalog,
RuntimeSettingsUpdate, RuntimeSettingsUpdateResult, ModelSelection, DefaultProvider,
AntigravityConfig, AntigravityCapabilities, AgyConfig, AgyCapabilities, ClaudeProvider, PiProvider, BaseBackendConfig, ClaudeConfig, CodexConfig, ModelBackendConfig, CursorConfig,
GrokConfig, OpenCodeConfig, PiConfig, BackendCapabilities, ClaudeCapabilities, CodexCapabilities, CursorCapabilities,
+ QoderConfig, CopilotConfig, CursorSdkConfig, PiDurableConfig, QoderCapabilities, CopilotCapabilities, CursorSdkCapabilities, PiDurableCapabilities,
GrokCapabilities, OpenCodeCapabilities, PiCapabilities, BackendExtensionSpec, BackendTypeSpec, BuiltinBackendSpecs, BackendId,
FixedCapabilities, ConfigOf, CapabilitiesOf, ExtensionsOf, ExtraEventOf, AgentInstructions, AgentLaunchContext, AgentMessage,
AgentDriverError, OpenSessionResult, DeliveryReceipt, InterruptResult, StopInput, StopReceipt, HostCleanupResult,
diff --git a/src/daemon/agent-driver/src/registry.test.ts b/src/daemon/agent-driver/src/registry.test.ts
index 1f3d3000e..da0476c48 100644
--- a/src/daemon/agent-driver/src/registry.test.ts
+++ b/src/daemon/agent-driver/src/registry.test.ts
@@ -13,10 +13,14 @@ import { ADAPTER_AUTHOR_CONTRACT_VERSION } from "./adapter-author.js";
* without updating `capabilities`) trips CI.
*/
const EXPECTED: Record<BuiltinBackendId, BackendCapabilities> = {
+ qoder: { modelSelection: "launchable", providerConfiguration: false, reasoningEffort: true, fastMode: false, disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "steer", interrupt: true },
+ copilot: { modelSelection: "launchable", providerConfiguration: false, reasoningEffort: true, fastMode: false, disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "steer", interrupt: true },
+ "cursor-sdk": { modelSelection: "launchable", providerConfiguration: false, reasoningEffort: true, fastMode: false, disallowedTools: false, commandOverride: false, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "steer", interrupt: true },
+ "pi-durable": { modelSelection: "launchable", providerConfiguration: true, reasoningEffort: true, fastMode: false, disallowedTools: false, commandOverride: false, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "steer", interrupt: true },
agy: { modelSelection: "launchable", providerConfiguration: false, reasoningEffort: true, fastMode: false, disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "next_turn_queue", interrupt: false },
antigravity: { modelSelection: "launchable", providerConfiguration: false, reasoningEffort: true, fastMode: false, disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "next_turn_queue", interrupt: true },
- claude: { modelSelection: "launchable", providerConfiguration: true, reasoningEffort: true, fastMode: true, disallowedTools: true, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "safe_boundary_queue", interrupt: true },
- codex: { modelSelection: "launchable", providerConfiguration: false, reasoningEffort: true, fastMode: true, disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "safe_boundary_queue", interrupt: true },
+ claude: { modelSelection: "launchable", providerConfiguration: true, reasoningEffort: true, fastMode: true, disallowedTools: true, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "steer", interrupt: true },
+ codex: { modelSelection: "launchable", providerConfiguration: false, reasoningEffort: true, fastMode: true, disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "steer", interrupt: true },
cursor: { modelSelection: "launchable", providerConfiguration: false, reasoningEffort: false, fastMode: false, disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "steer", interrupt: true },
grok: { modelSelection: "launchable", providerConfiguration: false, reasoningEffort: true, fastMode: false, disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "safe_boundary_queue", interrupt: true },
opencode: { modelSelection: "launchable", providerConfiguration: false, reasoningEffort: false, fastMode: false, disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "steer", interrupt: true },
@@ -29,9 +33,13 @@ describe("driver.capabilities", () => {
});
it("pins the orthogonal built-in execution matrix and adapter-author version", () => {
- expect(ADAPTER_AUTHOR_CONTRACT_VERSION).toBe(1);
+ expect(ADAPTER_AUTHOR_CONTRACT_VERSION).toBe(2);
const registry = createBuiltinAgentDriverRegistry();
const expected = {
+ "qoder": { lifetime: "session", transport: { kind: "stdio_rpc", protocol: "qoder.sdk-worker.v1" }, wakeStart: "immediate", terminalOwnership: "prompt_invocation" },
+ "copilot": { lifetime: "session", transport: { kind: "stdio_rpc", protocol: "copilot.sdk-worker.v1" }, wakeStart: "immediate", terminalOwnership: "prompt_invocation" },
+ "cursor-sdk": { lifetime: "session", transport: { kind: "stdio_rpc", protocol: "cursor-sdk.sdk-worker.v1" }, wakeStart: "immediate", terminalOwnership: "prompt_invocation" },
+ "pi-durable": { lifetime: "session", transport: { kind: "stdio_rpc", protocol: "pi-durable.sdk-worker.v1" }, wakeStart: "immediate", terminalOwnership: "prompt_invocation" },
agy: { lifetime: "session", transport: { kind: "stdio_stream", protocol: "agy.stream-json.v1" }, wakeStart: "immediate", terminalOwnership: "vendor_message" },
antigravity: { lifetime: "session", transport: { kind: "stdio_rpc", protocol: "antigravity.acp.v1" }, wakeStart: "immediate", terminalOwnership: "transport_request" },
claude: {
@@ -79,7 +87,7 @@ describe("driver.capabilities", () => {
} as const;
for (const id of BUILTIN_BACKEND_IDS) {
const registration = registry.get(id);
- expect(registration.contractVersion).toBe(1);
+ expect(registration.contractVersion).toBe(2);
expect(registration.createAdapter().execution).toEqual(expected[id]);
}
});
@@ -95,7 +103,7 @@ describe("adapter registration runtime boundary", () => {
}] as never)).toThrow("non-empty id");
const registration = {
id: "sixth",
- contractVersion: 1 as const,
+ contractVersion: 2 as const,
capabilities: EXPECTED.claude,
createAdapter: () => ({}),
};
@@ -105,7 +113,7 @@ describe("adapter registration runtime boundary", () => {
it("accepts the public suggestion_only model-selection capability for extension adapters", () => {
const registration = {
id: "sixth",
- contractVersion: 1 as const,
+ contractVersion: 2 as const,
capabilities: { ...EXPECTED.claude, modelSelection: "suggestion_only" },
createAdapter: () => ({}),
};
@@ -115,7 +123,7 @@ describe("adapter registration runtime boundary", () => {
it("rejects each malformed registration capability and adapter shape at runtime", () => {
const valid = {
id: "sixth",
- contractVersion: 1 as const,
+ contractVersion: 2 as const,
capabilities: EXPECTED.claude,
createAdapter: () => new (class {
id = "sixth";
@@ -146,11 +154,11 @@ describe("adapter registration runtime boundary", () => {
it("fails closed for missing, old, and unknown adapter-author contract versions", () => {
const valid = {
id: "sixth",
- contractVersion: 1,
+ contractVersion: 2,
capabilities: EXPECTED.claude,
createAdapter: () => ({}),
};
- for (const contractVersion of [undefined, 0, 2]) {
+ for (const contractVersion of [undefined, 0, 1, 3]) {
expect(() => createAgentDriverRegistry([{ ...valid, contractVersion }] as never))
.toThrow("unsupported adapter-author contract version");
}
diff --git a/src/daemon/agent-driver/src/registry.ts b/src/daemon/agent-driver/src/registry.ts
index 59a888b52..f086013bc 100644
--- a/src/daemon/agent-driver/src/registry.ts
+++ b/src/daemon/agent-driver/src/registry.ts
@@ -14,11 +14,16 @@ import { CursorDriver } from "./adapters/cursor/index.js";
import { GrokDriver } from "./adapters/grok/index.js";
import { OpenCodeDriver } from "./adapters/opencode/index.js";
import { PiDriver } from "./adapters/pi/index.js";
+import { OptionalSdkDriver } from "./internal/optional-sdk-driver.js";
+import { cursorSdkWorker } from "./adapters/cursor-sdk/worker.js";
+import { copilotWorker } from "./adapters/copilot/worker.js";
+import { qoderWorker } from "./adapters/qoder/worker.js";
+import { piDurableWorker } from "./adapters/pi-durable/worker.js";
import type { BackendAdapter } from "./internal/adapter.js";
export interface AgentBackendRegistration<Specs, Id extends BackendId<Specs>> {
readonly id: Id;
- readonly contractVersion: 1;
+ readonly contractVersion: 2;
readonly capabilities: CapabilitiesOf<Specs, Id>;
createAdapter(): BackendAdapter<Id, ConfigOf<Specs, Id>>;
}
@@ -58,7 +63,7 @@ export function assertRegistrationShape(registration: unknown): void {
if (typeof candidate.id !== "string" || candidate.id.length === 0) {
throw new Error("Agent backend registration requires a non-empty id");
}
- if (candidate.contractVersion !== 1) {
+ if (candidate.contractVersion !== 2) {
throw new Error(`Agent backend registration ${candidate.id} has an unsupported adapter-author contract version`);
}
if (!candidate.capabilities || typeof candidate.capabilities !== "object") {
@@ -185,9 +190,25 @@ export function assertAdapterCompatibility(
}
}
-export const BUILTIN_BACKEND_IDS = ["claude", "codex", "cursor", "grok", "opencode", "pi", "antigravity", "agy"] as const;
+export const BUILTIN_BACKEND_IDS = ["claude", "codex", "cursor", "grok", "opencode", "pi", "antigravity", "agy", "qoder", "copilot", "cursor-sdk", "pi-durable"] as const;
const capabilities = {
+ qoder: {
+ modelSelection: "launchable", providerConfiguration: false, reasoningEffort: true, fastMode: false,
+ disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "steer", interrupt: true,
+ },
+ copilot: {
+ modelSelection: "launchable", providerConfiguration: false, reasoningEffort: true, fastMode: false,
+ disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "steer", interrupt: true,
+ },
+ "cursor-sdk": {
+ modelSelection: "launchable", providerConfiguration: false, reasoningEffort: true, fastMode: false,
+ disallowedTools: false, commandOverride: false, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "steer", interrupt: true,
+ },
+ "pi-durable": {
+ modelSelection: "launchable", providerConfiguration: true, reasoningEffort: true, fastMode: false,
+ disallowedTools: false, commandOverride: false, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "steer", interrupt: true,
+ },
agy: {
modelSelection: "launchable", providerConfiguration: false, reasoningEffort: true, fastMode: false,
disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "next_turn_queue", interrupt: false,
@@ -198,11 +219,11 @@ const capabilities = {
},
claude: {
modelSelection: "launchable", providerConfiguration: true, reasoningEffort: true, fastMode: true,
- disallowedTools: true, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "safe_boundary_queue", interrupt: true,
+ disallowedTools: true, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "steer", interrupt: true,
},
codex: {
modelSelection: "launchable", providerConfiguration: false, reasoningEffort: true, fastMode: true,
- disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "safe_boundary_queue", interrupt: true,
+ disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "steer", interrupt: true,
},
cursor: {
modelSelection: "launchable", providerConfiguration: false, reasoningEffort: false, fastMode: false,
@@ -224,14 +245,18 @@ const capabilities = {
export function createBuiltinAgentDriverRegistry(): AgentDriverRegistry<BuiltinBackendSpecs> {
return createAgentDriverRegistry<BuiltinBackendSpecs>([
- { id: "claude", contractVersion: 1, capabilities: capabilities.claude, createAdapter: () => new ClaudeDriver() },
- { id: "codex", contractVersion: 1, capabilities: capabilities.codex, createAdapter: () => new CodexDriver() },
- { id: "cursor", contractVersion: 1, capabilities: capabilities.cursor, createAdapter: () => new CursorDriver() },
- { id: "grok", contractVersion: 1, capabilities: capabilities.grok, createAdapter: () => new GrokDriver() },
- { id: "opencode", contractVersion: 1, capabilities: capabilities.opencode, createAdapter: () => new OpenCodeDriver() },
- { id: "pi", contractVersion: 1, capabilities: capabilities.pi, createAdapter: () => new PiDriver() },
- { id: "antigravity", contractVersion: 1, capabilities: capabilities.antigravity, createAdapter: () => new AntigravityDriver() },
- { id: "agy", contractVersion: 1, capabilities: capabilities.agy, createAdapter: () => new AgyDriver() },
+ { id: "claude", contractVersion: 2, capabilities: capabilities.claude, createAdapter: () => new ClaudeDriver() },
+ { id: "codex", contractVersion: 2, capabilities: capabilities.codex, createAdapter: () => new CodexDriver() },
+ { id: "cursor", contractVersion: 2, capabilities: capabilities.cursor, createAdapter: () => new CursorDriver() },
+ { id: "grok", contractVersion: 2, capabilities: capabilities.grok, createAdapter: () => new GrokDriver() },
+ { id: "opencode", contractVersion: 2, capabilities: capabilities.opencode, createAdapter: () => new OpenCodeDriver() },
+ { id: "pi", contractVersion: 2, capabilities: capabilities.pi, createAdapter: () => new PiDriver() },
+ { id: "antigravity", contractVersion: 2, capabilities: capabilities.antigravity, createAdapter: () => new AntigravityDriver() },
+ { id: "agy", contractVersion: 2, capabilities: capabilities.agy, createAdapter: () => new AgyDriver() },
+ { id: "qoder", contractVersion: 2, capabilities: capabilities.qoder, createAdapter: () => new OptionalSdkDriver("qoder", "@qoder-ai/qoder-agent-sdk", qoderWorker, undefined, { kind: "native" }) },
+ { id: "copilot", contractVersion: 2, capabilities: capabilities.copilot, createAdapter: () => new OptionalSdkDriver("copilot", "@github/copilot-sdk", copilotWorker, undefined, { kind: "native" }) },
+ { id: "cursor-sdk", contractVersion: 2, capabilities: capabilities["cursor-sdk"], createAdapter: () => new OptionalSdkDriver("cursor-sdk", "@cursor/sdk", cursorSdkWorker) },
+ { id: "pi-durable", contractVersion: 2, capabilities: capabilities["pi-durable"], createAdapter: () => new OptionalSdkDriver("pi-durable", "@earendil-works/pi-durable", piDurableWorker, undefined, { kind: "native" }) },
]);
}
diff --git a/src/daemon/agent-driver/src/sdk.test.ts b/src/daemon/agent-driver/src/sdk.test.ts
index 8b56b1db9..358390899 100644
--- a/src/daemon/agent-driver/src/sdk.test.ts
+++ b/src/daemon/agent-driver/src/sdk.test.ts
@@ -39,7 +39,7 @@ const claudeCapabilities = {
commandOverride: true,
resume: "by_id",
sessionLifetime: "persistent",
- midTurnDelivery: "safe_boundary_queue",
+ midTurnDelivery: "steer",
interrupt: true,
} as const;
@@ -58,7 +58,7 @@ function sdkTestLane(receipt = "fresh-receipt") {
describe("createAgentDriverSdk", () => {
it("exposes the built-ins with default options", () => {
- expect(createAgentDriverSdk().backendIds).toEqual(["claude", "codex", "cursor", "grok", "opencode", "pi", "antigravity", "agy"]);
+ expect(createAgentDriverSdk().backendIds).toEqual(["claude", "codex", "cursor", "grok", "opencode", "pi", "antigravity", "agy", "qoder", "copilot", "cursor-sdk", "pi-durable"]);
expect(SESSION_FILE_DISCOVERY_CAPABILITIES).toEqual(["supported", "unavailable"]);
});
@@ -128,7 +128,7 @@ describe("createAgentDriverSdk", () => {
});
it("public SDK factory delegates to the built-in logical SDK", () => {
- expect(createPublicAgentDriverSdk().backendIds).toEqual(["claude", "codex", "cursor", "grok", "opencode", "pi", "antigravity", "agy"]);
+ expect(createPublicAgentDriverSdk().backendIds).toEqual(["claude", "codex", "cursor", "grok", "opencode", "pi", "antigravity", "agy", "qoder", "copilot", "cursor-sdk", "pi-durable"]);
});
it.each(["claude", "codex", "cursor", "grok", "opencode", "pi"] as const)(
@@ -225,7 +225,7 @@ describe("createAgentDriverSdk", () => {
const opened = await createAgentDriverSdk({ host, hostReleaseTimeoutMs: 25 }).open(claudeInput);
expect(opened.ok).toBe(true);
if (!opened.ok) throw new Error("expected a session");
- expect(opened.capabilities.midTurnDelivery).toBe("safe_boundary_queue");
+ expect(opened.capabilities.midTurnDelivery).toBe("steer");
expect(opened.session.snapshot()).toMatchObject({ state: "new", queuedCommands: [] });
await opened.session.stop({ reason: "shutdown", forceAfterMs: 1 });
expect(host.releases).toHaveLength(1);
@@ -246,7 +246,7 @@ describe("createAgentDriverSdk", () => {
});
const registry = createAgentDriverRegistry<BuiltinBackendSpecs>([{
id: "claude",
- contractVersion: 1,
+ contractVersion: 2,
capabilities: claudeCapabilities,
createAdapter: () => adapter,
}]);
@@ -286,7 +286,7 @@ describe("createAgentDriverSdk", () => {
});
const registry = createAgentDriverRegistry<BuiltinBackendSpecs>([{
id: "claude",
- contractVersion: 1,
+ contractVersion: 2,
capabilities: claudeCapabilities,
createAdapter: () => adapter,
}]);
@@ -319,7 +319,7 @@ describe("createAgentDriverSdk", () => {
vi.spyOn(adapter, "openLane").mockResolvedValue(lane);
const registry = createAgentDriverRegistry<BuiltinBackendSpecs>([{
id: "claude",
- contractVersion: 1,
+ contractVersion: 2,
capabilities: claudeCapabilities,
createAdapter: () => adapter,
}]);
@@ -354,7 +354,7 @@ describe("createAgentDriverSdk", () => {
const openLane = vi.spyOn(adapter, "openLane").mockResolvedValue(sdkTestLane());
const registry = createAgentDriverRegistry<BuiltinBackendSpecs>([{
id: "claude",
- contractVersion: 1,
+ contractVersion: 2,
capabilities: claudeCapabilities,
createAdapter: () => adapter,
}]);
@@ -422,7 +422,7 @@ describe("createAgentDriverSdk", () => {
};
const registry = createAgentDriverRegistry<SixthSpecs>([{
id: "sixth",
- contractVersion: 1,
+ contractVersion: 2,
capabilities,
createAdapter: () => adapter,
}]);
@@ -462,7 +462,7 @@ describe("createAgentDriverSdk", () => {
const prepare = vi.spyOn(host, "prepareExecution");
const registry = createAgentDriverRegistry<BuiltinBackendSpecs>([{
id: "claude",
- contractVersion: 1,
+ contractVersion: 2,
capabilities: claudeCapabilities,
createAdapter: () => {
const adapter = new ClaudeDriver();
@@ -491,7 +491,7 @@ describe("createAgentDriverSdk", () => {
});
const registry = createAgentDriverRegistry<BuiltinBackendSpecs>([{
id: "claude",
- contractVersion: 1,
+ contractVersion: 2,
capabilities: claudeCapabilities,
createAdapter: () => adapter,
}]);
@@ -514,8 +514,8 @@ describe("createAgentDriverSdk", () => {
it.each([
["missing", undefined],
- ["old", 0],
- ["unknown", 2],
+ ["old", 1],
+ ["unknown", 3],
] as const)("fails a %s contract version from an untrusted custom registry before side effects", async (_name, version) => {
const host = createFakeAgentDriverHost();
const prepare = vi.spyOn(host, "prepareExecution");
@@ -561,7 +561,7 @@ describe("createAgentDriverSdk", () => {
vi.spyOn(adapter, "probe").mockReturnValue({ status: "healthy", version: "7.0.0" });
const registry = createAgentDriverRegistry<BuiltinBackendSpecs>([{
id: "claude",
- contractVersion: 1,
+ contractVersion: 2,
capabilities: claudeCapabilities,
createAdapter: () => adapter,
}]);
@@ -600,7 +600,7 @@ describe("createAgentDriverSdk", () => {
const valid = new ClaudeDriver();
const registry = createAgentDriverRegistry<BuiltinBackendSpecs>([{
id: "claude",
- contractVersion: 1,
+ contractVersion: 2,
capabilities: claudeCapabilities,
createAdapter: () => {
for (const [key, value] of Object.entries(override)) {
diff --git a/src/daemon/agent-driver/src/testing/builtin-adapter-conformance.test.ts b/src/daemon/agent-driver/src/testing/builtin-adapter-conformance.test.ts
index 79e729ef9..77cb071a5 100644
--- a/src/daemon/agent-driver/src/testing/builtin-adapter-conformance.test.ts
+++ b/src/daemon/agent-driver/src/testing/builtin-adapter-conformance.test.ts
@@ -12,8 +12,12 @@ describe("builtin adapter protocol conformance", () => {
it("locks the exact built-in lifetime, transport, delivery, and terminal-owner matrix", () => {
const expected = {
- claude: ["session", "stdio_stream", "claude.stream-json.v1", "safe_boundary_queue", "vendor_message"],
- codex: ["session", "stdio_rpc", "codex.app-server.v1", "safe_boundary_queue", "transport_request"],
+ "qoder": ["session", "stdio_rpc", "qoder.sdk-worker.v1", "steer", "prompt_invocation"],
+ "copilot": ["session", "stdio_rpc", "copilot.sdk-worker.v1", "steer", "prompt_invocation"],
+ "cursor-sdk": ["session", "stdio_rpc", "cursor-sdk.sdk-worker.v1", "steer", "prompt_invocation"],
+ "pi-durable": ["session", "stdio_rpc", "pi-durable.sdk-worker.v1", "steer", "prompt_invocation"],
+ claude: ["session", "stdio_stream", "claude.stream-json.v1", "steer", "vendor_message"],
+ codex: ["session", "stdio_rpc", "codex.app-server.v1", "steer", "transport_request"],
cursor: ["session", "stdio_rpc", "cursor.acp.v1", "steer", "transport_request"],
agy: ["session", "stdio_stream", "agy.stream-json.v1", "next_turn_queue", "vendor_message"],
antigravity: ["session", "stdio_rpc", "antigravity.acp.v1", "next_turn_queue", "transport_request"],
@@ -85,7 +89,7 @@ describe("builtin adapter protocol conformance", () => {
});
});
- it("runs the real Codex adapter and rejects child completion/output in the shared contract", () => {
+ it("runs the real Codex adapter and keeps off-root completion/output outside root authority", () => {
const events = runAgentBackendAdapterConformance(registry.get("codex"), {
exercise(adapter) {
const rootThread = "codex-root";
@@ -100,9 +104,10 @@ describe("builtin adapter protocol conformance", () => {
...adapter.normalizeLine(line({ jsonrpc: "2.0", method: "turn/completed", params: { threadId: rootThread, turn: { id: rootTurn, status: "completed" } } })),
];
},
- expectedEventKinds: ["session_init", "turn_owner", "tool_call", "tool_output", "turn_end"],
+ expectedEventKinds: ["session_init", "turn_owner", "internal_progress", "assistant_message_delta", "tool_call", "tool_output", "turn_end"],
});
- expect(JSON.stringify(events)).not.toContain("must not leak");
+ expect(JSON.stringify(events.filter(event => !event.attribution || event.attribution.scope === "root"))).not.toContain("must not leak");
+ expect(events.filter(event => event.attribution?.scope === "unknown")).toHaveLength(2);
});
it("declares the real Cursor adapter as a lane-owned persistent ACP transport", () => {
diff --git a/src/daemon/agent-driver/src/testing/builtin-session-conformance.test.ts b/src/daemon/agent-driver/src/testing/builtin-session-conformance.test.ts
index add3c05e6..f4026fa31 100644
--- a/src/daemon/agent-driver/src/testing/builtin-session-conformance.test.ts
+++ b/src/daemon/agent-driver/src/testing/builtin-session-conformance.test.ts
@@ -41,6 +41,10 @@ import { capabilitiesFor, createAgentDriverRegistry, createBuiltinAgentDriverReg
import { createAgentDriverSdkWithRegistry } from "../sdk.js";
const configs: { [Id in BuiltinBackendId]: ConfigOf<BuiltinBackendSpecs, Id> } = {
+ qoder: { model: { kind: "default" } },
+ copilot: { model: { kind: "default" } },
+ "cursor-sdk": { model: { kind: "named", name: "fixture" } },
+ "pi-durable": { model: { kind: "named", name: "openai/fixture" }, provider: { kind: "default" } },
claude: { model: { kind: "default" }, provider: { kind: "default" }, mode: "default" },
codex: { model: { kind: "default" }, mode: "default" },
cursor: { model: { kind: "default" } },
@@ -195,7 +199,7 @@ function installVendorHarness(backend: BuiltinBackendId): VendorHarness {
return encoded;
});
}
- vi.spyOn(classes[backend].prototype, "spawn").mockImplementation(async (ctx: AdapterLaunchContext) => {
+ vi.spyOn(classes[backend as keyof typeof classes].prototype, "spawn").mockImplementation(async (ctx: AdapterLaunchContext) => {
contexts.push(ctx as AdapterLaunchContext);
const process = fakeProcess();
let stdinBuffer = "";
@@ -468,7 +472,7 @@ async function runPublicSessionLifecycle(backend: BuiltinBackendId): Promise<voi
});
const busy = await session.send({ id: "busy", kind: "user", text: "busy" });
- expect(busy.status).toBe(backend === "pi" || backend === "opencode" || backend === "cursor" ? "accepted" : "queued");
+ expect(busy.status).toBe(backend === "pi" || backend === "opencode" || backend === "cursor" || backend === "claude" || backend === "codex" ? "accepted" : "queued");
const interrupted = await session.interrupt({ requestId: "interrupt-1", reason: "conformance" });
expect(interrupted.status).toBe("accepted");
if (backend === "claude") {
@@ -578,6 +582,21 @@ function emitStaleTerminal(backend: BuiltinBackendId, harness: VendorHarness): v
}
describe("native primitive regressions through registered public sessions", () => {
+ describe.each(["cursor", "grok", "antigravity"] as const)("%s native stop reasons", (backend) => {
+ it.each(["end_turn", "refusal", "max_tokens", "max_turn_requests", "cancelled"] as const)("preserves %s through the public session and remains reusable", async (stopReason) => {
+ const fixture = await openRegisteredHarness(backend, "native-stop-reason");
+ try {
+ await settlePromptAdmission(backend, fixture.harness, 1, fixture.session.start({ id: "first", kind: "user", text: "first" }));
+ fixture.harness.duplicateTurn(1, { stopReason });
+ const outcome = stopReason === "end_turn" ? "success" : stopReason === "cancelled" ? "interrupted" : "failed";
+ await vi.waitFor(() => expect(fixture.events.filter(event => event.type === "turn_completed")).toMatchObject([{ result: { outcome, stopReason } }]));
+ await settlePromptAdmission(backend, fixture.harness, 2, fixture.session.send({ id: "next", kind: "user", text: "next" }));
+ fixture.harness.completeTurn(2);
+ await vi.waitFor(() => expect(fixture.events.filter(event => event.type === "turn_completed")).toMatchObject([{ result: { outcome } }, { result: { outcome: "success", stopReason: "end_turn" } }]));
+ } finally { await stopRegisteredHarness(backend, fixture); }
+ });
+ });
+
it.each(["codex", "cursor", "grok", "antigravity"] as const)("preserves provider-originated %s cancellation and permits the next turn", async (backend) => {
const fixture = await openRegisteredHarness(backend, "native-cancel");
try {
@@ -1333,9 +1352,9 @@ describe("claude persistent transport ownership", () => {
}));
for (const message of steering) {
expect(await opened.session.send({ id: message.id, kind: "user", text: message.text }))
- .toEqual({ status: "queued", reason: "unsafe_boundary", commandId: message.id });
+ .toMatchObject({ status: "accepted", delivery: "steer", commandId: message.id });
}
- expect(harness.stdinMessages).toHaveLength(0);
+ expect(harness.stdinMessages).toHaveLength(9);
harness.emitProvider({
type: "user",
@@ -1377,6 +1396,7 @@ describe("claude persistent transport ownership", () => {
expect(events.filter((event) => event.type === "turn_completed")).toHaveLength(0);
harness.resultForClaudeInput(steering.length);
await settle();
+ await vi.waitFor(() => expect(events.filter((event) => event.type === "turn_completed")).toHaveLength(1));
const completions = events.filter((event) => event.type === "turn_completed");
expect(completions).toHaveLength(1);
expect(completions[0]).toMatchObject({
@@ -1446,7 +1466,7 @@ it("Pi real adapter public chain owns identical turns by prompt invocation and i
} as never));
const registry = createAgentDriverRegistry<BuiltinBackendSpecs>([{
id: "pi",
- contractVersion: 1,
+ contractVersion: 2,
capabilities: capabilitiesFor("pi"),
createAdapter: () => adapter,
}] as never);
diff --git a/src/daemon/agent-driver/src/testing/fixtures/sdk/copilot-cli.mjs b/src/daemon/agent-driver/src/testing/fixtures/sdk/copilot-cli.mjs
new file mode 100755
index 000000000..2887f0c72
--- /dev/null
+++ b/src/daemon/agent-driver/src/testing/fixtures/sdk/copilot-cli.mjs
@@ -0,0 +1,54 @@
+#!/usr/bin/env node
+import {appendFileSync,existsSync,readFileSync,writeFileSync}from'node:fs';
+import{join}from'node:path';
+let sessionId,seq=0,buffer=Buffer.alloc(0),pending=[];
+const send=value=>{const body=Buffer.from(JSON.stringify(value));process.stdout.write(`Content-Length: ${body.length}\r\n\r\n`);process.stdout.write(body);};
+const reply=(f,result)=>send({jsonrpc:'2.0',id:f.id,result});
+const event=(type,data={},agentId)=>send({jsonrpc:'2.0',method:'session.event',params:{sessionId,event:{id:'event-'+(++seq),timestamp:new Date().toISOString(),parentId:null,type,data,...(agentId?{agentId}:{})}}});
+const flush=()=>{
+ for(const input of pending.splice(0)){
+ event('assistant.turn_start',{turnId:input.messageId});
+ event('assistant.message_delta',{deltaContent:'native:'+input.prompt});
+ }
+ event('session.idle');
+};
+const timer=setInterval(()=>{if(pending.length&&existsSync(join(process.cwd(),'release')))flush();},10);
+const handle=async f=>{
+ const p=f.params??{};
+ if(f.method==='connect'||f.method==='ping')reply(f,{protocolVersion:3});
+ else if(f.method==='session.create'||f.method==='session.resume'){
+ const history=join(process.cwd(),'copilot-history');sessionId=p.sessionId;
+ if(f.method==='session.resume'&&(!existsSync(history)||readFileSync(history,'utf8')!==sessionId))send({jsonrpc:'2.0',id:f.id,error:{code:-32602,message:'session history not found'}});
+ else{writeFileSync(history,sessionId);appendFileSync(join(process.cwd(),'copilot-opens'),String(process.pid)+'\n');reply(f,{sessionId,capabilities:{}});}
+ } else if(f.method==='models.list')reply(f,{models:[{id:'native-fixture',name:'Native Fixture',supportedReasoningEfforts:['high']}]});
+ else if(f.method==='session.send'){
+ const messageId='input-'+(++seq);appendFileSync(join(process.cwd(),'copilot-inputs'),JSON.stringify({text:p.prompt,mode:p.mode})+'\n');
+ if(p.prompt==='blocked extra'||p.prompt==='error extra'){
+ if(p.prompt==='blocked extra')event('session.warning',{warningType:'policy_blocked',originatingMessageId:messageId,message:'Fixture extra refused'});
+ else event('session.error',{originatingMessageId:messageId,message:'Fixture input failed'});
+ reply(f,{messageId});return;
+ }
+ if(p.prompt==='policy blocked'){
+ event('session.warning',{warningType:'policy_blocked',originatingMessageId:messageId,message:'Fixture policy denied input'});
+ reply(f,{messageId});event('session.idle');return;
+ }
+ event('user.message',{messageId,content:p.prompt});
+ event('session.idle',{},'child');
+ pending.push({messageId,prompt:p.prompt});reply(f,{messageId});
+ if(p.prompt==='hold auto switch'){
+ event('session.warning',{warningType:'mcp',message:'Fixture non-terminal warning'});
+ event('session.error',{errorType:'rate_limit',eligibleForAutoSwitch:true,originatingMessageId:messageId,message:'Fixture model switching'});
+ event('auto_mode_switch.requested',{reason:'rate_limit'});
+ appendFileSync(join(process.cwd(),'copilot-auto-switch'),'ready');
+ }
+ if(!p.prompt.includes('hold')&&pending.length===1)flush();
+ } else if(f.method==='session.abort'){pending=[];reply(f,{});event('session.idle',{aborted:true});}
+ else if(f.method==='session.detach')reply(f,{success:true});
+ else if(f.method==='runtime.shutdown'){reply(f,{});clearInterval(timer);setTimeout(()=>process.exit(0),10);}
+ else reply(f,{});
+};
+process.stdin.on('data',chunk=>{
+ buffer=Buffer.concat([buffer,chunk]);
+ while(true){const end=buffer.indexOf('\r\n\r\n');if(end<0)return;const length=Number(/Content-Length:\s*(\d+)/i.exec(buffer.subarray(0,end).toString())?.[1]);if(buffer.length<end+4+length)return;const data=buffer.subarray(end+4,end+4+length);buffer=buffer.subarray(end+4+length);void handle(JSON.parse(data.toString()));}
+});
+process.stdin.on('end',()=>{clearInterval(timer);process.exit(0)});
diff --git a/src/daemon/agent-driver/src/testing/fixtures/sdk/cursor-sdk.mjs b/src/daemon/agent-driver/src/testing/fixtures/sdk/cursor-sdk.mjs
new file mode 100644
index 000000000..a612ced25
--- /dev/null
+++ b/src/daemon/agent-driver/src/testing/fixtures/sdk/cursor-sdk.mjs
@@ -0,0 +1,57 @@
+import { appendFileSync, existsSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { spawn } from "node:child_process";
+
+export class JsonlLocalAgentStore {
+ constructor(path) { this.path = path; }
+}
+
+export class Cursor {
+ static models = { list: async () => [{ id: "fixture-model", displayName: "Fixture model" }] };
+}
+
+export class Agent {
+ static async create(options) { return this.open("fixture-agent", options, false); }
+ static async resume(id, options) { return this.open(id, options, true); }
+ static async open(id, options, resume) {
+ const cwd = options.local.cwd;
+ const history = join(cwd, "fixture-history");
+ if (resume && (!existsSync(history) || readFileSync(history, "utf8") !== id)) {
+ const error = new Error("Missing");
+ error.name = "AgentNotFoundError";
+ throw error;
+ }
+ writeFileSync(history, id);
+ appendFileSync(join(cwd, "opens"), `${JSON.stringify({ pid: process.pid, resume, id })}\n`);
+ return {
+ agentId: id,
+ model: { id: "fixture-model" },
+ close() {},
+ async send(text, { onDelta }) {
+ appendFileSync(join(cwd, "inputs"), `${text}\n`);
+ let finish;
+ let timer;
+ const result = new Promise((resolve) => { finish = resolve; });
+ const settle = (status) => { clearInterval(timer); finish({ status, result: "done" }); };
+ if (text === "spawn") {
+ const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { detached: true, stdio: "ignore" });
+ child.unref();
+ writeFileSync(join(cwd, "child-pid"), String(child.pid));
+ }
+ onDelta({ update: { type: "text-delta", text: "你好😀" } });
+ timer = setInterval(() => { if (existsSync(join(cwd, "release"))) settle("finished"); }, 10);
+ return {
+ id: `run-${text}`,
+ wait: () => result,
+ cancel: async () => settle("cancelled"),
+ steer: async (message) => {
+ appendFileSync(join(cwd, "steers"), `${message}\n`);
+ if (message === "refuse") return "revert_to_followup";
+ if (message === "unknown") throw new Error("unknown delivery");
+ return "complete_delivered";
+ },
+ };
+ },
+ };
+ }
+}
diff --git a/src/daemon/agent-driver/src/testing/fixtures/sdk/pi-harness.mjs b/src/daemon/agent-driver/src/testing/fixtures/sdk/pi-harness.mjs
new file mode 100644
index 000000000..229a7a0e0
--- /dev/null
+++ b/src/daemon/agent-driver/src/testing/fixtures/sdk/pi-harness.mjs
@@ -0,0 +1,26 @@
+import * as native from '@earendil-works/pi-durable';
+import { fauxProvider, fauxAssistantMessage } from '@earendil-works/pi-ai/providers/faux';
+import { existsSync, appendFileSync } from 'node:fs';
+import { join } from 'node:path';
+export * from '@earendil-works/pi-durable';
+export const Harness = { async open(storage, options, context) {
+ const faux=fauxProvider();
+ const response=async (ctx, request) => {
+ const users=ctx.messages.filter(message=>message.role==='user');
+ const text=users.at(-1)?.content;
+ const prompt=typeof text==='string'?text:JSON.stringify(text);
+ const target=options.env({cwd:process.cwd()},context);
+ void target;
+ if(prompt?.includes('hold')) {
+ while(!existsSync(join(process.cwd(),'release'))) {
+ if(request?.signal?.aborted) throw new Error('Fixture model aborted');
+ await new Promise(resolve=>setTimeout(resolve,10));
+ }
+ }
+ appendFileSync(join(process.cwd(),'native-requests'),JSON.stringify({prompt,roles:ctx.messages.map(m=>m.role)})+'\n');
+ return fauxAssistantMessage('native:'+prompt);
+ };
+ faux.setResponses(Array.from({length:30},()=>response));
+ options.models.setProvider(faux.provider);
+ return native.Harness.open(storage,options,context);
+} };
diff --git a/src/daemon/agent-driver/src/testing/fixtures/sdk/qoder-cli.mjs b/src/daemon/agent-driver/src/testing/fixtures/sdk/qoder-cli.mjs
new file mode 100755
index 000000000..5dcae6a7b
--- /dev/null
+++ b/src/daemon/agent-driver/src/testing/fixtures/sdk/qoder-cli.mjs
@@ -0,0 +1,40 @@
+#!/usr/bin/env node
+import {createInterface}from'node:readline';
+import {appendFileSync,existsSync,readFileSync,writeFileSync}from'node:fs';
+import {join}from'node:path';
+let sessionId;
+let pending=[];
+const send=f=>process.stdout.write(JSON.stringify(f)+'\n');
+const response=(f,body,session)=>send({type:'control_response',...(session?{session_id:session}:{}),response:{subtype:'success',request_id:f.request_id,...(body===undefined?{}:{response:body})}});
+const init=()=>send({type:'system',subtype:'init',session_id:sessionId,model:'native-fixture',cwd:process.cwd(),tools:['Bash'],mcp_servers:[],permissionMode:'bypassPermissions',slash_commands:[],capabilities:['msg_lifecycle_v1','plan_mode_v1']});
+const finish=f=>{
+ send({type:'command_lifecycle',session_id:sessionId,command_uuid:f.uuid,state:'started'});
+ send({type:'stream_event',session_id:sessionId,event:{type:'content_block_delta',index:0,delta:{type:'text_delta',text:'native:'+f.message.content[0].text}}});
+ send({type:'result',subtype:'success',session_id:sessionId,is_error:false,duration_ms:1,duration_api_ms:1,num_turns:1,result:'done',total_cost_usd:0,usage:{input_tokens:1,output_tokens:2,cache_read_input_tokens:0,cache_creation_input_tokens:0}});
+ send({type:'command_lifecycle',session_id:sessionId,command_uuid:f.uuid,state:'completed'});
+};
+const timer=setInterval(()=>{if(existsSync(join(process.cwd(),'release')))for(const f of pending.splice(0))finish(f)},10);
+for await(const line of createInterface({input:process.stdin,crlfDelay:Infinity})){
+ const f=JSON.parse(line);const r=f.request;
+ if(f.type==='control_request'){
+ if(r.type==='daemon.initialize')response(f,{daemon_protocol_version:2,daemon_version:'1.1.81-fixture',capabilities:['multi_session_v2','daemon_queries_v1','daemon_keep_alive_v1','daemon_async_session_teardown_v1']});
+ else if(r.type==='daemon.open_session'){
+ const args=r.worker_args;const index=args.indexOf('--session-id');const resume=args.indexOf('--resume');
+ sessionId=args[index>=0?index+1:resume+1];
+ const saved=join(process.cwd(),'qoder-history');
+ if(resume>=0&&(!existsSync(saved)||readFileSync(saved,'utf8')!==sessionId)){send({type:'control_response',response:{subtype:'error',request_id:f.request_id,error:'session history not found'}});continue;}
+ writeFileSync(saved,sessionId);appendFileSync(join(process.cwd(),'qoder-opens'),String(process.pid)+'\n');response(f,undefined,sessionId);
+ }else if(r.subtype==='initialize'){response(f,{commands:[],agents:[],output_style:'default',available_output_styles:[],capabilities:['msg_lifecycle_v1','plan_mode_v1']},sessionId);init();}
+ else if(r.type==='daemon.get_models')response(f,{models:[{value:'native-fixture',displayName:'Native Fixture',description:'local',efforts:['high'],isDefault:true}]});
+ else if(r.type==='daemon.close_session')response(f,undefined,sessionId);
+ else if(r.type==='daemon.shutdown'){response(f);clearInterval(timer);setTimeout(()=>process.exit(0),10);}
+ else if(r.subtype==='interrupt'){
+ for(const p of pending.splice(0))send({type:'command_lifecycle',session_id:sessionId,command_uuid:p.uuid,state:'cancelled'});
+ response(f,{},sessionId);
+ } else response(f,{},f.session_id);
+ }else if(f.type==='user'){
+ appendFileSync(join(process.cwd(),'qoder-inputs'),f.message.content[0].text+'\n');
+ if(f.message.content[0].text.includes('hold')||pending.length)pending.push(f);else finish(f);
+ }
+}
+clearInterval(timer);
diff --git a/src/daemon/agent-driver/src/testing/sdk-worker-artifact.spec.ts b/src/daemon/agent-driver/src/testing/sdk-worker-artifact.spec.ts
new file mode 100644
index 000000000..3819ec468
--- /dev/null
+++ b/src/daemon/agent-driver/src/testing/sdk-worker-artifact.spec.ts
@@ -0,0 +1,31 @@
+import { execFile } from "node:child_process";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { createRequire } from "node:module";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import { promisify } from "node:util";
+
+export async function buildSdkWorkerArtifact() {
+ const root = mkdtempSync(join(tmpdir(), "alook-sdk-worker-build-"));
+ const dispose = () => rmSync(root, { recursive: true, force: true });
+ try {
+ const packageRoot = fileURLToPath(new URL("../../", import.meta.url));
+ const require = createRequire(import.meta.url);
+ await promisify(execFile)(process.execPath, [require.resolve("typescript/bin/tsc"), "-p", "tsconfig.build.json", "--outDir", root, "--sourceMap", "false", "--declarationMap", "false"], { cwd: packageRoot });
+ writeFileSync(join(root, "package.json"), '{"type":"module"}\n');
+ const load = (url: string): Promise<unknown> => import(url);
+ const [lane, driver, qoder, copilot, cursor, pi] = await Promise.all([
+ load(pathToFileURL(join(root, "internal/sdk-worker-lane.js")).href) as Promise<typeof import("../internal/sdk-worker-lane.js")>,
+ load(pathToFileURL(join(root, "internal/optional-sdk-driver.js")).href) as Promise<typeof import("../internal/optional-sdk-driver.js")>,
+ load(pathToFileURL(join(root, "adapters/qoder/worker.js")).href) as Promise<typeof import("../adapters/qoder/worker.js")>,
+ load(pathToFileURL(join(root, "adapters/copilot/worker.js")).href) as Promise<typeof import("../adapters/copilot/worker.js")>,
+ load(pathToFileURL(join(root, "adapters/cursor-sdk/worker.js")).href) as Promise<typeof import("../adapters/cursor-sdk/worker.js")>,
+ load(pathToFileURL(join(root, "adapters/pi-durable/worker.js")).href) as Promise<typeof import("../adapters/pi-durable/worker.js")>,
+ ]);
+ return { ...lane, ...driver, ...qoder, ...copilot, ...cursor, ...pi, dispose };
+ } catch (error) {
+ dispose();
+ throw error;
+ }
+}
diff --git a/src/daemon/src/agent-driver-bundle.packed.test.ts b/src/daemon/src/agent-driver-bundle.packed.test.ts
index 436c57b21..e4668e228 100644
--- a/src/daemon/src/agent-driver-bundle.packed.test.ts
+++ b/src/daemon/src/agent-driver-bundle.packed.test.ts
@@ -3,7 +3,7 @@ import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "n
import { tmpdir } from "node:os";
import { join } from "node:path";
import { promisify } from "node:util";
-import { fileURLToPath } from "node:url";
+import { fileURLToPath, pathToFileURL } from "node:url";
import { afterEach, describe, expect, it } from "vitest";
import { execPackageManagerSync } from "./test-package-manager.js";
@@ -61,5 +61,18 @@ describe("packed daemon agent-driver boundary", () => {
"--eval",
"await import('@alook/daemon')",
], { cwd: installRoot, maxBuffer: 10 * 1024 * 1024 });
+ if (process.env.ALOOK_NATIVE_SDK_ROOT && process.platform !== "win32") {
+ const script = join(packageRoot, "agent-driver", "scripts", "test-bundled-sdk-workers.mjs");
+ const { stdout } = await execFileAsync(process.execPath, [
+ script,
+ pathToFileURL(join(installedRoot, "dist", "index.js")).href,
+ process.env.ALOOK_NATIVE_SDK_ROOT,
+ ], { cwd: installRoot, maxBuffer: 10 * 1024 * 1024 });
+ const reports = stdout.trim().split("\n").map((line) => JSON.parse(line) as { id: string; manager?: string });
+ for (const id of ["qoder", "copilot", "cursor-sdk", "pi-durable"]) {
+ expect(reports).toContainEqual(expect.objectContaining({ id, results: ["success", "interrupted"], closed: "stopped" }));
+ expect(reports).toContainEqual(expect.objectContaining({ id, manager: "wake-during-work", acks: 2, opens: 1, turnActive: false, sessionState: "idle" }));
+ }
+ }
});
});
diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.ts
index 6a6e87768..c4b2d07bd 100644
--- a/src/daemon/src/daemon/createDaemon.ts
+++ b/src/daemon/src/daemon/createDaemon.ts
@@ -72,7 +72,7 @@ const RUNTIME_RAW_TRACE_MAX_BYTES = 8 * 1024 * 1024;
export const RUNTIME_RAW_TRACE_AGENT_IDS_ENV = "ALOOK_RUNTIME_RAW_TRACE_AGENT_IDS";
/** How often the daemon rewrites the `daemon status` snapshot file (batch E2). */
const STATUS_WRITE_INTERVAL_MS = 5_000;
-const TOKEN_USAGE_BACKENDS = new Set<BuiltinBackendId>(["claude", "codex", "grok", "opencode", "pi", "antigravity", "agy"]);
+const TOKEN_USAGE_BACKENDS = new Set<BuiltinBackendId>(["claude", "codex", "grok", "opencode", "pi", "antigravity", "agy", "qoder", "copilot", "cursor-sdk", "pi-durable"]);
export function parseRuntimeRawTraceAgentIds(value: string | undefined): ReadonlySet<string> {
return new Set(
diff --git a/src/daemon/src/diagnostics/privacyPolicy.test.ts b/src/daemon/src/diagnostics/privacyPolicy.test.ts
index 787f20d4e..46067467d 100644
--- a/src/daemon/src/diagnostics/privacyPolicy.test.ts
+++ b/src/daemon/src/diagnostics/privacyPolicy.test.ts
@@ -172,7 +172,7 @@ const FSM_FIELD_RULES: Readonly<Record<string, ProjectionFieldRule>> = {
outstandingToolUses: { type: "integer", min: 0, max: Number.MAX_SAFE_INTEGER, optional: true },
anonymousOutstandingToolUses: { type: "integer", min: 0, max: Number.MAX_SAFE_INTEGER, optional: true },
toolLifecycleMismatchCount: { type: "integer", min: 0, max: Number.MAX_SAFE_INTEGER, optional: true },
- resumeOutcome: { type: "enum", values: ["not_requested", "pending", "resumed", "reset_required", "failed"], optional: true },
+ resumeOutcome: { type: "enum", values: ["not_requested", "pending", "resumed", "unverified", "reset_required", "failed"], optional: true },
terminalOwnerKind: { type: "enum", values: ["transport_request", "vendor_message", "prompt_invocation", "lane_generation"], optional: true },
effects: { type: "enum_array", values: EXPECTED_MANAGER_EFFECTS, maxItems: 32, dropUnknown: true },
nowMs: { type: "integer", min: 0, max: Number.MAX_SAFE_INTEGER },
diff --git a/src/daemon/src/diagnostics/privacyPolicy.ts b/src/daemon/src/diagnostics/privacyPolicy.ts
index 52b6895bc..c014e9e41 100644
--- a/src/daemon/src/diagnostics/privacyPolicy.ts
+++ b/src/daemon/src/diagnostics/privacyPolicy.ts
@@ -168,7 +168,7 @@ const MANAGER_EVENTS = ["register", "wake", "spawned", "session", "root_work", "
const MANAGER_EFFECTS = ["spawn", "send", "stop", "terminate_stalled", "clear_stall_recovery", "force_exit", "gated_hold"] as const;
const AGENT_STATUSES = ["idle", "starting", "running", "stopping"] as const;
const DELIVERY_PHASES = ["idle", "admission_wait", "steering", "next_turn_queued", "compacting", "reviewing", "tool_wait", "working"] as const;
-const RESUME_OUTCOMES = ["not_requested", "pending", "resumed", "reset_required", "failed"] as const;
+const RESUME_OUTCOMES = ["not_requested", "pending", "resumed", "unverified", "reset_required", "failed"] as const;
const TERMINAL_OWNER_KINDS = ["transport_request", "vendor_message", "prompt_invocation", "lane_generation"] as const;
const TERMINATION_CAUSES = ["runtime_error", "killed_stalled", "other"] as const;
const SPAWN_FAILURE_REASONS = ["ENOENT", "handshake_timeout", "pre_handshake_exit", "spawn_threw", "other"] as const;
diff --git a/src/daemon/src/discovery.test.ts b/src/daemon/src/discovery.test.ts
index db0a1a4b2..f389b154a 100644
--- a/src/daemon/src/discovery.test.ts
+++ b/src/daemon/src/discovery.test.ts
@@ -12,7 +12,7 @@ import {
} from "./discovery";
import * as drivers from "./drivers/index";
-const EXPECTED_RUNTIMES = ["claude", "codex", "cursor", "grok", "opencode", "pi", "antigravity", "agy"];
+const EXPECTED_RUNTIMES = ["claude", "codex", "cursor", "grok", "opencode", "pi", "antigravity", "agy", "qoder", "copilot", "cursor-sdk", "pi-durable"];
const tmpDirs: string[] = [];
function mkTmp(): string {
@@ -231,7 +231,7 @@ describe("driver registry", () => {
});
it("rejects removed and unknown runtimes", () => {
- for (const removed of ["copilot", "gemini", "kimi", "unknown-runtime"]) {
+ for (const removed of ["gemini", "kimi", "unknown-runtime"]) {
expect(() => drivers.getDriver(removed)).toThrow(/Unknown runtime/);
}
});
diff --git a/src/daemon/src/manager/managerPolicy.ts b/src/daemon/src/manager/managerPolicy.ts
index 588690f8a..a0ce41b53 100644
--- a/src/daemon/src/manager/managerPolicy.ts
+++ b/src/daemon/src/manager/managerPolicy.ts
@@ -143,7 +143,7 @@ export type ManagerEvent =
agentId: string;
sessionInstanceId: string;
commandId: string;
- outcome: "accepted" | "failed";
+ outcome: "accepted" | "failed" | "rejected";
}
| {
type: "admission_acknowledged";
@@ -630,6 +630,7 @@ function onWake(state: ManagerState, agentId: string, message: AgentMsg): Reduce
}
if (agent.status === "running") {
+ if (leaseIsWorking(agent.execution.lease) && agent.inbox.some((queued) => queued.preparedInput?.delivery === "next_turn")) return commit(state, agent, []);
const messages = drainInbox(agent);
const mode = leaseIsWorking(agent.execution.lease) || agent.pendingAdmissions.length > 0 ? "busy" : "idle";
return commit(state, agent, messages.map((queued) => ({ type: "send", agentId, message: queued, mode })));
diff --git a/src/daemon/src/manager/managerRuntime.test.ts b/src/daemon/src/manager/managerRuntime.test.ts
index 6f3aebd35..51ce172bf 100644
--- a/src/daemon/src/manager/managerRuntime.test.ts
+++ b/src/daemon/src/manager/managerRuntime.test.ts
@@ -321,6 +321,113 @@ function makeManager(opts: { logger?: Logger; tickIntervalMs?: number; idleTimeo
return { mgr, session, onRuntimeSpawnFailed, onRuntimeSessionEstablished };
}
+describe("AgentProcessManager returned input responsibility", () => {
+ it("requeues a proven-unsent input ahead of unsent work, keeps its identity, and ignores an old attempt", async () => {
+ const { mgr, session } = makeManager();
+ const send = vi.spyOn(session, "send");
+ const stop = vi.spyOn(session, "stop");
+ mgr.deliver("a1", { id: "A", seq: 1, text: "root" });
+ session.startResolver?.();
+ await vi.waitFor(() => expect(mgr.snapshot().agents.a1.turnActive).toBe(true));
+ mgr.deliver("a1", { id: "B", seq: 2, text: "extra" });
+ await vi.waitFor(() => expect(send).toHaveBeenCalledTimes(1));
+ const original = send.mock.calls[0]![0];
+ const returned = { type: "command_returned", input: { commandId: "B", attemptId: original.attemptId ?? original.id }, message: original, ordinal: 2, evidence: "explicitly_rejected", reason: "native_busy", retryable: true } as const;
+ await session.pushAgentEvent(returned);
+ expect(stop).not.toHaveBeenCalled();
+ expect(mgr.snapshot().agents.a1.turnActive).toBe(true);
+ mgr.deliver("a1", { id: "C", seq: 3, text: "later" });
+ expect(send).toHaveBeenCalledTimes(1);
+ expect(mgr.snapshot().agents.a1.inbox.map((input) => input.id)).toEqual(["B", "C"]);
+ await session.pushAgentEvent({ type: "turn_completed", turnId: "test-turn", commandIds: ["A"], result: { outcome: "success", backendSessionId: "thread_1" } });
+ await vi.waitFor(() => expect(send).toHaveBeenCalledTimes(3));
+ const retried = send.mock.calls[1]![0];
+ expect(retried).toMatchObject({ id: "B", text: original.text, sequence: 2 });
+ expect(retried.attemptId).not.toBe(returned.input.attemptId);
+ expect(send.mock.calls[2]![0].id).toBe("C");
+ await session.pushAgentEvent(returned);
+ expect(mgr.snapshot().agents.a1.inbox).toEqual([]);
+ expect(send).toHaveBeenCalledTimes(3);
+ await mgr.stopAll();
+ });
+
+ it("does not replay or reorder C that was already admitted before B returned", async () => {
+ const { mgr, session } = makeManager();
+ const send = vi.spyOn(session, "send");
+ mgr.deliver("a1", { id: "A", text: "root" });
+ session.startResolver?.();
+ await drainEventTasks();
+ mgr.deliver("a1", { id: "B", text: "extra" });
+ mgr.deliver("a1", { id: "C", text: "already delivered" });
+ await drainEventTasks();
+ const input = send.mock.calls[0]![0];
+ await session.pushAgentEvent({ type: "command_returned", input: { commandId: "B", attemptId: input.attemptId ?? input.id }, message: input, ordinal: 2, evidence: "explicitly_rejected", reason: "native refused", retryable: true });
+ expect(send.mock.calls.map(([input]) => input.id)).toEqual(["B", "C"]);
+ expect(mgr.snapshot().agents.a1.inbox.map(input => input.id)).toEqual(["B"]);
+ await session.pushAgentEvent({ type: "turn_completed", turnId: "test-turn", commandIds: ["A", "C"], result: { outcome: "success", backendSessionId: "thread_1" } });
+ await drainEventTasks();
+ expect(send.mock.calls.map(([input]) => input.id)).toEqual(["B", "C", "B"]);
+ expect(send.mock.calls[2]![0].attemptId).not.toBe(input.attemptId ?? input.id);
+ await mgr.stopAll();
+ });
+
+ it.each(["event", "receipt", "throw", "promise"] as const)("keeps root A alive after immediate busy-input refusal via %s", async (failure) => {
+ const { mgr, session } = makeManager();
+ const stop = vi.spyOn(session, "stop");
+ mgr.deliver("a1", { id: "A", text: "root" });
+ session.startResolver?.();
+ await vi.waitFor(() => expect(mgr.snapshot().agents.a1.turnActive).toBe(true));
+ const error = { category: "process", code: "delivery_failed", message: "input refused", retryable: false } as const;
+ vi.spyOn(session, "send").mockImplementation(() => {
+ if (failure === "throw") throw new Error(error.message);
+ if (failure === "promise") return Promise.reject(new Error(error.message));
+ if (failure === "event") void session.pushAgentEvent({ type: "command_failed", scope: "input", commandId: "B", turnId: "test-turn", error });
+ return Promise.resolve({ status: "rejected", reason: "runtime_unavailable", error });
+ });
+ mgr.deliver("a1", { id: "B", text: "extra" });
+ await drainEventTasks();
+ expect(mgr.snapshot().agents.a1.turnActive).toBe(true);
+ expect(stop).not.toHaveBeenCalled();
+ expect(mgr.snapshot().agents.a1.inbox).toEqual([]);
+ await session.pushAgentEvent({ type: "turn_completed", turnId: "test-turn", commandIds: ["A"], result: { outcome: "success", backendSessionId: "thread_1" } });
+ expect(mgr.snapshot().agents.a1.turnActive).toBe(false);
+ await mgr.stopAll();
+ });
+
+ it("releases completed input text while retaining inputs queued for a later turn", async () => {
+ const { mgr, session } = makeManager();
+ mgr.deliver("a1", { id: "A", text: "root" });
+ session.startResolver?.();
+ await vi.waitFor(() => expect(mgr.snapshot().agents.a1.turnActive).toBe(true));
+ mgr.deliver("a1", { id: "B", text: "extra" });
+ await drainEventTasks();
+ const internal = mgr as unknown as { activeSpawnState: Map<string, { inputDeliveries: Map<string, unknown> }> };
+ const inputs = internal.activeSpawnState.get("a1")!.inputDeliveries;
+ expect([...inputs.keys()]).toEqual(["A", "B"]);
+ await session.pushAgentEvent({ type: "turn_completed", turnId: "test-turn", commandIds: ["A", "B"], result: { outcome: "success", backendSessionId: "thread_1" } });
+ expect(inputs.size).toBe(0);
+ await mgr.stopAll();
+ });
+
+ it.each(["unknown", "explicitly_rejected"] as const)("does not blindly replay %s or stop a healthy root", async (evidence) => {
+ const { mgr, session } = makeManager();
+ const send = vi.spyOn(session, "send");
+ const stop = vi.spyOn(session, "stop");
+ mgr.deliver("a1", { id: "A", text: "root" });
+ session.startResolver?.();
+ await vi.waitFor(() => expect(mgr.snapshot().agents.a1.turnActive).toBe(true));
+ mgr.deliver("a1", { id: "B", text: "extra" });
+ await vi.waitFor(() => expect(send).toHaveBeenCalledTimes(1));
+ const input = send.mock.calls[0]![0];
+ await session.pushAgentEvent({ type: "command_returned", input: { commandId: "B", attemptId: input.attemptId ?? input.id }, message: input, ordinal: 2, evidence, reason: "not safe to replay", retryable: evidence === "unknown" });
+ expect(send).toHaveBeenCalledTimes(1);
+ expect(mgr.snapshot().agents.a1.inbox).toEqual([]);
+ expect(mgr.snapshot().agents.a1.turnActive).toBe(true);
+ expect(stop).not.toHaveBeenCalled();
+ await mgr.stopAll();
+ });
+});
+
describe("AgentProcessManager — running-turn interrupt", () => {
it("audits a daemon-accepted interrupt without deleting the session", async () => {
const onBotAuditEvent = vi.fn();
@@ -552,6 +659,22 @@ describe("AgentProcessManager runtime config revisions", () => {
runtimeConfigRevision: revision,
});
+ it("settles an acknowledged revision without restarting or applying it twice", async () => {
+ const { mgr, session } = makeManager();
+ session.updateSettings = vi.fn(async () => ({ status: "acknowledged", effective: "next_turn" } as const));
+ const stop = vi.spyOn(session, "stop");
+ mgr.register("a1", { runtimeConfig: config(1, "low") });
+ mgr.deliver("a1", { id: "root", text: "work" });
+ session.startResolver?.();
+ await vi.waitFor(() => expect(mgr.snapshot().agents.a1.turnActive).toBe(true));
+ await session.pushAgentEvent({ type: "turn_completed", turnId: "test-turn", commandIds: ["root"], result: { outcome: "success", backendSessionId: "thread_1" } });
+ await expect(mgr.updateRuntimeConfig("a1", config(2, "high"))).resolves.toBe("acknowledged");
+ await expect(mgr.updateRuntimeConfig("a1", config(2, "high"))).resolves.toBe("idempotent");
+ expect(session.updateSettings).toHaveBeenCalledTimes(1);
+ expect(stop).not.toHaveBeenCalled();
+ await mgr.stopAll();
+ });
+
it("coalesces busy updates and applies only the newest revision after turn completion", async () => {
const { mgr, session } = makeManager();
const updateSettings = vi.fn(async () => ({ status: "applied" as const }));
@@ -4608,7 +4731,7 @@ describe("AgentProcessManager — stopped delivery and original inputs", () => {
expect(input).toEqual({ id: "retry", kind: "user", text: expect.stringMatching(/^\[[^\]]+\] retry text\n\noriginal footer$/), sequence: 2 });
vi.setSystemTime(new Date("2026-10-13T07:00:30Z"));
await first.pushAgentEvent({
- type: "command_failed", commandId: "retry",
+ type: "command_failed", scope: "turn", commandId: "retry",
error: { category: "process", code: "delivery_failed", message: "failed", retryable: true },
});
expect(first.stop).toHaveBeenCalledOnce();
@@ -4719,59 +4842,35 @@ describe("AgentProcessManager — stopped delivery and original inputs", () => {
await second.fire("exit", { reason: "requested" });
});
- it.each([1, 2])("restores only unfinished startup sends when send %i throws, then replays after actual close", async (failingSend) => {
- vi.useFakeTimers({ toFake: ["Date"] });
- vi.setSystemTime(new Date("2026-10-13T07:00:00Z"));
+ it.each([1, 2])("keeps the startup root and other inputs alive when extra send %i throws", async (failingSend) => {
const first = fakeSession("throw-old");
- const second = b1Session([], "replacement", "test-turn", "throw-new");
- first.start = vi.fn(first.start);
const send = first.send.bind(first);
- const snapshot = first.snapshot.bind(first);
- const error = new Error("original synchronous send failure");
- const onBotAuditEvent = vi.fn();
+ const stop = vi.spyOn(first, "stop");
let attempts = 0;
- let stopping = false;
- first.snapshot = () => ({ ...snapshot(), state: stopping ? "stopping" : "working" });
- first.stop = vi.fn(async () => {
- stopping = true;
- return { status: "accepted" as const, requestId: "stop-throw-old" };
- });
first.send = vi.fn((input: AgentMessage) => {
- if (++attempts === failingSend) throw error;
+ if (++attempts === failingSend) throw new Error("synchronous input refusal");
return send(input);
});
- const { mgr } = b1Manager({ sessions: [first, second], stampWakePromptTime: true, wakePromptFooter: "original footer", onBotAuditEvent });
+ const onBotAuditEvent = vi.fn();
+ const { mgr } = b1Manager({ sessions: [first], onBotAuditEvent });
try {
mgr.deliver("a1", { id: "root", seq: 1, text: "root" });
mgr.deliver("a1", { id: "tail-a", seq: 2, text: "tail a" });
mgr.deliver("a1", { id: "tail-b", seq: 3, text: "tail b" });
first.startResolver?.();
- await new Promise<void>((resolve) => setImmediate(resolve));
- const failedInput = vi.mocked(first.send).mock.calls[failingSend - 1]![0];
- const pendingIds = ["tail-a", "tail-b"].slice(failingSend - 1);
- expect(first.start).toHaveBeenCalledOnce();
- expect(first.send).toHaveBeenCalledTimes(failingSend);
- expect(mgr.snapshot().agents.a1.inbox.map((message) => message.id)).toEqual(pendingIds);
- expect(mgr.snapshot().agents.a1.inbox[0]!.preparedInput).toBe(failedInput);
+ await drainEventTasks();
+ expect(first.send).toHaveBeenCalledTimes(2);
+ expect(stop).not.toHaveBeenCalled();
+ expect(mgr.snapshot().agents.a1).toMatchObject({ turnActive: true, inbox: [], execution: { sessionInstanceId: "throw-old" } });
expect(onBotAuditEvent).toHaveBeenCalledWith("a1", expect.objectContaining({
- kind: "error", payload: expect.objectContaining({ scope: "runtime", code: "send_failed", message: String(error) }),
+ kind: "error", payload: expect.objectContaining({ code: "send_failed" }),
}), expect.anything());
- expect(first.stop).toHaveBeenCalledExactlyOnceWith({ reason: "shutdown", forceAfterMs: 2_000 });
mgr.deliver("a1", { id: "newer", seq: 4, text: "newer" });
+ expect(first.send).toHaveBeenCalledTimes(3);
await first.fire("runtime_event", { kind: "turn_end" });
- expect(first.send).toHaveBeenCalledTimes(failingSend);
- expect(second.start).not.toHaveBeenCalled();
- expect(mgr.snapshot().agents.a1.inbox.map((message) => message.id)).toEqual([...pendingIds, "newer"]);
- vi.setSystemTime(new Date("2026-10-13T07:01:00Z"));
- await first.fire("exit", { reason: "requested" });
- await new Promise<void>((resolve) => setImmediate(resolve));
- expect(second.start).toHaveBeenCalledExactlyOnceWith(failedInput);
- expect(vi.mocked(second.send).mock.calls.map(([input]) => input.id)).toEqual([...pendingIds.slice(1), "newer"]);
- expect(mgr.snapshot().agents.a1).toMatchObject({ status: "running", inbox: [], execution: { sessionInstanceId: "throw-new" } });
- await second.fire("exit", { reason: "requested" });
+ expect(mgr.snapshot().agents.a1.turnActive).toBe(false);
} finally {
await mgr.stopAll();
- vi.useRealTimers();
}
});
});
@@ -5593,7 +5692,7 @@ describe("B1 red gate — exact-once terminal matrix", () => {
error: { category: "process" as const, code: "send_denied", message: "closed", retryable: true },
})],
["rejected promise", () => Promise.reject(new Error("send rejected"))],
- ] as const)("%s from an established send closes the active turn once", async (_name, send) => {
+ ] as const)("%s from an extra input preserves the active turn", async (_name, send) => {
const rows: B1TraceRow[] = [];
const session = b1Session([]);
const { mgr } = b1Manager({ sessions: [session], trace: (row) => rows.push(row) });
@@ -5605,7 +5704,10 @@ describe("B1 red gate — exact-once terminal matrix", () => {
await new Promise((resolve) => setTimeout(resolve, 0));
expect(session.send).toHaveBeenCalledTimes(1);
- expect(b1SpanRows(rows, "turn_abort").filter((row) => row.abortCause === "send_threw")).toHaveLength(1);
+ expect(b1SpanRows(rows, "turn_abort").filter((row) => row.abortCause === "send_threw")).toHaveLength(0);
+ expect(mgr.snapshot().agents.a1.turnActive).toBe(true);
+ expect(session.stop).not.toHaveBeenCalled();
+ await mgr.stopAll();
});
it("reports an event-stream rejection and a closed-promise rejection", async () => {
@@ -5736,6 +5838,7 @@ describe("B1 red gate — exact-once terminal matrix", () => {
const owner = internal.activeSpawnState.get("a1")!;
const failed = {
type: "command_failed",
+ scope: "turn",
commandId: "later",
turnId: "test-turn",
error: { category: "process", code: "delivery_failed", message: "failed", retryable: true },
@@ -5916,7 +6019,7 @@ describe("B1 red gate — exact-once terminal matrix", () => {
});
for (const mode of ["idle", "busy"] as const) {
- it(`${mode} send synchronous throw aborts once and rethrows without another send`, async () => {
+ it(`${mode} send synchronous throw follows root ownership without another send`, async () => {
const rows: B1TraceRow[] = [];
const error = new Error(`unique-send-${mode}-secret`);
const session = b1Session([]);
@@ -5929,12 +6032,13 @@ describe("B1 red gate — exact-once terminal matrix", () => {
throw error;
});
- expect(() => mgr.deliver("a1", { seq: 2, text: "throw" })).toThrow(error);
+ if (mode === "idle") expect(() => mgr.deliver("a1", { seq: 2, text: "throw" })).toThrow(error);
+ else expect(() => mgr.deliver("a1", { seq: 2, text: "throw" })).not.toThrow();
expect(session.send).toHaveBeenCalledTimes(1);
const aborts = b1SpanRows(rows, "turn_abort");
- expect(aborts.length).toBeGreaterThan(0);
- expect(aborts.at(-1)!.abortCause).toBe("send_threw");
- expect(aborts.filter((row) => row.abortCause === "send_threw")).toHaveLength(1);
+ expect(aborts.filter((row) => row.abortCause === "send_threw")).toHaveLength(mode === "idle" ? 1 : 0);
+ if (mode === "busy") expect(session.stop).not.toHaveBeenCalled();
+ await mgr.stopAll();
});
}
@@ -6326,7 +6430,9 @@ describe("Codex root event ownership — subagent completion isolation", () => {
const publishNormalized = async (events: readonly AdapterEvent[]) => {
for (const event of events) {
- if (event.kind === "session_init") {
+ if (event.attribution?.scope === "child" || event.attribution?.scope === "unknown") {
+ await session.pushAgentEvent({ type: "activity", attribution: event.attribution, kind: event.kind });
+ } else if (event.kind === "session_init") {
await session.pushAgentEvent({ type: "session_started", backendSessionId: event.sessionId });
} else if (event.kind === "assistant_reasoning_completed") {
await session.pushAgentEvent({ type: "assistant_reasoning_completed", turnId: "test-turn", text: event.text, truncated: false });
@@ -6362,7 +6468,7 @@ describe("Codex root event ownership — subagent completion isolation", () => {
threadId: `child-thread-${child}`,
turn: { id: `child-turn-${child}`, status: "completed" },
}));
- expect(events).toEqual([]);
+ expect(events).toEqual([expect.objectContaining({ attribution: expect.objectContaining({ scope: "unknown", agentId: `child-thread-${child}` }) })]);
await publishNormalized(events);
now += 40;
await publishNormalized(adapter.normalizeLine(notify(child % 2 === 0 ? "item/completed" : "item/started", {
diff --git a/src/daemon/src/manager/managerRuntime.ts b/src/daemon/src/manager/managerRuntime.ts
index 0400c9b29..b54a079bf 100644
--- a/src/daemon/src/manager/managerRuntime.ts
+++ b/src/daemon/src/manager/managerRuntime.ts
@@ -42,7 +42,7 @@ import type { TimelineTurnOwner } from "../timeline/recorder.js";
const SESSION_STOP_GRACE_MS = 2_000;
export type AgentActivityState = "idle" | "starting" | "running" | "stopping";
export type DaemonAgentSession = AgentSession<BuiltinBackendSpecs, BuiltinBackendId>;
-export type RuntimeConfigUpdateResult = "applied" | "deferred" | "saved_for_start" | "stale" | "idempotent";
+export type RuntimeConfigUpdateResult = "applied" | "acknowledged" | "deferred" | "saved_for_start" | "stale" | "idempotent";
type ManagedEvent = AgentEvent<BuiltinBackendSpecs, BuiltinBackendId>;
type TraceTerminationCause = "runtime_error" | "killed_stalled" | "other";
type TraceSpawnFailureReason = "ENOENT" | "handshake_timeout" | "pre_handshake_exit" | "spawn_threw" | "other";
@@ -95,6 +95,7 @@ interface ActiveSpawnState {
activeSpan: ActiveTurnSpan | null;
timelineTurnOwner: TimelineTurnOwner | null;
pendingDeliverySpans: Map<string, PendingDeliveryTrace>;
+ inputDeliveries: Map<string, AgentMsg>;
}
interface ManagedSessionLifecycle {
session: DaemonAgentSession;
@@ -145,7 +146,7 @@ interface FsmTraceRecord extends TraceRecordBase, Partial<TraceSpanMetadata> {
outstandingToolUses?: number;
anonymousOutstandingToolUses?: number;
toolLifecycleMismatchCount?: number;
- resumeOutcome?: "not_requested" | "pending" | "resumed" | "reset_required" | "failed";
+ resumeOutcome?: "not_requested" | "pending" | "resumed" | "unverified" | "reset_required" | "failed";
terminalOwnerKind?: "transport_request" | "vendor_message" | "prompt_invocation" | "lane_generation";
sinceProgressMs: number;
sinceNativeActivityMs: number;
@@ -670,7 +671,7 @@ export class AgentProcessManager {
return "saved_for_start";
}
}
- if (result.status !== "applied") {
+ if (result.status !== "applied" && result.status !== "acknowledged") {
this.log.warn("runtime config live apply unavailable; restarting at safe boundary", {
agentId,
revision: desiredRevision,
@@ -687,7 +688,7 @@ export class AgentProcessManager {
const latestRevision = this.runtimeConfigs.get(agentId)?.runtimeConfigRevision ?? 0;
if (latestRevision <= desiredRevision) {
this.dispatch({ type: "runtime_config_applied", agentId });
- return "applied";
+ return result.status;
}
}
return "saved_for_start";
@@ -1300,6 +1301,7 @@ export class AgentProcessManager {
): boolean {
const sessionInstanceId = owner.sessionInstanceId;
if (!sessionInstanceId || owner.pendingDeliverySpans.has(commandId)) return false;
+ owner.inputDeliveries.set(commandId, message);
owner.pendingDeliverySpans.set(commandId, {
sessionInstanceId,
span,
@@ -1335,7 +1337,7 @@ export class AgentProcessManager {
private settlePendingDelivery(
owner: ActiveSpawnState,
commandId: string,
- outcome: "accepted" | "failed" = "failed",
+ outcome: "accepted" | "failed" | "rejected" = "failed",
): PendingDeliveryTrace | undefined {
const pending = owner.pendingDeliverySpans.get(commandId);
if (!pending) return undefined;
@@ -1363,12 +1365,24 @@ export class AgentProcessManager {
const input = message.preparedInput;
const owner = this.activeSpawnState.get(effect.agentId);
const exactOwner = owner?.session === session ? owner : undefined;
+ const hasExistingRoot = exactOwner?.activeSpan != null;
+ const deliveryMode = hasExistingRoot ? "busy" : "idle";
const associatedSpan = exactOwner
? effect.mode === "idle"
? this.openTurn(exactOwner)
: exactOwner.activeSpan
: null;
- if (exactOwner) this.beginPendingDelivery(exactOwner, input.id, message, effect.mode, associatedSpan);
+ if (exactOwner) this.beginPendingDelivery(exactOwner, input.id, message, deliveryMode, associatedSpan);
+ const rejectDelivery = (code: string, detail: string) => {
+ if (!exactOwner || !exactOwner.pendingDeliverySpans.has(input.id)) return;
+ this.settlePendingDelivery(exactOwner, input.id, hasExistingRoot ? "rejected" : "failed");
+ exactOwner.inputDeliveries.delete(input.id);
+ this.emitErrorAudit(effect.agentId, "runtime", code, detail);
+ if (!hasExistingRoot) {
+ this.closeTurn(exactOwner, associatedSpan, { event: "turn_abort", abortCause: "send_threw" });
+ void session.stop({ reason: "shutdown", forceAfterMs: SESSION_STOP_GRACE_MS });
+ }
+ };
let sent: ReturnType<DaemonAgentSession["send"]>;
try {
sent = session.send(input);
@@ -1378,14 +1392,9 @@ export class AgentProcessManager {
mode: effect.mode,
});
} catch (error) {
- if (exactOwner) {
- this.settlePendingDelivery(exactOwner, input.id);
- this.closeTurn(exactOwner, associatedSpan, {
- event: "turn_abort",
- abortCause: "send_threw",
- });
- }
- throw error;
+ rejectDelivery("send_failed", String(error));
+ if (!hasExistingRoot) throw error;
+ break;
}
void Promise.resolve(sent).then((receipt) => {
if (
@@ -1396,18 +1405,7 @@ export class AgentProcessManager {
) return;
if (receipt.status === "rejected") {
if (!exactOwner.pendingDeliverySpans.has(input.id)) return;
- this.settlePendingDelivery(exactOwner, input.id);
- this.closeTurn(exactOwner, associatedSpan, {
- event: "turn_abort",
- abortCause: "send_threw",
- });
- this.emitErrorAudit(
- effect.agentId,
- "runtime",
- receipt.error?.code ?? receipt.reason,
- receipt.error?.message ?? `Delivery rejected (${receipt.reason})`,
- );
- void session.stop({ reason: "shutdown", forceAfterMs: SESSION_STOP_GRACE_MS });
+ rejectDelivery(receipt.error?.code ?? receipt.reason, receipt.error?.message ?? `Delivery rejected (${receipt.reason})`);
}
}).catch((error) => {
if (
@@ -1417,13 +1415,7 @@ export class AgentProcessManager {
|| this.activeSpawnState.get(effect.agentId) !== exactOwner
) return;
if (!exactOwner.pendingDeliverySpans.has(input.id)) return;
- this.settlePendingDelivery(exactOwner, input.id);
- this.closeTurn(exactOwner, associatedSpan, {
- event: "turn_abort",
- abortCause: "send_threw",
- });
- this.emitErrorAudit(effect.agentId, "runtime", "send_failed", String(error));
- void session.stop({ reason: "shutdown", forceAfterMs: SESSION_STOP_GRACE_MS });
+ rejectDelivery("send_failed", String(error));
});
} else {
this.dispatch({
@@ -1695,6 +1687,7 @@ export class AgentProcessManager {
activeSpan: null,
timelineTurnOwner: null,
pendingDeliverySpans: new Map(),
+ inputDeliveries: new Map(),
};
const previousOwner = this.activeSpawnState.get(agentId);
if (previousOwner && previousOwner !== state) {
@@ -2103,10 +2096,29 @@ export class AgentProcessManager {
);
}
}
+ if (event.type === "command_returned" && !sessionSuperseded) {
+ const original = owner.inputDeliveries.get(event.input.commandId);
+ const input = original?.preparedInput;
+ if (!original || !input || (input.attemptId ?? input.id) !== event.input.attemptId) return;
+ owner.inputDeliveries.delete(event.input.commandId);
+ if (event.evidence !== "unknown" && event.retryable) {
+ const retried: AgentMsg = { ...original, preparedInput: { ...input, attemptId: randomUUID(), delivery: "next_turn" } };
+ this.dispatch({ type: "queue_delivery", agentId, messages: [retried] }, owner);
+ } else {
+ this.emitErrorAudit(agentId, "runtime", "input_delivery_returned", `Input responsibility returned (${event.evidence}): ${event.reason}`);
+ }
+ return;
+ }
if (event.type === "command_queued") this.acknowledgePendingDelivery(owner, event.commandId);
if (event.type === "command_accepted") this.settlePendingDelivery(owner, event.commandId, "accepted");
if (event.type === "command_failed") {
- const pending = this.settlePendingDelivery(owner, event.commandId);
+ const inputFailure = event.scope === "input" || (event.scope !== "turn" && owner.pendingDeliverySpans.get(event.commandId)?.mode === "busy");
+ const pending = this.settlePendingDelivery(owner, event.commandId, inputFailure ? "rejected" : "failed");
+ owner.inputDeliveries.delete(event.commandId);
+ if (inputFailure) {
+ this.emitErrorAudit(agentId, "runtime", event.error.code, event.error.message);
+ return;
+ }
if (pending && !sessionSuperseded && this.state.agents[agentId]?.status === "running") {
this.closeTurn(owner, pending.span, { event: "turn_abort", abortCause: "send_threw" });
this.emitErrorAudit(agentId, "runtime", event.error.code, event.error.message);
@@ -2200,6 +2212,7 @@ export class AgentProcessManager {
}, owner);
}
if (event.type === "turn_completed") {
+ for (const commandId of event.commandIds) owner.inputDeliveries.delete(commandId);
this.logSessionEnded(agentId, "turn_end");
const marker = this.nonCleanEndMarker.get(agentId);
this.nonCleanEndMarker.delete(agentId);
diff --git a/src/daemon/src/manager/rootLeaseIntegration.test.ts b/src/daemon/src/manager/rootLeaseIntegration.test.ts
index abf5697be..7465fdff9 100644
--- a/src/daemon/src/manager/rootLeaseIntegration.test.ts
+++ b/src/daemon/src/manager/rootLeaseIntegration.test.ts
@@ -28,7 +28,7 @@ async function flushEvents(): Promise<void> {
}
describe("raw adapter → public session → manager root lease", () => {
- it("keeps a native failed command queued through old terminal and cleanup, then replays its original input", async () => {
+ it("keeps an explicitly deferred native input through root failure and cleanup, then replays its original input", async () => {
vi.useFakeTimers({ toFake: ["Date"] });
vi.setSystemTime(new Date("2026-10-13T07:00:00Z"));
let now = 0;
@@ -87,13 +87,13 @@ describe("raw adapter → public session → manager root lease", () => {
await raw(0, { jsonrpc: "2.0", method: "item/started", params: {
threadId: "root-thread", turnId: "root-vendor-turn", item: { id: "compaction", type: "contextCompaction" },
} });
- manager.deliver("a1", { id: "retry-command", seq: 2, text: "retry" });
+ manager.deliver("a1", { id: "retry-command", seq: 2, text: "retry", preparedInput: { id: "retry-command", kind: "user", text: "[fixed time] retry\n\nnative delivery footer", sequence: 2, delivery: "next_turn" } });
await flushEvents();
- expect(firstSend).toHaveBeenCalledOnce();
- const original: AgentMessage = firstSend.mock.calls[0]![0];
- expect(original).toEqual({ id: "retry-command", kind: "user", text: expect.stringMatching(/^\[[^\]]+\] retry\n\nnative delivery footer$/), sequence: 2 });
- expect(manager.snapshot().agents.a1.pendingAdmissions.map((entry) => entry.commandId)).toEqual(["retry-command"]);
- expect(sessions[0]!.snapshot().queuedCommands.map((command) => command.commandId)).toEqual(["retry-command"]);
+ expect(firstSend).not.toHaveBeenCalled();
+ const original: AgentMessage = manager.snapshot().agents.a1.inbox[0]!.preparedInput!;
+ expect(original).toEqual({ id: "retry-command", kind: "user", text: expect.stringMatching(/^\[[^\]]+\] retry\n\nnative delivery footer$/), sequence: 2, delivery: "next_turn" });
+ expect(manager.snapshot().agents.a1.pendingAdmissions).toEqual([]);
+ expect(sessions[0]!.snapshot().queuedCommands).toEqual([]);
now = 400_000;
vi.setSystemTime(new Date("2026-10-13T07:01:00Z"));
@@ -104,7 +104,7 @@ describe("raw adapter → public session → manager root lease", () => {
expect(release).toHaveBeenCalledOnce();
});
expect(sessions[0]!.snapshot().state).toBe("stopping");
- expect(firstSend).toHaveBeenCalledOnce();
+ expect(firstSend).not.toHaveBeenCalled();
expect(nextStart).not.toHaveBeenCalled();
expect(trace.some((row) => row.event === "turn_end" && row.status === "stopping" && !row.effects?.includes("send"))).toBe(true);
diff --git a/src/shared/src/community-bot-creation.test.ts b/src/shared/src/community-bot-creation.test.ts
new file mode 100644
index 000000000..bf866c146
--- /dev/null
+++ b/src/shared/src/community-bot-creation.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from "vitest"
+import { resolveBotCreationConfiguration } from "./community-bot-creation"
+
+const machine = { id: "machine", status: "online" }
+const backends = ["qoder", "copilot", "cursor-sdk", "pi-durable"]
+
+describe("new backend creation configuration", () => {
+ it.each(backends)("preserves the reported %s model and effort", (backendId) => {
+ const runtime = { id: backendId, status: "healthy" as const, reasoning: { updateMode: "unsupported" as const, models: [{ id: "provider/model", supportedReasoningEfforts: [{ value: "high" }] }] } }
+ expect(resolveBotCreationConfiguration(machine, runtime, { backendId, model: "provider/model", reasoningEffort: "high" }).supported).toBe(true)
+ expect(() => resolveBotCreationConfiguration(machine, runtime, { backendId, model: "provider/model", reasoningEffort: "invalid" })).toThrow("not supported")
+ expect(() => resolveBotCreationConfiguration(machine, { ...runtime, status: "unhealthy" }, { backendId, model: "provider/model" })).toThrow("currently unavailable")
+ })
+ it.each(["pi-durable", "cursor-sdk"])("rejects %s without an explicit model", (backendId) => {
+ for (const model of [undefined, null, "", " "]) {
+ expect(() => resolveBotCreationConfiguration(machine, { id: backendId, status: "healthy" }, { backendId, model })).toThrow("Choose a model before saving")
+ }
+ })
+ it.each(["qoder", "copilot", "codex"])("keeps %s native defaults", (backendId) => {
+ expect(resolveBotCreationConfiguration(machine, { id: backendId, status: "healthy" }, { backendId }).supported).toBe(true)
+ })
+})
diff --git a/src/shared/src/community/bot-model.test.ts b/src/shared/src/community/bot-model.test.ts
index bc4bea99e..b30e64636 100644
--- a/src/shared/src/community/bot-model.test.ts
+++ b/src/shared/src/community/bot-model.test.ts
@@ -1,6 +1,7 @@
import { describe, it, expect } from "vitest";
import {
resolveModelConfig,
+ requiresExplicitModel,
formatModelLabel,
modelSelectState,
modelNameFromSelect,
@@ -62,3 +63,10 @@ describe("modelSelectState / modelNameFromSelect round-trip", () => {
expect(modelNameFromSelect(MODEL_SELECT_CUSTOM, " ")).toBeNull();
});
});
+
+it.each(["opencode", "pi-durable", "cursor-sdk"])("%s requires a selected model", (runtime) => {
+ expect(requiresExplicitModel(runtime)).toBe(true);
+});
+it.each(["codex", "claude", "cursor", "pi", "qoder", "copilot", "unknown"])("%s preserves runtime defaults", (runtime) => {
+ expect(requiresExplicitModel(runtime)).toBe(false);
+});
diff --git a/src/shared/src/community/bot-model.ts b/src/shared/src/community/bot-model.ts
index 25b8877f2..c3013861c 100644
--- a/src/shared/src/community/bot-model.ts
+++ b/src/shared/src/community/bot-model.ts
@@ -15,7 +15,7 @@
import type { ModelConfig } from "../runtime-config";
export function requiresExplicitModel(runtime: string | null | undefined): boolean {
- return runtime === "opencode";
+ return runtime === "opencode" || runtime === "pi-durable" || runtime === "cursor-sdk";
}
/** Select sentinel for "Default (the runtime's own default)". */
diff --git a/src/web/public/providers/qoder.svg b/src/web/public/providers/qoder.svg
new file mode 100644
index 000000000..e6f339a28
--- /dev/null
+++ b/src/web/public/providers/qoder.svg
@@ -0,0 +1,4 @@
+<svg width="206" height="206" viewBox="28 28 150 150" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path fill-rule="evenodd" clip-rule="evenodd" d="M104.003 35.8361C104.122 35.8899 104.223 35.938 104.308 35.9805C104.575 36.1139 104.784 36.2211 104.937 36.3023L154.881 62.632L154.9 62.6418C154.992 62.6907 155.084 62.7426 155.173 62.7973C160.753 65.8115 165.083 70.1612 168.163 75.8464C171.221 81.491 172.75 87.925 172.75 95.1484V117.637C172.75 117.795 172.743 117.954 172.728 118.111V158.251C172.728 163.577 170.488 167.682 166.008 170.563C161.529 173.445 156.866 173.781 152.021 171.573L143.479 167.682L143.449 167.699L143.279 167.796C143.276 167.798 143.237 167.821 143.159 167.867C142.593 168.202 142.154 168.454 141.84 168.625C141.789 168.654 141.686 168.709 141.532 168.79C141.479 168.819 141.443 168.837 141.426 168.846L141.174 168.979C140.759 169.203 140.355 169.414 139.961 169.61L139.342 169.911L139.192 169.982C138.849 170.145 138.46 170.326 138.025 170.524L137.252 170.86C136.994 170.973 136.623 171.127 136.137 171.32L136.002 171.374L135.892 171.42C135.835 171.443 135.78 171.466 135.725 171.488C135.49 171.584 135.294 171.661 135.137 171.716C134.872 171.814 134.453 171.961 133.881 172.16L133.879 172.161L133.715 172.219C133.549 172.28 133.366 172.342 133.165 172.407C132.571 172.603 131.9 172.805 131.151 173.012L127.646 173.973C126.996 174.153 126.392 174.306 125.833 174.432L125.437 174.515L125.039 174.596C124.663 174.676 124.363 174.738 124.139 174.782C124.007 174.809 123.855 174.836 123.681 174.864C123.646 174.869 123.625 174.872 123.619 174.874L123.11 174.956C123.106 174.957 123.084 174.961 123.044 174.967C122.729 175.02 122.483 175.059 122.304 175.085C122.178 175.104 121.986 175.129 121.727 175.159L121.331 175.209L120.674 175.285C120.526 175.302 120.362 175.317 120.18 175.33L120.066 175.341L120.015 175.345C119.546 175.384 119.175 175.411 118.903 175.426C118.815 175.433 118.717 175.438 118.608 175.443L118.645 175.439C118.497 175.452 118.347 175.459 118.198 175.459H118.137C117.737 175.478 117.398 175.487 117.121 175.487H116.455C116.418 175.487 116.381 175.487 116.344 175.486C116.298 175.485 116.224 175.484 116.122 175.483C115.843 175.479 115.623 175.473 115.461 175.466C115.335 175.462 115.132 175.452 114.852 175.434L114.824 175.432L114.654 175.426L114.273 175.407C114.212 175.404 114.15 175.399 114.088 175.394L113.388 175.332C112.948 175.29 112.527 175.243 112.124 175.19L111.925 175.166C111.882 175.162 111.839 175.155 111.796 175.149C111.339 175.081 110.875 175.005 110.403 174.921L109.901 174.827L109.871 174.821C109.63 174.777 109.429 174.736 109.27 174.698L109.224 174.687L109.158 174.672L109.037 174.644C108.61 174.549 108.15 174.435 107.656 174.301L107.629 174.294C107.5 174.263 107.358 174.226 107.201 174.181L107.2 174.181C106.608 174.013 106.029 173.831 105.463 173.634C105.307 173.586 105.154 173.53 105.004 173.466L104.884 173.42C104.405 173.241 104.002 173.083 103.675 172.948C103.58 172.909 103.469 172.861 103.342 172.804C103.29 172.781 103.261 172.768 103.255 172.766L103.084 172.692C102.756 172.551 102.39 172.384 101.986 172.19L101.906 172.152L101.891 172.145C101.798 172.103 101.715 172.063 101.64 172.025C101.571 171.99 101.501 171.955 101.431 171.918C101.407 171.906 101.386 171.895 101.369 171.886C101.249 171.835 101.13 171.778 101.012 171.716L101.009 171.715L51.5574 145.645C51.215 145.509 50.8889 145.336 50.5849 145.128C48.367 143.914 46.3274 142.453 44.4659 140.744C44.4647 140.743 44.4635 140.742 44.4623 140.741C44.4584 140.737 44.4546 140.734 44.4507 140.73C44.4362 140.717 44.4214 140.704 44.4064 140.69C43.6029 139.953 42.8113 139.14 42.0317 138.252C42.0244 138.243 42.0171 138.235 42.0097 138.226C42.0082 138.224 42.0067 138.222 42.0051 138.22C41.5797 137.727 41.1892 137.252 40.8338 136.795C40.7387 136.672 40.6464 136.551 40.5567 136.432C35.6857 129.988 33.2502 122.172 33.2502 112.983V90.4946C33.2502 89.8308 33.2644 89.0633 33.2927 88.1921C33.3022 87.9838 33.3174 87.7494 33.3384 87.4888C33.3459 87.3951 33.3511 87.3283 33.3539 87.2882C33.3866 86.7286 33.4259 86.2074 33.4719 85.7247C33.4848 85.5587 33.5136 85.2969 33.5583 84.9392C33.5691 84.8524 33.5769 84.7892 33.5817 84.7498C33.589 84.6881 33.6006 84.5877 33.6166 84.4487C33.672 83.9681 33.7187 83.5958 33.7569 83.3318C33.7999 83.0465 33.8556 82.7028 33.9239 82.3007C33.9303 82.2616 33.9429 82.1836 33.9618 82.0668C34.0386 81.5927 34.1025 81.2235 34.1537 80.9593C34.1539 80.9576 34.1542 80.9559 34.1545 80.9542L34.1507 80.9713C34.1669 80.871 34.1817 80.7851 34.1951 80.7134C34.3125 80.1121 34.4286 79.5636 34.5433 79.0679C34.5554 79.0129 34.5689 78.9553 34.5837 78.895C34.704 78.3592 34.8544 77.7535 35.0349 77.078C35.0683 76.9444 35.1121 76.78 35.1663 76.5847C35.1764 76.5481 35.1839 76.5212 35.1886 76.5042C35.4221 75.6865 35.6047 75.0694 35.7364 74.653C35.7408 74.639 35.7453 74.6249 35.7499 74.6109C35.7573 74.5867 35.7647 74.5627 35.7723 74.539C35.7789 74.517 35.7857 74.495 35.7926 74.473C35.8241 74.3734 35.8643 74.2549 35.9134 74.1174L35.9251 74.085C36.1639 73.3479 36.3895 72.6905 36.6021 72.1127C36.6575 71.9603 36.7417 71.7385 36.8547 71.4475C36.8818 71.3777 36.9019 71.3258 36.9151 71.2917C36.9324 71.247 36.9593 71.177 36.9959 71.0817C37.2171 70.5062 37.3921 70.0651 37.5208 69.7585L37.5168 69.7661C37.5549 69.6676 37.5905 69.5789 37.6236 69.5C37.6858 69.3466 37.7661 69.1613 37.8644 68.944C37.8998 68.8657 37.9232 68.8133 37.9347 68.7869C38.152 68.2878 38.3184 67.9104 38.4338 67.6548C38.5471 67.4055 38.7105 67.0593 38.9238 66.6163C38.9706 66.5208 39.03 66.3991 39.1019 66.2511C39.2648 65.9163 39.392 65.6588 39.4835 65.4786L39.5155 65.4136C39.5653 65.3091 39.6106 65.2167 39.6516 65.1362C39.7258 64.9869 39.8207 64.8074 39.9362 64.5977C39.9744 64.5283 39.9996 64.4822 40.0115 64.4596C40.0477 64.3922 40.0935 64.3066 40.1489 64.2029C40.3258 63.872 40.463 63.6187 40.5605 63.4432C40.7672 63.0697 40.9619 62.726 41.1445 62.4123C41.2987 62.1332 41.489 61.8063 41.7152 61.4316C41.7383 61.3935 41.7619 61.3555 41.786 61.318L41.7824 61.323C41.7846 61.3193 41.7867 61.3156 41.7888 61.3118L41.7824 61.323C41.8335 61.2318 41.8771 61.1561 41.9132 61.0959C42.0161 60.9245 42.159 60.697 42.342 60.4136C42.5227 60.1209 42.7188 59.811 42.9304 59.484C43.0841 59.2469 43.3076 58.9123 43.601 58.4804L43.9154 58.0238L44.2115 57.5939C44.2325 57.5634 44.2537 57.5333 44.2753 57.5034L44.2749 57.5021C44.3548 57.3822 44.4252 57.2801 44.4861 57.1958C44.5458 57.1108 44.6445 56.9765 44.7821 56.7929C44.8446 56.7095 44.8877 56.6514 44.9115 56.6186C45.2257 56.1886 45.4678 55.8625 45.6377 55.6403L45.9946 55.1837L46.3262 54.7597C46.5387 54.4816 46.7902 54.1653 47.0808 53.811C47.0969 53.7914 47.1242 53.7575 47.1628 53.7094C47.2305 53.6246 47.2851 53.5571 47.3267 53.5067C47.4115 53.4034 47.53 53.264 47.6821 53.0885C47.7338 53.0289 47.771 52.9858 47.7938 52.9593C47.8766 52.8642 47.9852 52.7384 48.1197 52.582C48.3585 52.3041 48.544 52.0909 48.6764 51.9423L49.3723 51.1748C49.5804 50.9454 49.8853 50.6178 50.2869 50.1921C50.3199 50.1572 50.3534 50.1227 50.3874 50.0888L50.3985 50.0741C50.5274 49.9324 50.6395 49.8139 50.7349 49.7185C50.7855 49.6679 50.8533 49.6012 50.9383 49.5185C50.99 49.4683 51.0247 49.4343 51.0424 49.4165C51.4915 48.9675 51.9017 48.5656 52.2729 48.2107C52.3283 48.1583 52.4007 48.0891 52.49 48.0029C52.6771 47.8224 52.8271 47.6806 52.9399 47.5775C53.3761 47.1664 53.9052 46.6923 54.5271 46.155C54.5279 46.1543 54.5287 46.1536 54.5295 46.1528L54.5189 46.161C54.617 46.0697 54.7025 45.9924 54.7754 45.9292C54.8391 45.8741 54.904 45.8206 54.9705 45.7688C54.997 45.7476 55.0236 45.7269 55.0503 45.7065L55.0774 45.6851L55.0939 45.6717C55.5288 45.3081 55.9911 44.9311 56.4808 44.5407C56.5166 44.5125 56.5529 44.4839 56.5898 44.4548C56.7923 44.2954 56.9507 44.1724 57.0648 44.0858C57.2979 43.9051 57.6655 43.6275 58.1675 43.253C58.2075 43.2232 58.2479 43.1939 58.2888 43.1654C58.3729 43.1065 58.5143 43.0042 58.7128 42.8586C59.1025 42.577 59.5704 42.2518 60.1163 41.883L60.1145 41.8841L60.1593 41.8524C60.2852 41.7638 60.3942 41.6892 60.4862 41.6287C60.5329 41.5967 60.5792 41.5661 60.6251 41.5367C61.2865 41.1057 61.8541 40.7475 62.3278 40.4623C62.4222 40.4035 62.5743 40.3142 62.7839 40.1944C62.7838 40.1941 62.8182 40.1736 62.8873 40.1328C63.453 39.7986 63.8928 39.5462 64.2065 39.3754L64.8387 39.0383L64.872 39.0207C65.2867 38.7973 65.6911 38.5871 66.0852 38.39C66.2669 38.2991 66.5247 38.1744 66.8586 38.0158C67.1979 37.8542 67.5857 37.6746 68.0218 37.477L68.4373 37.2954L68.7948 37.1398C69.0934 37.0111 69.5097 36.84 70.0435 36.6265C70.1097 36.6005 70.1844 36.5712 70.2678 36.5384C70.5114 36.4427 70.6998 36.3699 70.833 36.3199C71.1527 36.2027 71.5991 36.0447 72.1722 35.8457C72.2132 35.8316 72.2719 35.8109 72.3482 35.7837C72.574 35.7031 72.7593 35.64 72.904 35.5945C73.5201 35.3928 74.1846 35.1929 74.8975 34.9948L78.4057 34.0333C79.0348 33.8574 79.6373 33.7044 80.2131 33.5744C80.378 33.5359 80.5868 33.4913 80.8395 33.4407C81.1612 33.3685 81.5282 33.2925 81.9406 33.2127C82.0871 33.1842 82.2808 33.151 82.5216 33.1131C82.5981 33.101 82.6517 33.0924 82.6826 33.0873C82.7524 33.0758 82.852 33.0591 82.9815 33.0372C83.2985 32.9834 83.5459 32.9435 83.7238 32.9177C83.7635 32.9119 83.8033 32.9066 83.8432 32.9018L84.1737 32.8619L84.504 32.822C84.5516 32.8162 84.6345 32.8056 84.7525 32.7903C85.0348 32.7538 85.2559 32.7271 85.4158 32.7105C85.5254 32.6991 85.6353 32.6913 85.7453 32.6873L86.07 32.6632C86.533 32.6238 86.9091 32.5967 87.1982 32.582C87.3378 32.5734 87.5561 32.5646 87.8533 32.5556L87.8692 32.5551C87.9598 32.5532 88.0717 32.5499 88.205 32.5453C88.4606 32.5364 88.6706 32.5314 88.835 32.5303C88.9748 32.5275 89.1472 32.5271 89.3523 32.529L89.537 32.5302C89.6342 32.5318 89.7388 32.5334 89.851 32.5349C90.1448 32.5389 90.3757 32.5444 90.5436 32.5514C90.6803 32.5549 90.9082 32.5655 91.2273 32.5832C91.2891 32.5871 91.3656 32.5912 91.4568 32.5957C91.6011 32.6026 91.7158 32.6089 91.8012 32.6144C91.9206 32.6204 92.0953 32.6356 92.3254 32.6598L92.6313 32.6871C93.0373 32.7257 93.4523 32.7724 93.8761 32.8271L93.8896 32.8288L93.8913 32.829C94.0015 32.8408 94.0983 32.8527 94.1819 32.8646C94.6093 32.9223 95.085 32.9984 95.6089 33.093C95.6739 33.1047 95.7386 33.1178 95.8031 33.1321L95.8062 33.1318C95.8842 33.1466 95.9548 33.1606 96.0179 33.1737C96.0408 33.1779 96.0713 33.1835 96.1093 33.1905C96.3333 33.2314 96.5177 33.2683 96.6627 33.301C96.7395 33.3173 96.8375 33.3418 96.9566 33.3744C96.9806 33.3797 97.0046 33.385 97.0288 33.3903C97.2476 33.4387 97.4749 33.4924 97.7107 33.5517C97.9063 33.6006 98.1067 33.6529 98.3119 33.7085L98.3072 33.7071L98.3401 33.7149C98.4501 33.742 98.5513 33.7682 98.6438 33.7934C98.6594 33.7976 98.6743 33.8018 98.6886 33.8058C98.7485 33.8224 98.8045 33.8387 98.8566 33.8545C98.8608 33.8557 98.865 33.8569 98.8692 33.8581C99.3732 34.0019 99.9241 34.1774 100.522 34.3846C100.548 34.3932 100.574 34.4019 100.6 34.4109C100.733 34.4556 100.881 34.5109 101.044 34.5769C101.508 34.7451 101.931 34.9089 102.311 35.0684C102.368 35.0928 102.417 35.1139 102.459 35.1317C102.655 35.2169 102.808 35.2839 102.918 35.3328C103.261 35.4856 103.61 35.6469 103.963 35.8169L104.003 35.8361ZM101.032 34.5728L101.03 34.5721C101.033 34.573 101.035 34.5739 101.038 34.5748C101.036 34.5741 101.034 34.5735 101.032 34.5728ZM104.903 162.561L105.666 162.963C105.717 162.991 105.807 163.037 105.935 163.102C105.972 163.121 106.002 163.136 106.025 163.148C106.092 163.178 106.131 163.197 106.145 163.205L106.281 163.269C106.554 163.401 106.811 163.519 107.052 163.622L107.063 163.627C107.148 163.663 107.253 163.708 107.38 163.765C107.425 163.785 107.449 163.796 107.452 163.797C107.68 163.891 107.998 164.015 108.408 164.169L108.458 164.189C108.52 164.211 108.58 164.234 108.641 164.257L108.655 164.263C109.054 164.403 109.476 164.536 109.919 164.661C109.914 164.66 109.885 164.654 109.835 164.643C109.904 164.659 109.973 164.675 110.041 164.693L110.249 164.747C110.596 164.84 110.948 164.927 111.306 165.008L111.379 165.025L111.451 165.041L111.564 165.067L111.672 165.086L111.703 165.092L112.139 165.174C112.496 165.238 112.847 165.295 113.191 165.347L113.391 165.372C113.685 165.41 113.977 165.443 114.269 165.47L114.88 165.525L115.066 165.535L115.442 165.551L115.47 165.553C115.644 165.565 115.787 165.572 115.899 165.576C115.964 165.579 116.087 165.581 116.267 165.584C116.363 165.585 116.443 165.586 116.506 165.587H117.121C117.26 165.587 117.474 165.58 117.764 165.566C117.848 165.561 117.932 165.559 118.015 165.559H118.037C118.081 165.557 118.126 165.555 118.174 165.552L118.156 165.555C118.215 165.55 118.274 165.546 118.334 165.542C118.501 165.534 118.779 165.514 119.169 165.481L119.325 165.467C119.376 165.462 119.427 165.458 119.479 165.455C119.506 165.453 119.53 165.451 119.549 165.449L120.088 165.388L120.592 165.324C120.728 165.308 120.832 165.295 120.904 165.284C121.005 165.27 121.174 165.243 121.411 165.203C121.454 165.196 121.491 165.19 121.522 165.185L121.924 165.119C121.976 165.11 122.042 165.1 122.123 165.087L122.114 165.091C122.152 165.082 122.191 165.074 122.23 165.067C122.398 165.035 122.677 164.977 123.068 164.895L123.398 164.828L123.653 164.775C124.058 164.683 124.517 164.567 125.03 164.425L128.507 163.472C129.101 163.307 129.652 163.141 130.162 162.973C130.219 162.955 130.253 162.943 130.266 162.939C130.308 162.922 130.35 162.907 130.393 162.892L130.632 162.808H130.634C131.154 162.628 131.551 162.487 131.825 162.387C131.834 162.383 131.882 162.364 131.971 162.328C132.052 162.295 132.097 162.276 132.106 162.273L132.326 162.182C132.367 162.166 132.414 162.147 132.467 162.126C132.853 161.972 133.13 161.858 133.299 161.784L133.938 161.506C134.318 161.334 134.65 161.181 134.935 161.045L135.024 161.003L135.533 160.756C135.838 160.604 136.178 160.426 136.553 160.224L136.711 160.141C136.766 160.112 136.839 160.073 136.929 160.025C136.993 159.992 137.052 159.961 137.107 159.93C137.318 159.814 137.658 159.619 138.125 159.343C138.192 159.304 138.261 159.263 138.332 159.221L138.46 159.147H138.461C138.544 159.098 138.619 159.055 138.687 159.017C139.131 158.749 139.551 158.484 139.947 158.224L140.305 157.979C141.736 157.002 143.572 156.845 145.148 157.563L156.125 162.564C157.693 163.279 159.202 163.17 160.652 162.237C162.103 161.304 162.828 159.976 162.828 158.251V117.614C162.828 117.456 162.835 117.298 162.85 117.14V95.1484C162.85 83.7403 158.651 75.8219 150.254 71.3934L149.959 71.2374C149.909 71.2132 149.855 71.1867 149.796 71.158C149.721 71.1217 149.663 71.0932 149.62 71.0724C149.384 70.9567 149.129 70.8386 148.853 70.718C148.676 70.6389 148.548 70.5828 148.468 70.5496C148.234 70.4515 147.944 70.3392 147.597 70.2126L147.415 70.1456L147.313 70.1067C146.939 69.9768 146.534 69.8488 146.096 69.7227L145.999 69.6973L145.777 69.6395C145.321 69.5221 144.979 69.4377 144.751 69.3863C144.724 69.3805 144.683 69.3717 144.629 69.3597C144.371 69.3034 144.185 69.2642 144.072 69.242C144.03 69.2339 143.989 69.2253 143.948 69.2162L143.83 69.1927C143.449 69.1241 143.093 69.0673 142.761 69.0223C142.792 69.0267 142.81 69.0291 142.814 69.0296C142.703 69.0177 142.628 69.0088 142.589 69.0029C142.287 68.9641 141.996 68.931 141.716 68.9037L141.71 68.9033L141.383 68.8734C141.233 68.8611 140.993 68.845 140.663 68.8252C140.435 68.8126 140.276 68.805 140.186 68.8025C140.128 68.8008 140.071 68.7982 140.014 68.7947C139.934 68.7897 139.76 68.7873 139.491 68.7873L138.982 68.7863C138.823 68.7894 138.572 68.7974 138.23 68.8105C138.13 68.8157 138.008 68.8205 137.866 68.8249C137.791 68.8271 137.731 68.8296 137.686 68.8322C137.515 68.8408 137.229 68.8619 136.827 68.8954L136.781 68.899C136.729 68.9029 136.661 68.9074 136.577 68.9127L136.442 68.9231C136.355 68.9316 136.204 68.9492 135.988 68.9761C135.849 68.9934 135.758 69.0044 135.717 69.0091C135.625 69.0209 135.503 69.035 135.352 69.0513C135.248 69.0625 135.179 69.0706 135.146 69.0756C135.049 69.09 134.884 69.1175 134.65 69.158C134.503 69.1832 134.384 69.2036 134.291 69.219C134.229 69.2289 134.145 69.2422 134.038 69.2587C133.907 69.2786 133.814 69.2938 133.759 69.3042C133.645 69.3251 133.444 69.3668 133.157 69.4293C133.028 69.4574 132.949 69.4744 132.92 69.4802C132.827 69.5013 132.7 69.5285 132.54 69.5617C132.451 69.5801 132.403 69.5901 132.396 69.5916C131.906 69.7035 131.445 69.8191 131.014 69.9384L127.538 70.8908C126.968 71.049 126.455 71.2026 125.998 71.3517L125.707 71.4525L125.352 71.575C124.951 71.7086 124.6 71.8325 124.3 71.9467C124.181 71.9913 123.979 72.0708 123.693 72.1852C123.284 72.3461 122.971 72.4736 122.752 72.5678L122.104 72.8516C121.973 72.9113 121.833 72.9757 121.684 73.0449V91.2807C121.684 92.0491 121.665 92.8184 121.628 93.5885C121.622 93.7365 121.609 93.9283 121.591 94.1637L121.59 94.1679L121.571 94.4471L121.57 94.4744C121.528 95.1281 121.491 95.6208 121.457 95.9524C121.439 96.1399 121.414 96.3666 121.381 96.6324L121.329 97.0655C121.322 97.1194 121.312 97.2021 121.299 97.3136C121.248 97.7482 121.207 98.0619 121.178 98.255C121.155 98.4224 121.12 98.6496 121.074 98.9367C121.068 98.9704 121.065 98.9883 121.065 98.9905L121.009 99.3453L121.009 99.3467C120.917 99.902 120.844 100.324 120.788 100.612C120.661 101.278 120.528 101.923 120.389 102.547L120.362 102.657C120.224 103.259 120.071 103.869 119.902 104.487L119.761 104.999C119.578 105.652 119.397 106.263 119.219 106.83L119.068 107.297C118.85 107.97 118.629 108.613 118.405 109.225C118.356 109.361 118.29 109.536 118.205 109.751L118.188 109.793L118.192 109.783L118.08 110.078C118.063 110.121 118.039 110.184 118.007 110.266C117.79 110.827 117.625 111.244 117.512 111.517C117.449 111.674 117.358 111.889 117.239 112.163C117.192 112.273 117.165 112.336 117.158 112.351L117.095 112.503C116.916 112.924 116.752 113.292 116.603 113.609C116.52 113.796 116.401 114.053 116.244 114.381C116.192 114.49 116.148 114.584 116.109 114.664C116.087 114.71 116.055 114.778 116.011 114.868C115.823 115.258 115.676 115.559 115.568 115.77C115.376 116.148 115.2 116.486 115.04 116.784L114.726 117.371L114.51 117.768C114.385 117.994 114.197 118.325 113.947 118.761C113.932 118.786 113.907 118.83 113.871 118.893C113.665 119.251 113.496 119.536 113.364 119.749C113.175 120.066 112.975 120.389 112.764 120.718C112.747 120.745 112.719 120.789 112.68 120.851C112.458 121.207 112.294 121.463 112.191 121.62C112.082 121.789 111.924 122.028 111.715 122.339C111.63 122.465 111.557 122.575 111.495 122.666L111.474 122.698L110.894 123.543L110.828 123.635L110.248 124.44C110.006 124.774 109.774 125.086 109.554 125.376C109.374 125.614 109.136 125.921 108.838 126.296C108.792 126.354 108.722 126.444 108.626 126.564C108.415 126.831 108.255 127.032 108.146 127.165C107.99 127.358 107.765 127.627 107.472 127.971L107.432 128.017L107.427 128.022C107.169 128.329 106.885 128.659 106.573 129.01C106.415 129.187 106.185 129.443 105.883 129.777C105.674 130.009 105.372 130.333 104.979 130.75C104.865 130.87 104.702 131.038 104.49 131.254C104.4 131.346 104.327 131.42 104.271 131.477C103.929 131.825 103.523 132.223 103.055 132.67L102.875 132.844L102.673 133.037L102.415 133.284C101.896 133.765 101.374 134.233 100.848 134.686L100.749 134.772L100.669 134.843L100.589 134.915C100.544 134.955 100.499 134.995 100.452 135.032L100.254 135.197C99.956 135.449 99.52 135.806 98.9463 136.268L98.9399 136.273C98.8505 136.346 98.7376 136.435 98.6012 136.539C98.551 136.577 98.5019 136.615 98.4539 136.652L98.3712 136.715C97.9722 137.023 97.5654 137.329 97.1506 137.632C97.1246 137.65 97.0729 137.688 96.9956 137.746C96.8643 137.844 96.7619 137.919 96.6886 137.971C96.2495 138.286 95.8236 138.581 95.4107 138.856L95.0917 139.078C95.0575 139.102 95.0231 139.126 94.9883 139.148C94.3982 139.537 93.7872 139.923 93.1553 140.305L93.1461 140.31C93.3774 150.816 97.2951 158.232 104.899 162.559C104.9 162.559 104.902 162.56 104.903 162.561ZM85.109 152.14C83.8619 148.186 83.2373 143.919 83.2353 139.337V137.521C83.2347 137.489 83.2344 137.458 83.2344 137.426V116.845C83.2344 116.045 83.2534 115.247 83.2913 114.451C83.2988 114.292 83.313 114.083 83.334 113.822C83.3415 113.729 83.3466 113.663 83.3493 113.626C83.3544 113.552 83.3621 113.44 83.3724 113.29C83.4083 112.76 83.4408 112.342 83.4697 112.035C83.4825 111.908 83.5022 111.733 83.5288 111.511C83.5477 111.353 83.5635 111.213 83.5763 111.091C83.5843 111.024 83.5963 110.921 83.6122 110.782C83.6676 110.301 83.7158 109.919 83.757 109.636C83.797 109.37 83.8504 109.041 83.917 108.649C83.9225 108.616 83.931 108.565 83.9424 108.496C84.0263 107.992 84.0935 107.6 84.144 107.32C84.2642 106.675 84.3948 106.043 84.5356 105.422C84.5486 105.362 84.5632 105.3 84.5794 105.234C84.5829 105.219 84.5864 105.203 84.59 105.188C84.7498 104.507 84.9083 103.874 85.0654 103.29C85.0711 103.27 85.0838 103.223 85.1035 103.148C85.1407 103.006 85.1675 102.907 85.1837 102.851C85.3667 102.187 85.5509 101.565 85.7364 100.984C85.7394 100.975 85.7425 100.965 85.7454 100.956C85.7604 100.907 85.7756 100.859 85.7911 100.812C85.8274 100.699 85.8714 100.57 85.9233 100.425C85.9267 100.416 85.9288 100.41 85.9293 100.409C86.1871 99.6224 86.4078 98.9796 86.5913 98.4808C86.651 98.3166 86.7374 98.0889 86.8505 97.7977C86.8777 97.7276 86.8935 97.687 86.8979 97.6759C87.1126 97.1079 87.3121 96.6018 87.4965 96.1574C87.5769 95.96 87.6945 95.6837 87.8495 95.3284C87.8867 95.2432 87.9153 95.1776 87.9353 95.1316C88.1491 94.6407 88.3155 94.2636 88.4344 94.0001C88.5435 93.7602 88.7034 93.4213 88.9141 92.9835C88.9155 92.9806 88.9169 92.9777 88.9182 92.9749C89.099 92.5951 89.2811 92.2247 89.4646 91.8639C89.5557 91.6816 89.689 91.4218 89.8645 91.0844C89.9194 90.9789 89.9656 90.8899 90.0032 90.8175C90.201 90.4424 90.3841 90.1034 90.5524 89.8004C90.7617 89.4223 90.9573 89.0771 91.1389 88.7647L91.4063 88.3047L91.7037 87.7941C91.8473 87.5548 92.0487 87.2295 92.3079 86.8181C92.4094 86.6532 92.5571 86.4188 92.7509 86.1149C92.8189 86.0084 92.8779 85.9158 92.9281 85.8371C93.0803 85.6022 93.2952 85.2806 93.5727 84.8722C93.8298 84.4867 94.0521 84.1637 94.2398 83.9033C94.4559 83.5971 94.6806 83.2865 94.9138 82.9715C95.2236 82.5476 95.4605 82.2284 95.6245 82.014C95.8073 81.7734 96.0476 81.4661 96.3452 81.0921L96.69 80.6582L97.0805 80.168C97.2347 79.9804 97.4631 79.7075 97.7656 79.3492L97.7895 79.3212C97.8343 79.2689 97.9023 79.1892 97.9935 79.0823C98.2842 78.7413 98.506 78.4851 98.6587 78.3137C98.8175 78.1339 99.0523 77.8728 99.3629 77.5304C99.5705 77.3015 99.8791 76.9701 100.289 76.536C100.534 76.2773 100.774 76.0318 101.006 75.7993C101.356 75.4442 101.766 75.0422 102.236 74.5932C102.529 74.3084 102.75 74.0982 102.898 73.9627C103.423 73.4747 103.975 72.9804 104.555 72.4797L104.568 72.4679C104.572 72.4646 104.575 72.4614 104.579 72.4582L104.568 72.4679C104.69 72.3555 104.78 72.2755 104.837 72.2279C104.93 72.1485 105.043 72.0556 105.178 71.9492C105.67 71.5386 106.104 71.1853 106.48 70.8893C106.615 70.7826 106.802 70.6384 107.041 70.4566C107.478 70.1188 107.863 69.8283 108.196 69.5852L108.738 69.1881C109.156 68.886 109.606 68.5732 110.088 68.2498C110.094 68.2454 110.111 68.2342 110.137 68.2159C110.281 68.1154 110.413 68.0272 110.532 67.9513C111.047 67.6097 111.632 67.2385 112.286 66.8376C112.329 66.8116 112.372 66.7861 112.415 66.7614C112.544 66.6878 112.642 66.6306 112.71 66.59C113.351 66.212 113.817 65.9444 114.107 65.7874C114.195 65.7371 114.288 65.6854 114.387 65.6323C114.427 65.6108 114.467 65.5899 114.507 65.5696C114.569 65.5368 114.639 65.5005 114.715 65.4606C114.784 65.425 114.833 65.3993 114.863 65.3835C115.228 65.1868 115.634 64.9766 116.082 64.7529C116.336 64.6259 116.591 64.5012 116.849 64.3787C117.279 64.1741 117.669 63.9926 118.018 63.8342L118.772 63.5029C119.128 63.3494 119.559 63.1731 120.064 62.9741C120.385 62.8458 120.638 62.7468 120.824 62.6771C121.224 62.5247 121.69 62.36 122.221 62.183L122.468 62.0972L122.76 61.9962C123.466 61.7648 124.175 61.5501 124.888 61.352L128.396 60.3905C128.613 60.3306 128.835 60.2715 129.063 60.213L100.3 45.0496C100.214 45.004 100.083 44.937 99.9066 44.8487C99.9047 44.8478 99.9027 44.8469 99.9007 44.846L99.9075 44.8496C99.7964 44.7991 99.6999 44.7535 99.6181 44.7129C99.4811 44.6472 99.3429 44.5824 99.2036 44.5184C99.1007 44.4713 98.9939 44.4231 98.8832 44.3739C98.8044 44.3386 98.6867 44.2871 98.53 44.2193C98.4876 44.201 98.455 44.1869 98.4322 44.177C98.4314 44.1767 98.4306 44.1763 98.4299 44.176C98.3382 44.1381 98.2427 44.0998 98.1433 44.061C97.9965 44.0041 97.8311 43.9427 97.6473 43.8766C97.5717 43.85 97.4776 43.814 97.3649 43.7686C97.3527 43.7645 97.3407 43.7603 97.3286 43.7561C96.8799 43.5998 96.4567 43.4648 96.059 43.3512L95.9727 43.3283C95.8926 43.3086 95.8272 43.2921 95.7763 43.2788C95.3802 43.1715 95.0531 43.0905 94.795 43.036C94.6972 43.0166 94.5792 42.9882 94.4409 42.9508C94.4084 42.9445 94.3714 42.9375 94.33 42.93C94.2346 42.9125 94.1589 42.8984 94.1029 42.8876C94.0584 42.8789 94.014 42.8697 93.9698 42.8599L93.9667 42.8601C93.9009 42.8477 93.8405 42.8359 93.7854 42.8246C93.4377 42.7625 93.1212 42.7121 92.8358 42.6733C92.725 42.6614 92.6275 42.6495 92.5435 42.6375C92.2732 42.6029 91.997 42.5722 91.7147 42.5453L91.3599 42.5131L91.2927 42.5057L91.289 42.5054L91.1859 42.4959C91.1239 42.4922 91.055 42.4886 90.9793 42.4849C90.835 42.478 90.7203 42.4717 90.6349 42.4662C90.4366 42.4553 90.292 42.4486 90.201 42.446C90.0797 42.4413 89.9183 42.4376 89.7169 42.4349C89.5824 42.433 89.4787 42.4313 89.4058 42.4298C89.4064 42.4305 89.3577 42.4304 89.26 42.4294C89.1424 42.4283 89.0705 42.4281 89.0444 42.4289C88.9973 42.4302 88.9501 42.4309 88.903 42.4309C88.8446 42.4309 88.7268 42.434 88.5495 42.4401C88.3825 42.4459 88.248 42.4499 88.1461 42.4522C87.9529 42.458 87.8209 42.4631 87.7499 42.4674C87.5399 42.4782 87.2415 42.5 86.8546 42.5328L86.5715 42.554L86.3409 42.5711C86.3298 42.572 86.3187 42.5728 86.3077 42.5735C86.2335 42.5825 86.1393 42.5944 86.0254 42.6091C85.8845 42.6274 85.7759 42.6412 85.6996 42.6505L85.3608 42.6915L85.0984 42.7231C84.9951 42.7388 84.8419 42.764 84.6388 42.7985C84.4899 42.8237 84.3759 42.8429 84.2967 42.8558C84.246 42.8643 84.1678 42.8768 84.0619 42.8935C83.9382 42.913 83.8599 42.9259 83.827 42.9323C83.5008 42.9954 83.1868 43.0605 82.885 43.1276C82.6666 43.172 82.5146 43.2042 82.429 43.2242C81.993 43.3228 81.5326 43.4398 81.0478 43.5754L77.5317 44.539C76.9734 44.6941 76.4388 44.8552 75.928 45.0223C75.8676 45.0416 75.7842 45.0701 75.6778 45.1081C75.5623 45.1493 75.4704 45.1817 75.4021 45.2051C74.8937 45.3817 74.5177 45.5145 74.2741 45.6037C74.2132 45.6267 74.085 45.6766 73.8895 45.7534C73.7991 45.7889 73.7301 45.816 73.6823 45.8346C73.2548 46.0058 72.9375 46.1359 72.7303 46.2251L72.3994 46.3693L72.0419 46.5249C71.7073 46.677 71.3972 46.821 71.1115 46.957L71.1072 46.9591C70.8335 47.0891 70.6356 47.1846 70.5135 47.2457C70.2089 47.398 69.8811 47.5686 69.5302 47.7576L69.4965 47.7756L68.9012 48.0927C68.7153 48.1941 68.3892 48.3824 67.9232 48.6577C67.8482 48.702 67.7923 48.735 67.7555 48.7567C67.6073 48.8417 67.518 48.8937 67.4876 48.9125C67.0806 49.1579 66.5958 49.4639 66.0332 49.8305C65.9931 49.8578 65.9533 49.8842 65.9139 49.9097L65.8575 49.9496C65.7862 49.9998 65.7282 50.0401 65.6836 50.0706C65.2073 50.3925 64.8258 50.657 64.5392 50.864C64.3368 51.0125 64.1686 51.1342 64.0344 51.2291C63.607 51.5482 63.2914 51.7866 63.0876 51.9444C62.9946 52.0152 62.8699 52.1121 62.7135 52.2352C62.6748 52.2656 62.6456 52.2887 62.6258 52.3042C62.2109 52.635 61.8299 52.9455 61.4827 53.2357C61.4226 53.2875 61.3346 53.3593 61.2187 53.4512C61.1402 53.5238 61.0704 53.5865 61.0095 53.6393C60.4881 54.0895 60.0428 54.4885 59.6734 54.8362C59.591 54.912 59.488 55.0095 59.3645 55.1286C59.248 55.241 59.1565 55.3286 59.0899 55.3914C58.7889 55.6792 58.4401 56.0213 58.0437 56.4178C57.9931 56.4684 57.9253 56.535 57.8403 56.6177C57.7886 56.6679 57.7539 56.7019 57.7362 56.7197L57.7249 56.7344C57.6255 56.8437 57.536 56.9393 57.4565 57.0211C57.1154 57.3829 56.865 57.6517 56.7055 57.8275L56.0398 58.5614C55.9662 58.6442 55.8292 58.8023 55.6287 59.0355C55.4778 59.2111 55.3624 59.3447 55.2825 59.4363C55.2667 59.4549 55.227 59.5009 55.1632 59.5745C55.0686 59.6836 55.0053 59.7575 54.9736 59.7962C54.9593 59.8136 54.9328 59.8464 54.8943 59.8946C54.8265 59.9794 54.7719 60.047 54.7303 60.0973C54.5152 60.3596 54.3244 60.5997 54.1578 60.8176L53.8013 61.2738L53.4693 61.6981C53.3654 61.8344 53.1797 62.0856 52.9122 62.4515C52.8654 62.5159 52.7968 62.6084 52.7064 62.7292C52.6248 62.8381 52.5706 62.9115 52.5439 62.9494L52.5131 62.9944C52.4514 63.087 52.3954 63.1689 52.345 63.2403L52.0696 63.6401L51.7733 64.0703C51.532 64.4257 51.3545 64.691 51.2409 64.8662C51.0597 65.1463 50.8943 65.4079 50.7447 65.6511C50.7251 65.683 50.7052 65.7146 50.6848 65.7459C50.5481 65.9573 50.4543 66.1054 50.4033 66.1903L50.3824 66.227C50.3045 66.3638 50.2323 66.4853 50.1657 66.5917C50.0113 66.8483 49.8731 67.0865 49.751 67.3064C49.5715 67.6161 49.3943 67.9291 49.2192 68.2454C49.1453 68.3783 49.0325 68.5866 48.881 68.8703C48.8223 68.98 48.7781 69.0627 48.7481 69.1185C48.72 69.1716 48.6738 69.2567 48.6094 69.3736C48.5585 69.4661 48.5308 69.5168 48.5265 69.5259C48.5046 69.571 48.482 69.6157 48.4588 69.66L48.4547 69.6708C48.3897 69.8073 48.3322 69.9233 48.2822 70.0189C48.2355 70.1113 48.1433 70.299 48.0058 70.5818C47.9333 70.7308 47.8767 70.8467 47.8361 70.9296C47.6588 71.2978 47.5309 71.5684 47.4524 71.7412C47.3585 71.9492 47.2134 72.2784 47.0172 72.7288C46.9875 72.7976 46.9436 72.8962 46.8857 73.0244C46.8378 73.1302 46.8106 73.1914 46.8041 73.2079C46.7849 73.2566 46.7649 73.305 46.7441 73.353C46.7433 73.3551 46.7425 73.3573 46.7417 73.3594L46.75 73.3409C46.7166 73.4274 46.6876 73.5004 46.6631 73.5599C46.5646 73.7947 46.4228 74.1529 46.2376 74.6347C46.1998 74.7329 46.1713 74.807 46.152 74.8571C46.1361 74.8984 46.1135 74.9566 46.0843 75.0318C45.9971 75.2565 45.9358 75.4173 45.9005 75.5143C45.7283 75.9826 45.5384 76.5369 45.3309 77.1772C45.3081 77.2459 45.2843 77.3155 45.2595 77.386C45.2346 77.4698 45.2075 77.5532 45.178 77.636C45.1726 77.6528 45.1672 77.6694 45.1617 77.6859C45.0586 78.0149 44.9117 78.5129 44.7212 79.1799L44.7065 79.2334C44.6722 79.3569 44.6508 79.4367 44.6421 79.4728C44.6323 79.5129 44.6222 79.553 44.6115 79.5928C44.4631 80.1463 44.3425 80.6288 44.2497 81.0401C44.2363 81.1019 44.2212 81.1671 44.2043 81.2356C44.2015 81.2478 44.1987 81.2602 44.1958 81.2724C44.1057 81.6601 44.0145 82.0896 43.9222 82.5611C43.9219 82.5631 43.9215 82.5651 43.9212 82.5671L43.9253 82.5485C43.9091 82.6488 43.8943 82.7348 43.8809 82.8064C43.8451 82.9907 43.7966 83.2719 43.7355 83.6497C43.7153 83.7743 43.6999 83.8688 43.6893 83.9332C43.6284 84.2926 43.5824 84.5751 43.5513 84.7805C43.5298 84.9296 43.4969 85.1967 43.4525 85.5819C43.4353 85.7314 43.4221 85.8449 43.4129 85.9225C43.4057 85.9831 43.3956 86.0649 43.3828 86.168C43.3563 86.3799 43.3402 86.5204 43.3347 86.5896C43.2957 87.0031 43.2621 87.4507 43.2337 87.9323C43.2261 88.0425 43.2174 88.1588 43.2075 88.2812C43.1952 88.435 43.1878 88.5377 43.1854 88.5891C43.1625 89.3034 43.1511 89.9389 43.1511 90.4954V112.984C43.1511 119.71 44.7969 125.37 48.0885 129.964C48.2105 130.135 48.3347 130.304 48.4612 130.471C48.7612 130.87 49.1067 131.296 49.4976 131.749C50.0389 132.365 50.5851 132.925 51.1362 133.429C51.1394 133.432 51.1427 133.435 51.146 133.438C51.159 133.45 51.1727 133.462 51.1869 133.475C52.1229 134.329 53.1204 135.091 54.1794 135.76C54.6482 136.057 55.1293 136.336 55.6229 136.597C55.6387 136.605 55.6545 136.613 55.6701 136.622L55.7005 136.637C55.7175 136.646 55.7346 136.655 55.7515 136.664L85.109 152.14ZM93.1353 128.236C93.4493 127.981 93.6922 127.78 93.8641 127.635L94.0621 127.471L94.0756 127.459L94.1552 127.388L94.3292 127.235C94.7991 126.83 95.2489 126.428 95.6787 126.029L95.8253 125.887L96.0277 125.694L96.1784 125.548C96.5995 125.146 96.9459 124.807 97.2176 124.531C97.2581 124.489 97.3285 124.417 97.4289 124.315C97.6004 124.141 97.7231 124.014 97.7971 123.936C98.1301 123.583 98.3794 123.315 98.5452 123.132C98.8197 122.829 99.0227 122.603 99.1543 122.453C99.428 122.145 99.6664 121.87 99.8696 121.627C99.8932 121.599 99.9173 121.571 99.9416 121.543L99.961 121.521C100.189 121.254 100.352 121.059 100.451 120.936C100.54 120.827 100.676 120.657 100.86 120.424C100.962 120.296 101.039 120.198 101.092 120.131C101.332 119.828 101.519 119.588 101.653 119.41C101.842 119.162 102.036 118.901 102.235 118.626L102.797 117.846L102.819 117.815L103.309 117.099L103.311 117.096C103.344 117.047 103.406 116.954 103.499 116.816C103.668 116.564 103.788 116.384 103.858 116.274C103.965 116.111 104.109 115.885 104.29 115.597C104.328 115.536 104.357 115.49 104.378 115.456C104.573 115.153 104.739 114.885 104.877 114.652C104.898 114.616 104.92 114.58 104.942 114.545C105.011 114.435 105.127 114.238 105.289 113.956C105.325 113.894 105.353 113.846 105.371 113.813C105.591 113.43 105.753 113.146 105.856 112.96L106.027 112.645L106.306 112.122C106.44 111.873 106.587 111.591 106.746 111.278C106.819 111.134 106.935 110.898 107.092 110.573C107.137 110.478 107.172 110.405 107.196 110.356C107.213 110.32 107.251 110.241 107.309 110.118C107.427 109.87 107.51 109.694 107.557 109.589C107.708 109.262 107.852 108.94 107.988 108.622L108.004 108.58C108.048 108.477 108.098 108.361 108.153 108.233C108.24 108.031 108.301 107.889 108.334 107.807C108.436 107.558 108.583 107.187 108.773 106.695C108.806 106.611 108.831 106.547 108.849 106.501L108.93 106.284C108.956 106.217 108.98 106.157 109 106.106C109.044 105.996 109.071 105.926 109.082 105.896C109.28 105.353 109.469 104.803 109.649 104.247L109.805 103.768C109.931 103.364 110.073 102.88 110.231 102.318L110.353 101.873C110.486 101.389 110.605 100.913 110.713 100.445L110.766 100.224C110.856 99.8165 110.954 99.3298 111.062 98.7642C111.104 98.5444 111.164 98.2039 111.239 97.7427L111.24 97.7413L111.286 97.4467C111.291 97.4136 111.297 97.3803 111.302 97.3468C111.335 97.1476 111.356 97.0084 111.367 96.9292C111.395 96.7383 111.429 96.4795 111.468 96.1528C111.482 96.0307 111.493 95.9379 111.501 95.8744L111.551 95.4529C111.576 95.2556 111.592 95.114 111.6 95.0279C111.626 94.7717 111.656 94.3788 111.689 93.8493L111.691 93.8218L111.715 93.4636C111.719 93.4193 111.721 93.3886 111.722 93.3716C111.731 93.2627 111.736 93.1977 111.737 93.1766C111.768 92.5227 111.784 91.8907 111.784 91.2807V79.3334C111.683 79.4164 111.58 79.5026 111.473 79.592C111.434 79.6239 111.396 79.6552 111.357 79.6859L111.24 79.7802C111.239 79.7812 111.238 79.7822 111.237 79.7833L111.249 79.7743C111.126 79.8862 111.041 79.9618 110.993 80.0012C110.538 80.3944 110.077 80.8076 109.611 81.2411C109.514 81.3295 109.345 81.4906 109.104 81.7244C108.688 82.1222 108.331 82.4721 108.034 82.7742C107.843 82.9645 107.658 83.1541 107.479 83.3429C107.121 83.7221 106.86 84.0021 106.696 84.1831C106.414 84.4937 106.204 84.7277 106.065 84.8851C105.951 85.0125 105.772 85.2195 105.528 85.5059C105.432 85.6192 105.366 85.6963 105.331 85.7372C105.056 86.0624 104.873 86.2807 104.78 86.3921L104.435 86.827L104.094 87.2552C103.841 87.5734 103.643 87.8273 103.498 88.0169C103.372 88.1822 103.169 88.4556 102.89 88.8374C102.689 89.1089 102.493 89.3801 102.302 89.651C102.166 89.8402 101.994 90.0899 101.787 90.4002C101.534 90.7732 101.359 91.034 101.262 91.1826C101.225 91.2418 101.17 91.3279 101.098 91.4409C100.933 91.6994 100.805 91.9027 100.713 92.0507C100.474 92.4308 100.313 92.6903 100.229 92.8291L99.9616 93.2888L99.698 93.7424C99.551 93.995 99.3887 94.2817 99.2111 94.6025C99.0755 94.8467 98.9312 95.1137 98.7783 95.4034C98.7492 95.4597 98.7058 95.5433 98.6481 95.6541C98.497 95.9446 98.3829 96.1669 98.3057 96.321C98.1488 96.6297 97.9937 96.9454 97.8402 97.268L97.8392 97.2703C97.658 97.6465 97.5293 97.9186 97.453 98.0866C97.3556 98.3021 97.2097 98.633 97.0154 99.0794C96.9949 99.1266 96.9646 99.1963 96.9244 99.2882C96.8019 99.5691 96.7118 99.7803 96.654 99.9218C96.5019 100.289 96.3327 100.718 96.1463 101.211C96.1315 101.25 96.1094 101.306 96.0801 101.382C95.9928 101.607 95.9293 101.774 95.8897 101.882C95.7393 102.291 95.5393 102.876 95.2896 103.637C95.2779 103.671 95.262 103.715 95.242 103.771L95.2393 103.772C95.2279 103.809 95.2161 103.847 95.204 103.884C95.1874 103.939 95.1706 103.991 95.1534 104.043C95.0129 104.485 94.8672 104.979 94.7164 105.526C94.7107 105.546 94.698 105.593 94.6784 105.668C94.6411 105.81 94.6173 105.898 94.607 105.932C94.4938 106.355 94.3708 106.848 94.2382 107.411C94.2266 107.464 94.2138 107.518 94.1998 107.575L94.1965 107.589C94.082 108.092 93.9774 108.598 93.8825 109.107C93.8433 109.324 93.7855 109.662 93.7091 110.122C93.6976 110.191 93.6881 110.247 93.6806 110.293C93.6225 110.634 93.5794 110.898 93.5513 111.084C93.5269 111.253 93.4925 111.53 93.4482 111.915C93.4309 112.065 93.421 112.149 93.4184 112.166C93.4056 112.294 93.3859 112.469 93.3592 112.691C93.3403 112.848 93.3287 112.949 93.3243 112.992C93.3052 113.194 93.2806 113.518 93.2505 113.962C93.2397 114.12 93.2313 114.243 93.2252 114.328C93.2203 114.397 93.213 114.492 93.2032 114.615C93.1908 114.769 93.1834 114.871 93.181 114.923C93.1505 115.562 93.1353 116.203 93.1353 116.846V128.236Z" fill="#0F0D0C"/>
+<path d="M41.7824 61.323L41.786 61.318C41.7619 61.3555 41.7383 61.3935 41.7152 61.4316C41.489 61.8063 41.2987 62.1332 41.1445 62.4123C40.9619 62.726 40.7672 63.0697 40.5605 63.4432C40.463 63.6187 40.3258 63.872 40.1489 64.2029C40.0935 64.3066 40.0477 64.3922 40.0115 64.4596C39.9996 64.4822 39.9744 64.5283 39.9362 64.5977C39.8207 64.8074 39.7258 64.9869 39.6516 65.1362C39.6106 65.2167 39.5653 65.3091 39.5155 65.4136L39.4835 65.4786C39.392 65.6588 39.2648 65.9163 39.1019 66.2511C39.03 66.3991 38.9706 66.5208 38.9238 66.6163C38.7105 67.0593 38.5471 67.4055 38.4338 67.6548C38.3184 67.9104 38.152 68.2878 37.9347 68.7869C37.9232 68.8133 37.8998 68.8657 37.8644 68.944C37.7661 69.1613 37.6858 69.3466 37.6236 69.5C37.5905 69.5789 37.5549 69.6676 37.5168 69.7661L37.5208 69.7585C37.3921 70.0651 37.2171 70.5062 36.9959 71.0817C36.9593 71.177 36.9324 71.247 36.9151 71.2917C36.9019 71.3258 36.8818 71.3777 36.8547 71.4475C36.7417 71.7385 36.6575 71.9603 36.6021 72.1127C36.3895 72.6905 36.1639 73.3479 35.9251 74.085L35.9134 74.1174C35.8643 74.2549 35.8241 74.3734 35.7926 74.473C35.7857 74.495 35.7789 74.517 35.7723 74.539C35.7647 74.5627 35.7573 74.5867 35.7499 74.6109C35.7453 74.6249 35.7408 74.639 35.7364 74.653C35.6047 75.0694 35.4221 75.6865 35.1886 76.5042C35.1839 76.5212 35.1764 76.5481 35.1663 76.5847C35.1121 76.78 35.0683 76.9444 35.0349 77.078C34.8544 77.7535 34.704 78.3592 34.5837 78.895C34.5689 78.9553 34.5554 79.0129 34.5433 79.0679C34.4286 79.5636 34.3125 80.1121 34.1951 80.7134C34.1817 80.7851 34.1669 80.871 34.1507 80.9713L34.1545 80.9542C34.1542 80.9559 34.1539 80.9576 34.1537 80.9593C34.1025 81.2235 34.0386 81.5927 33.9618 82.0668C33.9429 82.1836 33.9303 82.2616 33.9239 82.3007C33.8556 82.7028 33.7999 83.0465 33.7569 83.3318C33.7187 83.5958 33.672 83.9681 33.6166 84.4487C33.6006 84.5877 33.589 84.6881 33.5817 84.7498C33.5769 84.7892 33.5691 84.8524 33.5583 84.9392C33.5136 85.2969 33.4848 85.5587 33.4719 85.7247C33.4259 86.2074 33.3866 86.7286 33.3539 87.2882C33.3511 87.3283 33.3459 87.3951 33.3384 87.4888C33.3174 87.7494 33.3022 87.9838 33.2927 88.1921C33.2644 89.0633 33.2502 89.8308 33.2502 90.4946V112.983C33.2502 122.172 35.6857 129.988 40.5567 136.432C40.6464 136.551 40.7387 136.672 40.8338 136.795C41.1892 137.252 41.5797 137.727 42.0051 138.22C42.0067 138.222 42.0082 138.224 42.0097 138.226C42.0171 138.235 42.0244 138.243 42.0317 138.252C42.8113 139.14 43.6029 139.953 44.4064 140.69C44.4214 140.704 44.4362 140.717 44.4507 140.73C44.4546 140.734 44.4584 140.737 44.4623 140.741C44.4635 140.742 44.4647 140.743 44.4659 140.744C46.3274 142.453 48.367 143.914 50.5849 145.128C50.8889 145.336 51.215 145.509 51.5574 145.645L101.009 171.715L101.012 171.716C101.13 171.778 101.249 171.835 101.369 171.886C101.386 171.895 101.407 171.906 101.431 171.918C101.501 171.955 101.571 171.99 101.64 172.025C101.715 172.063 101.798 172.103 101.891 172.145L101.906 172.152L101.986 172.19C102.39 172.384 102.756 172.551 103.084 172.692L103.255 172.766C103.261 172.768 103.29 172.781 103.342 172.804C103.469 172.861 103.58 172.909 103.675 172.948C104.002 173.083 104.405 173.241 104.884 173.42L105.004 173.466C105.154 173.53 105.307 173.586 105.463 173.634C106.029 173.831 106.608 174.013 107.2 174.181L107.201 174.181C107.358 174.226 107.5 174.263 107.629 174.294L107.656 174.301C108.15 174.435 108.61 174.549 109.037 174.644L109.158 174.672L109.224 174.687L109.27 174.698C109.429 174.736 109.63 174.777 109.871 174.821L109.901 174.827L110.403 174.921C110.875 175.005 111.339 175.081 111.796 175.149C111.839 175.155 111.882 175.162 111.925 175.166L112.124 175.19C112.527 175.243 112.948 175.29 113.388 175.332L114.088 175.394C114.15 175.399 114.212 175.404 114.273 175.407L114.654 175.426L114.824 175.432L114.852 175.434C115.132 175.452 115.335 175.462 115.461 175.466C115.623 175.473 115.843 175.479 116.122 175.483C116.224 175.484 116.298 175.485 116.344 175.486C116.381 175.487 116.418 175.487 116.455 175.487H117.121C117.398 175.487 117.737 175.478 118.137 175.459H118.198C118.347 175.459 118.497 175.452 118.645 175.439L118.608 175.443C118.717 175.438 118.815 175.433 118.903 175.426C119.175 175.411 119.546 175.384 120.015 175.345L120.066 175.341L120.18 175.33C120.362 175.317 120.526 175.302 120.674 175.285L121.331 175.209L121.727 175.159C121.986 175.129 122.178 175.104 122.304 175.085C122.483 175.059 122.729 175.02 123.044 174.967C123.084 174.961 123.106 174.957 123.11 174.956L123.619 174.874C123.625 174.872 123.646 174.869 123.681 174.864C123.855 174.836 124.007 174.809 124.139 174.782C124.363 174.738 124.663 174.676 125.039 174.596L125.437 174.515L125.833 174.432C126.392 174.306 126.996 174.153 127.646 173.973L131.151 173.012C131.9 172.805 132.571 172.603 133.165 172.407C133.366 172.342 133.549 172.28 133.715 172.219L133.879 172.161L133.881 172.16C134.453 171.961 134.872 171.814 135.137 171.716C135.294 171.661 135.49 171.584 135.725 171.488C135.78 171.466 135.835 171.443 135.892 171.42L136.002 171.374L136.137 171.32C136.623 171.127 136.994 170.973 137.252 170.86L138.025 170.524C138.46 170.326 138.849 170.145 139.192 169.982L139.342 169.911L139.961 169.61C140.355 169.414 140.759 169.203 141.174 168.979L141.426 168.846C141.443 168.837 141.479 168.819 141.532 168.79C141.686 168.709 141.789 168.654 141.84 168.625C142.154 168.454 142.593 168.202 143.159 167.867C143.237 167.821 143.276 167.798 143.279 167.796L143.449 167.699L143.479 167.682L152.021 171.573C156.866 173.781 161.529 173.445 166.008 170.563C170.488 167.682 172.728 163.577 172.728 158.251V118.111C172.743 117.954 172.75 117.795 172.75 117.637V95.1484C172.75 87.925 171.221 81.491 168.163 75.8464C165.083 70.1612 160.753 65.8115 155.173 62.7973C155.084 62.7426 154.992 62.6907 154.9 62.6418L154.881 62.632L104.937 36.3023C104.784 36.2211 104.575 36.1139 104.308 35.9805C104.223 35.938 104.122 35.8899 104.003 35.8361L103.963 35.8169C103.61 35.6469 103.261 35.4856 102.918 35.3328C102.808 35.2839 102.655 35.2169 102.459 35.1317C102.417 35.1139 102.368 35.0928 102.311 35.0684C101.931 34.9089 101.508 34.7451 101.044 34.5769C100.881 34.5109 100.733 34.4556 100.6 34.4109C100.574 34.4019 100.548 34.3932 100.522 34.3846C99.9241 34.1774 99.3732 34.0019 98.8692 33.8581C98.865 33.8569 98.8608 33.8557 98.8566 33.8545C98.8045 33.8387 98.7485 33.8224 98.6886 33.8058C98.6743 33.8018 98.6594 33.7976 98.6438 33.7934C98.5513 33.7682 98.4501 33.742 98.3401 33.7149L98.3072 33.7071L98.3119 33.7085C98.1067 33.6529 97.9063 33.6006 97.7107 33.5517C97.4749 33.4924 97.2476 33.4387 97.0288 33.3903C97.0046 33.385 96.9806 33.3797 96.9566 33.3744C96.8375 33.3418 96.7395 33.3173 96.6627 33.301C96.5177 33.2683 96.3333 33.2314 96.1093 33.1905C96.0713 33.1835 96.0408 33.1779 96.0179 33.1737C95.9548 33.1606 95.8842 33.1466 95.8062 33.1318L95.8031 33.1321C95.7386 33.1178 95.6739 33.1047 95.6089 33.093C95.085 32.9984 94.6093 32.9223 94.1819 32.8646C94.0983 32.8527 94.0015 32.8408 93.8913 32.829L93.8896 32.8288L93.8761 32.8271C93.4523 32.7724 93.0373 32.7257 92.6313 32.6871L92.3254 32.6598C92.0953 32.6356 91.9206 32.6204 91.8012 32.6144C91.7158 32.6089 91.6011 32.6026 91.4568 32.5957C91.3656 32.5912 91.2891 32.5871 91.2273 32.5832C90.9082 32.5655 90.6803 32.5549 90.5436 32.5514C90.3757 32.5444 90.1448 32.5389 89.851 32.5349C89.7388 32.5334 89.6342 32.5318 89.537 32.5302L89.3523 32.529C89.1472 32.5271 88.9748 32.5275 88.835 32.5303C88.6706 32.5314 88.4606 32.5364 88.205 32.5453C88.0717 32.5499 87.9598 32.5532 87.8692 32.5551L87.8533 32.5556C87.5561 32.5646 87.3378 32.5734 87.1982 32.582C86.9091 32.5967 86.533 32.6238 86.07 32.6632L85.7453 32.6873C85.6353 32.6913 85.5254 32.6991 85.4158 32.7105C85.2559 32.7271 85.0348 32.7538 84.7525 32.7903C84.6345 32.8056 84.5516 32.8162 84.504 32.822L84.1737 32.8619L83.8432 32.9018C83.8033 32.9066 83.7635 32.9119 83.7238 32.9177C83.5459 32.9435 83.2985 32.9834 82.9815 33.0372C82.852 33.0591 82.7524 33.0758 82.6826 33.0873C82.6517 33.0924 82.5981 33.101 82.5216 33.1131C82.2808 33.151 82.0871 33.1842 81.9406 33.2127C81.5282 33.2925 81.1612 33.3685 80.8395 33.4407C80.5868 33.4913 80.378 33.5359 80.2131 33.5744C79.6373 33.7044 79.0348 33.8574 78.4057 34.0333L74.8975 34.9948C74.1846 35.1929 73.5201 35.3928 72.904 35.5945C72.7593 35.64 72.574 35.7031 72.3482 35.7837C72.2719 35.8109 72.2132 35.8316 72.1722 35.8457C71.5991 36.0447 71.1527 36.2027 70.833 36.3199C70.6998 36.3699 70.5114 36.4427 70.2678 36.5384C70.1844 36.5712 70.1097 36.6005 70.0435 36.6265C69.5097 36.84 69.0934 37.0111 68.7948 37.1398L68.4373 37.2954L68.0218 37.477C67.5857 37.6746 67.1979 37.8542 66.8586 38.0158C66.5247 38.1744 66.2669 38.2991 66.0852 38.39C65.6911 38.5871 65.2867 38.7973 64.872 39.0207L64.8387 39.0383L64.2065 39.3754C63.8928 39.5462 63.453 39.7986 62.8873 40.1328C62.8182 40.1736 62.7838 40.1941 62.7839 40.1944C62.5743 40.3142 62.4222 40.4035 62.3278 40.4623C61.8541 40.7475 61.2865 41.1057 60.6251 41.5367C60.5792 41.5661 60.5329 41.5967 60.4862 41.6287C60.3942 41.6892 60.2852 41.7638 60.1593 41.8524L60.1145 41.8841L60.1163 41.883C59.5704 42.2518 59.1025 42.577 58.7128 42.8586C58.5143 43.0042 58.3729 43.1065 58.2888 43.1654C58.2479 43.1939 58.2075 43.2232 58.1675 43.253C57.6655 43.6275 57.2979 43.9051 57.0648 44.0858C56.9507 44.1724 56.7923 44.2954 56.5898 44.4548C56.5529 44.4839 56.5166 44.5125 56.4808 44.5407C55.9911 44.9311 55.5288 45.3081 55.0939 45.6717L55.0774 45.6851L55.0503 45.7065C55.0236 45.7269 54.997 45.7476 54.9705 45.7688C54.904 45.8206 54.8391 45.8741 54.7754 45.9292C54.7025 45.9924 54.617 46.0697 54.5189 46.161L54.5295 46.1528C54.5287 46.1536 54.5279 46.1543 54.5271 46.155C53.9052 46.6923 53.3761 47.1664 52.9399 47.5775C52.8271 47.6806 52.6771 47.8224 52.49 48.0029C52.4007 48.0891 52.3283 48.1583 52.2729 48.2107C51.9017 48.5656 51.4915 48.9675 51.0424 49.4165C51.0247 49.4343 50.99 49.4683 50.9383 49.5185C50.8533 49.6012 50.7855 49.6679 50.7349 49.7185C50.6395 49.8139 50.5274 49.9324 50.3985 50.0741L50.3874 50.0888C50.3534 50.1227 50.3199 50.1572 50.2869 50.1921C49.8853 50.6178 49.5804 50.9454 49.3723 51.1748L48.6764 51.9423C48.544 52.0909 48.3585 52.3041 48.1197 52.582C47.9852 52.7384 47.8766 52.8642 47.7938 52.9593C47.771 52.9858 47.7338 53.0289 47.6821 53.0885C47.53 53.264 47.4115 53.4034 47.3267 53.5067C47.2851 53.5571 47.2305 53.6246 47.1628 53.7094C47.1242 53.7575 47.0969 53.7914 47.0808 53.811C46.7902 54.1653 46.5387 54.4816 46.3262 54.7597L45.9946 55.1837L45.6377 55.6403C45.4678 55.8625 45.2257 56.1886 44.9115 56.6186C44.8877 56.6514 44.8446 56.7095 44.7821 56.7929C44.6445 56.9765 44.5458 57.1108 44.4861 57.1958C44.4252 57.2801 44.3548 57.3822 44.2749 57.5021L44.2753 57.5034C44.2537 57.5333 44.2325 57.5634 44.2115 57.5939L43.9154 58.0238L43.601 58.4804C43.3076 58.9123 43.0841 59.2469 42.9304 59.484C42.7188 59.811 42.5227 60.1209 42.342 60.4136C42.159 60.697 42.0161 60.9245 41.9132 61.0959C41.8771 61.1561 41.8335 61.2318 41.7824 61.323ZM41.7824 61.323C41.7846 61.3193 41.7867 61.3156 41.7888 61.3118L41.7824 61.323ZM104.568 72.4679L104.555 72.4797C103.975 72.9804 103.423 73.4747 102.898 73.9627C102.75 74.0982 102.529 74.3084 102.236 74.5932C101.766 75.0422 101.356 75.4442 101.006 75.7993C100.774 76.0318 100.534 76.2773 100.289 76.536C99.8791 76.9701 99.5705 77.3015 99.3629 77.5304C99.0523 77.8728 98.8175 78.1339 98.6587 78.3137C98.506 78.4851 98.2842 78.7413 97.9935 79.0823C97.9023 79.1892 97.8343 79.2689 97.7895 79.3212L97.7656 79.3492C97.4631 79.7075 97.2347 79.9804 97.0805 80.168L96.69 80.6582L96.3452 81.0921C96.0476 81.4661 95.8073 81.7734 95.6245 82.014C95.4605 82.2284 95.2236 82.5476 94.9138 82.9715C94.6806 83.2865 94.4559 83.5971 94.2398 83.9033C94.0521 84.1637 93.8298 84.4867 93.5727 84.8722C93.2952 85.2806 93.0803 85.6022 92.9281 85.8371C92.878 85.9158 92.8189 86.0084 92.7509 86.1149C92.5571 86.4188 92.4094 86.6532 92.3079 86.8181C92.0487 87.2295 91.8473 87.5548 91.7037 87.7941L91.4063 88.3047L91.1389 88.7647C90.9573 89.0771 90.7617 89.4223 90.5524 89.8004C90.3841 90.1034 90.201 90.4424 90.0032 90.8175C89.9656 90.89 89.9194 90.9789 89.8645 91.0844C89.689 91.4218 89.5557 91.6816 89.4646 91.8639C89.2811 92.2247 89.099 92.5951 88.9182 92.9749C88.9169 92.9777 88.9155 92.9806 88.9141 92.9835C88.7034 93.4213 88.5435 93.7602 88.4344 94.0001C88.3155 94.2636 88.1491 94.6407 87.9353 95.1316C87.9153 95.1776 87.8867 95.2432 87.8495 95.3284C87.6946 95.6837 87.5769 95.96 87.4965 96.1574C87.3121 96.6018 87.1126 97.1079 86.8979 97.6759C86.8935 97.6871 86.8777 97.7276 86.8505 97.7977C86.7374 98.0889 86.651 98.3166 86.5913 98.4808C86.4078 98.9796 86.1871 99.6224 85.9293 100.409C85.9288 100.41 85.9267 100.416 85.9233 100.425C85.8714 100.57 85.8274 100.699 85.7911 100.812C85.7756 100.859 85.7604 100.907 85.7454 100.956C85.7425 100.965 85.7394 100.975 85.7364 100.984C85.5509 101.565 85.3667 102.187 85.1837 102.851C85.1675 102.907 85.1407 103.006 85.1034 103.148C85.0838 103.223 85.0711 103.27 85.0654 103.29C84.9083 103.874 84.7498 104.507 84.59 105.188C84.5864 105.203 84.5829 105.219 84.5794 105.234C84.5632 105.3 84.5486 105.362 84.5356 105.422C84.3948 106.043 84.2642 106.675 84.144 107.32C84.0935 107.6 84.0263 107.992 83.9424 108.496C83.931 108.565 83.9225 108.616 83.917 108.649C83.8504 109.041 83.797 109.37 83.757 109.636C83.7158 109.919 83.6676 110.301 83.6122 110.782C83.5963 110.921 83.5843 111.024 83.5763 111.091C83.5635 111.213 83.5477 111.353 83.5288 111.511C83.5022 111.733 83.4825 111.908 83.4697 112.035C83.4408 112.342 83.4083 112.76 83.3724 113.29C83.3621 113.44 83.3544 113.552 83.3493 113.626C83.3466 113.663 83.3415 113.729 83.334 113.822C83.313 114.083 83.2988 114.292 83.2913 114.451C83.2534 115.247 83.2344 116.045 83.2344 116.845V137.426C83.2344 137.458 83.2347 137.489 83.2353 137.521V139.337C83.2373 143.919 83.8619 148.186 85.109 152.14L55.7515 136.664C55.7346 136.655 55.7175 136.646 55.7005 136.637L55.6701 136.622C55.6545 136.613 55.6387 136.605 55.6229 136.597C55.1293 136.336 54.6482 136.057 54.1794 135.76C53.1204 135.091 52.1229 134.329 51.1869 133.475C51.1727 133.462 51.159 133.45 51.146 133.438C51.1427 133.435 51.1394 133.432 51.1362 133.429C50.5851 132.925 50.0389 132.365 49.4976 131.749C49.1067 131.296 48.7612 130.87 48.4612 130.471C48.3347 130.304 48.2105 130.135 48.0885 129.964C44.7969 125.37 43.1511 119.71 43.1511 112.984V90.4954C43.1511 89.9389 43.1625 89.3034 43.1854 88.5891C43.1878 88.5377 43.1952 88.435 43.2075 88.2812C43.2174 88.1588 43.2261 88.0425 43.2337 87.9323C43.2621 87.4507 43.2957 87.0031 43.3347 86.5896C43.3402 86.5204 43.3563 86.3799 43.3828 86.168C43.3956 86.0649 43.4057 85.9831 43.4129 85.9225C43.4221 85.8449 43.4353 85.7314 43.4525 85.5819C43.4969 85.1967 43.5298 84.9296 43.5513 84.7805C43.5824 84.5751 43.6284 84.2926 43.6893 83.9332C43.6999 83.8688 43.7153 83.7743 43.7355 83.6497C43.7966 83.2719 43.8451 82.9907 43.8809 82.8064C43.8943 82.7348 43.9091 82.6488 43.9253 82.5485L43.9212 82.5671C43.9215 82.5651 43.9219 82.5631 43.9222 82.5611C44.0145 82.0896 44.1057 81.6601 44.1958 81.2724C44.1987 81.2602 44.2015 81.2478 44.2043 81.2356C44.2212 81.1671 44.2363 81.1019 44.2497 81.0401C44.3425 80.6288 44.4631 80.1463 44.6115 79.5928C44.6222 79.553 44.6323 79.5129 44.6421 79.4728C44.6508 79.4367 44.6722 79.3569 44.7065 79.2334L44.7212 79.1799C44.9117 78.5129 45.0586 78.0149 45.1617 77.6859C45.1672 77.6694 45.1726 77.6528 45.178 77.636C45.2075 77.5532 45.2346 77.4698 45.2595 77.386C45.2843 77.3155 45.3081 77.2459 45.3309 77.1772C45.5384 76.5369 45.7283 75.9826 45.9005 75.5143C45.9358 75.4173 45.9971 75.2564 46.0843 75.0318C46.1135 74.9566 46.1361 74.8984 46.152 74.8571C46.1713 74.807 46.1998 74.7329 46.2376 74.6347C46.4228 74.1529 46.5646 73.7947 46.6631 73.5599C46.6876 73.5004 46.7166 73.4274 46.75 73.3409L46.7417 73.3594C46.7425 73.3573 46.7433 73.3551 46.7441 73.353C46.7649 73.305 46.7849 73.2566 46.8041 73.2079C46.8106 73.1914 46.8378 73.1302 46.8857 73.0244C46.9436 72.8962 46.9875 72.7976 47.0172 72.7288C47.2134 72.2784 47.3585 71.9492 47.4524 71.7412C47.5309 71.5684 47.6588 71.2978 47.8361 70.9296C47.8767 70.8467 47.9333 70.7308 48.0058 70.5818C48.1433 70.2989 48.2355 70.1113 48.2822 70.0189C48.3322 69.9233 48.3897 69.8073 48.4547 69.6708L48.4588 69.66C48.482 69.6157 48.5046 69.571 48.5265 69.5259C48.5308 69.5168 48.5585 69.4661 48.6094 69.3736C48.6738 69.2567 48.72 69.1716 48.7481 69.1184C48.7781 69.0627 48.8223 68.98 48.881 68.8703C49.0325 68.5866 49.1453 68.3783 49.2192 68.2454C49.3943 67.9291 49.5715 67.6161 49.751 67.3064C49.8731 67.0865 50.0113 66.8483 50.1657 66.5917C50.2323 66.4853 50.3045 66.3638 50.3824 66.227L50.4033 66.1903C50.4543 66.1054 50.5481 65.9573 50.6848 65.7459C50.7052 65.7146 50.7251 65.683 50.7447 65.6511C50.8943 65.4079 51.0597 65.1463 51.2409 64.8662C51.3545 64.691 51.532 64.4257 51.7733 64.0703L52.0696 63.6401L52.345 63.2403C52.3954 63.1689 52.4514 63.087 52.5131 62.9944L52.5439 62.9494C52.5706 62.9115 52.6248 62.8381 52.7064 62.7292C52.7968 62.6084 52.8654 62.5159 52.9122 62.4515C53.1797 62.0856 53.3654 61.8344 53.4693 61.6981L53.8013 61.2738L54.1578 60.8176C54.3244 60.5997 54.5152 60.3596 54.7303 60.0973C54.7719 60.047 54.8265 59.9794 54.8943 59.8946C54.9328 59.8464 54.9593 59.8136 54.9736 59.7962C55.0053 59.7575 55.0686 59.6836 55.1632 59.5745C55.227 59.5009 55.2667 59.4549 55.2825 59.4363C55.3624 59.3447 55.4778 59.2111 55.6287 59.0355C55.8292 58.8023 55.9662 58.6442 56.0398 58.5614L56.7055 57.8275C56.865 57.6517 57.1154 57.3829 57.4565 57.0211C57.536 56.9393 57.6255 56.8437 57.7249 56.7344L57.7362 56.7197C57.7539 56.7019 57.7886 56.6679 57.8403 56.6177C57.9253 56.535 57.9931 56.4684 58.0437 56.4178C58.4401 56.0213 58.7889 55.6792 59.0899 55.3914C59.1565 55.3286 59.248 55.241 59.3645 55.1286C59.488 55.0095 59.591 54.912 59.6734 54.8362C60.0428 54.4885 60.4881 54.0895 61.0095 53.6393C61.0704 53.5865 61.1402 53.5238 61.2187 53.4512C61.3346 53.3593 61.4226 53.2875 61.4827 53.2357C61.8299 52.9455 62.2109 52.635 62.6258 52.3042C62.6456 52.2887 62.6748 52.2656 62.7135 52.2352C62.8699 52.1121 62.9946 52.0152 63.0876 51.9444C63.2914 51.7866 63.607 51.5482 64.0344 51.2291C64.1686 51.1342 64.3368 51.0125 64.5392 50.864C64.8258 50.657 65.2073 50.3925 65.6836 50.0706C65.7282 50.0401 65.7862 49.9998 65.8575 49.9496L65.9139 49.9097C65.9533 49.8842 65.9931 49.8578 66.0332 49.8305C66.5958 49.4639 67.0806 49.1579 67.4876 48.9125C67.518 48.8937 67.6073 48.8417 67.7555 48.7567C67.7923 48.735 67.8482 48.702 67.9232 48.6577C68.3892 48.3824 68.7153 48.1941 68.9012 48.0927L69.4965 47.7756L69.5302 47.7576C69.8811 47.5686 70.2089 47.398 70.5135 47.2457C70.6356 47.1846 70.8335 47.0891 71.1072 46.9591L71.1115 46.957C71.3972 46.821 71.7073 46.677 72.0419 46.5249L72.3994 46.3693L72.7303 46.2251C72.9375 46.1359 73.2548 46.0058 73.6823 45.8346C73.7301 45.816 73.7991 45.7889 73.8894 45.7534C74.085 45.6766 74.2132 45.6267 74.2741 45.6037C74.5177 45.5145 74.8937 45.3817 75.4021 45.2051C75.4704 45.1817 75.5623 45.1493 75.6778 45.1081C75.7842 45.0701 75.8676 45.0416 75.928 45.0223C76.4388 44.8552 76.9734 44.6941 77.5317 44.539L81.0478 43.5754C81.5326 43.4398 81.993 43.3228 82.429 43.2242C82.5146 43.2042 82.6666 43.172 82.885 43.1276C83.1868 43.0605 83.5008 42.9954 83.827 42.9323C83.8599 42.9259 83.9382 42.913 84.0619 42.8935C84.1678 42.8768 84.246 42.8643 84.2967 42.8558C84.3759 42.8429 84.4899 42.8237 84.6388 42.7985C84.8419 42.764 84.9951 42.7388 85.0984 42.7231L85.3608 42.6915L85.6996 42.6505C85.7759 42.6412 85.8845 42.6274 86.0254 42.6091C86.1393 42.5944 86.2335 42.5825 86.3077 42.5735C86.3187 42.5728 86.3298 42.572 86.3409 42.5711L86.5715 42.554L86.8546 42.5328C87.2415 42.5 87.5399 42.4782 87.7499 42.4674C87.8209 42.4631 87.9529 42.458 88.1461 42.4522C88.248 42.4499 88.3825 42.4459 88.5495 42.4401C88.7268 42.434 88.8446 42.4309 88.903 42.4309C88.9501 42.4309 88.9973 42.4302 89.0444 42.4289C89.0705 42.4281 89.1424 42.4283 89.26 42.4294C89.3578 42.4304 89.4064 42.4305 89.4058 42.4298C89.4787 42.4313 89.5824 42.433 89.7169 42.4349C89.9183 42.4376 90.0797 42.4413 90.2011 42.446C90.292 42.4486 90.4366 42.4553 90.6349 42.4662C90.7203 42.4717 90.835 42.478 90.9793 42.4849C91.055 42.4886 91.1239 42.4922 91.1859 42.4959L91.289 42.5054L91.2927 42.5057L91.3599 42.5131L91.7147 42.5453C91.997 42.5722 92.2732 42.6029 92.5435 42.6375C92.6275 42.6495 92.725 42.6614 92.8358 42.6733C93.1212 42.7121 93.4377 42.7625 93.7854 42.8246C93.8405 42.8359 93.9009 42.8477 93.9667 42.8601L93.9698 42.8599C94.014 42.8697 94.0584 42.8789 94.1029 42.8876C94.1589 42.8984 94.2346 42.9125 94.33 42.93C94.3714 42.9375 94.4084 42.9445 94.4409 42.9508C94.5792 42.9882 94.6972 43.0166 94.795 43.036C95.0531 43.0905 95.3802 43.1715 95.7763 43.2788C95.8272 43.2921 95.8926 43.3086 95.9727 43.3283L96.059 43.3512C96.4567 43.4648 96.8799 43.5998 97.3286 43.7561C97.3407 43.7603 97.3527 43.7645 97.3649 43.7686C97.4776 43.814 97.5717 43.85 97.6473 43.8766C97.8311 43.9427 97.9965 44.0041 98.1433 44.061C98.2427 44.0998 98.3382 44.1381 98.4299 44.176C98.4306 44.1763 98.4314 44.1767 98.4322 44.177C98.455 44.1869 98.4876 44.201 98.53 44.2193C98.6867 44.2871 98.8044 44.3386 98.8832 44.3739C98.9939 44.4231 99.1007 44.4713 99.2036 44.5184C99.343 44.5824 99.4811 44.6472 99.6181 44.7129C99.6999 44.7535 99.7964 44.7991 99.9075 44.8496L99.9007 44.846C99.9027 44.8469 99.9047 44.8478 99.9066 44.8487C100.083 44.937 100.214 45.004 100.3 45.0496L129.063 60.213C128.835 60.2715 128.613 60.3306 128.396 60.3905L124.888 61.352C124.175 61.5501 123.466 61.7648 122.76 61.9962L122.468 62.0972L122.221 62.183C121.69 62.36 121.224 62.5247 120.824 62.6771C120.638 62.7468 120.385 62.8458 120.064 62.9741C119.559 63.1731 119.128 63.3494 118.772 63.5029L118.018 63.8342C117.669 63.9926 117.279 64.1741 116.849 64.3787C116.591 64.5012 116.336 64.6259 116.082 64.7529C115.634 64.9766 115.228 65.1868 114.863 65.3835C114.833 65.3993 114.784 65.425 114.715 65.4606C114.639 65.5005 114.569 65.5368 114.507 65.5696C114.467 65.5899 114.427 65.6108 114.387 65.6323C114.288 65.6854 114.195 65.7371 114.107 65.7874C113.817 65.9444 113.351 66.212 112.71 66.59C112.642 66.6306 112.544 66.6878 112.415 66.7614C112.372 66.7861 112.329 66.8116 112.286 66.8376C111.632 67.2385 111.047 67.6097 110.532 67.9513C110.413 68.0272 110.281 68.1154 110.137 68.2159C110.111 68.2342 110.094 68.2454 110.088 68.2498C109.606 68.5732 109.156 68.886 108.738 69.1881L108.196 69.5852C107.863 69.8283 107.478 70.1188 107.041 70.4566C106.802 70.6384 106.615 70.7826 106.48 70.8893C106.104 71.1853 105.67 71.5386 105.178 71.9492C105.043 72.0556 104.93 72.1485 104.837 72.2279C104.78 72.2755 104.69 72.3555 104.568 72.4679ZM104.568 72.4679C104.572 72.4646 104.575 72.4614 104.579 72.4582L104.568 72.4679ZM101.032 34.5728L101.03 34.5721C101.033 34.573 101.035 34.5739 101.038 34.5748C101.036 34.5741 101.034 34.5735 101.032 34.5728ZM104.903 162.561L105.666 162.963C105.717 162.991 105.807 163.037 105.935 163.102C105.972 163.121 106.002 163.136 106.025 163.148C106.092 163.178 106.131 163.197 106.145 163.205L106.281 163.269C106.554 163.401 106.811 163.519 107.052 163.622L107.063 163.627C107.148 163.663 107.253 163.708 107.38 163.765C107.425 163.785 107.449 163.796 107.452 163.797C107.68 163.891 107.998 164.015 108.408 164.169L108.458 164.189C108.519 164.211 108.58 164.234 108.641 164.257L108.655 164.263C109.054 164.403 109.476 164.536 109.919 164.661C109.914 164.66 109.885 164.654 109.835 164.643C109.904 164.659 109.973 164.675 110.041 164.693L110.249 164.747C110.596 164.84 110.948 164.927 111.306 165.008L111.379 165.025L111.451 165.041L111.564 165.067L111.672 165.086L111.703 165.092L112.139 165.174C112.496 165.238 112.847 165.295 113.191 165.347L113.391 165.372C113.685 165.41 113.977 165.443 114.269 165.47L114.88 165.525L115.066 165.535L115.442 165.551L115.47 165.553C115.644 165.565 115.787 165.572 115.899 165.576C115.964 165.579 116.087 165.581 116.267 165.584C116.363 165.585 116.443 165.586 116.506 165.587H117.121C117.26 165.587 117.474 165.58 117.764 165.566C117.848 165.561 117.932 165.559 118.015 165.559H118.037C118.081 165.557 118.126 165.555 118.174 165.552L118.156 165.555C118.215 165.55 118.274 165.546 118.334 165.542C118.501 165.534 118.779 165.514 119.169 165.481L119.325 165.467C119.376 165.462 119.427 165.458 119.479 165.455C119.506 165.453 119.53 165.451 119.549 165.449L120.088 165.388L120.592 165.324C120.728 165.308 120.832 165.295 120.904 165.284C121.005 165.27 121.174 165.243 121.411 165.203C121.454 165.196 121.491 165.19 121.522 165.185L121.924 165.119C121.976 165.11 122.042 165.1 122.123 165.087L122.114 165.091C122.152 165.082 122.191 165.074 122.23 165.067C122.398 165.035 122.677 164.977 123.068 164.895L123.398 164.828L123.653 164.775C124.058 164.683 124.517 164.567 125.03 164.425L128.507 163.472C129.101 163.307 129.652 163.141 130.162 162.973C130.219 162.955 130.253 162.943 130.266 162.939C130.308 162.922 130.35 162.907 130.393 162.892L130.632 162.808H130.634C131.154 162.628 131.551 162.487 131.825 162.387C131.834 162.383 131.882 162.364 131.971 162.328C132.052 162.295 132.097 162.276 132.106 162.273L132.326 162.182C132.367 162.166 132.414 162.147 132.467 162.126C132.853 161.972 133.13 161.858 133.299 161.784L133.938 161.506C134.318 161.334 134.65 161.181 134.935 161.045L135.024 161.003L135.533 160.756C135.838 160.604 136.178 160.426 136.553 160.224L136.711 160.141C136.766 160.112 136.839 160.073 136.929 160.025C136.993 159.992 137.052 159.961 137.107 159.93C137.318 159.814 137.658 159.619 138.125 159.343C138.192 159.304 138.261 159.263 138.332 159.221L138.46 159.147H138.461C138.544 159.098 138.619 159.055 138.687 159.017C139.131 158.749 139.551 158.484 139.947 158.224L140.305 157.979C141.736 157.002 143.572 156.845 145.148 157.563L156.125 162.564C157.693 163.279 159.202 163.17 160.652 162.237C162.103 161.304 162.828 159.976 162.828 158.251V117.614C162.828 117.456 162.835 117.298 162.85 117.14V95.1484C162.85 83.7403 158.651 75.8219 150.254 71.3934L149.959 71.2374C149.909 71.2132 149.855 71.1867 149.796 71.158C149.721 71.1217 149.663 71.0932 149.62 71.0724C149.384 70.9567 149.129 70.8386 148.853 70.718C148.676 70.6389 148.548 70.5828 148.468 70.5496C148.234 70.4515 147.944 70.3392 147.597 70.2126L147.415 70.1456L147.313 70.1067C146.939 69.9768 146.534 69.8488 146.096 69.7227L145.999 69.6973L145.777 69.6395C145.321 69.5221 144.979 69.4377 144.751 69.3863C144.724 69.3805 144.683 69.3717 144.629 69.3597C144.371 69.3034 144.185 69.2642 144.072 69.242C144.03 69.2339 143.989 69.2253 143.948 69.2162L143.83 69.1927C143.449 69.1241 143.093 69.0673 142.761 69.0223C142.792 69.0267 142.81 69.0291 142.814 69.0296C142.703 69.0177 142.628 69.0088 142.589 69.0029C142.287 68.9641 141.996 68.931 141.716 68.9037L141.71 68.9033L141.383 68.8734C141.233 68.8611 140.993 68.845 140.663 68.8252C140.435 68.8126 140.276 68.805 140.186 68.8025C140.128 68.8008 140.071 68.7982 140.014 68.7947C139.934 68.7897 139.76 68.7872 139.491 68.7872L138.982 68.7863C138.823 68.7894 138.572 68.7974 138.23 68.8105C138.13 68.8157 138.008 68.8205 137.866 68.8249C137.791 68.8271 137.731 68.8296 137.686 68.8322C137.515 68.8408 137.229 68.8619 136.827 68.8954L136.781 68.899C136.729 68.9029 136.661 68.9074 136.577 68.9127L136.442 68.9231C136.355 68.9316 136.204 68.9492 135.988 68.9761C135.849 68.9934 135.758 69.0044 135.717 69.0091C135.625 69.0209 135.503 69.035 135.352 69.0513C135.248 69.0625 135.179 69.0706 135.146 69.0756C135.049 69.09 134.884 69.1175 134.65 69.158C134.503 69.1832 134.384 69.2036 134.291 69.219C134.229 69.2289 134.145 69.2422 134.038 69.2587C133.907 69.2786 133.814 69.2938 133.759 69.3042C133.645 69.3251 133.444 69.3668 133.157 69.4293C133.028 69.4574 132.949 69.4744 132.92 69.4802C132.827 69.5013 132.7 69.5285 132.54 69.5617C132.451 69.5801 132.403 69.5901 132.396 69.5916C131.906 69.7035 131.445 69.8191 131.014 69.9384L127.538 70.8908C126.968 71.049 126.455 71.2026 125.998 71.3517L125.707 71.4525L125.352 71.575C124.951 71.7086 124.6 71.8325 124.3 71.9467C124.181 71.9913 123.979 72.0708 123.693 72.1852C123.284 72.3461 122.971 72.4736 122.752 72.5678L122.104 72.8516C121.973 72.9113 121.833 72.9757 121.684 73.0449V91.2807C121.684 92.0491 121.665 92.8184 121.628 93.5885C121.622 93.7365 121.609 93.9283 121.591 94.1637L121.59 94.1679L121.571 94.4471L121.57 94.4744C121.528 95.1281 121.491 95.6208 121.457 95.9524C121.439 96.1399 121.414 96.3666 121.381 96.6324L121.329 97.0655C121.322 97.1194 121.312 97.2021 121.299 97.3136C121.248 97.7482 121.207 98.0619 121.178 98.255C121.155 98.4224 121.12 98.6496 121.074 98.9367C121.068 98.9704 121.065 98.9883 121.065 98.9905L121.009 99.3453L121.009 99.3467C120.917 99.902 120.844 100.324 120.788 100.612C120.661 101.278 120.528 101.923 120.389 102.547L120.362 102.657C120.224 103.259 120.071 103.869 119.902 104.487L119.761 104.999C119.578 105.652 119.397 106.263 119.219 106.83L119.068 107.297C118.85 107.97 118.629 108.613 118.405 109.225C118.356 109.361 118.29 109.536 118.205 109.751L118.188 109.793L118.192 109.783L118.08 110.078C118.063 110.121 118.039 110.184 118.007 110.266C117.79 110.827 117.625 111.244 117.512 111.517C117.449 111.674 117.358 111.889 117.239 112.163C117.192 112.273 117.165 112.336 117.158 112.351L117.095 112.503C116.916 112.924 116.752 113.292 116.603 113.609C116.52 113.796 116.401 114.053 116.244 114.381C116.192 114.49 116.148 114.584 116.109 114.664C116.087 114.71 116.055 114.778 116.011 114.868C115.823 115.258 115.676 115.559 115.568 115.77C115.376 116.148 115.2 116.486 115.04 116.784L114.726 117.371L114.51 117.768C114.385 117.994 114.197 118.325 113.947 118.761C113.932 118.786 113.907 118.83 113.871 118.893C113.665 119.251 113.496 119.536 113.364 119.749C113.175 120.066 112.975 120.389 112.764 120.718C112.747 120.745 112.719 120.789 112.68 120.851C112.458 121.207 112.294 121.463 112.191 121.62C112.082 121.789 111.924 122.028 111.715 122.339C111.63 122.465 111.557 122.575 111.495 122.666L111.474 122.698L110.894 123.543L110.828 123.635L110.248 124.44C110.006 124.774 109.774 125.086 109.554 125.376C109.374 125.614 109.136 125.921 108.838 126.296C108.792 126.354 108.722 126.444 108.626 126.564C108.415 126.831 108.255 127.032 108.146 127.165C107.99 127.358 107.765 127.627 107.472 127.971L107.432 128.017L107.427 128.022C107.169 128.329 106.885 128.659 106.573 129.01C106.415 129.187 106.185 129.443 105.883 129.777C105.674 130.009 105.372 130.333 104.979 130.75C104.865 130.87 104.702 131.038 104.49 131.254C104.4 131.346 104.327 131.42 104.271 131.477C103.929 131.825 103.523 132.223 103.055 132.67L102.875 132.844L102.673 133.037L102.415 133.284C101.896 133.765 101.374 134.233 100.848 134.686L100.749 134.772L100.669 134.843L100.589 134.915C100.544 134.955 100.499 134.995 100.452 135.032L100.254 135.197C99.956 135.449 99.52 135.806 98.9463 136.268L98.9399 136.273C98.8505 136.346 98.7376 136.435 98.6012 136.539C98.551 136.577 98.5019 136.615 98.4539 136.652L98.3712 136.715C97.9722 137.023 97.5654 137.329 97.1506 137.632C97.1246 137.65 97.0729 137.688 96.9956 137.746C96.8643 137.844 96.7619 137.919 96.6886 137.971C96.2495 138.286 95.8236 138.581 95.4107 138.856L95.0917 139.078C95.0575 139.102 95.0231 139.126 94.9883 139.148C94.3982 139.537 93.7872 139.923 93.1553 140.305L93.1461 140.31C93.3774 150.816 97.2951 158.232 104.899 162.559C104.9 162.559 104.902 162.56 104.903 162.561ZM93.1353 128.236C93.4493 127.981 93.6922 127.78 93.8641 127.635L94.0621 127.471L94.0756 127.459L94.1552 127.388L94.3292 127.235C94.7991 126.83 95.2489 126.428 95.6787 126.029L95.8253 125.887L96.0277 125.694L96.1784 125.548C96.5995 125.146 96.9459 124.807 97.2176 124.531C97.2581 124.489 97.3285 124.417 97.429 124.315C97.6004 124.141 97.7231 124.014 97.7971 123.936C98.1301 123.583 98.3794 123.315 98.5452 123.132C98.8197 122.829 99.0227 122.603 99.1543 122.453C99.428 122.145 99.6664 121.87 99.8696 121.627C99.8932 121.599 99.9173 121.571 99.9416 121.543L99.961 121.521C100.189 121.254 100.352 121.059 100.451 120.936C100.54 120.827 100.676 120.657 100.86 120.424C100.962 120.296 101.039 120.198 101.092 120.131C101.332 119.828 101.519 119.588 101.653 119.41C101.842 119.162 102.036 118.901 102.235 118.626L102.797 117.846L102.819 117.815L103.309 117.099L103.311 117.096C103.344 117.047 103.406 116.954 103.499 116.816C103.668 116.564 103.788 116.384 103.858 116.274C103.965 116.111 104.109 115.885 104.29 115.597C104.328 115.536 104.357 115.49 104.378 115.456C104.573 115.153 104.739 114.885 104.877 114.652C104.898 114.616 104.92 114.58 104.942 114.545C105.011 114.435 105.127 114.238 105.289 113.956C105.325 113.894 105.353 113.846 105.371 113.813C105.591 113.43 105.753 113.146 105.856 112.96L106.027 112.645L106.306 112.122C106.44 111.873 106.587 111.591 106.746 111.278C106.819 111.134 106.935 110.898 107.092 110.573C107.137 110.478 107.172 110.405 107.196 110.356C107.213 110.32 107.251 110.241 107.309 110.118C107.427 109.87 107.51 109.694 107.557 109.589C107.708 109.262 107.852 108.94 107.988 108.622L108.004 108.58C108.048 108.477 108.098 108.361 108.153 108.233C108.24 108.031 108.301 107.889 108.334 107.807C108.436 107.558 108.583 107.187 108.773 106.695C108.806 106.611 108.831 106.547 108.849 106.501L108.93 106.284C108.956 106.217 108.98 106.157 109 106.106C109.044 105.996 109.071 105.926 109.082 105.896C109.28 105.353 109.469 104.803 109.649 104.247L109.805 103.768C109.931 103.364 110.073 102.88 110.231 102.318L110.353 101.873C110.486 101.389 110.605 100.913 110.713 100.445L110.766 100.224C110.856 99.8165 110.954 99.3298 111.062 98.7642C111.104 98.5444 111.164 98.2039 111.239 97.7427L111.24 97.7413L111.286 97.4468C111.291 97.4136 111.297 97.3803 111.302 97.3468C111.335 97.1476 111.356 97.0084 111.367 96.9292C111.395 96.7383 111.429 96.4795 111.468 96.1528C111.482 96.0307 111.493 95.9379 111.501 95.8744L111.551 95.4529C111.576 95.2556 111.592 95.114 111.6 95.0279C111.626 94.7717 111.656 94.3788 111.689 93.8493L111.691 93.8218L111.715 93.4636C111.719 93.4193 111.721 93.3886 111.722 93.3716C111.731 93.2627 111.736 93.1977 111.737 93.1766C111.768 92.5227 111.784 91.8907 111.784 91.2807V79.3334C111.683 79.4164 111.58 79.5026 111.473 79.592C111.434 79.6239 111.396 79.6552 111.357 79.6859L111.24 79.7802C111.239 79.7812 111.238 79.7822 111.237 79.7833L111.249 79.7743C111.126 79.8862 111.041 79.9618 110.993 80.0012C110.538 80.3944 110.077 80.8076 109.611 81.2411C109.514 81.3295 109.345 81.4906 109.104 81.7244C108.688 82.1222 108.331 82.4721 108.034 82.7741C107.843 82.9645 107.658 83.1541 107.479 83.3429C107.121 83.7221 106.86 84.0021 106.696 84.1831C106.414 84.4937 106.204 84.7277 106.065 84.8851C105.951 85.0125 105.772 85.2195 105.528 85.5059C105.432 85.6192 105.366 85.6963 105.331 85.7372C105.056 86.0624 104.873 86.2807 104.78 86.3921L104.435 86.827L104.094 87.2552C103.841 87.5734 103.643 87.8273 103.498 88.0169C103.372 88.1822 103.169 88.4556 102.89 88.8374C102.689 89.1089 102.493 89.3801 102.302 89.651C102.166 89.8402 101.994 90.0899 101.787 90.4002C101.534 90.7732 101.359 91.034 101.262 91.1826C101.225 91.2418 101.17 91.3279 101.098 91.4409C100.933 91.6994 100.805 91.9027 100.713 92.0507C100.474 92.4308 100.313 92.6903 100.229 92.8291L99.9616 93.2888L99.698 93.7424C99.551 93.995 99.3887 94.2817 99.2111 94.6025C99.0755 94.8467 98.9312 95.1137 98.7783 95.4034C98.7492 95.4597 98.7058 95.5433 98.6481 95.6541C98.497 95.9446 98.3829 96.1669 98.3057 96.321C98.1488 96.6297 97.9937 96.9454 97.8403 97.268L97.8392 97.2703C97.658 97.6465 97.5293 97.9186 97.453 98.0866C97.3556 98.3021 97.2097 98.633 97.0154 99.0794C96.9949 99.1266 96.9646 99.1963 96.9244 99.2882C96.8019 99.5691 96.7118 99.7803 96.6541 99.9218C96.502 100.289 96.3327 100.718 96.1463 101.211C96.1314 101.25 96.1094 101.306 96.0801 101.382C95.9928 101.607 95.9293 101.774 95.8897 101.882C95.7393 102.291 95.5393 102.876 95.2897 103.637C95.2779 103.671 95.262 103.715 95.2419 103.771L95.2393 103.772C95.2279 103.809 95.2161 103.847 95.204 103.884C95.1874 103.939 95.1706 103.991 95.1534 104.043C95.0129 104.485 94.8672 104.979 94.7164 105.526C94.7107 105.546 94.698 105.593 94.6784 105.668C94.6411 105.81 94.6173 105.898 94.607 105.932C94.4938 106.355 94.3708 106.848 94.2382 107.411C94.2266 107.464 94.2138 107.518 94.1998 107.575L94.1965 107.589C94.082 108.092 93.9774 108.598 93.8825 109.107C93.8433 109.324 93.7855 109.662 93.7091 110.122C93.6976 110.191 93.6881 110.247 93.6806 110.293C93.6225 110.634 93.5794 110.898 93.5513 111.084C93.5269 111.253 93.4925 111.53 93.4482 111.915C93.4309 112.065 93.421 112.149 93.4184 112.166C93.4056 112.294 93.3859 112.469 93.3592 112.691C93.3403 112.848 93.3287 112.949 93.3243 112.992C93.3052 113.194 93.2806 113.518 93.2505 113.962C93.2397 114.12 93.2313 114.243 93.2252 114.328C93.2203 114.397 93.213 114.492 93.2032 114.615C93.1908 114.769 93.1834 114.871 93.1809 114.923C93.1505 115.562 93.1353 116.203 93.1353 116.846V128.236Z" stroke="#0F0D0C" stroke-width="3.5"/>
+</svg>
diff --git a/src/web/src/components/community/bots/create-bot-sheet.dom.test.ts b/src/web/src/components/community/bots/create-bot-sheet.dom.test.ts
index c8742df5a..0abce1baa 100644
--- a/src/web/src/components/community/bots/create-bot-sheet.dom.test.ts
+++ b/src/web/src/components/community/bots/create-bot-sheet.dom.test.ts
@@ -14,7 +14,7 @@ import type { CommunityMachineSummary, RuntimeReasoningCatalog } from "@alook/sh
import { hasBotCreateFieldErrors, validateBotCreateFields } from "./bot-form-validation"
it("guards programmatic create submissions while preserving other backend defaults", () => {
- for (const [runtime, model, invalid] of [["opencode", null, true], ["opencode", " ", true], ["opencode", "provider/custom", false], ["codex", null, false]] as const) {
+ for (const [runtime, model, invalid] of [["opencode", null, true], ["opencode", " ", true], ["opencode", "provider/custom", false], ["pi-durable", null, true], ["pi-durable", " ", true], ["pi-durable", "provider/custom", false], ["cursor-sdk", null, true], ["cursor-sdk", " ", true], ["cursor-sdk", "provider/custom", false], ["codex", null, false]] as const) {
const errors = validateBotCreateFields({ name: "Bot", machineId: "mac", runtime, model })
expect(hasBotCreateFieldErrors(errors)).toBe(invalid)
expect(errors.model).toBe(invalid ? "Choose a model before saving" : undefined)
@@ -229,9 +229,9 @@ describe("CreateBotSheet — auto-select defaults", () => {
expect(botFormFieldsRenders.at(-1)?.avatarDraft.image).toBe("avatar:beam:guide-face-7")
})
- it.each([false, true])("requires an explicit OpenCode model, including guided creation=%s", async (guided) => {
+ it.each([["opencode", false], ["opencode", true], ["pi-durable", false], ["pi-durable", true], ["cursor-sdk", false], ["cursor-sdk", true]] as const)("requires an explicit %s model, including guided creation=%s", async (runtime, guided) => {
useMachinesMock.mockReturnValue({ machines: [machine({ id: "mac", availableRuntimes: [{
- id: "opencode", status: "healthy", reasoning: {
+ id: runtime, status: "healthy", reasoning: {
updateMode: "unsupported", defaultModelId: "provider/picked", models: [{ id: "provider/picked", supportedReasoningEfforts: [] }],
},
}] })] })
@@ -244,7 +244,7 @@ describe("CreateBotSheet — auto-select defaults", () => {
fireEvent.click(renderer.getByTestId("set-model"))
expect(create).toBeEnabled()
await act(async () => { fireEvent.click(create); await Promise.resolve() })
- expect(createMutateAsync).toHaveBeenCalledWith(expect.objectContaining({ runtime: "opencode", model: "provider/picked" }))
+ expect(createMutateAsync).toHaveBeenCalledWith(expect.objectContaining({ runtime, model: "provider/picked" }))
})
it("pre-checks the machine and runtime with one online machine + one healthy runtime", () => {
diff --git a/src/web/src/components/community/bots/edit-bot-sheet.dom.test.ts b/src/web/src/components/community/bots/edit-bot-sheet.dom.test.ts
index 46ad8bdcd..fefda17cf 100644
--- a/src/web/src/components/community/bots/edit-bot-sheet.dom.test.ts
+++ b/src/web/src/components/community/bots/edit-bot-sheet.dom.test.ts
@@ -255,9 +255,9 @@ describe("EditBotSheet — model switch toast (online-only)", () => {
expect(toastSuccess.mock.calls.join(" ")).not.toMatch(/offline|next wake|applies when/i)
})
- it("blocks an unconfigured OpenCode bot until a model is explicitly picked", async () => {
- updateMutateAsync.mockResolvedValue({ bot: { ...BOT, runtime: "opencode" } })
- const renderer = renderSheet({ ...BOT, runtime: "opencode" })
+ it.each(["opencode", "pi-durable", "cursor-sdk"])("blocks an unconfigured %s bot until a model is explicitly picked", async (runtime) => {
+ updateMutateAsync.mockResolvedValue({ bot: { ...BOT, runtime } })
+ const renderer = renderSheet({ ...BOT, runtime })
expect(saveButton(renderer)).toBeDisabled()
fireEvent.click(saveButton(renderer))
expect(updateMutateAsync).not.toHaveBeenCalled()
@@ -268,12 +268,12 @@ describe("EditBotSheet — model switch toast (online-only)", () => {
expect(updateMutateAsync).toHaveBeenCalledWith(expect.objectContaining({ model: "claude-sonnet-4-6" }))
})
- it("requires a fresh model before confirming a switch into OpenCode and restores Default on switching back", () => {
+ it.each(["opencode", "pi-durable", "cursor-sdk"])("requires a fresh model before switching into %s and restores Default on switching back", (runtime) => {
useMachinesMock.mockReturnValue({ machines: [{ id: "mac1", availableRuntimes: [
- { id: "claude", status: "healthy" }, { id: "opencode", status: "healthy" },
+ { id: "claude", status: "healthy" }, { id: runtime, status: "healthy" },
] }] })
const renderer = renderSheet({ ...BOT, modelName: "opus" })
- pickRuntime(renderer, "opencode")
+ pickRuntime(renderer, runtime)
expect(saveButton(renderer)).toBeDisabled()
fireEvent.click(saveButton(renderer))
expect(renderer.queryByTestId("provider-confirm")).not.toBeInTheDocument()
diff --git a/src/web/src/components/community/onboarding/community-onboarding-form.navigation.dom.test.ts b/src/web/src/components/community/onboarding/community-onboarding-form.navigation.dom.test.ts
index 3a42de350..ea1239f6f 100644
--- a/src/web/src/components/community/onboarding/community-onboarding-form.navigation.dom.test.ts
+++ b/src/web/src/components/community/onboarding/community-onboarding-form.navigation.dom.test.ts
@@ -14,6 +14,7 @@ function render(node: React.ReactNode) {
const mocks = vi.hoisted(() => ({
pathname: "/c/me/machines",
+ selectedHarness: "codex",
complete: vi.fn(),
capture: vi.fn(async () => {}),
navigate: vi.fn(),
@@ -76,7 +77,7 @@ vi.mock("./onboarding-select-dialog", () => ({
}) => createElement("div", {}, createElement("button", {
"data-testid": "select-harness",
"data-value": value,
- onClick: () => { onValueChange("codex"); if (advanceOnSelect) onSubmit("codex") },
+ onClick: () => { onValueChange(mocks.selectedHarness); if (advanceOnSelect) onSubmit(mocks.selectedHarness) },
}), advanceOnSelect ? null : createElement("button", { onClick: () => onSubmit("developer") }, "Finish setup")),
}))
vi.mock("@/hooks/community/use-machines", () => ({ useMachines: () => ({ machines: [] }) }))
@@ -230,8 +231,8 @@ describe("CommunityOnboardingForm room navigation", () => {
expect(screen.getByTestId("select-harness")).toHaveAttribute("data-value", "")
})
- it("blocks OpenCode setup until a model is chosen and passes it to initialization", async () => {
- mocks.state = { status: "active", stage: "model", machineId: "machine-1", harness: "opencode" }
+ it.each(["opencode", "pi-durable", "cursor-sdk"])("blocks %s setup until a model is chosen and passes it to initialization", async (harness) => {
+ mocks.state = { status: "active", stage: "model", machineId: "machine-1", harness }
render(createElement(CommunityOnboardingForm))
expect(screen.getByRole("button", { name: "Continue" })).toBeDisabled()
fireEvent.click(screen.getByRole("button", { name: "Continue" }))
@@ -240,14 +241,28 @@ describe("CommunityOnboardingForm room navigation", () => {
fireEvent.click(screen.getByRole("button", { name: "Continue" }))
expect(mocks.initialize).not.toHaveBeenCalled()
fireEvent.click(screen.getByRole("button", { name: "Finish setup" }))
- await waitFor(() => expect(mocks.initialize).toHaveBeenCalledWith(expect.objectContaining({ runtime: "opencode", model: "custom/model" })))
+ await waitFor(() => expect(mocks.initialize).toHaveBeenCalledWith(expect.objectContaining({ runtime: harness, model: "custom/model" })))
})
- it.each(["codex", "opencode"])("routes a connected %s machine through only its required steps", (harness) => {
+ it.each(["codex", "opencode", "qoder", "copilot", "cursor-sdk", "pi-durable"])("routes a connected %s machine through only its required steps", (harness) => {
mocks.state = { status: "active", stage: "machine", harness }
render(createElement(CommunityOnboardingForm))
fireEvent.click(screen.getByRole("button", { name: "Machine connected" }))
- expect(owner.runtime.ui.get().onboardingState?.stage).toBe(harness === "opencode" ? "model" : "identity")
- expect(screen.queryByRole("textbox", { name: "Model" }) !== null).toBe(harness === "opencode")
+ expect(owner.runtime.ui.get().onboardingState?.stage).toBe(["opencode", "pi-durable", "cursor-sdk"].includes(harness) ? "model" : "identity")
+ expect(screen.queryByRole("textbox", { name: "Model" }) !== null).toBe(["opencode", "pi-durable", "cursor-sdk"].includes(harness))
})
+
+ it.each(["qoder", "copilot", "cursor-sdk", "pi-durable"])("starts %s with a usable setup method", (harness) => {
+ mocks.state = { status: "active", stage: "harness" }
+ mocks.selectedHarness = harness
+ render(createElement(CommunityOnboardingForm))
+ fireEvent.click(screen.getByTestId("select-harness"))
+ const sdkOnly = harness === "cursor-sdk" || harness === "pi-durable"
+ expect(owner.runtime.ui.get().onboardingState?.setupMode).toBe(sdkOnly ? "manual" : "agent")
+ expect(screen.getByTestId("onboarding-mode-agent").hasAttribute("disabled")).toBe(sdkOnly)
+ if (sdkOnly) expect(screen.getByRole("button", { name: "Machine connected" })).toBeInTheDocument()
+ else expect(screen.getByText("Agent Setup")).toBeInTheDocument()
+ mocks.selectedHarness = "codex"
+ })
+
})
diff --git a/src/web/src/components/community/onboarding/community-onboarding-form.tsx b/src/web/src/components/community/onboarding/community-onboarding-form.tsx
index cb5def448..092534868 100644
--- a/src/web/src/components/community/onboarding/community-onboarding-form.tsx
+++ b/src/web/src/components/community/onboarding/community-onboarding-form.tsx
@@ -24,6 +24,7 @@ import { OnboardingMachineDialog } from "./onboarding-machine-dialog"
import {
ONBOARDING_HARNESSES,
ONBOARDING_IDENTITIES,
+ supportsAgentSetup,
} from "./onboarding-form-options"
import { beginOnboardingAnalytics } from "@/lib/product-analytics"
import { initializeCommunityOnboarding } from "./initialize-community-onboarding"
@@ -168,7 +169,7 @@ function CommunityOnboardingSteps() {
advanceOnSelect
submitLabel="Continue"
onSubmit={(value) => {
- advanceCommunityOnboarding(communityRuntime, "harness", "machine", { harness: value, setupMode: "agent" })
+ advanceCommunityOnboarding(communityRuntime, "harness", "machine", { harness: value, setupMode: supportsAgentSetup(value) ? "agent" : "manual" })
}}
testId={tid.onboardingHarnessDialog}
optionTestId={tid.onboardingHarnessOption}
@@ -176,7 +177,7 @@ function CommunityOnboardingSteps() {
)
}
- if (state.stage === "machine" && state.setupMode === "agent") {
+ if (state.stage === "machine" && state.setupMode === "agent" && supportsAgentSetup(state.harness)) {
return <OnboardingAgentDialog
harness={state.harness ?? ""}
harnessLabel={harnessLabel(state.harness)}
@@ -285,7 +286,8 @@ export function CommunityOnboardingForm() {
const state = useCommunityOnboarding()
if (!state) return null
const selected = Boolean(state.harness)
- const mode = state.setupMode === "agent" ? "agent" : "manual"
+ const agentSetup = supportsAgentSetup(state.harness)
+ const mode = state.setupMode === "agent" && agentSetup ? "agent" : "manual"
const switching = selected && ["machine", "model", "identity"].includes(state.stage)
return <SetupDialog.Root open onOpenChange={(_open, details) => details.cancel()}>
<SetupDialog.Portal>
@@ -296,7 +298,7 @@ export function CommunityOnboardingForm() {
<nav aria-label="Setup method" className="flex gap-4">
{selected ? (["agent", "manual"] as const).map((value) => <button
key={value} type="button" data-testid={`onboarding-mode-${value}`} aria-pressed={mode === value}
- disabled={!switching} onClick={() => { if (mode !== value) switchCommunityOnboardingSetup(runtime, value) }}
+ disabled={!switching || (value === "agent" && !agentSetup)} onClick={() => { if (mode !== value) switchCommunityOnboardingSetup(runtime, value) }}
className={`inline-flex min-h-11 items-center bg-transparent px-2 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed ${mode === value ? "text-foreground" : "text-muted-foreground hover:text-foreground"}`}
><span className={`border-b-2 pb-1 ${mode === value ? "border-foreground" : "border-transparent"}`}>{value === "agent" ? "Agent" : "Manual"}</span></button>) : <span className="text-sm text-muted-foreground">Pick your local agent</span>}
</nav>
diff --git a/src/web/src/components/community/onboarding/onboarding-form-options.test.ts b/src/web/src/components/community/onboarding/onboarding-form-options.test.ts
index 2ec102dd7..f6755e34d 100644
--- a/src/web/src/components/community/onboarding/onboarding-form-options.test.ts
+++ b/src/web/src/components/community/onboarding/onboarding-form-options.test.ts
@@ -6,7 +6,7 @@ import {
} from "./onboarding-form-options"
describe("onboarding form options", () => {
- it("offers exactly the six supported harnesses with their provider logos", () => {
+ it("offers the supported harnesses with their provider logos", () => {
expect(ONBOARDING_HARNESSES.map(({ value, label, provider }) => ({
value,
label,
@@ -18,6 +18,10 @@ describe("onboarding form options", () => {
{ value: "cursor", label: "Cursor", provider: "cursor" },
{ value: "opencode", label: "OpenCode", provider: "opencode" },
{ value: "pi", label: "Pi", provider: "pi" },
+ { value: "qoder", label: "Qoder", provider: "qoder" },
+ { value: "copilot", label: "GitHub Copilot", provider: "copilot" },
+ { value: "cursor-sdk", label: "Cursor SDK", provider: "cursor-sdk" },
+ { value: "pi-durable", label: "Pi Durable", provider: "pi-durable" },
])
})
diff --git a/src/web/src/components/community/onboarding/onboarding-form-options.ts b/src/web/src/components/community/onboarding/onboarding-form-options.ts
index 04a8e400b..b84884acf 100644
--- a/src/web/src/components/community/onboarding/onboarding-form-options.ts
+++ b/src/web/src/components/community/onboarding/onboarding-form-options.ts
@@ -38,6 +38,10 @@ export const ONBOARDING_HARNESSES = [
label: "Pi",
provider: "pi",
},
+ { value: "qoder", label: "Qoder", provider: "qoder" },
+ { value: "copilot", label: "GitHub Copilot", provider: "copilot" },
+ { value: "cursor-sdk", label: "Cursor SDK", provider: "cursor-sdk" },
+ { value: "pi-durable", label: "Pi Durable", provider: "pi-durable" },
] as const satisfies readonly OnboardingSelectOption[]
export const ONBOARDING_IDENTITIES = [
@@ -66,3 +70,7 @@ export const ONBOARDING_IDENTITIES = [
accentKey: "coral",
},
] as const satisfies readonly OnboardingSelectOption[]
+
+export function supportsAgentSetup(harness: string | undefined): boolean {
+ return harness !== "cursor-sdk" && harness !== "pi-durable"
+}
diff --git a/src/web/src/components/provider-logo.dom.test.tsx b/src/web/src/components/provider-logo.dom.test.tsx
new file mode 100644
index 000000000..a342d673c
--- /dev/null
+++ b/src/web/src/components/provider-logo.dom.test.tsx
@@ -0,0 +1,19 @@
+import { expect, it } from "vitest"
+import { render } from "@/test/react-dom-harness"
+import { ProviderLogo } from "./provider-logo"
+import { runtimeLabel } from "@/lib/community/runtime-label"
+
+it.each([
+ ["qoder", "Qoder", "qoder"],
+ ["copilot", "GitHub Copilot", "copilot"],
+ ["cursor-sdk", "Cursor SDK", "cursor"],
+ ["pi-durable", "Pi Durable", "pi"],
+])("identifies %s with its name and brand icon", (backend, label, logo) => {
+ expect(runtimeLabel(backend)).toBe(label)
+ const markup = render(<ProviderLogo provider={backend} />).container.innerHTML
+ expect(markup).toContain(`data-provider-logo="${logo}"`)
+ expect(markup).not.toContain("lucide-monitor")
+})
+it("keeps unknown runtime labels intact", () => {
+ expect(runtimeLabel("custom-backend")).toBe("custom-backend")
+})
diff --git a/src/web/src/components/provider-logo.tsx b/src/web/src/components/provider-logo.tsx
index d107415cb..fcc42292e 100644
--- a/src/web/src/components/provider-logo.tsx
+++ b/src/web/src/components/provider-logo.tsx
@@ -65,30 +65,27 @@ function HermesLogo({ className }: { className: string }) {
}
function PiLogo({ className }: { className: string }) {
- return (
- <svg viewBox="0 0 800 800" fill="none" className={className}>
- <rect width="800" height="800" rx="150" fill="#09090b" />
- <path
- fill="#fff"
- fillRule="evenodd"
- d="M165.29 165.29H517.36V400H400V517.36H282.65V634.72H165.29ZM282.65 282.65V400H400V282.65Z"
- />
- <path fill="#fff" d="M517.36 400H634.72V634.72H517.36Z" />
- </svg>
- );
+ return <svg viewBox="0 0 560 560" fill="currentColor" className={className} data-provider-logo="pi" aria-hidden="true">
+ <path d="M420 280H280V140H0V0H420V280Z" />
+ <path d="M560 560H420V280H560V560Z" />
+ <path d="M140 560H0V140H140V280H280V420H140V560Z" />
+ </svg>;
}
function CopilotLogo({ className }: { className: string }) {
- return (
- <svg viewBox="0 0 24 24" fill="currentColor" className={className}>
- <path d="M12 1C5.9225 1 1 5.9225 1 12C1 16.8675 4.14875 20.9787 8.52125 22.4362C9.07125 22.5325 9.2775 22.2025 9.2775 21.9137C9.2775 21.6525 9.26375 20.7862 9.26375 19.865C6.5 20.3737 5.785 19.1912 5.565 18.5725C5.44125 18.2562 4.905 17.28 4.4375 17.0187C4.0525 16.8125 3.5025 16.3037 4.42375 16.29C5.29 16.2762 5.90875 17.0875 6.115 17.4175C7.105 19.0812 8.68625 18.6137 9.31875 18.325C9.415 17.61 9.70375 17.1287 10.02 16.8537C7.5725 16.5787 5.015 15.63 5.015 11.4225C5.015 10.2262 5.44125 9.23625 6.1425 8.46625C6.0325 8.19125 5.6475 7.06375 6.2525 5.55125C6.2525 5.55125 7.17375 5.2625 9.2775 6.67875C10.1575 6.43125 11.0925 6.3075 12.0275 6.3075C12.9625 6.3075 13.8975 6.43125 14.7775 6.67875C16.8813 5.24875 17.8025 5.55125 17.8025 5.55125C18.4075 7.06375 18.0225 8.19125 17.9125 8.46625C18.6138 9.23625 19.04 10.2125 19.04 11.4225C19.04 15.6437 16.4688 16.5787 14.0213 16.8537C14.42 17.1975 14.7638 17.8575 14.7638 18.8887C14.7638 20.36 14.75 21.5425 14.75 21.9137C14.75 22.2025 14.9563 22.5462 15.5063 22.4362C19.8513 20.9787 23 16.8537 23 12C23 5.9225 18.0775 1 12 1Z" />
- </svg>
- );
+ return <svg viewBox="0 0 24 24" fill="currentColor" className={className} data-provider-logo="copilot" aria-hidden="true">
+ <path d="M23.922 16.992c-.861 1.495-5.859 5.023-11.922 5.023-6.063 0-11.061-3.528-11.922-5.023A.641.641 0 0 1 0 16.736v-2.869a.841.841 0 0 1 .053-.22c.372-.935 1.347-2.292 2.605-2.656.167-.429.414-1.055.644-1.517a10.195 10.195 0 0 1-.052-1.086c0-1.331.282-2.499 1.132-3.368.397-.406.89-.717 1.474-.952 1.399-1.136 3.392-2.093 6.122-2.093 2.731 0 4.767.957 6.166 2.093.584.235 1.077.546 1.474.952.85.869 1.132 2.037 1.132 3.368 0 .368-.014.733-.052 1.086.23.462.477 1.088.644 1.517 1.258.364 2.233 1.721 2.605 2.656a.832.832 0 0 1 .053.22v2.869a.641.641 0 0 1-.078.256ZM12.172 11h-.344a4.323 4.323 0 0 1-.355.508C10.703 12.455 9.555 13 7.965 13c-1.725 0-2.989-.359-3.782-1.259a2.005 2.005 0 0 1-.085-.104L4 11.741v6.585c1.435.779 4.514 2.179 8 2.179 3.486 0 6.565-1.4 8-2.179v-6.585l-.098-.104s-.033.045-.085.104c-.793.9-2.057 1.259-3.782 1.259-1.59 0-2.738-.545-3.508-1.492a4.323 4.323 0 0 1-.355-.508h-.016.016Zm.641-2.935c.136 1.057.403 1.913.878 2.497.442.544 1.134.938 2.344.938 1.573 0 2.292-.337 2.657-.751.384-.435.558-1.15.558-2.361 0-1.14-.243-1.847-.705-2.319-.477-.488-1.319-.862-2.824-1.025-1.487-.161-2.192.138-2.533.529-.269.307-.437.808-.438 1.578v.021c0 .265.021.562.063.893Zm-1.626 0c.042-.331.063-.628.063-.894v-.02c-.001-.77-.169-1.271-.438-1.578-.341-.391-1.046-.69-2.533-.529-1.505.163-2.347.537-2.824 1.025-.462.472-.705 1.179-.705 2.319 0 1.211.175 1.926.558 2.361.365.414 1.084.751 2.657.751 1.21 0 1.902-.394 2.344-.938.475-.584.742-1.44.878-2.497Z"/>
+ <path d="M14.5 14.25a1 1 0 0 1 1 1v2a1 1 0 0 1-2 0v-2a1 1 0 0 1 1-1Zm-5 0a1 1 0 0 1 1 1v2a1 1 0 0 1-2 0v-2a1 1 0 0 1 1-1Z"/>
+ </svg>;
+}
+
+function QoderLogo({ className }: { className: string }) {
+ return <img src="/providers/qoder.svg" alt="" className={`${className} dark:invert`} data-provider-logo="qoder" />;
}
function CursorLogo({ className }: { className: string }) {
return (
- <svg viewBox="600 300 400 400" fill="none" className={className}>
+ <svg viewBox="600 300 400 400" fill="none" className={className} data-provider-logo="cursor" aria-hidden="true">
<path fill="#14120B" d="M999.994 554.294C999.994 559.859 999.994 565.419 999.962 570.984C999.935 575.67 999.882 580.357 999.753 585.038C999.475 595.247 998.875 605.542 997.059 615.639C995.217 625.88 992.212 635.409 987.477 644.718C982.822 653.861 976.738 662.233 969.485 669.491C962.227 676.748 953.861 682.828 944.712 687.482C935.409 692.217 925.875 695.222 915.633 697.065C905.537 698.88 895.242 699.48 885.033 699.759C880.346 699.887 875.665 699.941 870.978 699.968C865.413 700.005 859.853 700 854.288 700H745.695C740.13 700 734.571 700 729.005 699.968C724.319 699.941 719.632 699.887 714.951 699.759C704.742 699.48 694.447 698.88 684.35 697.065C674.109 695.222 664.58 692.217 655.271 687.482C646.128 682.828 637.756 676.743 630.499 669.491C623.241 662.233 617.161 653.866 612.507 644.718C607.772 635.414 604.767 625.88 602.925 615.639C601.109 605.542 600.509 595.247 600.23 585.038C600.102 580.352 600.048 575.67 600.021 570.984C600 565.419 600 559.859 600 554.294V445.701C600 440.136 600 434.576 600.032 429.011C600.059 424.324 600.112 419.637 600.241 414.956C600.52 404.747 601.119 394.452 602.935 384.356C604.778 374.115 607.783 364.586 612.518 355.277C617.172 346.133 623.257 337.762 630.509 330.504C637.767 323.246 646.133 317.167 655.282 312.512C664.586 307.777 674.12 304.772 684.361 302.93C694.458 301.114 704.752 300.514 714.961 300.236C719.648 300.107 724.329 300.054 729.016 300.027C734.576 300 740.136 300 745.701 300H854.294C859.859 300 865.419 300 870.984 300.032C875.67 300.059 880.357 300.112 885.038 300.241C895.247 300.52 905.542 301.119 915.639 302.935C925.88 304.778 935.409 307.783 944.718 312.518C953.861 317.172 962.233 323.257 969.491 330.509C976.748 337.767 982.828 346.133 987.482 355.282C992.217 364.586 995.222 374.12 997.065 384.361C998.88 394.458 999.48 404.752 999.759 414.961C999.887 419.648 999.941 424.329 999.968 429.016C1000.01 434.581 1000 440.141 1000 445.706V554.299L999.994 554.294Z"/>
<path fill="#72716D" d="M800.004 500L923.821 571.486C923.061 572.804 921.957 573.929 920.591 574.716L804.863 641.531C801.858 643.266 798.151 643.266 795.146 641.531L679.417 574.716C678.052 573.929 676.948 572.804 676.188 571.486L800.004 500Z"/>
<path fill="#55544F" d="M800.005 357.168V500L676.188 571.486C675.427 570.168 675.004 568.647 675.004 567.072V432.928C675.004 429.774 676.686 426.865 679.418 425.285L795.141 358.47C796.646 357.602 798.323 357.168 799.999 357.168H800.005Z"/>
@@ -183,10 +180,14 @@ export function ProviderLogo({
return <OpenClawLogo className={className} />;
case "hermes":
return <HermesLogo className={className} />;
+ case "pi-durable":
case "pi":
return <PiLogo className={className} />;
+ case "qoder":
+ return <QoderLogo className={className} />;
case "copilot":
return <CopilotLogo className={className} />;
+ case "cursor-sdk":
case "cursor":
return <CursorLogo className={className} />;
case "gemini":
diff --git a/src/web/src/lib/community/backend-telemetry.server.test.ts b/src/web/src/lib/community/backend-telemetry.server.test.ts
new file mode 100644
index 000000000..3c4f0818b
--- /dev/null
+++ b/src/web/src/lib/community/backend-telemetry.server.test.ts
@@ -0,0 +1,25 @@
+import { expect, it, vi } from "vitest"
+const mocks = vi.hoisted(() => ({ machines: vi.fn(), bots: vi.fn() }))
+vi.mock("@alook/shared", async (original) => {
+ const actual = await original<typeof import("@alook/shared")>()
+ return { ...actual, queries: { ...actual.queries,
+ communityMachine: { ...actual.queries.communityMachine, listMachinesForUser: mocks.machines, listMachineBackendQuotasForUser: vi.fn(async () => new Map()) },
+ communityBot: { ...actual.queries.communityBot, listBotsForOwner: mocks.bots, getBotDailyActivityForOwner: vi.fn(async () => new Map()), getBotDailyTokenUsageForOwner: vi.fn(async () => new Map()) },
+ productPlan: { ...actual.queries.productPlan, resolveMachinesMaxForUser: vi.fn(async () => ({ plan: "free", value: 10 })), getBotCapacitySummary: vi.fn(async () => ({ plan: "free", limit: 10, ownedCount: 4, activeCount: 4 })) },
+ } }
+})
+import { readCommunityMachines } from "./machines.server"
+import { readCommunityBots } from "./bots.server"
+
+const backends = ["qoder", "copilot", "cursor-sdk", "pi-durable"]
+it("reports unsupported quota for installed SDK backends and keeps unknown backends unknown", async () => {
+ mocks.machines.mockResolvedValue([{ id: "machine", status: "online", availableRuntimes: [...backends, "unknown"].map(id => ({ id })) }])
+ const result = await readCommunityMachines({} as never, "owner")
+ expect(result.machines[0].quota.map(({ capability }) => capability)).toEqual([...backends.map(() => "unsupported"), "unknown"])
+})
+it("reports supported usage for all four new backends without inventing measured tokens", async () => {
+ mocks.bots.mockResolvedValue([...backends, "unknown"].map((runtime, index) => ({ id: `bot-${index}`, runtime, name: runtime, discriminator: "1234", description: "", image: null, avatarVersion: 0, presence: "offline", ownerUserId: "owner" })))
+ const result = await readCommunityBots({} as never, "owner")
+ expect(result.bots.map(({ usage }) => usage.capability)).toEqual([...backends.map(() => "supported"), "unknown"])
+ expect(result.bots[0].usage.days.at(-1)?.metrics).toEqual({ input: null, output: null, cache: null })
+})
diff --git a/src/web/src/lib/community/bots.server.ts b/src/web/src/lib/community/bots.server.ts
index 5f1c975b3..a62de5090 100644
--- a/src/web/src/lib/community/bots.server.ts
+++ b/src/web/src/lib/community/bots.server.ts
@@ -45,7 +45,7 @@ export async function readCommunityBots(db: Database, userId: string) {
image: canonicalUserImage(bot.id, bot.image, bot.avatarVersion),
dailyActivity: activityByBot.get(bot.id) ?? [],
usage: {
- capability: (["claude", "codex", "grok", "opencode", "pi", "antigravity", "agy"] as string[]).includes(bot.runtime)
+ capability: (["claude", "codex", "grok", "opencode", "pi", "antigravity", "agy", "qoder", "copilot", "cursor-sdk", "pi-durable"] as string[]).includes(bot.runtime)
? "supported" as const
: ["cursor"].includes(bot.runtime)
? "unsupported" as const
diff --git a/src/web/src/lib/community/machine-options.server.test.ts b/src/web/src/lib/community/machine-options.server.test.ts
index 4875f4ec5..be2cb30a7 100644
--- a/src/web/src/lib/community/machine-options.server.test.ts
+++ b/src/web/src/lib/community/machine-options.server.test.ts
@@ -21,3 +21,8 @@ it("distinguishes an unreported catalog from a reported empty catalog", () => {
expect(projectModelOptions("m1", { id: "opencode" })).toMatchObject({ modelRequired: true, catalogState: "not_reported", catalogOrigin: "unknown", defaultModelId: null, models: null })
expect(projectModelOptions("m1", { id: "codex", reasoning: { updateMode: "live_next_turn", models: [] } })).toMatchObject({ catalogState: "reported", defaultModelId: null, models: [] })
})
+it.each([["qoder", false], ["copilot", false], ["cursor-sdk", true], ["pi-durable", true]] as const)("projects %s model options without losing effort or required-model semantics", (backendId, modelRequired) => {
+ expect(projectModelOptions("m1", { id: backendId, reasoning: { updateMode: "unsupported", models: [{ id: "provider/model", supportedReasoningEfforts: [{ value: "high" }] }] } })).toMatchObject({
+ backendId, modelRequired, models: [{ id: "provider/model", reasoningEfforts: [{ value: "high" }] }],
+ })
+})
diff --git a/src/web/src/lib/community/machines.server.ts b/src/web/src/lib/community/machines.server.ts
index 74c8eb3eb..af754c6cb 100644
--- a/src/web/src/lib/community/machines.server.ts
+++ b/src/web/src/lib/community/machines.server.ts
@@ -19,7 +19,7 @@ export async function readCommunityMachines(db: Database, userId: string) {
const quota = machine.availableRuntimes.map((runtime) => {
const capability = runtime.id === "claude" || runtime.id === "codex" || runtime.id === "grok" || runtime.id === "antigravity"
? "supported" as const
- : runtime.id === "cursor" || runtime.id === "opencode" || runtime.id === "pi" || runtime.id === "agy"
+ : runtime.id === "cursor" || runtime.id === "opencode" || runtime.id === "pi" || runtime.id === "agy" || ["qoder", "copilot", "cursor-sdk", "pi-durable"].includes(runtime.id)
? "unsupported" as const
: "unknown" as const
const runtimeState = machine.status === "offline"
diff --git a/src/web/src/lib/community/runtime-label.ts b/src/web/src/lib/community/runtime-label.ts
index 271ba6a1e..ed8fb7d0a 100644
--- a/src/web/src/lib/community/runtime-label.ts
+++ b/src/web/src/lib/community/runtime-label.ts
@@ -1,3 +1,11 @@
+const backendLabels = new Map([
+ ["agy", "antigravity cli"],
+ ["qoder", "Qoder"],
+ ["copilot", "GitHub Copilot"],
+ ["cursor-sdk", "Cursor SDK"],
+ ["pi-durable", "Pi Durable"],
+])
+
export function runtimeLabel(runtime: string): string {
- return runtime === "agy" ? "antigravity cli" : runtime
+ return backendLabels.get(runtime) ?? runtime
}
diff --git a/tests/integration/daemon/control-plane.test.ts b/tests/integration/daemon/control-plane.test.ts
index 51a4ba45e..e80bea56c 100644
--- a/tests/integration/daemon/control-plane.test.ts
+++ b/tests/integration/daemon/control-plane.test.ts
@@ -304,7 +304,7 @@ describe("daemon control plane — real ws-do wake round-trip", () => {
headers: { Authorization: `Bearer ${fixture.paired.credential}`, "content-type": "application/json" },
body: JSON.stringify({ agentId: bot.botUserId }),
})
- expect(enrollRes.ok).toBe(true)
+ await assertResOk(enrollRes, "agent enrollment (multi-bot wake→enroll)")
const { runnerKey } = (await enrollRes.json()) as { runnerKey: string }
const pullRes = await fetchWithRetry(`${APP_URL}/api/community/users/me/inbox/pull`, {