@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/README.md
CHANGED
|
@@ -29,6 +29,7 @@ bun add @gobing-ai/ts-ai-runner
|
|
|
29
29
|
| `MessageStore` / `DrainedMessage` | ai-runner-owned orchestration persistence port and minimal message view consumed by `TeamOrchestrator` |
|
|
30
30
|
| `TeamAgentProcess` | Manages a long-running agent subprocess with pipe-mode stdin/stdout |
|
|
31
31
|
| `TeamOrchestrator` | Loads specs, starts/stops agents, routes durable/live messages, and emits lifecycle events |
|
|
32
|
+
| `AiRunner.openTurnSession()` | Opens a correlated warm-turn session over one long-lived agent process: one turn at a time, typed refusals (never throws), acceptance separate from outcome, deterministic settlement (`success`/`failure`/`interrupted`/`not-started`/`outcome-unknown`/`contract-violation`), bounded cancel grace. 0.x ships the contract only — `TURN_SESSION_DRIVERS` is empty; real per-agent drivers land with qualification evidence. |
|
|
32
33
|
| `AgentEvents` / `AiRunnerProcessEvents` | Typed event maps for agent and process-level observability |
|
|
33
34
|
| `AGENT_SHIMS` / `TIER1_PRIORITY` / `TIER2_AGENTS` / `DISPLAY_ORDER` | Agent registry constants |
|
|
34
35
|
| `isAgentName()` | Type guard for supported agent identifiers |
|
|
@@ -929,8 +930,11 @@ safe to call more than once; the maker is not usable afterwards.
|
|
|
929
930
|
|
|
930
931
|
## Boundary Notes
|
|
931
932
|
|
|
932
|
-
-
|
|
933
|
-
|
|
933
|
+
- The turn-session facade (task 1284) owns only process/protocol mechanics (ADR-145): consumers own
|
|
934
|
+
policy, receipts and validation. `TURN_SESSION_DRIVERS` registers a driver only with recorded
|
|
935
|
+
`verifiedAgainst` qualification evidence; the scripted fake in `@gobing-ai/ts-ai-runner/testing`
|
|
936
|
+
is for consumer tests, never library code.
|
|
937
|
+
- This package is a command adapter, not an agent orchestration framework.- It does not install agent CLIs or manage credentials.
|
|
934
938
|
- It does not parse agent responses beyond process result capture.
|
|
935
939
|
- It keeps subprocess launching behind `ProcessExecutor` / `PipeProcess`, so tests can stay deterministic.
|
|
936
940
|
- Team-mode persistence is consumed through the ai-runner-owned `MessageStore` port; `InboxMessageDao` from `@gobing-ai/ts-db/inbox` is one structural provider. Host apps own migrations and adapter lifecycle, and `@gobing-ai/ts-db` is a development dependency of this package (only the DB-backed integration test resolves the concrete DAO).
|
package/dist/agents/shims.d.ts
CHANGED
|
@@ -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;IAClB,8EAA8E;IAC9E,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,2DAA2D;IAC3D,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,kCAAkC;IAClC,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;IAChB;;;;OAIG;IACH,SAAS,CAAC,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SAAS,CAAyB,CAAC;AAU1E;;;;;;;;;GASG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,SAAS,CAQrE;AAED;mEACmE;AACnE,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAElD;AAED,6EAA6E;AAC7E,wBAAgB,YAAY,CAAC,KAAK,EAAE,SAAS,GAAG,SAAS,CAMxD"}
|
package/dist/agents/shims.js
CHANGED
|
@@ -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',
|
|
@@ -427,10 +427,11 @@ const AGENT_SESSION_CAPABILITY = {
|
|
|
427
427
|
supportsSessionDir: false,
|
|
428
428
|
supportsPersistentStdin: true,
|
|
429
429
|
supportsStructuredOutput: true,
|
|
430
|
-
verifiedAgainst: '2.1.
|
|
431
|
-
// Persistent stdin
|
|
432
|
-
//
|
|
433
|
-
//
|
|
430
|
+
verifiedAgainst: '2.1.308',
|
|
431
|
+
// Persistent stdin re-verified with a live two-turn capture on 2026-10-22 (task 1276): one
|
|
432
|
+
// process served two keyed turns and emitted one `result` record per turn with a constant
|
|
433
|
+
// session id (fixtures: ai-runner tests/fixtures/turn-drivers/claude). Stream-json input
|
|
434
|
+
// only works with --print, and stream-json output requires --verbose (observed 2.1.308).
|
|
434
435
|
note: 'no session-dir flag — sessionDir is ignored (best-effort isolate)',
|
|
435
436
|
},
|
|
436
437
|
codex: {
|
package/dist/ai-runner.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { type ProcessExecutor, type ProcessOutputChunk, type TracerPort } from '
|
|
|
3
3
|
import { type AgentName, type PromptOptions, type ShimCommand } from './agents/shims';
|
|
4
4
|
import type { AgentEvents, AiRunnerProcessEvents } from './events';
|
|
5
5
|
import { type QuotaAttribution } from './quota';
|
|
6
|
+
import { type OpenTurnSessionResult, type TurnBinary, type TurnSessionDriver, type TurnSessionPolicy } from './turn-session';
|
|
6
7
|
/** Result returned by every AI runner dispatch method. */
|
|
7
8
|
export interface AgentRunResult {
|
|
8
9
|
/** Process exit code; null indicates signal or timeout termination. */
|
|
@@ -116,6 +117,17 @@ export declare class AiRunner {
|
|
|
116
117
|
buildPromptCommand(agent: AgentName, promptOptions: PromptOptions, options?: AgentRunOptions): ShimCommand;
|
|
117
118
|
/** Run an agent authentication command, or return null when unsupported. */
|
|
118
119
|
runAuthCommand(agent: AgentName, options?: AgentRunOptions): Promise<AgentRunResult> | null;
|
|
120
|
+
/** Open a correlated warm-turn session (task 1284). Expected refusals are typed, never throws. */
|
|
121
|
+
openTurnSession(agent: AgentName, options: {
|
|
122
|
+
policy: TurnSessionPolicy;
|
|
123
|
+
/** Test/injection seam; defaults to the built-in registry (empty in 0.x). */
|
|
124
|
+
driver?: TurnSessionDriver;
|
|
125
|
+
/** Pre-resolved binary identity; defaults to probing the shim's version command. */
|
|
126
|
+
binary?: TurnBinary;
|
|
127
|
+
handshakeTimeoutMs?: number;
|
|
128
|
+
}): Promise<OpenTurnSessionResult>;
|
|
129
|
+
/** Probe the agent binary for qualification: path + best-effort semver from the version command. */
|
|
130
|
+
private resolveTurnBinary;
|
|
119
131
|
private invoke;
|
|
120
132
|
}
|
|
121
133
|
/**
|
package/dist/ai-runner.d.ts.map
CHANGED
|
@@ -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,EAAE,KAAK,WAAW,EAAE,MAAM,gBAAgB,CAAC;AACpG,OAAO,KAAK,EAAE,WAAW,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AAEnE,OAAO,EAGH,KAAK,gBAAgB,EAExB,MAAM,SAAS,CAAC;
|
|
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,EAAE,KAAK,WAAW,EAAE,MAAM,gBAAgB,CAAC;AACpG,OAAO,KAAK,EAAE,WAAW,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AAEnE,OAAO,EAGH,KAAK,gBAAgB,EAExB,MAAM,SAAS,CAAC;AAEjB,OAAO,EACH,KAAK,qBAAqB,EAG1B,KAAK,UAAU,EACf,KAAK,iBAAiB,EACtB,KAAK,iBAAiB,EACzB,MAAM,gBAAgB,CAAC;AAExB,0DAA0D;AAC1D,MAAM,WAAW,cAAc;IAC3B,uEAAuE;IACvE,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,uBAAuB;IACvB,MAAM,EAAE,MAAM,CAAC;IACf,u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eAAoB,GAAG,WAAW;IAa9G,4EAA4E;IAC5E,cAAc,CAAC,KAAK,EAAE,SAAS,EAAE,OAAO,GAAE,eAAoB,GAAG,OAAO,CAAC,cAAc,CAAC,GAAG,IAAI;IAK/F,kGAAkG;IAC5F,eAAe,CACjB,KAAK,EAAE,SAAS,EAChB,OAAO,EAAE;QACL,MAAM,EAAE,iBAAiB,CAAC;QAC1B,6EAA6E;QAC7E,MAAM,CAAC,EAAE,iBAAiB,CAAC;QAC3B,oFAAoF;QACpF,MAAM,CAAC,EAAE,UAAU,CAAC;QACpB,kBAAkB,CAAC,EAAE,MAAM,CAAC;KAC/B,GACF,OAAO,CAAC,qBAAqB,CAAC;IA+BjC,oGAAoG;YACtF,iBAAiB;YAcjB,MAAM;CAuEvB;AAWD;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAC7B,KAAK,EAAE,SAAS,EAChB,aAAa,EAAE,aAAa,EAC5B,OAAO,EAAE;IAAE,SAAS,EAAE,MAAM,CAAA;CAAE,GAC/B,WAAW,CAKb"}
|
package/dist/ai-runner.js
CHANGED
|
@@ -4,6 +4,7 @@ import { getAgentShim } from './agents/shims.js';
|
|
|
4
4
|
import { buildIdentityPreamble } from './identity.js';
|
|
5
5
|
import { buildQuotaObservation, classifyQuotaErrorRecord, QuotaObservationProducer, } from './quota.js';
|
|
6
6
|
import { translateSlashCommand } from './slash-command.js';
|
|
7
|
+
import { openTurnSessionWithDriver, TURN_SESSION_DRIVERS, } from './turn-session.js';
|
|
7
8
|
/**
|
|
8
9
|
* Public environment-variable contract for agent run correlation.
|
|
9
10
|
*
|
|
@@ -117,6 +118,52 @@ export class AiRunner {
|
|
|
117
118
|
const command = getAgentShim(agent).getAuthCommand();
|
|
118
119
|
return command === null ? null : this.invoke(agent, 'auth', command, options, true);
|
|
119
120
|
}
|
|
121
|
+
/** Open a correlated warm-turn session (task 1284). Expected refusals are typed, never throws. */
|
|
122
|
+
async openTurnSession(agent, options) {
|
|
123
|
+
// Driver lookup BEFORE any binary probe: an unsupported agent must not spawn (AC1).
|
|
124
|
+
const driver = options.driver ?? TURN_SESSION_DRIVERS.get(agent);
|
|
125
|
+
if (driver === undefined) {
|
|
126
|
+
return {
|
|
127
|
+
ok: false,
|
|
128
|
+
reason: 'unsupported-agent',
|
|
129
|
+
detail: `no turn-session driver registered for agent '${agent}' (registry: ${[...TURN_SESSION_DRIVERS.keys()].join(', ') || 'empty'})`,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
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
|
+
}
|
|
144
|
+
return await openTurnSessionWithDriver({
|
|
145
|
+
agent,
|
|
146
|
+
driver,
|
|
147
|
+
policy: options.policy,
|
|
148
|
+
binary,
|
|
149
|
+
processExecutor: this.processExecutor,
|
|
150
|
+
...(options.handshakeTimeoutMs !== undefined ? { handshakeTimeoutMs: options.handshakeTimeoutMs } : {}),
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
/** Probe the agent binary for qualification: path + best-effort semver from the version command. */
|
|
154
|
+
async resolveTurnBinary(agent) {
|
|
155
|
+
const command = getAgentShim(agent).getVersionCommand();
|
|
156
|
+
const result = await this.processExecutor.run({
|
|
157
|
+
command: command.command,
|
|
158
|
+
args: command.args,
|
|
159
|
+
label: `ai-runner.${agent}.version`,
|
|
160
|
+
rejectOnError: false,
|
|
161
|
+
forceBuffered: true,
|
|
162
|
+
...(this.defaultCwd !== undefined ? { cwd: this.defaultCwd } : {}),
|
|
163
|
+
});
|
|
164
|
+
const match = /[0-9]+\.[0-9]+\.[0-9]+[^\s]*/.exec(result.stdout);
|
|
165
|
+
return { path: command.command, version: match?.[0] ?? null };
|
|
166
|
+
}
|
|
120
167
|
async invoke(agent, operation, command, options, forceBuffered) {
|
|
121
168
|
const label = `ai-runner.${agent}.${operation}`;
|
|
122
169
|
this.logger.debug('invoke', { label, command: command.command, args: command.args.join(' ') });
|
package/dist/index.d.ts
CHANGED
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,kBAAkB,CAAC;AACjC,cAAc,cAAc,CAAC;AAC7B,cAAc,qBAAqB,CAAC;AACpC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,aAAa,CAAC;AAC5B,cAAc,2BAA2B,CAAC;AAC1C,cAAc,mBAAmB,CAAC;AAClC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,kBAAkB,CAAC;AACjC,cAAc,uBAAuB,CAAC;AACtC,cAAc,iBAAiB,CAAC;AAChC,cAAc,UAAU,CAAC;AACzB,cAAc,YAAY,CAAC;AAC3B,cAAc,iBAAiB,CAAC;AAChC,cAAc,YAAY,CAAC;AAC3B,cAAc,sBAAsB,CAAC;AACrC,cAAc,SAAS,CAAC;AACxB,cAAc,iBAAiB,CAAC;AAChC,cAAc,sBAAsB,CAAC;AACrC,cAAc,qBAAqB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,kBAAkB,CAAC;AACjC,cAAc,cAAc,CAAC;AAC7B,cAAc,qBAAqB,CAAC;AACpC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,aAAa,CAAC;AAC5B,cAAc,2BAA2B,CAAC;AAC1C,cAAc,mBAAmB,CAAC;AAClC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,kBAAkB,CAAC;AACjC,cAAc,uBAAuB,CAAC;AACtC,cAAc,iBAAiB,CAAC;AAChC,cAAc,UAAU,CAAC;AACzB,cAAc,YAAY,CAAC;AAC3B,cAAc,iBAAiB,CAAC;AAChC,cAAc,YAAY,CAAC;AAC3B,cAAc,sBAAsB,CAAC;AACrC,cAAc,SAAS,CAAC;AACxB,cAAc,iBAAiB,CAAC;AAChC,cAAc,sBAAsB,CAAC;AACrC,cAAc,qBAAqB,CAAC;AACpC,cAAc,gBAAgB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fake-turn-agent.d.ts","sourceRoot":"","sources":["../../src/testing/fake-turn-agent.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,114 @@
|
|
|
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
|
+
const script = JSON.parse(process.argv[2] ?? '[]');
|
|
17
|
+
const readyAction = script.find((action) => action.op === 'ready');
|
|
18
|
+
const turnActions = script.filter((action) => action.op !== 'ready');
|
|
19
|
+
/** Skip the startup ready frame when the script dies immediately (broken-agent handshake test). */
|
|
20
|
+
const startsWithExit = script[0]?.op === 'exit';
|
|
21
|
+
let currentTurnId = null;
|
|
22
|
+
let ignoreCancel = false;
|
|
23
|
+
let flushing = false;
|
|
24
|
+
/** Pending sleep timers mapped to their resolvers so a cancel can wake them (not just clear them). */
|
|
25
|
+
const sleepers = new Map();
|
|
26
|
+
function send(line) {
|
|
27
|
+
process.stdout.write(`${JSON.stringify(line)}\n`);
|
|
28
|
+
}
|
|
29
|
+
// Parent may drop stdout (kill/close) while frames are in flight — exit instead of crashing on EPIPE.
|
|
30
|
+
process.stdout.on('error', () => process.exit(0));
|
|
31
|
+
// Handshake: explicit ready action first (nativeSessionId control), else the default.
|
|
32
|
+
if (readyAction !== undefined) {
|
|
33
|
+
send({
|
|
34
|
+
ctl: 'ready',
|
|
35
|
+
...(readyAction.nativeSessionId !== undefined ? { nativeSessionId: readyAction.nativeSessionId } : {}),
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
else if (!startsWithExit) {
|
|
39
|
+
send({ ctl: 'ready', nativeSessionId: 'fake-session-1' });
|
|
40
|
+
}
|
|
41
|
+
function sleep(ms) {
|
|
42
|
+
return new Promise((resolve) => {
|
|
43
|
+
const timer = setTimeout(() => {
|
|
44
|
+
sleepers.delete(timer);
|
|
45
|
+
resolve();
|
|
46
|
+
}, ms);
|
|
47
|
+
sleepers.set(timer, resolve);
|
|
48
|
+
if (flushing) {
|
|
49
|
+
clearTimeout(timer);
|
|
50
|
+
sleepers.delete(timer);
|
|
51
|
+
resolve();
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
async function replay() {
|
|
56
|
+
for (const action of turnActions) {
|
|
57
|
+
if (action.op === 'accept')
|
|
58
|
+
send({ turn: currentTurnId, type: 'accepted' });
|
|
59
|
+
else if (action.op === 'output')
|
|
60
|
+
send({ turn: currentTurnId, type: 'output', data: action.data ?? '' });
|
|
61
|
+
else if (action.op === 'terminal')
|
|
62
|
+
send({
|
|
63
|
+
turn: currentTurnId,
|
|
64
|
+
type: 'terminal',
|
|
65
|
+
kind: action.kind ?? 'success',
|
|
66
|
+
...(action.nativeTurnId !== undefined ? { nativeTurnId: action.nativeTurnId } : {}),
|
|
67
|
+
...(action.finalText !== undefined ? { finalText: action.finalText } : {}),
|
|
68
|
+
});
|
|
69
|
+
else if (action.op === 'stray' && action.line !== undefined)
|
|
70
|
+
send(action.line);
|
|
71
|
+
else if (action.op === 'flood')
|
|
72
|
+
// Written by the child so the >1MiB line never passes through argv (macOS E2BIG limit).
|
|
73
|
+
send({ turn: currentTurnId, type: 'output', data: 'x'.repeat(1024 * 1024 + 64) });
|
|
74
|
+
else if (action.op === 'sleep')
|
|
75
|
+
await sleep(action.ms ?? 0);
|
|
76
|
+
else if (action.op === 'ignore-cancel')
|
|
77
|
+
ignoreCancel = true;
|
|
78
|
+
else if (action.op === 'exit')
|
|
79
|
+
process.exit(action.code ?? 0);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
const rl = createInterface({ input: process.stdin });
|
|
83
|
+
rl.on('line', (raw) => {
|
|
84
|
+
let frame;
|
|
85
|
+
try {
|
|
86
|
+
frame = JSON.parse(raw);
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
if (frame.type === 'turn' && typeof frame.turnId === 'string') {
|
|
92
|
+
currentTurnId = frame.turnId;
|
|
93
|
+
flushing = false;
|
|
94
|
+
void replay();
|
|
95
|
+
}
|
|
96
|
+
else if (frame.type === 'cancel') {
|
|
97
|
+
if (ignoreCancel)
|
|
98
|
+
return;
|
|
99
|
+
// Answering cancel: wake pending sleeps so the scripted terminal arrives promptly.
|
|
100
|
+
flushing = true;
|
|
101
|
+
for (const [timer, resolve] of sleepers) {
|
|
102
|
+
clearTimeout(timer);
|
|
103
|
+
resolve();
|
|
104
|
+
}
|
|
105
|
+
sleepers.clear();
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
rl.on('close', () => {
|
|
109
|
+
process.exit(0);
|
|
110
|
+
});
|
|
111
|
+
// Scripts that lead with `exit` run at startup (direct child drives and handshake tests);
|
|
112
|
+
// turn-dependent actions replay with a null turnId in that mode.
|
|
113
|
+
if (startsWithExit)
|
|
114
|
+
void replay();
|
|
@@ -0,0 +1,22 @@
|
|
|
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 { TurnSessionDriver } from '../turn-session';
|
|
8
|
+
/** One scripted child action (see `fake-turn-agent.ts` for the wire semantics). */
|
|
9
|
+
export interface FakeTurnAction {
|
|
10
|
+
op: 'ready' | 'accept' | 'output' | 'terminal' | 'stray' | 'sleep' | 'ignore-cancel' | 'flood' | 'exit';
|
|
11
|
+
nativeSessionId?: string;
|
|
12
|
+
data?: string;
|
|
13
|
+
kind?: 'success' | 'failure';
|
|
14
|
+
nativeTurnId?: string;
|
|
15
|
+
finalText?: string;
|
|
16
|
+
line?: Record<string, unknown>;
|
|
17
|
+
ms?: number;
|
|
18
|
+
code?: number;
|
|
19
|
+
}
|
|
20
|
+
/** Build a turn-session driver over the scripted child. `overrides` tailors qualify/agent for refusal tests. */
|
|
21
|
+
export declare function createFakeTurnSessionDriver(actions: FakeTurnAction[], overrides?: Partial<Pick<TurnSessionDriver, 'qualify' | 'agent'>>): TurnSessionDriver;
|
|
22
|
+
//# sourceMappingURL=fake-turn-driver.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fake-turn-driver.d.ts","sourceRoot":"","sources":["../../src/testing/fake-turn-driver.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,KAAK,EAA6B,iBAAiB,EAAoC,MAAM,iBAAiB,CAAC;AAGtH,mFAAmF;AACnF,MAAM,WAAW,cAAc;IAC3B,EAAE,EAAE,OAAO,GAAG,QAAQ,GAAG,QAAQ,GAAG,UAAU,GAAG,OAAO,GAAG,OAAO,GAAG,eAAe,GAAG,OAAO,GAAG,MAAM,CAAC;IACxG,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,SAAS,GAAG,SAAS,CAAC;IAC7B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC/B,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,IAAI,CAAC,EAAE,MAAM,CAAC;CACjB;AAsBD,gHAAgH;AAChH,wBAAgB,2BAA2B,CACvC,OAAO,EAAE,cAAc,EAAE,EACzB,SAAS,GAAE,OAAO,CAAC,IAAI,CAAC,iBAAiB,EAAE,SAAS,GAAG,OAAO,CAAC,CAAM,GACtE,iBAAiB,CAoDnB"}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { TurnProtocolError } from '../turn-session.js';
|
|
2
|
+
/** Path of the child script: source tree in dev/checkouts, compiled sibling in built packages. */
|
|
3
|
+
function fakeTurnAgentPath() {
|
|
4
|
+
// No node:path/node:fs (runtime-boundaries rule): import.meta.dir is already absolute, so a
|
|
5
|
+
// separator-safe marker check picks the compiled sibling in built packages.
|
|
6
|
+
const isBuilt = import.meta.dir.replace(/\\/g, '/').includes('/dist/');
|
|
7
|
+
return `${import.meta.dir}/fake-turn-agent.${isBuilt ? 'js' : 'ts'}`;
|
|
8
|
+
}
|
|
9
|
+
/** Build a turn-session driver over the scripted child. `overrides` tailors qualify/agent for refusal tests. */
|
|
10
|
+
export function createFakeTurnSessionDriver(actions, overrides = {}) {
|
|
11
|
+
const scriptJson = JSON.stringify(actions);
|
|
12
|
+
const driver = {
|
|
13
|
+
agent: overrides.agent ?? 'pi',
|
|
14
|
+
qualify: overrides.qualify ?? (() => ({ qualified: true })),
|
|
15
|
+
spawnArgv: (_binary, _policy) => ({
|
|
16
|
+
command: process.execPath,
|
|
17
|
+
args: [fakeTurnAgentPath(), scriptJson],
|
|
18
|
+
}),
|
|
19
|
+
handshake: async (pull) => {
|
|
20
|
+
const raw = await pull(2_000);
|
|
21
|
+
if (raw === null)
|
|
22
|
+
return null; // EOF or timeout before ready
|
|
23
|
+
const frame = JSON.parse(raw);
|
|
24
|
+
if (frame.ctl !== 'ready')
|
|
25
|
+
return null;
|
|
26
|
+
return frame.nativeSessionId !== undefined ? { nativeSessionId: frame.nativeSessionId } : null;
|
|
27
|
+
},
|
|
28
|
+
encodeTurn: (input) => `${JSON.stringify({ type: 'turn', ...input })}\n`,
|
|
29
|
+
decode: (line) => {
|
|
30
|
+
let frame;
|
|
31
|
+
try {
|
|
32
|
+
frame = JSON.parse(line);
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
throw new TurnProtocolError(`malformed frame: ${line.slice(0, 80)}`);
|
|
36
|
+
}
|
|
37
|
+
if (frame.ctl !== undefined)
|
|
38
|
+
return []; // control frames (ready) are handshake-only
|
|
39
|
+
if (frame.type !== 'accepted' && frame.type !== 'output' && frame.type !== 'terminal') {
|
|
40
|
+
throw new TurnProtocolError(`unknown frame type: ${String(frame.type)}`);
|
|
41
|
+
}
|
|
42
|
+
return [
|
|
43
|
+
{
|
|
44
|
+
turnId: frame.turn ?? null,
|
|
45
|
+
type: frame.type,
|
|
46
|
+
...(frame.data !== undefined ? { data: frame.data } : {}),
|
|
47
|
+
...(frame.type === 'terminal'
|
|
48
|
+
? {
|
|
49
|
+
terminal: {
|
|
50
|
+
kind: frame.kind === 'failure' ? 'failure' : 'success',
|
|
51
|
+
...(frame.nativeTurnId !== undefined ? { nativeTurnId: frame.nativeTurnId } : {}),
|
|
52
|
+
...(frame.nativeSessionId !== undefined
|
|
53
|
+
? { nativeSessionId: frame.nativeSessionId }
|
|
54
|
+
: {}),
|
|
55
|
+
...(frame.finalText !== undefined ? { finalText: frame.finalText } : {}),
|
|
56
|
+
...(frame.reason !== undefined ? { reason: frame.reason } : {}),
|
|
57
|
+
},
|
|
58
|
+
}
|
|
59
|
+
: {}),
|
|
60
|
+
},
|
|
61
|
+
];
|
|
62
|
+
},
|
|
63
|
+
encodeCancel: (reason) => `${JSON.stringify({ type: 'cancel', reason })}\n`,
|
|
64
|
+
};
|
|
65
|
+
return driver;
|
|
66
|
+
}
|
|
@@ -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
|
+
}
|