@gobing-ai/ts-ai-runner 0.5.33 → 0.6.1
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.
- package/README.md +6 -2
- package/dist/agents/shims.d.ts +2 -0
- package/dist/agents/shims.d.ts.map +1 -1
- package/dist/agents/shims.js +6 -5
- package/dist/ai-runner.d.ts +12 -0
- package/dist/ai-runner.d.ts.map +1 -1
- package/dist/ai-runner.js +47 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/testing/fake-turn-agent.d.ts +2 -0
- package/dist/testing/fake-turn-agent.d.ts.map +1 -0
- package/dist/testing/fake-turn-agent.js +114 -0
- package/dist/testing/fake-turn-driver.d.ts +22 -0
- package/dist/testing/fake-turn-driver.d.ts.map +1 -0
- package/dist/testing/fake-turn-driver.js +66 -0
- package/dist/turn-drivers/claude-stream-json.d.ts +16 -0
- package/dist/turn-drivers/claude-stream-json.d.ts.map +1 -0
- package/dist/turn-drivers/claude-stream-json.js +100 -0
- package/dist/turn-session.d.ts +220 -0
- package/dist/turn-session.d.ts.map +1 -0
- package/dist/turn-session.js +463 -0
- package/package.json +8 -4
- package/src/agents/shims.ts +6 -5
- package/src/ai-runner.ts +65 -0
- package/src/index.ts +1 -0
- package/src/testing/fake-turn-agent.ts +123 -0
- package/src/testing/fake-turn-driver.ts +99 -0
- package/src/turn-drivers/claude-stream-json.ts +138 -0
- package/src/turn-session.ts +655 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gobing-ai/ts-ai-runner",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.1",
|
|
4
4
|
"description": "@gobing-ai/ts-ai-runner — Coding-agent shims, detection, doctor checks, and prompt execution.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"typescript",
|
|
@@ -28,6 +28,10 @@
|
|
|
28
28
|
".": {
|
|
29
29
|
"types": "./dist/index.d.ts",
|
|
30
30
|
"import": "./dist/index.js"
|
|
31
|
+
},
|
|
32
|
+
"./testing": {
|
|
33
|
+
"types": "./dist/testing/fake-turn-driver.d.ts",
|
|
34
|
+
"import": "./dist/testing/fake-turn-driver.js"
|
|
31
35
|
}
|
|
32
36
|
},
|
|
33
37
|
"files": [
|
|
@@ -47,12 +51,12 @@
|
|
|
47
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"
|
|
48
52
|
},
|
|
49
53
|
"dependencies": {
|
|
50
|
-
"@gobing-ai/ts-infra": "^0.
|
|
51
|
-
"@gobing-ai/ts-runtime": "^0.
|
|
54
|
+
"@gobing-ai/ts-infra": "^0.6.1",
|
|
55
|
+
"@gobing-ai/ts-runtime": "^0.6.1"
|
|
52
56
|
},
|
|
53
57
|
"devDependencies": {
|
|
54
58
|
"@types/bun": "1.4.3",
|
|
55
|
-
"@gobing-ai/ts-db": "^0.
|
|
59
|
+
"@gobing-ai/ts-db": "^0.6.1"
|
|
56
60
|
},
|
|
57
61
|
"publishConfig": {
|
|
58
62
|
"access": "public"
|
package/src/agents/shims.ts
CHANGED
|
@@ -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. */
|
|
@@ -550,10 +550,11 @@ const AGENT_SESSION_CAPABILITY: Readonly<Record<AgentName, AgentSessionCapabilit
|
|
|
550
550
|
supportsSessionDir: false,
|
|
551
551
|
supportsPersistentStdin: true,
|
|
552
552
|
supportsStructuredOutput: true,
|
|
553
|
-
verifiedAgainst: '2.1.
|
|
554
|
-
// Persistent stdin
|
|
555
|
-
//
|
|
556
|
-
//
|
|
553
|
+
verifiedAgainst: '2.1.308',
|
|
554
|
+
// Persistent stdin re-verified with a live two-turn capture on 2026-10-22 (task 1276): one
|
|
555
|
+
// process served two keyed turns and emitted one `result` record per turn with a constant
|
|
556
|
+
// session id (fixtures: ai-runner tests/fixtures/turn-drivers/claude). Stream-json input
|
|
557
|
+
// only works with --print, and stream-json output requires --verbose (observed 2.1.308).
|
|
557
558
|
note: 'no session-dir flag — sessionDir is ignored (best-effort isolate)',
|
|
558
559
|
},
|
|
559
560
|
codex: {
|
package/src/ai-runner.ts
CHANGED
|
@@ -17,6 +17,14 @@ import {
|
|
|
17
17
|
QuotaObservationProducer,
|
|
18
18
|
} from './quota';
|
|
19
19
|
import { translateSlashCommand } from './slash-command';
|
|
20
|
+
import {
|
|
21
|
+
type OpenTurnSessionResult,
|
|
22
|
+
openTurnSessionWithDriver,
|
|
23
|
+
TURN_SESSION_DRIVERS,
|
|
24
|
+
type TurnBinary,
|
|
25
|
+
type TurnSessionDriver,
|
|
26
|
+
type TurnSessionPolicy,
|
|
27
|
+
} from './turn-session';
|
|
20
28
|
|
|
21
29
|
/** Result returned by every AI runner dispatch method. */
|
|
22
30
|
export interface AgentRunResult {
|
|
@@ -220,6 +228,63 @@ export class AiRunner {
|
|
|
220
228
|
return command === null ? null : this.invoke(agent, 'auth', command, options, true);
|
|
221
229
|
}
|
|
222
230
|
|
|
231
|
+
/** Open a correlated warm-turn session (task 1284). Expected refusals are typed, never throws. */
|
|
232
|
+
async openTurnSession(
|
|
233
|
+
agent: AgentName,
|
|
234
|
+
options: {
|
|
235
|
+
policy: TurnSessionPolicy;
|
|
236
|
+
/** Test/injection seam; defaults to the built-in registry (empty in 0.x). */
|
|
237
|
+
driver?: TurnSessionDriver;
|
|
238
|
+
/** Pre-resolved binary identity; defaults to probing the shim's version command. */
|
|
239
|
+
binary?: TurnBinary;
|
|
240
|
+
handshakeTimeoutMs?: number;
|
|
241
|
+
},
|
|
242
|
+
): Promise<OpenTurnSessionResult> {
|
|
243
|
+
// Driver lookup BEFORE any binary probe: an unsupported agent must not spawn (AC1).
|
|
244
|
+
const driver = options.driver ?? TURN_SESSION_DRIVERS.get(agent);
|
|
245
|
+
if (driver === undefined) {
|
|
246
|
+
return {
|
|
247
|
+
ok: false,
|
|
248
|
+
reason: 'unsupported-agent',
|
|
249
|
+
detail: `no turn-session driver registered for agent '${agent}' (registry: ${[...TURN_SESSION_DRIVERS.keys()].join(', ') || 'empty'})`,
|
|
250
|
+
};
|
|
251
|
+
}
|
|
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
|
+
}
|
|
263
|
+
return await openTurnSessionWithDriver({
|
|
264
|
+
agent,
|
|
265
|
+
driver,
|
|
266
|
+
policy: options.policy,
|
|
267
|
+
binary,
|
|
268
|
+
processExecutor: this.processExecutor,
|
|
269
|
+
...(options.handshakeTimeoutMs !== undefined ? { handshakeTimeoutMs: options.handshakeTimeoutMs } : {}),
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Probe the agent binary for qualification: path + best-effort semver from the version command. */
|
|
274
|
+
private async resolveTurnBinary(agent: AgentName): Promise<TurnBinary> {
|
|
275
|
+
const command = getAgentShim(agent).getVersionCommand();
|
|
276
|
+
const result = await this.processExecutor.run({
|
|
277
|
+
command: command.command,
|
|
278
|
+
args: command.args,
|
|
279
|
+
label: `ai-runner.${agent}.version`,
|
|
280
|
+
rejectOnError: false,
|
|
281
|
+
forceBuffered: true,
|
|
282
|
+
...(this.defaultCwd !== undefined ? { cwd: this.defaultCwd } : {}),
|
|
283
|
+
});
|
|
284
|
+
const match = /[0-9]+\.[0-9]+\.[0-9]+[^\s]*/.exec(result.stdout);
|
|
285
|
+
return { path: command.command, version: match?.[0] ?? null };
|
|
286
|
+
}
|
|
287
|
+
|
|
223
288
|
private async invoke(
|
|
224
289
|
agent: AgentName,
|
|
225
290
|
operation: string,
|
package/src/index.ts
CHANGED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Scripted fake turn agent for turn-session tests (task 1284). A REAL child process: it speaks a
|
|
3
|
+
* JSONL protocol over stdin/stdout, replaying a script passed as `argv[2]` (JSON array). Only for
|
|
4
|
+
* tests via `./testing` — never imported by library code.
|
|
5
|
+
*
|
|
6
|
+
* Protocol (parent → child):
|
|
7
|
+
* {"type":"turn","turnId":...,"prompt":...,"correlation":{...}} start replaying the script
|
|
8
|
+
* {"type":"cancel","reason":...} flush pending sleeps (unless ignored)
|
|
9
|
+
* Protocol (child → parent):
|
|
10
|
+
* {"ctl":"ready","nativeSessionId":...} handshake (auto-emitted at startup)
|
|
11
|
+
* {"turn":T,"type":"accepted"} | {"turn":T,"type":"output","data":...}
|
|
12
|
+
* {"turn":T,"type":"terminal","kind":"success"|"failure",...}
|
|
13
|
+
* {"ctl":"exit"} echoes are the raw scripted `stray` lines.
|
|
14
|
+
*/
|
|
15
|
+
import { createInterface } from 'node:readline';
|
|
16
|
+
|
|
17
|
+
interface FakeAction {
|
|
18
|
+
op: 'ready' | 'accept' | 'output' | 'terminal' | 'stray' | 'sleep' | 'ignore-cancel' | 'flood' | 'exit';
|
|
19
|
+
nativeSessionId?: string;
|
|
20
|
+
data?: string;
|
|
21
|
+
kind?: 'success' | 'failure';
|
|
22
|
+
nativeTurnId?: string;
|
|
23
|
+
finalText?: string;
|
|
24
|
+
line?: Record<string, unknown>;
|
|
25
|
+
ms?: number;
|
|
26
|
+
code?: number;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const script: FakeAction[] = JSON.parse(process.argv[2] ?? '[]');
|
|
30
|
+
const readyAction = script.find((action) => action.op === 'ready');
|
|
31
|
+
const turnActions = script.filter((action) => action.op !== 'ready');
|
|
32
|
+
/** Skip the startup ready frame when the script dies immediately (broken-agent handshake test). */
|
|
33
|
+
const startsWithExit = script[0]?.op === 'exit';
|
|
34
|
+
|
|
35
|
+
let currentTurnId: string | null = null;
|
|
36
|
+
let ignoreCancel = false;
|
|
37
|
+
let flushing = false;
|
|
38
|
+
/** Pending sleep timers mapped to their resolvers so a cancel can wake them (not just clear them). */
|
|
39
|
+
const sleepers = new Map<NodeJS.Timeout, () => void>();
|
|
40
|
+
|
|
41
|
+
function send(line: Record<string, unknown>): void {
|
|
42
|
+
process.stdout.write(`${JSON.stringify(line)}\n`);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Parent may drop stdout (kill/close) while frames are in flight — exit instead of crashing on EPIPE.
|
|
46
|
+
process.stdout.on('error', () => process.exit(0));
|
|
47
|
+
|
|
48
|
+
// Handshake: explicit ready action first (nativeSessionId control), else the default.
|
|
49
|
+
if (readyAction !== undefined) {
|
|
50
|
+
send({
|
|
51
|
+
ctl: 'ready',
|
|
52
|
+
...(readyAction.nativeSessionId !== undefined ? { nativeSessionId: readyAction.nativeSessionId } : {}),
|
|
53
|
+
});
|
|
54
|
+
} else if (!startsWithExit) {
|
|
55
|
+
send({ ctl: 'ready', nativeSessionId: 'fake-session-1' });
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function sleep(ms: number): Promise<void> {
|
|
59
|
+
return new Promise((resolve) => {
|
|
60
|
+
const timer = setTimeout(() => {
|
|
61
|
+
sleepers.delete(timer);
|
|
62
|
+
resolve();
|
|
63
|
+
}, ms);
|
|
64
|
+
sleepers.set(timer, resolve);
|
|
65
|
+
if (flushing) {
|
|
66
|
+
clearTimeout(timer);
|
|
67
|
+
sleepers.delete(timer);
|
|
68
|
+
resolve();
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function replay(): Promise<void> {
|
|
74
|
+
for (const action of turnActions) {
|
|
75
|
+
if (action.op === 'accept') send({ turn: currentTurnId, type: 'accepted' });
|
|
76
|
+
else if (action.op === 'output') send({ turn: currentTurnId, type: 'output', data: action.data ?? '' });
|
|
77
|
+
else if (action.op === 'terminal')
|
|
78
|
+
send({
|
|
79
|
+
turn: currentTurnId,
|
|
80
|
+
type: 'terminal',
|
|
81
|
+
kind: action.kind ?? 'success',
|
|
82
|
+
...(action.nativeTurnId !== undefined ? { nativeTurnId: action.nativeTurnId } : {}),
|
|
83
|
+
...(action.finalText !== undefined ? { finalText: action.finalText } : {}),
|
|
84
|
+
});
|
|
85
|
+
else if (action.op === 'stray' && action.line !== undefined) send(action.line);
|
|
86
|
+
else if (action.op === 'flood')
|
|
87
|
+
// Written by the child so the >1MiB line never passes through argv (macOS E2BIG limit).
|
|
88
|
+
send({ turn: currentTurnId, type: 'output', data: 'x'.repeat(1024 * 1024 + 64) });
|
|
89
|
+
else if (action.op === 'sleep') await sleep(action.ms ?? 0);
|
|
90
|
+
else if (action.op === 'ignore-cancel') ignoreCancel = true;
|
|
91
|
+
else if (action.op === 'exit') process.exit(action.code ?? 0);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const rl = createInterface({ input: process.stdin });
|
|
96
|
+
rl.on('line', (raw) => {
|
|
97
|
+
let frame: Record<string, unknown>;
|
|
98
|
+
try {
|
|
99
|
+
frame = JSON.parse(raw) as Record<string, unknown>;
|
|
100
|
+
} catch {
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
if (frame.type === 'turn' && typeof frame.turnId === 'string') {
|
|
104
|
+
currentTurnId = frame.turnId;
|
|
105
|
+
flushing = false;
|
|
106
|
+
void replay();
|
|
107
|
+
} else if (frame.type === 'cancel') {
|
|
108
|
+
if (ignoreCancel) return;
|
|
109
|
+
// Answering cancel: wake pending sleeps so the scripted terminal arrives promptly.
|
|
110
|
+
flushing = true;
|
|
111
|
+
for (const [timer, resolve] of sleepers) {
|
|
112
|
+
clearTimeout(timer);
|
|
113
|
+
resolve();
|
|
114
|
+
}
|
|
115
|
+
sleepers.clear();
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
rl.on('close', () => {
|
|
119
|
+
process.exit(0);
|
|
120
|
+
});
|
|
121
|
+
// Scripts that lead with `exit` run at startup (direct child drives and handshake tests);
|
|
122
|
+
// turn-dependent actions replay with a null turnId in that mode.
|
|
123
|
+
if (startsWithExit) void replay();
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fake turn-session driver for tests (task 1284). Spawns a REAL child process
|
|
3
|
+
* (`fake-turn-agent.ts`) that replays a scripted JSONL protocol across the process boundary,
|
|
4
|
+
* so sessions are exercised end-to-end — never against an in-process stub of the transport.
|
|
5
|
+
* Exported from the `./testing` subpath only; never imported by library code.
|
|
6
|
+
*/
|
|
7
|
+
import type { TurnBinary, TurnHandshake, TurnSessionDriver, TurnSessionPolicy, TurnWireEvent } from '../turn-session';
|
|
8
|
+
import { TurnProtocolError } from '../turn-session';
|
|
9
|
+
|
|
10
|
+
/** One scripted child action (see `fake-turn-agent.ts` for the wire semantics). */
|
|
11
|
+
export interface FakeTurnAction {
|
|
12
|
+
op: 'ready' | 'accept' | 'output' | 'terminal' | 'stray' | 'sleep' | 'ignore-cancel' | 'flood' | 'exit';
|
|
13
|
+
nativeSessionId?: string;
|
|
14
|
+
data?: string;
|
|
15
|
+
kind?: 'success' | 'failure';
|
|
16
|
+
nativeTurnId?: string;
|
|
17
|
+
finalText?: string;
|
|
18
|
+
line?: Record<string, unknown>;
|
|
19
|
+
ms?: number;
|
|
20
|
+
code?: number;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Path of the child script: source tree in dev/checkouts, compiled sibling in built packages. */
|
|
24
|
+
function fakeTurnAgentPath(): string {
|
|
25
|
+
// No node:path/node:fs (runtime-boundaries rule): import.meta.dir is already absolute, so a
|
|
26
|
+
// separator-safe marker check picks the compiled sibling in built packages.
|
|
27
|
+
const isBuilt = import.meta.dir.replace(/\\/g, '/').includes('/dist/');
|
|
28
|
+
return `${import.meta.dir}/fake-turn-agent.${isBuilt ? 'js' : 'ts'}`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
interface FakeFrame {
|
|
32
|
+
ctl?: string;
|
|
33
|
+
turn?: string | null;
|
|
34
|
+
type?: string;
|
|
35
|
+
data?: unknown;
|
|
36
|
+
kind?: string;
|
|
37
|
+
nativeTurnId?: string;
|
|
38
|
+
nativeSessionId?: string;
|
|
39
|
+
finalText?: string;
|
|
40
|
+
reason?: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Build a turn-session driver over the scripted child. `overrides` tailors qualify/agent for refusal tests. */
|
|
44
|
+
export function createFakeTurnSessionDriver(
|
|
45
|
+
actions: FakeTurnAction[],
|
|
46
|
+
overrides: Partial<Pick<TurnSessionDriver, 'qualify' | 'agent'>> = {},
|
|
47
|
+
): TurnSessionDriver {
|
|
48
|
+
const scriptJson = JSON.stringify(actions);
|
|
49
|
+
const driver: TurnSessionDriver = {
|
|
50
|
+
agent: overrides.agent ?? 'pi',
|
|
51
|
+
qualify: overrides.qualify ?? (() => ({ qualified: true })),
|
|
52
|
+
spawnArgv: (_binary: TurnBinary, _policy: TurnSessionPolicy) => ({
|
|
53
|
+
command: process.execPath,
|
|
54
|
+
args: [fakeTurnAgentPath(), scriptJson],
|
|
55
|
+
}),
|
|
56
|
+
handshake: async (pull: (timeoutMs: number) => Promise<string | null>): Promise<TurnHandshake> => {
|
|
57
|
+
const raw = await pull(2_000);
|
|
58
|
+
if (raw === null) return null; // EOF or timeout before ready
|
|
59
|
+
const frame = JSON.parse(raw) as FakeFrame;
|
|
60
|
+
if (frame.ctl !== 'ready') return null;
|
|
61
|
+
return frame.nativeSessionId !== undefined ? { nativeSessionId: frame.nativeSessionId } : null;
|
|
62
|
+
},
|
|
63
|
+
encodeTurn: (input) => `${JSON.stringify({ type: 'turn', ...input })}\n`,
|
|
64
|
+
decode: (line: string): TurnWireEvent[] => {
|
|
65
|
+
let frame: FakeFrame & { ctl?: string };
|
|
66
|
+
try {
|
|
67
|
+
frame = JSON.parse(line) as FakeFrame & { ctl?: string };
|
|
68
|
+
} catch {
|
|
69
|
+
throw new TurnProtocolError(`malformed frame: ${line.slice(0, 80)}`);
|
|
70
|
+
}
|
|
71
|
+
if (frame.ctl !== undefined) return []; // control frames (ready) are handshake-only
|
|
72
|
+
if (frame.type !== 'accepted' && frame.type !== 'output' && frame.type !== 'terminal') {
|
|
73
|
+
throw new TurnProtocolError(`unknown frame type: ${String(frame.type)}`);
|
|
74
|
+
}
|
|
75
|
+
return [
|
|
76
|
+
{
|
|
77
|
+
turnId: frame.turn ?? null,
|
|
78
|
+
type: frame.type,
|
|
79
|
+
...(frame.data !== undefined ? { data: frame.data } : {}),
|
|
80
|
+
...(frame.type === 'terminal'
|
|
81
|
+
? {
|
|
82
|
+
terminal: {
|
|
83
|
+
kind: frame.kind === 'failure' ? 'failure' : 'success',
|
|
84
|
+
...(frame.nativeTurnId !== undefined ? { nativeTurnId: frame.nativeTurnId } : {}),
|
|
85
|
+
...(frame.nativeSessionId !== undefined
|
|
86
|
+
? { nativeSessionId: frame.nativeSessionId }
|
|
87
|
+
: {}),
|
|
88
|
+
...(frame.finalText !== undefined ? { finalText: frame.finalText } : {}),
|
|
89
|
+
...(frame.reason !== undefined ? { reason: frame.reason } : {}),
|
|
90
|
+
},
|
|
91
|
+
}
|
|
92
|
+
: {}),
|
|
93
|
+
},
|
|
94
|
+
];
|
|
95
|
+
},
|
|
96
|
+
encodeCancel: (reason: string) => `${JSON.stringify({ type: 'cancel', reason })}\n`,
|
|
97
|
+
};
|
|
98
|
+
return driver;
|
|
99
|
+
}
|
|
@@ -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
|
+
}
|