@noetic-tools/acp 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Platform adapters backed by the ACP *client* — the server direction's
3
+ * inversion of the client-side handlers. A served harness built on these
4
+ * routes its file reads through the editor (seeing unsaved buffer state, the
5
+ * point of ACP's client-side filesystem) and its shell commands through the
6
+ * editor's terminals.
7
+ *
8
+ * The wire only carries `fs/read_text_file`, `fs/write_text_file`, and
9
+ * `terminal/*`, so these adapters are honest about their limits: an operation
10
+ * with no wire representation (binary writes, stat, readdir, …) rejects with
11
+ * {@link AcpCapabilityError} rather than pretending, and a factory author who
12
+ * needs those falls back to a local adapter for them.
13
+ */
14
+ import type { FsAdapter, ShellAdapter } from '@noetic-tools/types';
15
+ import type * as acp from '@zed-industries/agent-client-protocol';
16
+ import type { AgentSideConnection } from '@zed-industries/agent-client-protocol';
17
+ /** @public Options for {@link clientFsAdapter}. */
18
+ export interface ClientFsAdapterOptions {
19
+ conn: AgentSideConnection;
20
+ sessionId: string;
21
+ capabilities: acp.ClientCapabilities | undefined;
22
+ }
23
+ /**
24
+ * An `FsAdapter` over the client's `fs/read_text_file` / `fs/write_text_file`.
25
+ * Text reads and writes hit the editor (unsaved buffers included); everything
26
+ * the wire cannot express rejects with {@link AcpCapabilityError}.
27
+ * @public
28
+ */
29
+ export declare function clientFsAdapter(options: ClientFsAdapterOptions): FsAdapter;
30
+ /** @public Options for {@link clientShellAdapter}. */
31
+ export interface ClientShellAdapterOptions {
32
+ conn: AgentSideConnection;
33
+ sessionId: string;
34
+ capabilities: acp.ClientCapabilities | undefined;
35
+ /** Shell used to run the command string. Default `/bin/sh -c`. */
36
+ shell?: [
37
+ string,
38
+ ...string[]
39
+ ];
40
+ }
41
+ /**
42
+ * A `ShellAdapter` over the client's `terminal/*` methods: each `exec` runs
43
+ * in an editor-owned terminal, so the user watches the command live.
44
+ * @public
45
+ */
46
+ export declare function clientShellAdapter(options: ClientShellAdapterOptions): ShellAdapter;
@@ -0,0 +1,216 @@
1
+ /**
2
+ * Platform adapters backed by the ACP *client* — the server direction's
3
+ * inversion of the client-side handlers. A served harness built on these
4
+ * routes its file reads through the editor (seeing unsaved buffer state, the
5
+ * point of ACP's client-side filesystem) and its shell commands through the
6
+ * editor's terminals.
7
+ *
8
+ * The wire only carries `fs/read_text_file`, `fs/write_text_file`, and
9
+ * `terminal/*`, so these adapters are honest about their limits: an operation
10
+ * with no wire representation (binary writes, stat, readdir, …) rejects with
11
+ * {@link AcpCapabilityError} rather than pretending, and a factory author who
12
+ * needs those falls back to a local adapter for them.
13
+ */
14
+ import { AcpCapabilityError, frameworkCast, TIMEOUT_ERROR_PREFIX } from '@noetic-tools/types';
15
+ const CLIENT_AGENT_ID = 'acp-client';
16
+ function unsupported(capability) {
17
+ return new AcpCapabilityError({
18
+ agentId: CLIENT_AGENT_ID,
19
+ capability,
20
+ message: `the ACP client cannot back '${capability}' — it has no wire representation`,
21
+ });
22
+ }
23
+ function notAdvertised(capability) {
24
+ return new AcpCapabilityError({
25
+ agentId: CLIENT_AGENT_ID,
26
+ capability,
27
+ });
28
+ }
29
+ /**
30
+ * UTF-8 bytes without assuming a Node runtime: the `.` entry is
31
+ * runtime-neutral, and the `Buffer` global (which `FsAdapter`'s contract
32
+ * names) only exists under Node/Bun — elsewhere a structurally-compatible
33
+ * `Uint8Array` is the best the platform offers.
34
+ */
35
+ function toBytes(text) {
36
+ const BufferCtor = frameworkCast(frameworkCast(globalThis).Buffer);
37
+ if (BufferCtor) {
38
+ return BufferCtor.from(text, 'utf8');
39
+ }
40
+ return frameworkCast(new TextEncoder().encode(text));
41
+ }
42
+ /** Errors that read as "file does not exist", across adapters and clients. */
43
+ const NOT_FOUND_RE = /enoent|not found|no such file|does not exist/i;
44
+ /**
45
+ * Whether a read failure means "the file does not exist". The wire wraps the
46
+ * client adapter's error as a generic JSON-RPC internal error with the detail
47
+ * in `data`, so the serialized error is scanned, not just the message.
48
+ */
49
+ function looksLikeMissingFile(e) {
50
+ if (e instanceof Error && NOT_FOUND_RE.test(e.message)) {
51
+ return true;
52
+ }
53
+ try {
54
+ return NOT_FOUND_RE.test(JSON.stringify(e));
55
+ }
56
+ catch {
57
+ return false;
58
+ }
59
+ }
60
+ /**
61
+ * An `FsAdapter` over the client's `fs/read_text_file` / `fs/write_text_file`.
62
+ * Text reads and writes hit the editor (unsaved buffers included); everything
63
+ * the wire cannot express rejects with {@link AcpCapabilityError}.
64
+ * @public
65
+ */
66
+ export function clientFsAdapter(options) {
67
+ const { conn, sessionId, capabilities } = options;
68
+ const canRead = capabilities?.fs?.readTextFile === true;
69
+ const canWrite = capabilities?.fs?.writeTextFile === true;
70
+ const readFileText = async (path) => {
71
+ if (!canRead) {
72
+ throw notAdvertised('fs.readTextFile');
73
+ }
74
+ const response = await conn.readTextFile({
75
+ sessionId,
76
+ path,
77
+ });
78
+ return response.content;
79
+ };
80
+ const writeFile = async (path, content) => {
81
+ if (!canWrite) {
82
+ throw notAdvertised('fs.writeTextFile');
83
+ }
84
+ await conn.writeTextFile({
85
+ sessionId,
86
+ path,
87
+ content,
88
+ });
89
+ };
90
+ return {
91
+ readFileText,
92
+ writeFile,
93
+ async readFile(path) {
94
+ return toBytes(await readFileText(path));
95
+ },
96
+ async appendFile(path, content) {
97
+ let existing = '';
98
+ try {
99
+ existing = await readFileText(path);
100
+ }
101
+ catch (e) {
102
+ // Only a genuinely-missing file appends from empty (matching local
103
+ // adapters). Any OTHER read failure — transport error, permission
104
+ // denial, path confinement — must propagate: writing just the
105
+ // fragment would silently truncate a file we failed to read.
106
+ if (e instanceof AcpCapabilityError || !looksLikeMissingFile(e)) {
107
+ throw e;
108
+ }
109
+ }
110
+ await writeFile(path, `${existing}${content}`);
111
+ },
112
+ async mkdir() {
113
+ // No directory method exists on the wire; ACP clients create parent
114
+ // directories on write, so this is a deliberate no-op rather than a
115
+ // refusal — refusing would break every write-through-mkdir call path.
116
+ },
117
+ writeFileBytes() {
118
+ return Promise.reject(unsupported('fs.writeFileBytes'));
119
+ },
120
+ rename() {
121
+ return Promise.reject(unsupported('fs.rename'));
122
+ },
123
+ rm() {
124
+ return Promise.reject(unsupported('fs.rm'));
125
+ },
126
+ access() {
127
+ return Promise.reject(unsupported('fs.access'));
128
+ },
129
+ stat() {
130
+ return Promise.reject(unsupported('fs.stat'));
131
+ },
132
+ lstat() {
133
+ return Promise.reject(unsupported('fs.lstat'));
134
+ },
135
+ readdir() {
136
+ return Promise.reject(unsupported('fs.readdir'));
137
+ },
138
+ };
139
+ }
140
+ /**
141
+ * A `ShellAdapter` over the client's `terminal/*` methods: each `exec` runs
142
+ * in an editor-owned terminal, so the user watches the command live.
143
+ * @public
144
+ */
145
+ export function clientShellAdapter(options) {
146
+ const { conn, sessionId, capabilities } = options;
147
+ const [shellCommand, ...shellArgs] = options.shell ?? [
148
+ '/bin/sh',
149
+ '-c',
150
+ ];
151
+ return {
152
+ async exec(command, execOptions) {
153
+ if (capabilities?.terminal !== true) {
154
+ throw notAdvertised('terminal');
155
+ }
156
+ if (execOptions.stdin !== undefined) {
157
+ throw unsupported('terminal.stdin');
158
+ }
159
+ // Matches the local adapter's contract: a signal abort (including an
160
+ // already-aborted signal) RESOLVES with what was collected; only a
161
+ // timeout rejects, with the TIMEOUT_ERROR_PREFIX message callers parse.
162
+ if (execOptions.signal?.aborted) {
163
+ return {
164
+ stdout: '',
165
+ stderr: '',
166
+ exitCode: null,
167
+ };
168
+ }
169
+ const terminal = await conn.createTerminal({
170
+ sessionId,
171
+ command: shellCommand,
172
+ args: [
173
+ ...shellArgs,
174
+ command,
175
+ ],
176
+ cwd: execOptions.cwd,
177
+ env: Object.entries(execOptions.env ?? {}).map(([name, value]) => ({
178
+ name,
179
+ value,
180
+ })),
181
+ });
182
+ let timedOut = false;
183
+ const stop = () => {
184
+ void terminal.kill().catch(() => undefined);
185
+ };
186
+ const timer = execOptions.timeout !== undefined
187
+ ? setTimeout(() => {
188
+ timedOut = true;
189
+ stop();
190
+ }, execOptions.timeout * 1e3)
191
+ : undefined;
192
+ execOptions.signal?.addEventListener('abort', stop, {
193
+ once: true,
194
+ });
195
+ try {
196
+ const exit = await terminal.waitForExit();
197
+ const output = await terminal.currentOutput();
198
+ if (timedOut) {
199
+ throw new Error(`${TIMEOUT_ERROR_PREFIX}${execOptions.timeout}`);
200
+ }
201
+ execOptions.onData?.(toBytes(output.output));
202
+ return {
203
+ stdout: output.output,
204
+ stderr: '',
205
+ exitCode: exit.exitCode ?? null,
206
+ };
207
+ }
208
+ finally {
209
+ clearTimeout(timer);
210
+ execOptions.signal?.removeEventListener('abort', stop);
211
+ await terminal.release().catch(() => undefined);
212
+ }
213
+ },
214
+ };
215
+ }
216
+ //#endregion
package/dist/index.d.ts CHANGED
@@ -43,6 +43,30 @@ export { ACP_PERMISSION_SCOPE, AcpPermissionPromptSchema, AcpPermissionReplySche
43
43
  */
44
44
  export { isAbsolutePath, isWithinRoots, normalizePath } from './paths.js';
45
45
  /** @public */
46
+ export type { ClientFsAdapterOptions, ClientShellAdapterOptions } from './client-adapters.js';
47
+ /**
48
+ * Adapters backed by the ACP client's `fs/*` and `terminal/*` methods —
49
+ * usually reached through `AcpServeSessionInit.client` in a per-session
50
+ * harness factory rather than constructed by hand.
51
+ * @public
52
+ */
53
+ export { clientFsAdapter, clientShellAdapter } from './client-adapters.js';
54
+ /** @public */
55
+ export type { AcpServedAgent } from './serve.js';
56
+ /**
57
+ * Adapt a harness into an ACP `Agent` factory — compose with
58
+ * `loopbackTransport(toAcpAgent(harness))` for in-process serving, or bind it
59
+ * to process stdio with `serveAcp` from `@noetic-tools/acp/server`.
60
+ * @public
61
+ */
62
+ export { toAcpAgent } from './serve.js';
63
+ /** @public */
64
+ export type { ServeTurnOutcome } from './serve-events.js';
65
+ /** @public */
66
+ export { evaluateServePolicy } from './serve-permissions.js';
67
+ /** @public */
68
+ export type { AcpPresentableTool, AcpServeCommand, AcpServeCommandContext, AcpServeHarness, AcpServeHarnessSource, AcpServeHistory, AcpServeOptions, AcpServePermissionDecision, AcpServePermissionPolicy, AcpServePermissionPrompt, AcpServePermissionReply, AcpServePermissionRule, AcpServeSessionInit, } from './serve-types.js';
69
+ /** @public */
46
70
  export type { NoeticAcpClientOptions } from './client.js';
47
71
  /** @public */
48
72
  export { NoeticAcpClient } from './client.js';
package/dist/index.js CHANGED
@@ -34,6 +34,22 @@ export { ACP_PERMISSION_SCOPE, AcpPermissionPromptSchema, AcpPermissionReplySche
34
34
  * @public
35
35
  */
36
36
  export { isAbsolutePath, isWithinRoots, normalizePath } from './paths.js';
37
+ /**
38
+ * Adapters backed by the ACP client's `fs/*` and `terminal/*` methods —
39
+ * usually reached through `AcpServeSessionInit.client` in a per-session
40
+ * harness factory rather than constructed by hand.
41
+ * @public
42
+ */
43
+ export { clientFsAdapter, clientShellAdapter } from './client-adapters.js';
44
+ /**
45
+ * Adapt a harness into an ACP `Agent` factory — compose with
46
+ * `loopbackTransport(toAcpAgent(harness))` for in-process serving, or bind it
47
+ * to process stdio with `serveAcp` from `@noetic-tools/acp/server`.
48
+ * @public
49
+ */
50
+ export { toAcpAgent } from './serve.js';
51
+ /** @public */
52
+ export { evaluateServePolicy } from './serve-permissions.js';
37
53
  /** @public */
38
54
  export { NoeticAcpClient } from './client.js';
39
55
  /** @public */
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Turn translation for the server direction: the client-direction event
3
+ * bridge's table (spec 27, "Output → harness events") run backwards. One pump
4
+ * consumes the harness's full event stream for a single prompt turn and emits
5
+ * `session/update` notifications until the turn boundary resolves the
6
+ * `session/prompt` request with a stop reason.
7
+ */
8
+ import type { AcpSessionNotification, AcpStopReason, StreamEvent } from '@noetic-tools/types';
9
+ /** One `session/update` payload. */
10
+ export type ServeSessionUpdate = AcpSessionNotification['update'];
11
+ /** How a tool call is presented on the wire. */
12
+ export interface ServeToolCallPresentation {
13
+ title: string;
14
+ kind?: ServeToolCallKind;
15
+ locations?: Array<{
16
+ path: string;
17
+ }>;
18
+ /** Initial status: `pending` when the policy will ask, `in_progress` otherwise. */
19
+ status: 'pending' | 'in_progress';
20
+ }
21
+ type ServeToolCallKind = Extract<ServeSessionUpdate, {
22
+ sessionUpdate: 'tool_call';
23
+ }>['kind'];
24
+ /** @public How a served prompt turn ended. */
25
+ export type ServeTurnOutcome = {
26
+ kind: 'stop';
27
+ stopReason: AcpStopReason;
28
+ } | {
29
+ kind: 'error';
30
+ message: string;
31
+ };
32
+ export interface PumpTurnParams {
33
+ events: AsyncIterable<StreamEvent>;
34
+ /** The id passed to `execute()`; claims the turn in `turn_started.messageIds`. */
35
+ messageId: string;
36
+ /** Send one notification to the client. */
37
+ notify(update: ServeSessionUpdate): Promise<void>;
38
+ /** Resolve presentation for a first-party tool call. */
39
+ present(toolName: string, callId: string, args: unknown): ServeToolCallPresentation;
40
+ /** Whether `session/cancel` was received for this session. */
41
+ cancelRequested(): boolean;
42
+ }
43
+ /**
44
+ * Consume the harness event stream for one prompt turn, translating to
45
+ * `session/update` notifications, and return how the turn ended.
46
+ */
47
+ export declare function pumpTurnEvents(params: PumpTurnParams): Promise<ServeTurnOutcome>;
48
+ export {};
@@ -0,0 +1,285 @@
1
+ /**
2
+ * Turn translation for the server direction: the client-direction event
3
+ * bridge's table (spec 27, "Output → harness events") run backwards. One pump
4
+ * consumes the harness's full event stream for a single prompt turn and emits
5
+ * `session/update` notifications until the turn boundary resolves the
6
+ * `session/prompt` request with a stop reason.
7
+ */
8
+ import { frameworkCast } from '@noetic-tools/types';
9
+ //#endregion
10
+ //#region Claim helpers (same suffix-matching rules as chat-sdk's translator)
11
+ function hasEventName(event, name) {
12
+ return event.source === 'framework' && event.type.endsWith(`:${name}`);
13
+ }
14
+ function matchClaim(event, messageId) {
15
+ if (!hasEventName(event, 'turn_started') && !hasEventName(event, 'inbox_injected')) {
16
+ return {
17
+ kind: 'none',
18
+ };
19
+ }
20
+ const ids = event.data.messageIds;
21
+ if (!Array.isArray(ids) || !ids.includes(messageId)) {
22
+ return {
23
+ kind: 'none',
24
+ };
25
+ }
26
+ return {
27
+ kind: 'ours',
28
+ turnId: typeof event.data.turnId === 'string' ? event.data.turnId : null,
29
+ // When queued prompts coalesce into one turn, only the FIRST id's pump
30
+ // sends notifications — the others resolve silently at the same boundary,
31
+ // so the client never sees the turn twice.
32
+ primary: ids[0] === messageId,
33
+ };
34
+ }
35
+ function matchesTurn(event, turnId) {
36
+ return turnId === null || event.data.turnId === turnId;
37
+ }
38
+ //#endregion
39
+ //#region Event readers
40
+ function readToolCall(event) {
41
+ const { name, callId } = event.data;
42
+ if (typeof name !== 'string' || typeof callId !== 'string') {
43
+ return null;
44
+ }
45
+ return {
46
+ name,
47
+ callId,
48
+ };
49
+ }
50
+ /**
51
+ * Capture parsed args from the model's completed function_call item so
52
+ * presentation (title functions, locations) can see them; emitted before the
53
+ * tool round runs, so it always precedes the matching `tool_call_started`.
54
+ */
55
+ function readFunctionCallArgs(event) {
56
+ if (event.type !== 'response.output_item.done') {
57
+ return null;
58
+ }
59
+ const item = event.data.item;
60
+ if (typeof item !== 'object' || item === null) {
61
+ return null;
62
+ }
63
+ const record = frameworkCast(item);
64
+ if (record.type !== 'function_call' || typeof record.callId !== 'string') {
65
+ return null;
66
+ }
67
+ let args;
68
+ if (typeof record.arguments === 'string') {
69
+ try {
70
+ args = JSON.parse(record.arguments);
71
+ }
72
+ catch {
73
+ args = record.arguments;
74
+ }
75
+ }
76
+ return {
77
+ callId: record.callId,
78
+ args,
79
+ };
80
+ }
81
+ /**
82
+ * Prefix applied to a nested sub-agent's tool-call ids so they can never
83
+ * collide with a first-party call's id in the same session.
84
+ */
85
+ const NESTED_ID_PREFIX = 'sub:';
86
+ /**
87
+ * A nested `step.acpAgent` turn re-emits its protocol traffic as
88
+ * `acp.<sessionUpdate>` sdk events carrying the raw update — the proxy path.
89
+ * Only call-shaped updates are forwarded (message chunks already surface
90
+ * through the model-stream events and would double otherwise), each is
91
+ * shape-checked before it can reach the wire, and tool-call ids are
92
+ * namespaced into the sub-agent's own id space.
93
+ */
94
+ function readNestedUpdate(event) {
95
+ if (!event.type.startsWith('acp.')) {
96
+ return null;
97
+ }
98
+ const update = event.data.update;
99
+ if (typeof update !== 'object' || update === null) {
100
+ return null;
101
+ }
102
+ const record = frameworkCast(update);
103
+ if (record.sessionUpdate === 'plan') {
104
+ return Array.isArray(record.entries) ? frameworkCast(update) : null;
105
+ }
106
+ if (record.sessionUpdate !== 'tool_call' && record.sessionUpdate !== 'tool_call_update') {
107
+ return null;
108
+ }
109
+ if (typeof record.toolCallId !== 'string') {
110
+ return null;
111
+ }
112
+ if (record.sessionUpdate === 'tool_call' && typeof record.title !== 'string') {
113
+ return null;
114
+ }
115
+ return frameworkCast({
116
+ ...record,
117
+ toolCallId: `${NESTED_ID_PREFIX}${record.toolCallId}`,
118
+ });
119
+ }
120
+ //#endregion
121
+ //#region Pump
122
+ /**
123
+ * Consume the harness event stream for one prompt turn, translating to
124
+ * `session/update` notifications, and return how the turn ended.
125
+ */
126
+ export async function pumpTurnEvents(params) {
127
+ let claimed = false;
128
+ let primary = false;
129
+ let turnId = null;
130
+ const argsByCallId = new Map();
131
+ /** Calls started but not completed — flushed at the turn boundary so the client is never left with a spinner. */
132
+ const openCalls = new Set();
133
+ const flushOpenCalls = async (status) => {
134
+ for (const toolCallId of openCalls) {
135
+ await notifyIfPrimary(params, primary, {
136
+ sessionUpdate: 'tool_call_update',
137
+ toolCallId,
138
+ status,
139
+ });
140
+ }
141
+ openCalls.clear();
142
+ };
143
+ for await (const event of params.events) {
144
+ if (!claimed) {
145
+ const claim = matchClaim(event, params.messageId);
146
+ if (claim.kind === 'ours') {
147
+ claimed = true;
148
+ primary = claim.primary;
149
+ turnId = claim.turnId;
150
+ }
151
+ continue;
152
+ }
153
+ if (event.source === 'sdk') {
154
+ if (event.type === 'response.output_text.delta' && typeof event.data.delta === 'string') {
155
+ await notifyIfPrimary(params, primary, textChunk('agent_message_chunk', event.data.delta));
156
+ continue;
157
+ }
158
+ if (event.type === 'response.reasoning.delta' && typeof event.data.delta === 'string') {
159
+ await notifyIfPrimary(params, primary, textChunk('agent_thought_chunk', event.data.delta));
160
+ continue;
161
+ }
162
+ const fc = readFunctionCallArgs(event);
163
+ if (fc) {
164
+ argsByCallId.set(fc.callId, fc.args);
165
+ continue;
166
+ }
167
+ const nested = readNestedUpdate(event);
168
+ if (nested) {
169
+ await notifyIfPrimary(params, primary, nested);
170
+ }
171
+ continue;
172
+ }
173
+ if (hasEventName(event, 'tool_call_started')) {
174
+ const call = readToolCall(event);
175
+ if (call) {
176
+ openCalls.add(call.callId);
177
+ const presentation = params.present(call.name, call.callId, argsByCallId.get(call.callId));
178
+ await notifyIfPrimary(params, primary, {
179
+ sessionUpdate: 'tool_call',
180
+ toolCallId: call.callId,
181
+ title: presentation.title,
182
+ kind: presentation.kind,
183
+ status: presentation.status,
184
+ locations: presentation.locations,
185
+ rawInput: asRecord(argsByCallId.get(call.callId)),
186
+ });
187
+ }
188
+ continue;
189
+ }
190
+ if (hasEventName(event, 'tool_call_completed')) {
191
+ const call = readToolCall(event);
192
+ if (call) {
193
+ openCalls.delete(call.callId);
194
+ const output = typeof event.data.output === 'string' ? event.data.output : undefined;
195
+ await notifyIfPrimary(params, primary, {
196
+ sessionUpdate: 'tool_call_update',
197
+ toolCallId: call.callId,
198
+ status: event.data.error === true ? 'failed' : 'completed',
199
+ // The tool's output (or failure text) as renderable content — the
200
+ // spec's "completed with the output as content, failed carrying the
201
+ // error".
202
+ content: output !== undefined
203
+ ? [
204
+ {
205
+ type: 'content',
206
+ content: {
207
+ type: 'text',
208
+ text: output,
209
+ },
210
+ },
211
+ ]
212
+ : undefined,
213
+ });
214
+ }
215
+ continue;
216
+ }
217
+ if (hasEventName(event, 'turn_completed') && matchesTurn(event, turnId)) {
218
+ await flushOpenCalls('completed');
219
+ return {
220
+ kind: 'stop',
221
+ stopReason: 'end_turn',
222
+ };
223
+ }
224
+ if (hasEventName(event, 'turn_aborted') && matchesTurn(event, turnId)) {
225
+ await flushOpenCalls('failed');
226
+ // The typed error kind (spec 31 gate contract) classifies the abort;
227
+ // the session-level cancel flag covers aborts that carry no kind (a
228
+ // host-initiated harness.abort has only a reason string).
229
+ const errorKind = typeof event.data.errorKind === 'string' ? event.data.errorKind : undefined;
230
+ if (errorKind === 'cancelled' || params.cancelRequested()) {
231
+ return {
232
+ kind: 'stop',
233
+ stopReason: 'cancelled',
234
+ };
235
+ }
236
+ if (errorKind === 'model_refused') {
237
+ return {
238
+ kind: 'stop',
239
+ stopReason: 'refusal',
240
+ };
241
+ }
242
+ if (errorKind === 'budget_exceeded') {
243
+ // The closest wire vocabulary for a spent token budget — an editor
244
+ // renders it as a native budget stop instead of a generic error.
245
+ return {
246
+ kind: 'stop',
247
+ stopReason: 'max_tokens',
248
+ };
249
+ }
250
+ return {
251
+ kind: 'error',
252
+ message: typeof event.data.reason === 'string' ? event.data.reason : 'turn aborted',
253
+ };
254
+ }
255
+ }
256
+ // The stream ended without a boundary — the harness (or connection) is
257
+ // shutting down. Cancelled is the honest stop reason: the turn did not
258
+ // complete and no error was reported.
259
+ return {
260
+ kind: 'stop',
261
+ stopReason: 'cancelled',
262
+ };
263
+ }
264
+ async function notifyIfPrimary(params, primary, update) {
265
+ if (!primary) {
266
+ return;
267
+ }
268
+ await params.notify(update);
269
+ }
270
+ function textChunk(kind, text) {
271
+ return {
272
+ sessionUpdate: kind,
273
+ content: {
274
+ type: 'text',
275
+ text,
276
+ },
277
+ };
278
+ }
279
+ function asRecord(value) {
280
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
281
+ return undefined;
282
+ }
283
+ return frameworkCast(value);
284
+ }
285
+ //#endregion