@gobing-ai/ts-ai-runner 0.6.4 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -29,7 +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
+ | `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. Drivers land only with qualification evidence (`claude`, `pi`, `codex`). |
33
33
  | `AgentEvents` / `AiRunnerProcessEvents` | Typed event maps for agent and process-level observability |
34
34
  | `AGENT_SHIMS` / `TIER1_PRIORITY` / `TIER2_AGENTS` / `DISPLAY_ORDER` | Agent registry constants |
35
35
  | `isAgentName()` | Type guard for supported agent identifiers |
@@ -935,10 +935,16 @@ safe to call more than once; the maker is not usable afterwards.
935
935
  `verifiedAgainst` qualification evidence; the scripted fake in `@gobing-ai/ts-ai-runner/testing`
936
936
  is for consumer tests, never library code.
937
937
  - Registered drivers (evidence in `tests/fixtures/turn-drivers/<agent>/`): `claude` 2.1.308
938
- stream-json (task 1276) and `pi` 0.87.1 rpc (task 1277 — probed live 2026-10-23 against the
938
+ stream-json (task 1276), `pi` 0.87.1 rpc (task 1277 — probed live 2026-10-23 against the
939
939
  repository dependency; the PATH 1.4.0 binary speaks the same family but is not the spawn
940
- target, so `qualify()` pins 0.87.1 only). Any other version refuses `unqualified-version` and
941
- the consumer falls back to resume/one-shot — never a guessed protocol.
940
+ target, so `qualify()` pins 0.87.1 only) and `codex` 0.164.0 app-server (task 1278 — probed live
941
+ 2026-10-24: two serial turns on one native thread plus a `thread/resume` from a second process).
942
+ Any other version refuses `unqualified-version` and the consumer falls back to resume/one-shot —
943
+ never a guessed protocol.
944
+ - Codex needs the two extended driver hooks: its `handshake` also WRITES (it must send
945
+ `initialize`/`initialized`/`thread/start` and return the native thread id), and its turn/cancel
946
+ frames address that thread plus the native turn id, which reach the driver as `scope`. Protocols
947
+ that carry their own addressing (pi's command-id echo, claude's constant session id) ignore both.
942
948
  - Outcome classification (task 1277 escalation Q2): a definite pre-acceptance end settles
943
949
  `not-started`, uniformly across the process-exit path and decoder terminals (pi's prompt
944
950
  rejection before acceptance). `failure` is reserved for definite post-acceptance ends. The pi
@@ -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,Q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eAAO,MAAM,YAAY,EAAE,WAAW,CAAC,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"}
@@ -447,12 +447,15 @@ const AGENT_SESSION_CAPABILITY = {
447
447
  codex: {
448
448
  supportsResumeById: true,
449
449
  supportsSessionDir: false,
450
- supportsPersistentStdin: false,
450
+ supportsPersistentStdin: true,
451
451
  supportsStructuredOutput: true,
452
- verifiedAgainst: '0.155.1',
453
- // R3 branch 2: `exec resume <id> <prompt>` is the working non-interactive
454
- // resume (verified 0.154.0) — wired in getPromptCommand below.
455
- note: 'no session-dir flag — sessionDir is ignored; `exec` carries one prompt arg (stdin `-` is one-shot), so no multi-turn stdin',
452
+ verifiedAgainst: '0.164.0',
453
+ // Persistent stdin re-verified with a live two-turn capture on 2026-10-24 (task 1278):
454
+ // `codex app-server` kept one process across initialize → thread/start → two turn/start
455
+ // turns (thread/turn ids echoed per notification), and a second process resumed the same
456
+ // thread with thread/resume (fixtures: ai-runner tests/fixtures/turn-drivers/codex).
457
+ // `exec resume <id> <prompt>` remains the non-interactive resume path in getPromptCommand.
458
+ note: 'no session-dir flag — sessionDir is ignored; warm turns go through `app-server` (turn-session driver), one-shot/`exec resume` through the shim argv',
456
459
  },
457
460
  'antigravity-cli': {
458
461
  supportsResumeById: true,
@@ -0,0 +1,17 @@
1
+ import type { TurnSessionDriver } from '../turn-session';
2
+ /**
3
+ * Codex version this driver's protocol was qualified against — probed live on 2026-10-24
4
+ * (`codex-cli 0.164.0`, the binary the generated bindings came from).
5
+ */
6
+ export declare const CODEX_TURN_VERIFIED_VERSION = "0.164.0";
7
+ /**
8
+ * Build the driver. `spawn` overrides the child argv for tests (the registry instance spawns the
9
+ * real `codex` binary); production callers use `TURN_SESSION_DRIVERS.get('codex')`.
10
+ */
11
+ export declare function createCodexTurnSessionDriver(options?: {
12
+ spawn?: {
13
+ command: string;
14
+ args: string[];
15
+ };
16
+ }): TurnSessionDriver;
17
+ //# sourceMappingURL=codex-app-server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codex-app-server.d.ts","sourceRoot":"","sources":["../../src/turn-drivers/codex-app-server.ts"],"names":[],"mappings":"AAyBA,OAAO,KAAK,EAIR,iBAAiB,EAKpB,MAAM,iBAAiB,CAAC;AAEzB;;;GAGG;AACH,eAAO,MAAM,2BAA2B,YAAY,CAAC;AAyCrD;;;GAGG;AACH,wBAAgB,4BAA4B,CACxC,OAAO,GAAE;IAAE,KAAK,CAAC,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,EAAE,CAAA;KAAE,CAAA;CAAO,GAC9D,iBAAiB,CA4JnB"}
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Codex version this driver's protocol was qualified against — probed live on 2026-10-24
3
+ * (`codex-cli 0.164.0`, the binary the generated bindings came from).
4
+ */
5
+ export const CODEX_TURN_VERIFIED_VERSION = '0.164.0';
6
+ /** Client identity declared in `initialize`; the server echoes it in its `initialize` result. */
7
+ const CLIENT_INFO = { name: 'spur-turn-session', title: 'Spur turn session', version: '0.7.0' };
8
+ /** JSON-RPC id of the `initialize` request (the only id the driver does not derive from a turn). */
9
+ const INITIALIZE_ID = '__spur_initialize';
10
+ /** JSON-RPC id of the thread bootstrap request. */
11
+ const THREAD_ID = '__spur_thread';
12
+ /** Final answer text of a turn: the `final_answer` agent message, else the last agent message. */
13
+ function finalTextOf(turn) {
14
+ const messages = (turn.items ?? []).filter((item) => item.type === 'agentMessage' && typeof item.text === 'string');
15
+ const final = messages.find((item) => item.phase === 'final_answer') ?? messages.at(-1);
16
+ return final?.text;
17
+ }
18
+ /**
19
+ * Build the driver. `spawn` overrides the child argv for tests (the registry instance spawns the
20
+ * real `codex` binary); production callers use `TURN_SESSION_DRIVERS.get('codex')`.
21
+ */
22
+ export function createCodexTurnSessionDriver(options = {}) {
23
+ const write = (frame) => `${JSON.stringify(frame)}\n`;
24
+ return {
25
+ agent: 'codex',
26
+ qualify: (binary) => binary.version === CODEX_TURN_VERIFIED_VERSION
27
+ ? { qualified: true }
28
+ : {
29
+ qualified: false,
30
+ reason: `codex ${binary.version ?? '<no version>'} is not the qualified app-server version ${CODEX_TURN_VERIFIED_VERSION}`,
31
+ },
32
+ spawnArgv: (_binary, policy) => options.spawn ?? {
33
+ command: 'codex',
34
+ args: [
35
+ 'app-server',
36
+ // Thread model overrides are TOML config in 0.164.0 (`-c model="…"`); turn/start
37
+ // carries no model field, so the session policy has to reach the thread here.
38
+ ...(policy.model !== undefined ? ['-c', `model=${JSON.stringify(policy.model)}`] : []),
39
+ ],
40
+ },
41
+ handshake: async (pull, send) => {
42
+ send(write({
43
+ id: INITIALIZE_ID,
44
+ method: 'initialize',
45
+ params: { clientInfo: CLIENT_INFO, capabilities: null },
46
+ }));
47
+ let initialized = false;
48
+ let threadId;
49
+ // Startup emits unrelated notifications (mcp/startup status, hooks, warnings) — read
50
+ // until both of OUR responses arrive; anything else is bootstrap noise.
51
+ for (let seen = 0; seen < 200 && (!initialized || threadId === undefined); seen += 1) {
52
+ const line = await pull(5_000);
53
+ if (line === null)
54
+ throw new Error('codex app-server closed during the handshake');
55
+ let frame;
56
+ try {
57
+ frame = JSON.parse(line);
58
+ }
59
+ catch {
60
+ continue;
61
+ }
62
+ if (frame.id === INITIALIZE_ID) {
63
+ if (frame.error !== undefined) {
64
+ throw new Error(`codex initialize failed: ${frame.error.message ?? 'unspecified error'}`);
65
+ }
66
+ // `initialized` is a notification: the server starts serving after it, and
67
+ // thread/start before it is rejected on some builds.
68
+ send(write({ method: 'initialized' }));
69
+ send(write({ id: THREAD_ID, method: 'thread/start', params: {} }));
70
+ initialized = true;
71
+ continue;
72
+ }
73
+ if (frame.id === THREAD_ID) {
74
+ if (frame.error !== undefined) {
75
+ throw new Error(`codex thread/start failed: ${frame.error.message ?? 'unspecified error'}`);
76
+ }
77
+ threadId = frame.result?.thread?.id;
78
+ }
79
+ }
80
+ if (threadId === undefined || threadId === '') {
81
+ throw new Error('codex app-server did not report a native thread id');
82
+ }
83
+ return { nativeSessionId: threadId };
84
+ },
85
+ encodeTurn: (input) => {
86
+ const threadId = input.scope?.nativeSessionId;
87
+ if (threadId === undefined) {
88
+ // Facade settles `not-started`: a turn cannot be addressed without the session id.
89
+ throw new Error('codex turn/start requires the handshake thread id');
90
+ }
91
+ return write({
92
+ id: input.turnId,
93
+ method: 'turn/start',
94
+ params: {
95
+ threadId,
96
+ input: [{ type: 'text', text: input.prompt, text_elements: [] }],
97
+ },
98
+ });
99
+ },
100
+ decode: (line, context) => {
101
+ let frame;
102
+ try {
103
+ frame = JSON.parse(line);
104
+ }
105
+ catch {
106
+ // Plain Error with the protocol name: importing TurnProtocolError would make this
107
+ // module a runtime dependency of turn-session.ts (which registers it).
108
+ const error = new Error(`codex app-server: malformed JSON line: ${line.slice(0, 80)}`);
109
+ error.name = 'TurnProtocolError';
110
+ throw error;
111
+ }
112
+ if (context === undefined)
113
+ return [];
114
+ // Our own request ids are the runner turn id, so a response addresses its turn directly.
115
+ if (frame.id === context.turnId) {
116
+ if (frame.error !== undefined) {
117
+ return [
118
+ {
119
+ turnId: context.turnId,
120
+ type: 'terminal',
121
+ terminal: {
122
+ // Rejected before any turn ran = never started (uniform rule).
123
+ kind: context.accepted ? 'failure' : 'not-started',
124
+ reason: `codex rejected turn/start: ${frame.error.message ?? 'unspecified error'}`,
125
+ },
126
+ },
127
+ ];
128
+ }
129
+ const nativeTurnId = frame.result?.turn?.id;
130
+ if (!context.accepted) {
131
+ return [
132
+ {
133
+ turnId: context.turnId,
134
+ type: 'accepted',
135
+ ...(nativeTurnId !== undefined ? { nativeTurnId } : {}),
136
+ },
137
+ ];
138
+ }
139
+ return [];
140
+ }
141
+ // The session admits one turn at a time, so any `turn/completed` belongs to the
142
+ // active turn; the NATIVE ids on it are what the outcome reports.
143
+ if (frame.params?.turn !== undefined && frame.method === 'turn/completed') {
144
+ const turn = frame.params.turn;
145
+ const terminal = {
146
+ // `interrupted` is a native interruption the caller did not request; the facade
147
+ // upgrades a caller-requested cancel to `interrupted` itself.
148
+ kind: turn.status === 'completed' ? 'success' : 'failure',
149
+ ...(turn.id !== undefined ? { nativeTurnId: turn.id } : {}),
150
+ ...(frame.params.threadId !== undefined ? { nativeSessionId: frame.params.threadId } : {}),
151
+ };
152
+ if (turn.status === 'interrupted')
153
+ terminal.reason = 'codex turn status interrupted';
154
+ else if (turn.status === 'failed')
155
+ terminal.reason = `codex turn failed: ${turn.error?.message ?? 'unspecified error'}`;
156
+ else if (turn.status !== 'completed')
157
+ return [{ turnId: context.turnId, type: 'diagnostic', data: frame }];
158
+ const text = finalTextOf(turn);
159
+ if (text !== undefined)
160
+ terminal.finalText = text;
161
+ return [{ turnId: context.turnId, type: 'terminal', terminal }];
162
+ }
163
+ if (frame.method === 'error' && frame.params?.error !== undefined) {
164
+ // Server-level error notification: surfaced as output so the consumer's artifact
165
+ // validation sees it; the turn terminal still comes from turn/completed.
166
+ return [{ turnId: context.turnId, type: 'diagnostic', data: frame }];
167
+ }
168
+ return [];
169
+ },
170
+ encodeCancel: (_reason, scope) => write({
171
+ id: '__spur_interrupt',
172
+ method: 'turn/interrupt',
173
+ params: { threadId: scope?.nativeSessionId, turnId: scope?.nativeTurnId },
174
+ }),
175
+ };
176
+ }
@@ -98,6 +98,17 @@ export interface TurnBinary {
98
98
  /** `null` when the version could not be probed — drivers decide whether that qualifies. */
99
99
  version: string | null;
100
100
  }
101
+ /**
102
+ * Session-scoped native identity handed to a driver's encode paths (task 1278). Codex addresses a
103
+ * native thread on every `turn/start` and needs the native turn id to interrupt; protocols that
104
+ * carry their own addressing ignore it.
105
+ */
106
+ export interface TurnWireScope {
107
+ /** Native session/thread id the handshake established (`undefined` when the driver has none). */
108
+ readonly nativeSessionId?: string;
109
+ /** Native turn id the driver reported at acceptance for the ACTIVE turn. */
110
+ readonly nativeTurnId?: string;
111
+ }
101
112
  /** A wire-level terminal extracted from one decoded line. */
102
113
  export interface TurnWireTerminal {
103
114
  kind: 'success' | 'failure' | 'not-started';
@@ -112,6 +123,8 @@ export interface TurnWireEvent {
112
123
  type: 'accepted' | 'output' | 'diagnostic' | 'terminal';
113
124
  data?: unknown;
114
125
  terminal?: TurnWireTerminal;
126
+ /** Native turn id observed on the acceptance frame (codex `turn/start` result). */
127
+ nativeTurnId?: string;
115
128
  }
116
129
  /** Thrown by `TurnSessionDriver.decode` on a malformed frame — settles the turn `contract-violation`. */
117
130
  export declare class TurnProtocolError extends Error {
@@ -153,11 +166,13 @@ export interface TurnSessionDriver {
153
166
  * no handshake. Pull via `pull(timeoutMs)` — NOT `for await` over a stream — because an
154
167
  * early `return`/`break` in a for-await CLOSES the shared iterator the session pump needs.
155
168
  */
156
- handshake?(pull: (timeoutMs: number) => Promise<string | null>): Promise<TurnHandshake>;
169
+ handshake?(pull: (timeoutMs: number) => Promise<string | null>, write: (line: string) => void): Promise<TurnHandshake>;
157
170
  encodeTurn(input: {
158
171
  turnId: string;
159
172
  prompt: string;
160
173
  correlation: TurnCorrelation;
174
+ /** Native identity for drivers whose turn frame must address a native thread (codex). */
175
+ scope?: TurnWireScope;
161
176
  }): string;
162
177
  /**
163
178
  * Decode one stdout line into zero or more frames; throws {@link TurnProtocolError} on
@@ -165,7 +180,7 @@ export interface TurnSessionDriver {
165
180
  * protocol cannot self-attribute (claude); drivers that echo turn ids may ignore it.
166
181
  */
167
182
  decode(line: string, context?: TurnDecodeContext): TurnWireEvent[];
168
- encodeCancel(reason: string): string;
183
+ encodeCancel(reason: string, scope?: TurnWireScope): string;
169
184
  }
170
185
  /** Outcome of {@link AiRunner.openTurnSession}: an open session or a typed failure reason. */
171
186
  export type OpenTurnSessionResult = {
@@ -179,8 +194,9 @@ export type OpenTurnSessionResult = {
179
194
  /**
180
195
  * Built-in driver registry. Entries land only with recorded qualification evidence (anti-pattern:
181
196
  * registration without evidence): claude 2.1.308 stream-json (task 1276, fixtures under
182
- * `tests/fixtures/turn-drivers/claude`) and pi 0.87.1 rpc (task 1277, fixtures under
183
- * `tests/fixtures/turn-drivers/pi`). 0.x shipped this empty by design.
197
+ * `tests/fixtures/turn-drivers/claude`), pi 0.87.1 rpc (task 1277, fixtures under
198
+ * `tests/fixtures/turn-drivers/pi`) and codex 0.164.0 app-server (task 1278, fixtures under
199
+ * `tests/fixtures/turn-drivers/codex`). 0.x shipped this empty by design.
184
200
  */
185
201
  export declare const TURN_SESSION_DRIVERS: ReadonlyMap<AgentName, TurnSessionDriver>;
186
202
  /** How long `cancel()` waits for native terminal evidence before resolving `outcome-unknown`. */
@@ -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;AAIhD;;;;;;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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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,5 +1,6 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
2
  import { createClaudeTurnSessionDriver } from './turn-drivers/claude-stream-json.js';
3
+ import { createCodexTurnSessionDriver } from './turn-drivers/codex-app-server.js';
3
4
  import { createPiTurnSessionDriver } from './turn-drivers/pi-rpc.js';
4
5
  /** Thrown by `TurnSessionDriver.decode` on a malformed frame — settles the turn `contract-violation`. */
5
6
  export class TurnProtocolError extends Error {
@@ -11,11 +12,13 @@ export class TurnProtocolError extends Error {
11
12
  /**
12
13
  * Built-in driver registry. Entries land only with recorded qualification evidence (anti-pattern:
13
14
  * registration without evidence): claude 2.1.308 stream-json (task 1276, fixtures under
14
- * `tests/fixtures/turn-drivers/claude`) and pi 0.87.1 rpc (task 1277, fixtures under
15
- * `tests/fixtures/turn-drivers/pi`). 0.x shipped this empty by design.
15
+ * `tests/fixtures/turn-drivers/claude`), pi 0.87.1 rpc (task 1277, fixtures under
16
+ * `tests/fixtures/turn-drivers/pi`) and codex 0.164.0 app-server (task 1278, fixtures under
17
+ * `tests/fixtures/turn-drivers/codex`). 0.x shipped this empty by design.
16
18
  */
17
19
  export const TURN_SESSION_DRIVERS = new Map([
18
20
  ['claude', createClaudeTurnSessionDriver()],
21
+ ['codex', createCodexTurnSessionDriver()],
19
22
  ['pi', createPiTurnSessionDriver()],
20
23
  ]);
21
24
  /** How long `cancel()` waits for native terminal evidence before resolving `outcome-unknown`. */
@@ -100,6 +103,8 @@ class ActiveTurn {
100
103
  correlation;
101
104
  startedAt = new Date().toISOString();
102
105
  acceptedAt;
106
+ /** Native turn id the driver reported at acceptance (codex) — carried to cancel and the outcome. */
107
+ nativeTurnId;
103
108
  firstOutputAt;
104
109
  outcomeResolved = false;
105
110
  cancelRequested = false;
@@ -238,7 +243,12 @@ class TurnSessionImpl {
238
243
  this.active = turn;
239
244
  this.state = 'busy';
240
245
  try {
241
- this.process.writeStdin(this.driver.encodeTurn({ turnId, prompt: input.prompt, correlation: input.correlation }));
246
+ this.process.writeStdin(this.driver.encodeTurn({
247
+ turnId,
248
+ prompt: input.prompt,
249
+ correlation: input.correlation,
250
+ scope: { nativeSessionId: this.nativeSessionId },
251
+ }));
242
252
  }
243
253
  catch (error) {
244
254
  // A dead stdin means the process is gone: the turn never started.
@@ -251,7 +261,10 @@ class TurnSessionImpl {
251
261
  if (!turn.outcomeResolved) {
252
262
  turn.cancelRequested = true;
253
263
  try {
254
- this.process.writeStdin(this.driver.encodeCancel(reason));
264
+ this.process.writeStdin(this.driver.encodeCancel(reason, {
265
+ nativeSessionId: this.nativeSessionId,
266
+ nativeTurnId: turn.nativeTurnId,
267
+ }));
255
268
  }
256
269
  catch {
257
270
  // stdin gone — the exit handler settles deterministically.
@@ -272,7 +285,10 @@ class TurnSessionImpl {
272
285
  if (turn !== undefined && !turn.outcomeResolved) {
273
286
  turn.cancelRequested = true;
274
287
  try {
275
- this.process.writeStdin(this.driver.encodeCancel('session closing'));
288
+ this.process.writeStdin(this.driver.encodeCancel('session closing', {
289
+ nativeSessionId: this.nativeSessionId,
290
+ nativeTurnId: turn.nativeTurnId,
291
+ }));
276
292
  }
277
293
  catch {
278
294
  // stdin gone
@@ -317,7 +333,11 @@ class TurnSessionImpl {
317
333
  const kind = turn.cancelRequested ? 'interrupted' : wire.terminal.kind;
318
334
  turn.settle({
319
335
  kind,
320
- ...(wire.terminal.nativeTurnId !== undefined ? { nativeTurnId: wire.terminal.nativeTurnId } : {}),
336
+ ...(wire.terminal.nativeTurnId !== undefined
337
+ ? { nativeTurnId: wire.terminal.nativeTurnId }
338
+ : turn.nativeTurnId !== undefined
339
+ ? { nativeTurnId: turn.nativeTurnId }
340
+ : {}),
321
341
  ...(wire.terminal.nativeSessionId !== undefined
322
342
  ? { nativeSessionId: wire.terminal.nativeSessionId }
323
343
  : {}),
@@ -334,8 +354,11 @@ class TurnSessionImpl {
334
354
  return;
335
355
  }
336
356
  if (wire.type === 'accepted') {
357
+ if (wire.nativeTurnId !== undefined && turn.nativeTurnId === undefined)
358
+ turn.nativeTurnId = wire.nativeTurnId;
337
359
  if (turn.acceptedAt === undefined) {
338
- turn.acceptedAt = at;
360
+ // `markAccepted` owns the `acceptedAt` write — setting it first would make its own
361
+ // idempotence guard skip `resolveAccepted`, leaving the `accepted` promise pending.
339
362
  turn.markAccepted();
340
363
  turn.emit({ type: 'accepted' });
341
364
  }
@@ -433,7 +456,7 @@ export async function openTurnSessionWithDriver(options) {
433
456
  let handshakeResult = null;
434
457
  if (driver.handshake !== undefined) {
435
458
  // A handshake that loses the race (or throws) must not surface as an unhandled rejection.
436
- const handshake = driver.handshake(pull).catch(() => null);
459
+ const handshake = driver.handshake(pull, (line) => process.writeStdin(line)).catch(() => null);
437
460
  try {
438
461
  handshakeResult = await Promise.race([handshake, delay(handshakeTimeoutMs)]);
439
462
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gobing-ai/ts-ai-runner",
3
- "version": "0.6.4",
3
+ "version": "0.7.0",
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.4",
55
- "@gobing-ai/ts-runtime": "^0.6.4"
54
+ "@gobing-ai/ts-infra": "^0.7.0",
55
+ "@gobing-ai/ts-runtime": "^0.7.0"
56
56
  },
57
57
  "devDependencies": {
58
58
  "@types/bun": "1.4.3",
59
- "@gobing-ai/ts-db": "^0.6.4"
59
+ "@gobing-ai/ts-db": "^0.7.0"
60
60
  },
61
61
  "publishConfig": {
62
62
  "access": "public"
@@ -570,12 +570,15 @@ const AGENT_SESSION_CAPABILITY: Readonly<Record<AgentName, AgentSessionCapabilit
570
570
  codex: {
571
571
  supportsResumeById: true,
572
572
  supportsSessionDir: false,
573
- supportsPersistentStdin: false,
573
+ supportsPersistentStdin: true,
574
574
  supportsStructuredOutput: true,
575
- verifiedAgainst: '0.155.1',
576
- // R3 branch 2: `exec resume <id> <prompt>` is the working non-interactive
577
- // resume (verified 0.154.0) — wired in getPromptCommand below.
578
- note: 'no session-dir flag — sessionDir is ignored; `exec` carries one prompt arg (stdin `-` is one-shot), so no multi-turn stdin',
575
+ verifiedAgainst: '0.164.0',
576
+ // Persistent stdin re-verified with a live two-turn capture on 2026-10-24 (task 1278):
577
+ // `codex app-server` kept one process across initialize → thread/start → two turn/start
578
+ // turns (thread/turn ids echoed per notification), and a second process resumed the same
579
+ // thread with thread/resume (fixtures: ai-runner tests/fixtures/turn-drivers/codex).
580
+ // `exec resume <id> <prompt>` remains the non-interactive resume path in getPromptCommand.
581
+ note: 'no session-dir flag — sessionDir is ignored; warm turns go through `app-server` (turn-session driver), one-shot/`exec resume` through the shim argv',
579
582
  },
580
583
  'antigravity-cli': {
581
584
  supportsResumeById: true,
@@ -0,0 +1,244 @@
1
+ /**
2
+ * Codex App Server turn-session driver (task 1278, design `fleet-task-turn-execution.md` §5).
3
+ * Speaks the protocol generated from `codex app-server generate-ts` and captured live on
4
+ * `codex-cli` 0.164.0 (2026-10-24; fixtures under `tests/fixtures/turn-drivers/codex`):
5
+ *
6
+ * - `codex app-server` is a JSONL control channel. The client bootstraps with
7
+ * `initialize` (`clientInfo`+`capabilities`) and an `initialized` notification, then opens a
8
+ * native thread (`thread/start`, or `thread/resume` for an existing thread id) and starts turns
9
+ * with `turn/start { threadId, input: [{ type: 'text', text, text_elements }] }`.
10
+ * - Every notification echoes `params.threadId` and `params.turnId`, so frames are
11
+ * self-attributing; the driver still validates against the facade's active turn because the
12
+ * session admits one turn at a time and a late frame must not be read as the next turn's.
13
+ * - `turn/start` responds with the native turn (`status: 'inProgress'`) — that response is
14
+ * ACCEPTANCE, never completion. The only turn terminal is `turn/completed`, whose
15
+ * `params.turn.status` is `completed | failed | interrupted` (`inProgress` never terminates).
16
+ * - Failed turns carry `turn.error.message`; interrupted ones carry `error: null`, so an
17
+ * interruption is observable only through the status (the facade maps a caller-requested cancel
18
+ * to `interrupted`).
19
+ * - Codex-generated ids are UUIDv7 thread/turn ids; both are surfaced so a consumer can link
20
+ * receipts to native turns.
21
+ *
22
+ * `codex` also ships `exec`/`exec resume` one-shot paths (capability row); this driver is the
23
+ * warm session only.
24
+ */
25
+ import type { AgentName } from '../agents/shims';
26
+ import type {
27
+ TurnBinary,
28
+ TurnDecodeContext,
29
+ TurnHandshake,
30
+ TurnSessionDriver,
31
+ TurnSessionPolicy,
32
+ TurnWireEvent,
33
+ TurnWireScope,
34
+ TurnWireTerminal,
35
+ } from '../turn-session';
36
+
37
+ /**
38
+ * Codex version this driver's protocol was qualified against — probed live on 2026-10-24
39
+ * (`codex-cli 0.164.0`, the binary the generated bindings came from).
40
+ */
41
+ export const CODEX_TURN_VERIFIED_VERSION = '0.164.0';
42
+
43
+ /** Client identity declared in `initialize`; the server echoes it in its `initialize` result. */
44
+ const CLIENT_INFO = { name: 'spur-turn-session', title: 'Spur turn session', version: '0.7.0' } as const;
45
+
46
+ /** JSON-RPC id of the `initialize` request (the only id the driver does not derive from a turn). */
47
+ const INITIALIZE_ID = '__spur_initialize';
48
+ /** JSON-RPC id of the thread bootstrap request. */
49
+ const THREAD_ID = '__spur_thread';
50
+
51
+ interface CodexFrame {
52
+ id?: string | number;
53
+ method?: string;
54
+ params?: {
55
+ threadId?: string;
56
+ turnId?: string;
57
+ turn?: CodexTurn;
58
+ item?: { type?: string; text?: string; phase?: string };
59
+ error?: { message?: string };
60
+ };
61
+ result?: {
62
+ thread?: { id?: string };
63
+ turn?: CodexTurn;
64
+ };
65
+ error?: { message?: string; code?: number };
66
+ }
67
+
68
+ interface CodexTurn {
69
+ id?: string;
70
+ status?: string;
71
+ error?: { message?: string } | null;
72
+ items?: { type?: string; text?: string; phase?: string }[];
73
+ }
74
+
75
+ /** Final answer text of a turn: the `final_answer` agent message, else the last agent message. */
76
+ function finalTextOf(turn: CodexTurn): string | undefined {
77
+ const messages = (turn.items ?? []).filter((item) => item.type === 'agentMessage' && typeof item.text === 'string');
78
+ const final = messages.find((item) => item.phase === 'final_answer') ?? messages.at(-1);
79
+ return final?.text;
80
+ }
81
+
82
+ /**
83
+ * Build the driver. `spawn` overrides the child argv for tests (the registry instance spawns the
84
+ * real `codex` binary); production callers use `TURN_SESSION_DRIVERS.get('codex')`.
85
+ */
86
+ export function createCodexTurnSessionDriver(
87
+ options: { spawn?: { command: string; args: string[] } } = {},
88
+ ): TurnSessionDriver {
89
+ const write = (frame: unknown): string => `${JSON.stringify(frame)}\n`;
90
+ return {
91
+ agent: 'codex' as AgentName,
92
+ qualify: (binary: TurnBinary) =>
93
+ binary.version === CODEX_TURN_VERIFIED_VERSION
94
+ ? { qualified: true }
95
+ : {
96
+ qualified: false,
97
+ reason: `codex ${binary.version ?? '<no version>'} is not the qualified app-server version ${CODEX_TURN_VERIFIED_VERSION}`,
98
+ },
99
+ spawnArgv: (_binary: TurnBinary, policy: TurnSessionPolicy) =>
100
+ options.spawn ?? {
101
+ command: 'codex',
102
+ args: [
103
+ 'app-server',
104
+ // Thread model overrides are TOML config in 0.164.0 (`-c model="…"`); turn/start
105
+ // carries no model field, so the session policy has to reach the thread here.
106
+ ...(policy.model !== undefined ? ['-c', `model=${JSON.stringify(policy.model)}`] : []),
107
+ ],
108
+ },
109
+ handshake: async (
110
+ pull: (timeoutMs: number) => Promise<string | null>,
111
+ send: (line: string) => void,
112
+ ): Promise<TurnHandshake> => {
113
+ send(
114
+ write({
115
+ id: INITIALIZE_ID,
116
+ method: 'initialize',
117
+ params: { clientInfo: CLIENT_INFO, capabilities: null },
118
+ }),
119
+ );
120
+ let initialized = false;
121
+ let threadId: string | undefined;
122
+ // Startup emits unrelated notifications (mcp/startup status, hooks, warnings) — read
123
+ // until both of OUR responses arrive; anything else is bootstrap noise.
124
+ for (let seen = 0; seen < 200 && (!initialized || threadId === undefined); seen += 1) {
125
+ const line = await pull(5_000);
126
+ if (line === null) throw new Error('codex app-server closed during the handshake');
127
+ let frame: CodexFrame;
128
+ try {
129
+ frame = JSON.parse(line) as CodexFrame;
130
+ } catch {
131
+ continue;
132
+ }
133
+ if (frame.id === INITIALIZE_ID) {
134
+ if (frame.error !== undefined) {
135
+ throw new Error(`codex initialize failed: ${frame.error.message ?? 'unspecified error'}`);
136
+ }
137
+ // `initialized` is a notification: the server starts serving after it, and
138
+ // thread/start before it is rejected on some builds.
139
+ send(write({ method: 'initialized' }));
140
+ send(write({ id: THREAD_ID, method: 'thread/start', params: {} }));
141
+ initialized = true;
142
+ continue;
143
+ }
144
+ if (frame.id === THREAD_ID) {
145
+ if (frame.error !== undefined) {
146
+ throw new Error(`codex thread/start failed: ${frame.error.message ?? 'unspecified error'}`);
147
+ }
148
+ threadId = frame.result?.thread?.id;
149
+ }
150
+ }
151
+ if (threadId === undefined || threadId === '') {
152
+ throw new Error('codex app-server did not report a native thread id');
153
+ }
154
+ return { nativeSessionId: threadId };
155
+ },
156
+ encodeTurn: (input: { turnId: string; prompt: string; scope?: TurnWireScope }) => {
157
+ const threadId = input.scope?.nativeSessionId;
158
+ if (threadId === undefined) {
159
+ // Facade settles `not-started`: a turn cannot be addressed without the session id.
160
+ throw new Error('codex turn/start requires the handshake thread id');
161
+ }
162
+ return write({
163
+ id: input.turnId,
164
+ method: 'turn/start',
165
+ params: {
166
+ threadId,
167
+ input: [{ type: 'text', text: input.prompt, text_elements: [] }],
168
+ },
169
+ });
170
+ },
171
+ decode: (line: string, context?: TurnDecodeContext): TurnWireEvent[] => {
172
+ let frame: CodexFrame;
173
+ try {
174
+ frame = JSON.parse(line) as CodexFrame;
175
+ } catch {
176
+ // Plain Error with the protocol name: importing TurnProtocolError would make this
177
+ // module a runtime dependency of turn-session.ts (which registers it).
178
+ const error = new Error(`codex app-server: malformed JSON line: ${line.slice(0, 80)}`);
179
+ error.name = 'TurnProtocolError';
180
+ throw error;
181
+ }
182
+ if (context === undefined) return [];
183
+ // Our own request ids are the runner turn id, so a response addresses its turn directly.
184
+ if (frame.id === context.turnId) {
185
+ if (frame.error !== undefined) {
186
+ return [
187
+ {
188
+ turnId: context.turnId,
189
+ type: 'terminal',
190
+ terminal: {
191
+ // Rejected before any turn ran = never started (uniform rule).
192
+ kind: context.accepted ? 'failure' : 'not-started',
193
+ reason: `codex rejected turn/start: ${frame.error.message ?? 'unspecified error'}`,
194
+ },
195
+ },
196
+ ];
197
+ }
198
+ const nativeTurnId = frame.result?.turn?.id;
199
+ if (!context.accepted) {
200
+ return [
201
+ {
202
+ turnId: context.turnId,
203
+ type: 'accepted',
204
+ ...(nativeTurnId !== undefined ? { nativeTurnId } : {}),
205
+ },
206
+ ];
207
+ }
208
+ return [];
209
+ }
210
+ // The session admits one turn at a time, so any `turn/completed` belongs to the
211
+ // active turn; the NATIVE ids on it are what the outcome reports.
212
+ if (frame.params?.turn !== undefined && frame.method === 'turn/completed') {
213
+ const turn = frame.params.turn;
214
+ const terminal: TurnWireTerminal = {
215
+ // `interrupted` is a native interruption the caller did not request; the facade
216
+ // upgrades a caller-requested cancel to `interrupted` itself.
217
+ kind: turn.status === 'completed' ? 'success' : 'failure',
218
+ ...(turn.id !== undefined ? { nativeTurnId: turn.id } : {}),
219
+ ...(frame.params.threadId !== undefined ? { nativeSessionId: frame.params.threadId } : {}),
220
+ };
221
+ if (turn.status === 'interrupted') terminal.reason = 'codex turn status interrupted';
222
+ else if (turn.status === 'failed')
223
+ terminal.reason = `codex turn failed: ${turn.error?.message ?? 'unspecified error'}`;
224
+ else if (turn.status !== 'completed')
225
+ return [{ turnId: context.turnId, type: 'diagnostic', data: frame }];
226
+ const text = finalTextOf(turn);
227
+ if (text !== undefined) terminal.finalText = text;
228
+ return [{ turnId: context.turnId, type: 'terminal', terminal }];
229
+ }
230
+ if (frame.method === 'error' && frame.params?.error !== undefined) {
231
+ // Server-level error notification: surfaced as output so the consumer's artifact
232
+ // validation sees it; the turn terminal still comes from turn/completed.
233
+ return [{ turnId: context.turnId, type: 'diagnostic', data: frame }];
234
+ }
235
+ return [];
236
+ },
237
+ encodeCancel: (_reason: string, scope?: TurnWireScope) =>
238
+ write({
239
+ id: '__spur_interrupt',
240
+ method: 'turn/interrupt',
241
+ params: { threadId: scope?.nativeSessionId, turnId: scope?.nativeTurnId },
242
+ }),
243
+ };
244
+ }
@@ -2,6 +2,7 @@ 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
4
  import { createClaudeTurnSessionDriver } from './turn-drivers/claude-stream-json';
5
+ import { createCodexTurnSessionDriver } from './turn-drivers/codex-app-server';
5
6
  import { createPiTurnSessionDriver } from './turn-drivers/pi-rpc';
6
7
 
7
8
  /**
@@ -98,6 +99,18 @@ export interface TurnBinary {
98
99
  version: string | null;
99
100
  }
100
101
 
102
+ /**
103
+ * Session-scoped native identity handed to a driver's encode paths (task 1278). Codex addresses a
104
+ * native thread on every `turn/start` and needs the native turn id to interrupt; protocols that
105
+ * carry their own addressing ignore it.
106
+ */
107
+ export interface TurnWireScope {
108
+ /** Native session/thread id the handshake established (`undefined` when the driver has none). */
109
+ readonly nativeSessionId?: string;
110
+ /** Native turn id the driver reported at acceptance for the ACTIVE turn. */
111
+ readonly nativeTurnId?: string;
112
+ }
113
+
101
114
  /** A wire-level terminal extracted from one decoded line. */
102
115
  export interface TurnWireTerminal {
103
116
  // `not-started` is the pre-acceptance definite-end classification (e.g. pi rejecting the
@@ -115,6 +128,8 @@ export interface TurnWireEvent {
115
128
  type: 'accepted' | 'output' | 'diagnostic' | 'terminal';
116
129
  data?: unknown;
117
130
  terminal?: TurnWireTerminal;
131
+ /** Native turn id observed on the acceptance frame (codex `turn/start` result). */
132
+ nativeTurnId?: string;
118
133
  }
119
134
 
120
135
  /** Thrown by `TurnSessionDriver.decode` on a malformed frame — settles the turn `contract-violation`. */
@@ -153,15 +168,24 @@ export interface TurnSessionDriver {
153
168
  * no handshake. Pull via `pull(timeoutMs)` — NOT `for await` over a stream — because an
154
169
  * early `return`/`break` in a for-await CLOSES the shared iterator the session pump needs.
155
170
  */
156
- handshake?(pull: (timeoutMs: number) => Promise<string | null>): Promise<TurnHandshake>;
157
- encodeTurn(input: { turnId: string; prompt: string; correlation: TurnCorrelation }): string;
171
+ handshake?(
172
+ pull: (timeoutMs: number) => Promise<string | null>,
173
+ write: (line: string) => void,
174
+ ): Promise<TurnHandshake>;
175
+ encodeTurn(input: {
176
+ turnId: string;
177
+ prompt: string;
178
+ correlation: TurnCorrelation;
179
+ /** Native identity for drivers whose turn frame must address a native thread (codex). */
180
+ scope?: TurnWireScope;
181
+ }): string;
158
182
  /**
159
183
  * Decode one stdout line into zero or more frames; throws {@link TurnProtocolError} on
160
184
  * malformed input. `context` carries the session's current active turn for drivers whose
161
185
  * protocol cannot self-attribute (claude); drivers that echo turn ids may ignore it.
162
186
  */
163
187
  decode(line: string, context?: TurnDecodeContext): TurnWireEvent[];
164
- encodeCancel(reason: string): string;
188
+ encodeCancel(reason: string, scope?: TurnWireScope): string;
165
189
  }
166
190
 
167
191
  /** Outcome of {@link AiRunner.openTurnSession}: an open session or a typed failure reason. */
@@ -176,11 +200,13 @@ export type OpenTurnSessionResult =
176
200
  /**
177
201
  * Built-in driver registry. Entries land only with recorded qualification evidence (anti-pattern:
178
202
  * registration without evidence): claude 2.1.308 stream-json (task 1276, fixtures under
179
- * `tests/fixtures/turn-drivers/claude`) and pi 0.87.1 rpc (task 1277, fixtures under
180
- * `tests/fixtures/turn-drivers/pi`). 0.x shipped this empty by design.
203
+ * `tests/fixtures/turn-drivers/claude`), pi 0.87.1 rpc (task 1277, fixtures under
204
+ * `tests/fixtures/turn-drivers/pi`) and codex 0.164.0 app-server (task 1278, fixtures under
205
+ * `tests/fixtures/turn-drivers/codex`). 0.x shipped this empty by design.
181
206
  */
182
207
  export const TURN_SESSION_DRIVERS: ReadonlyMap<AgentName, TurnSessionDriver> = new Map([
183
208
  ['claude', createClaudeTurnSessionDriver()],
209
+ ['codex', createCodexTurnSessionDriver()],
184
210
  ['pi', createPiTurnSessionDriver()],
185
211
  ]);
186
212
 
@@ -269,6 +295,8 @@ class ActiveTurn implements TurnHandle {
269
295
  readonly correlation: TurnCorrelation;
270
296
  readonly startedAt = new Date().toISOString();
271
297
  acceptedAt: string | undefined;
298
+ /** Native turn id the driver reported at acceptance (codex) — carried to cancel and the outcome. */
299
+ nativeTurnId: string | undefined;
272
300
  firstOutputAt: string | undefined;
273
301
  outcomeResolved = false;
274
302
  cancelRequested = false;
@@ -431,7 +459,12 @@ class TurnSessionImpl implements TurnSession {
431
459
  this.state = 'busy';
432
460
  try {
433
461
  this.process.writeStdin(
434
- this.driver.encodeTurn({ turnId, prompt: input.prompt, correlation: input.correlation }),
462
+ this.driver.encodeTurn({
463
+ turnId,
464
+ prompt: input.prompt,
465
+ correlation: input.correlation,
466
+ scope: { nativeSessionId: this.nativeSessionId },
467
+ }),
435
468
  );
436
469
  } catch (error) {
437
470
  // A dead stdin means the process is gone: the turn never started.
@@ -445,7 +478,12 @@ class TurnSessionImpl implements TurnSession {
445
478
  if (!turn.outcomeResolved) {
446
479
  turn.cancelRequested = true;
447
480
  try {
448
- this.process.writeStdin(this.driver.encodeCancel(reason));
481
+ this.process.writeStdin(
482
+ this.driver.encodeCancel(reason, {
483
+ nativeSessionId: this.nativeSessionId,
484
+ nativeTurnId: turn.nativeTurnId,
485
+ }),
486
+ );
449
487
  } catch {
450
488
  // stdin gone — the exit handler settles deterministically.
451
489
  }
@@ -465,7 +503,12 @@ class TurnSessionImpl implements TurnSession {
465
503
  if (turn !== undefined && !turn.outcomeResolved) {
466
504
  turn.cancelRequested = true;
467
505
  try {
468
- this.process.writeStdin(this.driver.encodeCancel('session closing'));
506
+ this.process.writeStdin(
507
+ this.driver.encodeCancel('session closing', {
508
+ nativeSessionId: this.nativeSessionId,
509
+ nativeTurnId: turn.nativeTurnId,
510
+ }),
511
+ );
469
512
  } catch {
470
513
  // stdin gone
471
514
  }
@@ -507,7 +550,11 @@ class TurnSessionImpl implements TurnSession {
507
550
  const kind: TurnOutcomeKind = turn.cancelRequested ? 'interrupted' : wire.terminal.kind;
508
551
  turn.settle({
509
552
  kind,
510
- ...(wire.terminal.nativeTurnId !== undefined ? { nativeTurnId: wire.terminal.nativeTurnId } : {}),
553
+ ...(wire.terminal.nativeTurnId !== undefined
554
+ ? { nativeTurnId: wire.terminal.nativeTurnId }
555
+ : turn.nativeTurnId !== undefined
556
+ ? { nativeTurnId: turn.nativeTurnId }
557
+ : {}),
511
558
  ...(wire.terminal.nativeSessionId !== undefined
512
559
  ? { nativeSessionId: wire.terminal.nativeSessionId }
513
560
  : {}),
@@ -523,8 +570,11 @@ class TurnSessionImpl implements TurnSession {
523
570
  return;
524
571
  }
525
572
  if (wire.type === 'accepted') {
573
+ if (wire.nativeTurnId !== undefined && turn.nativeTurnId === undefined)
574
+ turn.nativeTurnId = wire.nativeTurnId;
526
575
  if (turn.acceptedAt === undefined) {
527
- turn.acceptedAt = at;
576
+ // `markAccepted` owns the `acceptedAt` write — setting it first would make its own
577
+ // idempotence guard skip `resolveAccepted`, leaving the `accepted` promise pending.
528
578
  turn.markAccepted();
529
579
  turn.emit({ type: 'accepted' });
530
580
  } else {
@@ -628,7 +678,7 @@ export async function openTurnSessionWithDriver(options: {
628
678
  let handshakeResult: TurnHandshake = null;
629
679
  if (driver.handshake !== undefined) {
630
680
  // A handshake that loses the race (or throws) must not surface as an unhandled rejection.
631
- const handshake = driver.handshake(pull).catch(() => null);
681
+ const handshake = driver.handshake(pull, (line) => process.writeStdin(line)).catch(() => null);
632
682
  try {
633
683
  handshakeResult = await Promise.race([handshake, delay(handshakeTimeoutMs)]);
634
684
  } catch {