@gobing-ai/ts-ai-runner 0.6.0 → 0.6.2

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.
@@ -69,6 +69,8 @@ export interface PromptOptions {
69
69
  }
70
70
  /** Frames one user prompt as a single stdin line for a persistent-stdin dispatch. */
71
71
  export type StdinFrame = (input: string) => string;
72
+ /** claude stream-json input dialect: one user-message JSONL envelope per line. */
73
+ export declare const claudeStreamJsonFrame: StdinFrame;
72
74
  /** Deprecation metadata attached to a retired or superseded agent shim. */
73
75
  export interface AgentDeprecation {
74
76
  /** Release date (ISO) when the id was marked deprecated. */
@@ -1 +1 @@
1
- {"version":3,"file":"shims.d.ts","sourceRoot":"","sources":["../../src/agents/shims.ts"],"names":[],"mappings":"AAIA,gEAAgE;AAChE,MAAM,MAAM,SAAS,GACf,QAAQ,GACR,OAAO,GACP,QAAQ,GACR,IAAI,GACJ,UAAU,GACV,iBAAiB,GACjB,UAAU,GACV,QAAQ,GACR,KAAK,GACL,MAAM,GACN,UAAU,GACV,IAAI,CAAC;AAEX,0CAA0C;AAC1C,MAAM,MAAM,UAAU,GAAG,MAAM,GAAG,MAAM,CAAC;AAEzC,mEAAmE;AACnE,MAAM,WAAW,WAAW;IACxB,4BAA4B;IAC5B,OAAO,EAAE,MAAM,CAAC;IAChB,2CAA2C;IAC3C,IAAI,EAAE,MAAM,EAAE,CAAC;CAClB;AAED,4CAA4C;AAC5C,MAAM,WAAW,aAAa;IAC1B,yDAAyD;IACzD,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,8DAA8D;IAC9D,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB;;;;;OAKG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;OAIG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,wDAAwD;IACxD,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,mDAAmD;IACnD,IAAI,CAAC,EAAE,UAAU,CAAC;IACl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S,CAMxD"}
@@ -4,7 +4,7 @@ import { assertSafeSessionId } from '../agent-spec.js';
4
4
  /** pi-family rpc dialect (pi docs/rpc.md): one JSON object per line. */
5
5
  const piRpcFrame = (input) => `${JSON.stringify({ type: 'prompt', message: input })}\n`;
6
6
  /** claude stream-json input dialect: one user-message JSONL envelope per line. */
7
- const claudeStreamJsonFrame = (input) => `${JSON.stringify({ type: 'user', message: { role: 'user', content: [{ type: 'text', text: input }] } })}\n`;
7
+ export const claudeStreamJsonFrame = (input) => `${JSON.stringify({ type: 'user', message: { role: 'user', content: [{ type: 'text', text: input }] } })}\n`;
8
8
  const claudeShim = {
9
9
  name: 'claude',
10
10
  command: 'claude',
@@ -168,17 +168,22 @@ const antigravityCliShim = {
168
168
  getHelpCommand: () => ({ command: 'agy', args: ['--help'] }),
169
169
  getVersionCommand: () => ({ command: 'agy', args: ['--version'] }),
170
170
  getPromptCommand: (options) => {
171
- // Print mode is headless: agy auto-denies any tool that would prompt
172
- // (write_file et al.), so expectFile-style automation dead-ends without
173
- // a permission affordance (spur 0689). `--mode accept-edits` is the
174
- // narrowest grant verified to suppress the denial (live probe
175
- // 2026-08-27: write_file succeeds, multi-step write-read-write passes);
176
- // it auto-approves edit permission requests only, not all tools. Trust
177
- // assumption: the dispatch is already an operator-initiated, headless,
178
- // workspace-scoped subprocess running agent-emitted commands under the
179
- // caller's supervision. This is the narrow edit-only policy shared by
180
- // configured headless executors that otherwise prompt (spur 0689).
181
- const args = ['-p', options.input ?? '', '--mode', 'accept-edits'];
171
+ // Print mode is headless: agy auto-denies any tool that would prompt,
172
+ // so expectFile-style automation dead-ends without a permission
173
+ // affordance (spur 0689). `--mode accept-edits` alone proved too narrow
174
+ // in the field (spur task 1276 review lane, 2026-10-23): the sandbox
175
+ // (toolPermission=proceed-in-sandbox) blocked reads outside the
176
+ // workspace (~/.gitconfig) and hard-denied allowlisted-command
177
+ // variants (e.g. `bun <script>` vs the built-in `bun run` prefix),
178
+ // producing exit-0 empty answers from healthy models. The CLI's own
179
+ // documented remedy for headless automation is
180
+ // `--dangerously-skip-permissions` (auto-approve all tool permission
181
+ // requests, sandbox included). Trust assumption (0689, widened with
182
+ // operator sanction 2026-10-23): the dispatch is an operator-initiated,
183
+ // headless, workspace-scoped subprocess running agent-emitted commands
184
+ // under the caller's supervision; the flag is scoped to print mode
185
+ // only — interactive agy sessions keep their own permission flow.
186
+ const args = ['-p', options.input ?? '', '--mode', 'accept-edits', '--dangerously-skip-permissions'];
182
187
  if (options.timeoutMs !== undefined)
183
188
  args.push('--print-timeout', `${options.timeoutMs}ms`);
184
189
  // Headless agy resolves relative file-tool paths against a scratch dir,
@@ -427,10 +432,11 @@ const AGENT_SESSION_CAPABILITY = {
427
432
  supportsSessionDir: false,
428
433
  supportsPersistentStdin: true,
429
434
  supportsStructuredOutput: true,
430
- verifiedAgainst: '2.1.278',
431
- // Persistent stdin is shim-wired: `-p --input-format stream-json --output-format
432
- // stream-json` keeps the process alive reading JSONL envelopes (verified --help;
433
- // --input-format only works with --print).
435
+ verifiedAgainst: '2.1.308',
436
+ // Persistent stdin re-verified with a live two-turn capture on 2026-10-22 (task 1276): one
437
+ // process served two keyed turns and emitted one `result` record per turn with a constant
438
+ // session id (fixtures: ai-runner tests/fixtures/turn-drivers/claude). Stream-json input
439
+ // only works with --print, and stream-json output requires --verbose (observed 2.1.308).
434
440
  note: 'no session-dir flag — sessionDir is ignored (best-effort isolate)',
435
441
  },
436
442
  codex: {
@@ -1 +1 @@
1
- {"version":3,"file":"ai-runner.d.ts","sourceRoot":"","sources":["../src/ai-runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,kBAAkB,EAAE,QAAQ,EAAa,KAAK,MAAM,EAAc,MAAM,qBAAqB,CAAC;AAC5G,OAAO,EAGH,KAAK,eAAe,EACpB,KAAK,kBAAkB,EAEvB,KAAK,UAAU,EAClB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,KAAK,SAAS,EAAgB,KAAK,aAAa,EA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,CAKb"}
package/dist/ai-runner.js CHANGED
@@ -129,7 +129,18 @@ export class AiRunner {
129
129
  detail: `no turn-session driver registered for agent '${agent}' (registry: ${[...TURN_SESSION_DRIVERS.keys()].join(', ') || 'empty'})`,
130
130
  };
131
131
  }
132
- const binary = options.binary ?? (await this.resolveTurnBinary(agent));
132
+ let binary;
133
+ try {
134
+ binary = options.binary ?? (await this.resolveTurnBinary(agent));
135
+ }
136
+ catch (error) {
137
+ // Probe explosions (executor bugs, missing shims) are refusals, never throws (AC1).
138
+ return {
139
+ ok: false,
140
+ reason: 'spawn-failed',
141
+ detail: `binary probe failed for agent '${agent}': ${error instanceof Error ? error.message : String(error)}`,
142
+ };
143
+ }
133
144
  return await openTurnSessionWithDriver({
134
145
  agent,
135
146
  driver,
@@ -0,0 +1,16 @@
1
+ import type { TurnSessionDriver } from '../turn-session';
2
+ /** Claude Code version this driver's protocol was qualified against (probed, never fabricated). */
3
+ export declare const CLAUDE_TURN_VERIFIED_VERSION = "2.1.308";
4
+ /** Upper bound on startup rows scanned for a session id before the handshake gives up. */
5
+ export declare const HANDSHAKE_MAX_LINES = 64;
6
+ /**
7
+ * Build the driver. `spawn` overrides the child argv for tests (the registry instance spawns the
8
+ * real `claude` binary); production callers use `TURN_SESSION_DRIVERS.get('claude')`.
9
+ */
10
+ export declare function createClaudeTurnSessionDriver(options?: {
11
+ spawn?: {
12
+ command: string;
13
+ args: string[];
14
+ };
15
+ }): TurnSessionDriver;
16
+ //# sourceMappingURL=claude-stream-json.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"claude-stream-json.d.ts","sourceRoot":"","sources":["../../src/turn-drivers/claude-stream-json.ts"],"names":[],"mappings":"AAkBA,OAAO,KAAK,EAIR,iBAAiB,EAIpB,MAAM,iBAAiB,CAAC;AAEzB,mGAAmG;AACnG,eAAO,MAAM,4BAA4B,YAAY,CAAC;AAEtD,0FAA0F;AAC1F,eAAO,MAAM,mBAAmB,KAAK,CAAC;AAUtC;;;GAGG;AACH,wBAAgB,6BAA6B,CACzC,OAAO,GAAE;IAAE,KAAK,CAAC,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,EAAE,CAAA;KAAE,CAAA;CAAO,GAC9D,iBAAiB,CAyFnB"}
@@ -0,0 +1,100 @@
1
+ import { claudeStreamJsonFrame } from '../agents/shims.js';
2
+ /** Claude Code version this driver's protocol was qualified against (probed, never fabricated). */
3
+ export const CLAUDE_TURN_VERIFIED_VERSION = '2.1.308';
4
+ /** Upper bound on startup rows scanned for a session id before the handshake gives up. */
5
+ export const HANDSHAKE_MAX_LINES = 64;
6
+ /**
7
+ * Build the driver. `spawn` overrides the child argv for tests (the registry instance spawns the
8
+ * real `claude` binary); production callers use `TURN_SESSION_DRIVERS.get('claude')`.
9
+ */
10
+ export function createClaudeTurnSessionDriver(options = {}) {
11
+ return {
12
+ agent: 'claude',
13
+ qualify: (binary) => binary.version === CLAUDE_TURN_VERIFIED_VERSION
14
+ ? { qualified: true }
15
+ : {
16
+ qualified: false,
17
+ reason: `claude ${binary.version ?? '<no version>'} is not the qualified stream-json version ${CLAUDE_TURN_VERIFIED_VERSION}`,
18
+ },
19
+ spawnArgv: (_binary, policy) => options.spawn ?? {
20
+ command: 'claude',
21
+ args: [
22
+ '-p',
23
+ '--input-format',
24
+ 'stream-json',
25
+ '--output-format',
26
+ 'stream-json',
27
+ // stream-json output refuses to start without --verbose (observed 2.1.308).
28
+ '--verbose',
29
+ ...(policy.model !== undefined ? ['--model', policy.model] : []),
30
+ ...(policy.role !== undefined ? ['--append-system-prompt', policy.role] : []),
31
+ ],
32
+ },
33
+ handshake: async (pull) => {
34
+ // Startup rows (hook noise, init) all carry the constant session id; the first record
35
+ // that has one is enough. Leave everything else on the stream for the pump so the
36
+ // first turn still sees its `init` (acceptance) if handshake stopped before it.
37
+ for (let seen = 0; seen < HANDSHAKE_MAX_LINES; seen += 1) {
38
+ const line = await pull(2_000);
39
+ if (line === null)
40
+ return null; // EOF or timeout before any session evidence
41
+ let record;
42
+ try {
43
+ record = JSON.parse(line);
44
+ }
45
+ catch {
46
+ continue; // pre-protocol noise; the pump's decoder is the strict one
47
+ }
48
+ if (typeof record.session_id === 'string')
49
+ return { nativeSessionId: record.session_id };
50
+ }
51
+ return null;
52
+ },
53
+ encodeTurn: (input) => claudeStreamJsonFrame(input.prompt),
54
+ decode: (line, context) => {
55
+ let record;
56
+ try {
57
+ record = JSON.parse(line);
58
+ }
59
+ catch {
60
+ // Plain Error, not TurnProtocolError: importing the class would make this module
61
+ // a runtime dependency of turn-session.ts (which registers this driver). The pump
62
+ // settles contract-violation for ANY decoder throw, which is the real contract.
63
+ const error = new Error(`claude stream-json: malformed JSON line: ${line.slice(0, 80)}`);
64
+ error.name = 'TurnProtocolError';
65
+ throw error;
66
+ }
67
+ const turnId = context?.turnId ?? null;
68
+ const events = [];
69
+ if (record.type === 'system' && record.subtype === 'init' && context !== undefined && !context.accepted) {
70
+ events.push({ turnId, type: 'accepted' });
71
+ }
72
+ if (record.type === 'assistant') {
73
+ // A turn whose boundary init was consumed still accepts on its first output. (The
74
+ // init branch above is the only accepted source, and it never fires for this record.)
75
+ if (context !== undefined && !context.accepted) {
76
+ events.push({ turnId, type: 'accepted' });
77
+ }
78
+ events.push({ turnId, type: 'output', data: record });
79
+ return events;
80
+ }
81
+ if (record.type === 'result') {
82
+ const terminal = {
83
+ kind: record.is_error === true ? 'failure' : 'success',
84
+ ...(typeof record.session_id === 'string' ? { nativeSessionId: record.session_id } : {}),
85
+ ...(typeof record.result === 'string' ? { finalText: record.result } : {}),
86
+ ...(record.is_error === true
87
+ ? { reason: `claude result subtype '${record.subtype ?? 'unknown'}' reported an error` }
88
+ : {}),
89
+ };
90
+ events.push({ turnId, type: 'terminal', terminal });
91
+ return events;
92
+ }
93
+ return events; // system/rate_limit_event/control_response/unknown — tolerated noise
94
+ },
95
+ encodeCancel: (reason) =>
96
+ // Interrupt control request (observed 2.1.308): acknowledged with a `control_response`,
97
+ // then the interrupted turn settles with a `result error_during_execution` record.
98
+ `${JSON.stringify({ type: 'control_request', request_id: `cancel-${reason}`, request: { subtype: 'interrupt' } })}\n`,
99
+ };
100
+ }
@@ -117,6 +117,17 @@ export interface TurnWireEvent {
117
117
  export declare class TurnProtocolError extends Error {
118
118
  constructor(message: string);
119
119
  }
120
+ /**
121
+ * Session-scoped decode attribution (task 1276): the facade hands each driver the caller's current
122
+ * active turn, when one exists. Protocols whose records echo a runner turn id (the fake driver)
123
+ * ignore it; protocols like claude stream-json — whose records carry only a constant session id —
124
+ * stamp `turnId` on every frame so `route` can attribute them. `accepted` lets a driver infer
125
+ * acceptance for turns whose boundary record was consumed by the handshake (claude turn 1).
126
+ */
127
+ export interface TurnDecodeContext {
128
+ readonly turnId: string;
129
+ readonly accepted: boolean;
130
+ }
120
131
  /** Handshake result: the native session id when the agent reported one during startup. */
121
132
  export type TurnHandshake = {
122
133
  nativeSessionId?: string;
@@ -148,8 +159,12 @@ export interface TurnSessionDriver {
148
159
  prompt: string;
149
160
  correlation: TurnCorrelation;
150
161
  }): string;
151
- /** Decode one stdout line into zero or more frames; throws {@link TurnProtocolError} on malformed input. */
152
- decode(line: string): TurnWireEvent[];
162
+ /**
163
+ * Decode one stdout line into zero or more frames; throws {@link TurnProtocolError} on
164
+ * malformed input. `context` carries the session's current active turn for drivers whose
165
+ * protocol cannot self-attribute (claude); drivers that echo turn ids may ignore it.
166
+ */
167
+ decode(line: string, context?: TurnDecodeContext): TurnWireEvent[];
153
168
  encodeCancel(reason: string): string;
154
169
  }
155
170
  /** Outcome of {@link AiRunner.openTurnSession}: an open session or a typed failure reason. */
@@ -161,7 +176,11 @@ export type OpenTurnSessionResult = {
161
176
  reason: 'unsupported-agent' | 'unqualified-version' | 'spawn-failed' | 'handshake-failed';
162
177
  detail: string;
163
178
  };
164
- /** Built-in driver registry. Empty in 0.x by design — real drivers land with qualification evidence. */
179
+ /**
180
+ * Built-in driver registry. Entries land only with recorded qualification evidence (anti-pattern:
181
+ * registration without evidence): claude 2.1.308 stream-json (task 1276, fixtures under
182
+ * `tests/fixtures/turn-drivers/claude`). 0.x shipped this empty by design.
183
+ */
165
184
  export declare const TURN_SESSION_DRIVERS: ReadonlyMap<AgentName, TurnSessionDriver>;
166
185
  /** How long `cancel()` waits for native terminal evidence before resolving `outcome-unknown`. */
167
186
  export declare const TURN_CANCEL_GRACE_MS = 5000;
@@ -1 +1 @@
1
- {"version":3,"file":"turn-session.d.ts","sourceRoot":"","sources":["../src/turn-session.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAe,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAC1E,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAEhD;;;;;;GAMG;AAEH,0GAA0G;AAC1G,MAAM,MAAM,eAAe,GACrB,SAAS,GACT,SAAS,GACT,aAAa,GACb,aAAa,GACb,iBAAiB,GACjB,oBAAoB,CAAC;AAE3B,sGAAsG;AACtG,MAAM,WAAW,eAAe;IAC5B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;CAC5B;AAED,8FAA8F;AAC9F,MAAM,WAAW,iBAAiB;IAC9B,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1B,WAAW,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,0GAA0G;AAC1G,MAAM,WAAW,WAAW;IACxB,IAAI,EAAE,eAAe,CAAC;IACtB,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,eA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;AAED,uCAAuC;AACvC,qBAAa,sBAAuB,SAAQ,KAAK;;CAKhD;AAED,uGAAuG;AACvG,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,iBAAiB,GAAG,MAAM,CAezE;AAED;;;;GAIG;AACH,wBAAuB,SAAS,CAAC,MAAM,EAAE,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC,MAAM,CAAC,CAyB3F;AA4TD;;;;GAIG;AACH,wBAAsB,yBAAyB,CAAC,OAAO,EAAE;IACrD,KAAK,EAAE,SAAS,CAAC;IACjB,MAAM,EAAE,iBAAiB,GAAG,SAAS,CAAC;IACtC,MAAM,EAAE,iBAAiB,CAAC;IAC1B,MAAM,EAAE,UAAU,CAAC;IACnB,eAAe,EAAE,eAAe,CAAC;IACjC,kBAAkB,CAAC,EAAE,MAAM,CAAC;CAC/B,GAAG,OAAO,CAAC,qBAAqB,CAAC,CA0EjC"}
@@ -1,4 +1,5 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
+ import { createClaudeTurnSessionDriver } from './turn-drivers/claude-stream-json.js';
2
3
  /** Thrown by `TurnSessionDriver.decode` on a malformed frame — settles the turn `contract-violation`. */
3
4
  export class TurnProtocolError extends Error {
4
5
  constructor(message) {
@@ -6,8 +7,14 @@ export class TurnProtocolError extends Error {
6
7
  this.name = 'TurnProtocolError';
7
8
  }
8
9
  }
9
- /** Built-in driver registry. Empty in 0.x by design — real drivers land with qualification evidence. */
10
- export const TURN_SESSION_DRIVERS = new Map();
10
+ /**
11
+ * Built-in driver registry. Entries land only with recorded qualification evidence (anti-pattern:
12
+ * registration without evidence): claude 2.1.308 stream-json (task 1276, fixtures under
13
+ * `tests/fixtures/turn-drivers/claude`). 0.x shipped this empty by design.
14
+ */
15
+ export const TURN_SESSION_DRIVERS = new Map([
16
+ ['claude', createClaudeTurnSessionDriver()],
17
+ ]);
11
18
  /** How long `cancel()` waits for native terminal evidence before resolving `outcome-unknown`. */
12
19
  export const TURN_CANCEL_GRACE_MS = 5_000;
13
20
  /** Handshake bound for `openTurnSession`. */
@@ -343,7 +350,11 @@ class TurnSessionImpl {
343
350
  // settles contract-violation.
344
351
  try {
345
352
  for await (const line of this.lines) {
346
- const wires = this.driver.decode(line);
353
+ const active = this.active;
354
+ const context = active === undefined
355
+ ? undefined
356
+ : { turnId: active.turnId, accepted: active.acceptedAt !== undefined };
357
+ const wires = this.driver.decode(line, context);
347
358
  for (const wire of wires)
348
359
  this.route(wire);
349
360
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gobing-ai/ts-ai-runner",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
4
4
  "description": "@gobing-ai/ts-ai-runner — Coding-agent shims, detection, doctor checks, and prompt execution.",
5
5
  "keywords": [
6
6
  "typescript",
@@ -51,12 +51,12 @@
51
51
  "release": "echo 'Manual publish is disabled. Releases go through GitHub Actions via Trusted Publishing — push a tag: git tag @gobing-ai/ts-ai-runner-v<version> && git push --tags' && exit 1"
52
52
  },
53
53
  "dependencies": {
54
- "@gobing-ai/ts-infra": "^0.6.0",
55
- "@gobing-ai/ts-runtime": "^0.6.0"
54
+ "@gobing-ai/ts-infra": "^0.6.2",
55
+ "@gobing-ai/ts-runtime": "^0.6.2"
56
56
  },
57
57
  "devDependencies": {
58
58
  "@types/bun": "1.4.3",
59
- "@gobing-ai/ts-db": "^0.6.0"
59
+ "@gobing-ai/ts-db": "^0.6.2"
60
60
  },
61
61
  "publishConfig": {
62
62
  "access": "public"
@@ -90,7 +90,7 @@ export type StdinFrame = (input: string) => string;
90
90
  const piRpcFrame: StdinFrame = (input) => `${JSON.stringify({ type: 'prompt', message: input })}\n`;
91
91
 
92
92
  /** claude stream-json input dialect: one user-message JSONL envelope per line. */
93
- const claudeStreamJsonFrame: StdinFrame = (input) =>
93
+ export const claudeStreamJsonFrame: StdinFrame = (input) =>
94
94
  `${JSON.stringify({ type: 'user', message: { role: 'user', content: [{ type: 'text', text: input }] } })}\n`;
95
95
 
96
96
  /** Deprecation metadata attached to a retired or superseded agent shim. */
@@ -285,17 +285,22 @@ const antigravityCliShim: AgentShim = {
285
285
  getHelpCommand: () => ({ command: 'agy', args: ['--help'] }),
286
286
  getVersionCommand: () => ({ command: 'agy', args: ['--version'] }),
287
287
  getPromptCommand: (options) => {
288
- // Print mode is headless: agy auto-denies any tool that would prompt
289
- // (write_file et al.), so expectFile-style automation dead-ends without
290
- // a permission affordance (spur 0689). `--mode accept-edits` is the
291
- // narrowest grant verified to suppress the denial (live probe
292
- // 2026-08-27: write_file succeeds, multi-step write-read-write passes);
293
- // it auto-approves edit permission requests only, not all tools. Trust
294
- // assumption: the dispatch is already an operator-initiated, headless,
295
- // workspace-scoped subprocess running agent-emitted commands under the
296
- // caller's supervision. This is the narrow edit-only policy shared by
297
- // configured headless executors that otherwise prompt (spur 0689).
298
- const args = ['-p', options.input ?? '', '--mode', 'accept-edits'];
288
+ // Print mode is headless: agy auto-denies any tool that would prompt,
289
+ // so expectFile-style automation dead-ends without a permission
290
+ // affordance (spur 0689). `--mode accept-edits` alone proved too narrow
291
+ // in the field (spur task 1276 review lane, 2026-10-23): the sandbox
292
+ // (toolPermission=proceed-in-sandbox) blocked reads outside the
293
+ // workspace (~/.gitconfig) and hard-denied allowlisted-command
294
+ // variants (e.g. `bun <script>` vs the built-in `bun run` prefix),
295
+ // producing exit-0 empty answers from healthy models. The CLI's own
296
+ // documented remedy for headless automation is
297
+ // `--dangerously-skip-permissions` (auto-approve all tool permission
298
+ // requests, sandbox included). Trust assumption (0689, widened with
299
+ // operator sanction 2026-10-23): the dispatch is an operator-initiated,
300
+ // headless, workspace-scoped subprocess running agent-emitted commands
301
+ // under the caller's supervision; the flag is scoped to print mode
302
+ // only — interactive agy sessions keep their own permission flow.
303
+ const args = ['-p', options.input ?? '', '--mode', 'accept-edits', '--dangerously-skip-permissions'];
299
304
  if (options.timeoutMs !== undefined) args.push('--print-timeout', `${options.timeoutMs}ms`);
300
305
  // Headless agy resolves relative file-tool paths against a scratch dir,
301
306
  // not the process cwd; --add-dir re-roots them into the real workspace
@@ -550,10 +555,11 @@ const AGENT_SESSION_CAPABILITY: Readonly<Record<AgentName, AgentSessionCapabilit
550
555
  supportsSessionDir: false,
551
556
  supportsPersistentStdin: true,
552
557
  supportsStructuredOutput: true,
553
- verifiedAgainst: '2.1.278',
554
- // Persistent stdin is shim-wired: `-p --input-format stream-json --output-format
555
- // stream-json` keeps the process alive reading JSONL envelopes (verified --help;
556
- // --input-format only works with --print).
558
+ verifiedAgainst: '2.1.308',
559
+ // Persistent stdin re-verified with a live two-turn capture on 2026-10-22 (task 1276): one
560
+ // process served two keyed turns and emitted one `result` record per turn with a constant
561
+ // session id (fixtures: ai-runner tests/fixtures/turn-drivers/claude). Stream-json input
562
+ // only works with --print, and stream-json output requires --verbose (observed 2.1.308).
557
563
  note: 'no session-dir flag — sessionDir is ignored (best-effort isolate)',
558
564
  },
559
565
  codex: {
package/src/ai-runner.ts CHANGED
@@ -249,7 +249,17 @@ export class AiRunner {
249
249
  detail: `no turn-session driver registered for agent '${agent}' (registry: ${[...TURN_SESSION_DRIVERS.keys()].join(', ') || 'empty'})`,
250
250
  };
251
251
  }
252
- const binary = options.binary ?? (await this.resolveTurnBinary(agent));
252
+ let binary: TurnBinary;
253
+ try {
254
+ binary = options.binary ?? (await this.resolveTurnBinary(agent));
255
+ } catch (error) {
256
+ // Probe explosions (executor bugs, missing shims) are refusals, never throws (AC1).
257
+ return {
258
+ ok: false,
259
+ reason: 'spawn-failed',
260
+ detail: `binary probe failed for agent '${agent}': ${error instanceof Error ? error.message : String(error)}`,
261
+ };
262
+ }
253
263
  return await openTurnSessionWithDriver({
254
264
  agent,
255
265
  driver,
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Claude Code stream-json turn-session driver (task 1276, design `fleet-task-turn-execution.md`
3
+ * §5). Speaks the protocol observed on the installed 2.1.308 binary (captured 2026-10-22, fixtures
4
+ * under `tests/fixtures/turn-drivers/claude`):
5
+ *
6
+ * - `claude -p --input-format stream-json --output-format stream-json --verbose` keeps ONE process
7
+ * alive reading user-message JSONL envelopes; each turn ends with exactly one `result` record.
8
+ * - Startup noise (`system hook_started/hook_response` rows, every record carrying the constant
9
+ * `session_id`) precedes a `system init`; every later turn repeats `init → … → result`.
10
+ * - `result.is_error` carries failure — API errors keep `subtype: 'success'` with `is_error: true`
11
+ * (exit 1); interrupts answer an interrupt control request with `error_during_execution`.
12
+ *
13
+ * Records echo no runner turn id, so `decode` stamps the facade-provided `context.turnId` on every
14
+ * frame; the first turn's `init` may be consumed as pre-session noise, in which case acceptance is
15
+ * inferred from the first frame of an unaccepted turn (see `TurnDecodeContext`).
16
+ */
17
+ import type { AgentName } from '../agents/shims';
18
+ import { claudeStreamJsonFrame } from '../agents/shims';
19
+ import type {
20
+ TurnBinary,
21
+ TurnDecodeContext,
22
+ TurnHandshake,
23
+ TurnSessionDriver,
24
+ TurnSessionPolicy,
25
+ TurnWireEvent,
26
+ TurnWireTerminal,
27
+ } from '../turn-session';
28
+
29
+ /** Claude Code version this driver's protocol was qualified against (probed, never fabricated). */
30
+ export const CLAUDE_TURN_VERIFIED_VERSION = '2.1.308';
31
+
32
+ /** Upper bound on startup rows scanned for a session id before the handshake gives up. */
33
+ export const HANDSHAKE_MAX_LINES = 64;
34
+
35
+ interface ClaudeRecord {
36
+ type?: string;
37
+ subtype?: string;
38
+ session_id?: string;
39
+ is_error?: boolean;
40
+ result?: string;
41
+ }
42
+
43
+ /**
44
+ * Build the driver. `spawn` overrides the child argv for tests (the registry instance spawns the
45
+ * real `claude` binary); production callers use `TURN_SESSION_DRIVERS.get('claude')`.
46
+ */
47
+ export function createClaudeTurnSessionDriver(
48
+ options: { spawn?: { command: string; args: string[] } } = {},
49
+ ): TurnSessionDriver {
50
+ return {
51
+ agent: 'claude' as AgentName,
52
+ qualify: (binary: TurnBinary) =>
53
+ binary.version === CLAUDE_TURN_VERIFIED_VERSION
54
+ ? { qualified: true }
55
+ : {
56
+ qualified: false,
57
+ reason: `claude ${binary.version ?? '<no version>'} is not the qualified stream-json version ${CLAUDE_TURN_VERIFIED_VERSION}`,
58
+ },
59
+ spawnArgv: (_binary: TurnBinary, policy: TurnSessionPolicy) =>
60
+ options.spawn ?? {
61
+ command: 'claude',
62
+ args: [
63
+ '-p',
64
+ '--input-format',
65
+ 'stream-json',
66
+ '--output-format',
67
+ 'stream-json',
68
+ // stream-json output refuses to start without --verbose (observed 2.1.308).
69
+ '--verbose',
70
+ ...(policy.model !== undefined ? ['--model', policy.model] : []),
71
+ ...(policy.role !== undefined ? ['--append-system-prompt', policy.role] : []),
72
+ ],
73
+ },
74
+ handshake: async (pull: (timeoutMs: number) => Promise<string | null>): Promise<TurnHandshake> => {
75
+ // Startup rows (hook noise, init) all carry the constant session id; the first record
76
+ // that has one is enough. Leave everything else on the stream for the pump so the
77
+ // first turn still sees its `init` (acceptance) if handshake stopped before it.
78
+ for (let seen = 0; seen < HANDSHAKE_MAX_LINES; seen += 1) {
79
+ const line = await pull(2_000);
80
+ if (line === null) return null; // EOF or timeout before any session evidence
81
+ let record: ClaudeRecord;
82
+ try {
83
+ record = JSON.parse(line) as ClaudeRecord;
84
+ } catch {
85
+ continue; // pre-protocol noise; the pump's decoder is the strict one
86
+ }
87
+ if (typeof record.session_id === 'string') return { nativeSessionId: record.session_id };
88
+ }
89
+ return null;
90
+ },
91
+ encodeTurn: (input: { turnId: string; prompt: string; correlation: { runId: string } }) =>
92
+ claudeStreamJsonFrame(input.prompt),
93
+ decode: (line: string, context?: TurnDecodeContext): TurnWireEvent[] => {
94
+ let record: ClaudeRecord;
95
+ try {
96
+ record = JSON.parse(line) as ClaudeRecord;
97
+ } catch {
98
+ // Plain Error, not TurnProtocolError: importing the class would make this module
99
+ // a runtime dependency of turn-session.ts (which registers this driver). The pump
100
+ // settles contract-violation for ANY decoder throw, which is the real contract.
101
+ const error = new Error(`claude stream-json: malformed JSON line: ${line.slice(0, 80)}`);
102
+ error.name = 'TurnProtocolError';
103
+ throw error;
104
+ }
105
+ const turnId = context?.turnId ?? null;
106
+ const events: TurnWireEvent[] = [];
107
+ if (record.type === 'system' && record.subtype === 'init' && context !== undefined && !context.accepted) {
108
+ events.push({ turnId, type: 'accepted' });
109
+ }
110
+ if (record.type === 'assistant') {
111
+ // A turn whose boundary init was consumed still accepts on its first output. (The
112
+ // init branch above is the only accepted source, and it never fires for this record.)
113
+ if (context !== undefined && !context.accepted) {
114
+ events.push({ turnId, type: 'accepted' });
115
+ }
116
+ events.push({ turnId, type: 'output', data: record });
117
+ return events;
118
+ }
119
+ if (record.type === 'result') {
120
+ const terminal: TurnWireTerminal = {
121
+ kind: record.is_error === true ? 'failure' : 'success',
122
+ ...(typeof record.session_id === 'string' ? { nativeSessionId: record.session_id } : {}),
123
+ ...(typeof record.result === 'string' ? { finalText: record.result } : {}),
124
+ ...(record.is_error === true
125
+ ? { reason: `claude result subtype '${record.subtype ?? 'unknown'}' reported an error` }
126
+ : {}),
127
+ };
128
+ events.push({ turnId, type: 'terminal', terminal });
129
+ return events;
130
+ }
131
+ return events; // system/rate_limit_event/control_response/unknown — tolerated noise
132
+ },
133
+ encodeCancel: (reason: string) =>
134
+ // Interrupt control request (observed 2.1.308): acknowledged with a `control_response`,
135
+ // then the interrupted turn settles with a `result error_during_execution` record.
136
+ `${JSON.stringify({ type: 'control_request', request_id: `cancel-${reason}`, request: { subtype: 'interrupt' } })}\n`,
137
+ };
138
+ }
@@ -1,6 +1,7 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
2
  import type { PipeProcess, ProcessExecutor } from '@gobing-ai/ts-runtime';
3
3
  import type { AgentName } from './agents/shims';
4
+ import { createClaudeTurnSessionDriver } from './turn-drivers/claude-stream-json';
4
5
 
5
6
  /**
6
7
  * Correlated warm-turn session facade (task 1284, design `fleet-task-turn-execution.md` §4–5,
@@ -121,6 +122,18 @@ export class TurnProtocolError extends Error {
121
122
  }
122
123
  }
123
124
 
125
+ /**
126
+ * Session-scoped decode attribution (task 1276): the facade hands each driver the caller's current
127
+ * active turn, when one exists. Protocols whose records echo a runner turn id (the fake driver)
128
+ * ignore it; protocols like claude stream-json — whose records carry only a constant session id —
129
+ * stamp `turnId` on every frame so `route` can attribute them. `accepted` lets a driver infer
130
+ * acceptance for turns whose boundary record was consumed by the handshake (claude turn 1).
131
+ */
132
+ export interface TurnDecodeContext {
133
+ readonly turnId: string;
134
+ readonly accepted: boolean;
135
+ }
136
+
124
137
  /** Handshake result: the native session id when the agent reported one during startup. */
125
138
  export type TurnHandshake = { nativeSessionId?: string } | null;
126
139
 
@@ -139,8 +152,12 @@ export interface TurnSessionDriver {
139
152
  */
140
153
  handshake?(pull: (timeoutMs: number) => Promise<string | null>): Promise<TurnHandshake>;
141
154
  encodeTurn(input: { turnId: string; prompt: string; correlation: TurnCorrelation }): string;
142
- /** Decode one stdout line into zero or more frames; throws {@link TurnProtocolError} on malformed input. */
143
- decode(line: string): TurnWireEvent[];
155
+ /**
156
+ * Decode one stdout line into zero or more frames; throws {@link TurnProtocolError} on
157
+ * malformed input. `context` carries the session's current active turn for drivers whose
158
+ * protocol cannot self-attribute (claude); drivers that echo turn ids may ignore it.
159
+ */
160
+ decode(line: string, context?: TurnDecodeContext): TurnWireEvent[];
144
161
  encodeCancel(reason: string): string;
145
162
  }
146
163
 
@@ -153,8 +170,14 @@ export type OpenTurnSessionResult =
153
170
  detail: string;
154
171
  };
155
172
 
156
- /** Built-in driver registry. Empty in 0.x by design — real drivers land with qualification evidence. */
157
- export const TURN_SESSION_DRIVERS: ReadonlyMap<AgentName, TurnSessionDriver> = new Map();
173
+ /**
174
+ * Built-in driver registry. Entries land only with recorded qualification evidence (anti-pattern:
175
+ * registration without evidence): claude 2.1.308 stream-json (task 1276, fixtures under
176
+ * `tests/fixtures/turn-drivers/claude`). 0.x shipped this empty by design.
177
+ */
178
+ export const TURN_SESSION_DRIVERS: ReadonlyMap<AgentName, TurnSessionDriver> = new Map([
179
+ ['claude', createClaudeTurnSessionDriver()],
180
+ ]);
158
181
 
159
182
  /** How long `cancel()` waits for native terminal evidence before resolving `outcome-unknown`. */
160
183
  export const TURN_CANCEL_GRACE_MS = 5_000;
@@ -514,7 +537,12 @@ class TurnSessionImpl implements TurnSession {
514
537
  // settles contract-violation.
515
538
  try {
516
539
  for await (const line of this.lines) {
517
- const wires = this.driver.decode(line);
540
+ const active = this.active;
541
+ const context: TurnDecodeContext | undefined =
542
+ active === undefined
543
+ ? undefined
544
+ : { turnId: active.turnId, accepted: active.acceptedAt !== undefined };
545
+ const wires = this.driver.decode(line, context);
518
546
  for (const wire of wires) this.route(wire);
519
547
  }
520
548
  } catch (error) {