@gobing-ai/ts-ai-runner 0.6.4 → 0.7.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 +10 -4
- package/dist/agents/shims.d.ts.map +1 -1
- package/dist/agents/shims.js +8 -5
- package/dist/turn-drivers/codex-app-server.d.ts +17 -0
- package/dist/turn-drivers/codex-app-server.d.ts.map +1 -0
- package/dist/turn-drivers/codex-app-server.js +188 -0
- package/dist/turn-session.d.ts +29 -5
- package/dist/turn-session.d.ts.map +1 -1
- package/dist/turn-session.js +39 -9
- package/package.json +4 -4
- package/src/agents/shims.ts +8 -5
- package/src/turn-drivers/codex-app-server.ts +258 -0
- package/src/turn-session.ts +81 -14
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.
|
|
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)
|
|
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).
|
|
941
|
-
|
|
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,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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
|
@@ -447,12 +447,15 @@ const AGENT_SESSION_CAPABILITY = {
|
|
|
447
447
|
codex: {
|
|
448
448
|
supportsResumeById: true,
|
|
449
449
|
supportsSessionDir: false,
|
|
450
|
-
supportsPersistentStdin:
|
|
450
|
+
supportsPersistentStdin: true,
|
|
451
451
|
supportsStructuredOutput: true,
|
|
452
|
-
verifiedAgainst: '0.
|
|
453
|
-
//
|
|
454
|
-
//
|
|
455
|
-
|
|
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,CA0KnB"}
|
|
@@ -0,0 +1,188 @@
|
|
|
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
|
+
// A `turn/completed` is attributed ONLY to the turn whose native identity it echoes:
|
|
142
|
+
// a foreign thread, or a native turn id that is not the accepted one, is foreign or
|
|
143
|
+
// stale and must never settle the active turn (task 1278 AC3 identity fence).
|
|
144
|
+
if (frame.params?.turn !== undefined && frame.method === 'turn/completed') {
|
|
145
|
+
const turn = frame.params.turn;
|
|
146
|
+
const frameThread = frame.params.threadId;
|
|
147
|
+
const foreignThread = context.nativeSessionId !== undefined &&
|
|
148
|
+
frameThread !== undefined &&
|
|
149
|
+
frameThread !== context.nativeSessionId;
|
|
150
|
+
const foreignTurn = context.nativeTurnId !== undefined && turn.id !== undefined && turn.id !== context.nativeTurnId;
|
|
151
|
+
if (foreignThread || foreignTurn)
|
|
152
|
+
return [{ turnId: context.turnId, type: 'diagnostic', data: frame }];
|
|
153
|
+
const terminal = {
|
|
154
|
+
// A native interruption is its own outcome when the caller did not request the
|
|
155
|
+
// cancel; the facade's cancel precedence still upgrades a requested one.
|
|
156
|
+
kind: turn.status === 'completed'
|
|
157
|
+
? 'success'
|
|
158
|
+
: turn.status === 'interrupted'
|
|
159
|
+
? 'interrupted'
|
|
160
|
+
: 'failure',
|
|
161
|
+
...(turn.id !== undefined ? { nativeTurnId: turn.id } : {}),
|
|
162
|
+
...(frameThread !== undefined ? { nativeSessionId: frameThread } : {}),
|
|
163
|
+
};
|
|
164
|
+
if (turn.status === 'interrupted')
|
|
165
|
+
terminal.reason = 'codex turn status interrupted';
|
|
166
|
+
else if (turn.status === 'failed')
|
|
167
|
+
terminal.reason = `codex turn failed: ${turn.error?.message ?? 'unspecified error'}`;
|
|
168
|
+
else if (turn.status !== 'completed')
|
|
169
|
+
return [{ turnId: context.turnId, type: 'diagnostic', data: frame }];
|
|
170
|
+
const text = finalTextOf(turn);
|
|
171
|
+
if (text !== undefined)
|
|
172
|
+
terminal.finalText = text;
|
|
173
|
+
return [{ turnId: context.turnId, type: 'terminal', terminal }];
|
|
174
|
+
}
|
|
175
|
+
if (frame.method === 'error' && frame.params?.error !== undefined) {
|
|
176
|
+
// Server-level error notification: surfaced as output so the consumer's artifact
|
|
177
|
+
// validation sees it; the turn terminal still comes from turn/completed.
|
|
178
|
+
return [{ turnId: context.turnId, type: 'diagnostic', data: frame }];
|
|
179
|
+
}
|
|
180
|
+
return [];
|
|
181
|
+
},
|
|
182
|
+
encodeCancel: (_reason, scope) => write({
|
|
183
|
+
id: '__spur_interrupt',
|
|
184
|
+
method: 'turn/interrupt',
|
|
185
|
+
params: { threadId: scope?.nativeSessionId, turnId: scope?.nativeTurnId },
|
|
186
|
+
}),
|
|
187
|
+
};
|
|
188
|
+
}
|
package/dist/turn-session.d.ts
CHANGED
|
@@ -98,9 +98,20 @@ 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
|
-
kind: 'success' | 'failure' | 'not-started';
|
|
114
|
+
kind: 'success' | 'failure' | 'interrupted' | 'not-started';
|
|
104
115
|
nativeTurnId?: string;
|
|
105
116
|
nativeSessionId?: string;
|
|
106
117
|
finalText?: string;
|
|
@@ -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 {
|
|
@@ -127,6 +140,14 @@ export declare class TurnProtocolError extends Error {
|
|
|
127
140
|
export interface TurnDecodeContext {
|
|
128
141
|
readonly turnId: string;
|
|
129
142
|
readonly accepted: boolean;
|
|
143
|
+
/**
|
|
144
|
+
* Native turn id the driver reported at acceptance for this turn (codex). A decoder whose
|
|
145
|
+
* notifications echo the native turn id must fence on it: a frame carrying a different native
|
|
146
|
+
* turn is foreign or stale and becomes a diagnostic, never this turn's terminal.
|
|
147
|
+
*/
|
|
148
|
+
readonly nativeTurnId?: string;
|
|
149
|
+
/** Native session/thread id of the open session, for the same identity fence. */
|
|
150
|
+
readonly nativeSessionId?: string;
|
|
130
151
|
}
|
|
131
152
|
/** Handshake result: the native session id when the agent reported one during startup. */
|
|
132
153
|
export type TurnHandshake = {
|
|
@@ -153,11 +174,13 @@ export interface TurnSessionDriver {
|
|
|
153
174
|
* no handshake. Pull via `pull(timeoutMs)` — NOT `for await` over a stream — because an
|
|
154
175
|
* early `return`/`break` in a for-await CLOSES the shared iterator the session pump needs.
|
|
155
176
|
*/
|
|
156
|
-
handshake?(pull: (timeoutMs: number) => Promise<string | null
|
|
177
|
+
handshake?(pull: (timeoutMs: number) => Promise<string | null>, write: (line: string) => void): Promise<TurnHandshake>;
|
|
157
178
|
encodeTurn(input: {
|
|
158
179
|
turnId: string;
|
|
159
180
|
prompt: string;
|
|
160
181
|
correlation: TurnCorrelation;
|
|
182
|
+
/** Native identity for drivers whose turn frame must address a native thread (codex). */
|
|
183
|
+
scope?: TurnWireScope;
|
|
161
184
|
}): string;
|
|
162
185
|
/**
|
|
163
186
|
* Decode one stdout line into zero or more frames; throws {@link TurnProtocolError} on
|
|
@@ -165,7 +188,7 @@ export interface TurnSessionDriver {
|
|
|
165
188
|
* protocol cannot self-attribute (claude); drivers that echo turn ids may ignore it.
|
|
166
189
|
*/
|
|
167
190
|
decode(line: string, context?: TurnDecodeContext): TurnWireEvent[];
|
|
168
|
-
encodeCancel(reason: string): string;
|
|
191
|
+
encodeCancel(reason: string, scope?: TurnWireScope): string;
|
|
169
192
|
}
|
|
170
193
|
/** Outcome of {@link AiRunner.openTurnSession}: an open session or a typed failure reason. */
|
|
171
194
|
export type OpenTurnSessionResult = {
|
|
@@ -179,8 +202,9 @@ export type OpenTurnSessionResult = {
|
|
|
179
202
|
/**
|
|
180
203
|
* Built-in driver registry. Entries land only with recorded qualification evidence (anti-pattern:
|
|
181
204
|
* registration without evidence): claude 2.1.308 stream-json (task 1276, fixtures under
|
|
182
|
-
* `tests/fixtures/turn-drivers/claude`)
|
|
183
|
-
* `tests/fixtures/turn-drivers/pi`)
|
|
205
|
+
* `tests/fixtures/turn-drivers/claude`), pi 0.87.1 rpc (task 1277, fixtures under
|
|
206
|
+
* `tests/fixtures/turn-drivers/pi`) and codex 0.164.0 app-server (task 1278, fixtures under
|
|
207
|
+
* `tests/fixtures/turn-drivers/codex`). 0.x shipped this empty by design.
|
|
184
208
|
*/
|
|
185
209
|
export declare const TURN_SESSION_DRIVERS: ReadonlyMap<AgentName, TurnSessionDriver>;
|
|
186
210
|
/** 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;
|
|
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;AAKhD;;;;;;GAMG;AAEH,0GAA0G;AAC1G,MAAM,MAAM,eA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SessionDriver } 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`)
|
|
15
|
-
* `tests/fixtures/turn-drivers/pi`)
|
|
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({
|
|
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
|
|
@@ -314,10 +330,16 @@ class TurnSessionImpl {
|
|
|
314
330
|
if (wire.type === 'terminal' && wire.terminal !== undefined) {
|
|
315
331
|
// Decoder terminals carry their own pre-acceptance classification (`not-started`);
|
|
316
332
|
// cancel precedence still wins over whatever the wire reported.
|
|
333
|
+
// Cancel precedence: a caller-requested cancel is `interrupted` whatever the wire said;
|
|
334
|
+
// otherwise the wire kind passes through, including a NATIVE `interrupted` (1278).
|
|
317
335
|
const kind = turn.cancelRequested ? 'interrupted' : wire.terminal.kind;
|
|
318
336
|
turn.settle({
|
|
319
337
|
kind,
|
|
320
|
-
...(wire.terminal.nativeTurnId !== undefined
|
|
338
|
+
...(wire.terminal.nativeTurnId !== undefined
|
|
339
|
+
? { nativeTurnId: wire.terminal.nativeTurnId }
|
|
340
|
+
: turn.nativeTurnId !== undefined
|
|
341
|
+
? { nativeTurnId: turn.nativeTurnId }
|
|
342
|
+
: {}),
|
|
321
343
|
...(wire.terminal.nativeSessionId !== undefined
|
|
322
344
|
? { nativeSessionId: wire.terminal.nativeSessionId }
|
|
323
345
|
: {}),
|
|
@@ -334,8 +356,11 @@ class TurnSessionImpl {
|
|
|
334
356
|
return;
|
|
335
357
|
}
|
|
336
358
|
if (wire.type === 'accepted') {
|
|
359
|
+
if (wire.nativeTurnId !== undefined && turn.nativeTurnId === undefined)
|
|
360
|
+
turn.nativeTurnId = wire.nativeTurnId;
|
|
337
361
|
if (turn.acceptedAt === undefined) {
|
|
338
|
-
|
|
362
|
+
// `markAccepted` owns the `acceptedAt` write — setting it first would make its own
|
|
363
|
+
// idempotence guard skip `resolveAccepted`, leaving the `accepted` promise pending.
|
|
339
364
|
turn.markAccepted();
|
|
340
365
|
turn.emit({ type: 'accepted' });
|
|
341
366
|
}
|
|
@@ -354,7 +379,12 @@ class TurnSessionImpl {
|
|
|
354
379
|
const active = this.active;
|
|
355
380
|
const context = active === undefined
|
|
356
381
|
? undefined
|
|
357
|
-
: {
|
|
382
|
+
: {
|
|
383
|
+
turnId: active.turnId,
|
|
384
|
+
accepted: active.acceptedAt !== undefined,
|
|
385
|
+
...(active.nativeTurnId !== undefined ? { nativeTurnId: active.nativeTurnId } : {}),
|
|
386
|
+
...(this.nativeSessionId !== undefined ? { nativeSessionId: this.nativeSessionId } : {}),
|
|
387
|
+
};
|
|
358
388
|
const wires = this.driver.decode(line, context);
|
|
359
389
|
for (const wire of wires)
|
|
360
390
|
this.route(wire);
|
|
@@ -433,7 +463,7 @@ export async function openTurnSessionWithDriver(options) {
|
|
|
433
463
|
let handshakeResult = null;
|
|
434
464
|
if (driver.handshake !== undefined) {
|
|
435
465
|
// A handshake that loses the race (or throws) must not surface as an unhandled rejection.
|
|
436
|
-
const handshake = driver.handshake(pull).catch(() => null);
|
|
466
|
+
const handshake = driver.handshake(pull, (line) => process.writeStdin(line)).catch(() => null);
|
|
437
467
|
try {
|
|
438
468
|
handshakeResult = await Promise.race([handshake, delay(handshakeTimeoutMs)]);
|
|
439
469
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gobing-ai/ts-ai-runner",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.1",
|
|
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.
|
|
55
|
-
"@gobing-ai/ts-runtime": "^0.
|
|
54
|
+
"@gobing-ai/ts-infra": "^0.7.1",
|
|
55
|
+
"@gobing-ai/ts-runtime": "^0.7.1"
|
|
56
56
|
},
|
|
57
57
|
"devDependencies": {
|
|
58
58
|
"@types/bun": "1.4.3",
|
|
59
|
-
"@gobing-ai/ts-db": "^0.
|
|
59
|
+
"@gobing-ai/ts-db": "^0.7.1"
|
|
60
60
|
},
|
|
61
61
|
"publishConfig": {
|
|
62
62
|
"access": "public"
|
package/src/agents/shims.ts
CHANGED
|
@@ -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:
|
|
573
|
+
supportsPersistentStdin: true,
|
|
574
574
|
supportsStructuredOutput: true,
|
|
575
|
-
verifiedAgainst: '0.
|
|
576
|
-
//
|
|
577
|
-
//
|
|
578
|
-
|
|
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,258 @@
|
|
|
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
|
+
// A `turn/completed` is attributed ONLY to the turn whose native identity it echoes:
|
|
211
|
+
// a foreign thread, or a native turn id that is not the accepted one, is foreign or
|
|
212
|
+
// stale and must never settle the active turn (task 1278 AC3 identity fence).
|
|
213
|
+
if (frame.params?.turn !== undefined && frame.method === 'turn/completed') {
|
|
214
|
+
const turn = frame.params.turn;
|
|
215
|
+
const frameThread = frame.params.threadId;
|
|
216
|
+
const foreignThread =
|
|
217
|
+
context.nativeSessionId !== undefined &&
|
|
218
|
+
frameThread !== undefined &&
|
|
219
|
+
frameThread !== context.nativeSessionId;
|
|
220
|
+
const foreignTurn =
|
|
221
|
+
context.nativeTurnId !== undefined && turn.id !== undefined && turn.id !== context.nativeTurnId;
|
|
222
|
+
if (foreignThread || foreignTurn) return [{ turnId: context.turnId, type: 'diagnostic', data: frame }];
|
|
223
|
+
const terminal: TurnWireTerminal = {
|
|
224
|
+
// A native interruption is its own outcome when the caller did not request the
|
|
225
|
+
// cancel; the facade's cancel precedence still upgrades a requested one.
|
|
226
|
+
kind:
|
|
227
|
+
turn.status === 'completed'
|
|
228
|
+
? 'success'
|
|
229
|
+
: turn.status === 'interrupted'
|
|
230
|
+
? 'interrupted'
|
|
231
|
+
: 'failure',
|
|
232
|
+
...(turn.id !== undefined ? { nativeTurnId: turn.id } : {}),
|
|
233
|
+
...(frameThread !== undefined ? { nativeSessionId: frameThread } : {}),
|
|
234
|
+
};
|
|
235
|
+
if (turn.status === 'interrupted') terminal.reason = 'codex turn status interrupted';
|
|
236
|
+
else if (turn.status === 'failed')
|
|
237
|
+
terminal.reason = `codex turn failed: ${turn.error?.message ?? 'unspecified error'}`;
|
|
238
|
+
else if (turn.status !== 'completed')
|
|
239
|
+
return [{ turnId: context.turnId, type: 'diagnostic', data: frame }];
|
|
240
|
+
const text = finalTextOf(turn);
|
|
241
|
+
if (text !== undefined) terminal.finalText = text;
|
|
242
|
+
return [{ turnId: context.turnId, type: 'terminal', terminal }];
|
|
243
|
+
}
|
|
244
|
+
if (frame.method === 'error' && frame.params?.error !== undefined) {
|
|
245
|
+
// Server-level error notification: surfaced as output so the consumer's artifact
|
|
246
|
+
// validation sees it; the turn terminal still comes from turn/completed.
|
|
247
|
+
return [{ turnId: context.turnId, type: 'diagnostic', data: frame }];
|
|
248
|
+
}
|
|
249
|
+
return [];
|
|
250
|
+
},
|
|
251
|
+
encodeCancel: (_reason: string, scope?: TurnWireScope) =>
|
|
252
|
+
write({
|
|
253
|
+
id: '__spur_interrupt',
|
|
254
|
+
method: 'turn/interrupt',
|
|
255
|
+
params: { threadId: scope?.nativeSessionId, turnId: scope?.nativeTurnId },
|
|
256
|
+
}),
|
|
257
|
+
};
|
|
258
|
+
}
|
package/src/turn-session.ts
CHANGED
|
@@ -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,11 +99,25 @@ 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
|
|
104
|
-
// prompt command before any run started)
|
|
105
|
-
|
|
117
|
+
// prompt command before any run started) and `interrupted` is a NATIVE interruption the
|
|
118
|
+
// caller did not necessarily request (codex `turn/completed` status, task 1278) — both must
|
|
119
|
+
// survive the facade mapping unchanged. A caller-requested cancel still wins over the wire.
|
|
120
|
+
kind: 'success' | 'failure' | 'interrupted' | 'not-started';
|
|
106
121
|
nativeTurnId?: string;
|
|
107
122
|
nativeSessionId?: string;
|
|
108
123
|
finalText?: string;
|
|
@@ -115,6 +130,8 @@ export interface TurnWireEvent {
|
|
|
115
130
|
type: 'accepted' | 'output' | 'diagnostic' | 'terminal';
|
|
116
131
|
data?: unknown;
|
|
117
132
|
terminal?: TurnWireTerminal;
|
|
133
|
+
/** Native turn id observed on the acceptance frame (codex `turn/start` result). */
|
|
134
|
+
nativeTurnId?: string;
|
|
118
135
|
}
|
|
119
136
|
|
|
120
137
|
/** Thrown by `TurnSessionDriver.decode` on a malformed frame — settles the turn `contract-violation`. */
|
|
@@ -135,6 +152,14 @@ export class TurnProtocolError extends Error {
|
|
|
135
152
|
export interface TurnDecodeContext {
|
|
136
153
|
readonly turnId: string;
|
|
137
154
|
readonly accepted: boolean;
|
|
155
|
+
/**
|
|
156
|
+
* Native turn id the driver reported at acceptance for this turn (codex). A decoder whose
|
|
157
|
+
* notifications echo the native turn id must fence on it: a frame carrying a different native
|
|
158
|
+
* turn is foreign or stale and becomes a diagnostic, never this turn's terminal.
|
|
159
|
+
*/
|
|
160
|
+
readonly nativeTurnId?: string;
|
|
161
|
+
/** Native session/thread id of the open session, for the same identity fence. */
|
|
162
|
+
readonly nativeSessionId?: string;
|
|
138
163
|
}
|
|
139
164
|
|
|
140
165
|
/** Handshake result: the native session id when the agent reported one during startup. */
|
|
@@ -153,15 +178,24 @@ export interface TurnSessionDriver {
|
|
|
153
178
|
* no handshake. Pull via `pull(timeoutMs)` — NOT `for await` over a stream — because an
|
|
154
179
|
* early `return`/`break` in a for-await CLOSES the shared iterator the session pump needs.
|
|
155
180
|
*/
|
|
156
|
-
handshake?(
|
|
157
|
-
|
|
181
|
+
handshake?(
|
|
182
|
+
pull: (timeoutMs: number) => Promise<string | null>,
|
|
183
|
+
write: (line: string) => void,
|
|
184
|
+
): Promise<TurnHandshake>;
|
|
185
|
+
encodeTurn(input: {
|
|
186
|
+
turnId: string;
|
|
187
|
+
prompt: string;
|
|
188
|
+
correlation: TurnCorrelation;
|
|
189
|
+
/** Native identity for drivers whose turn frame must address a native thread (codex). */
|
|
190
|
+
scope?: TurnWireScope;
|
|
191
|
+
}): string;
|
|
158
192
|
/**
|
|
159
193
|
* Decode one stdout line into zero or more frames; throws {@link TurnProtocolError} on
|
|
160
194
|
* malformed input. `context` carries the session's current active turn for drivers whose
|
|
161
195
|
* protocol cannot self-attribute (claude); drivers that echo turn ids may ignore it.
|
|
162
196
|
*/
|
|
163
197
|
decode(line: string, context?: TurnDecodeContext): TurnWireEvent[];
|
|
164
|
-
encodeCancel(reason: string): string;
|
|
198
|
+
encodeCancel(reason: string, scope?: TurnWireScope): string;
|
|
165
199
|
}
|
|
166
200
|
|
|
167
201
|
/** Outcome of {@link AiRunner.openTurnSession}: an open session or a typed failure reason. */
|
|
@@ -176,11 +210,13 @@ export type OpenTurnSessionResult =
|
|
|
176
210
|
/**
|
|
177
211
|
* Built-in driver registry. Entries land only with recorded qualification evidence (anti-pattern:
|
|
178
212
|
* registration without evidence): claude 2.1.308 stream-json (task 1276, fixtures under
|
|
179
|
-
* `tests/fixtures/turn-drivers/claude`)
|
|
180
|
-
* `tests/fixtures/turn-drivers/pi`)
|
|
213
|
+
* `tests/fixtures/turn-drivers/claude`), pi 0.87.1 rpc (task 1277, fixtures under
|
|
214
|
+
* `tests/fixtures/turn-drivers/pi`) and codex 0.164.0 app-server (task 1278, fixtures under
|
|
215
|
+
* `tests/fixtures/turn-drivers/codex`). 0.x shipped this empty by design.
|
|
181
216
|
*/
|
|
182
217
|
export const TURN_SESSION_DRIVERS: ReadonlyMap<AgentName, TurnSessionDriver> = new Map([
|
|
183
218
|
['claude', createClaudeTurnSessionDriver()],
|
|
219
|
+
['codex', createCodexTurnSessionDriver()],
|
|
184
220
|
['pi', createPiTurnSessionDriver()],
|
|
185
221
|
]);
|
|
186
222
|
|
|
@@ -269,6 +305,8 @@ class ActiveTurn implements TurnHandle {
|
|
|
269
305
|
readonly correlation: TurnCorrelation;
|
|
270
306
|
readonly startedAt = new Date().toISOString();
|
|
271
307
|
acceptedAt: string | undefined;
|
|
308
|
+
/** Native turn id the driver reported at acceptance (codex) — carried to cancel and the outcome. */
|
|
309
|
+
nativeTurnId: string | undefined;
|
|
272
310
|
firstOutputAt: string | undefined;
|
|
273
311
|
outcomeResolved = false;
|
|
274
312
|
cancelRequested = false;
|
|
@@ -431,7 +469,12 @@ class TurnSessionImpl implements TurnSession {
|
|
|
431
469
|
this.state = 'busy';
|
|
432
470
|
try {
|
|
433
471
|
this.process.writeStdin(
|
|
434
|
-
this.driver.encodeTurn({
|
|
472
|
+
this.driver.encodeTurn({
|
|
473
|
+
turnId,
|
|
474
|
+
prompt: input.prompt,
|
|
475
|
+
correlation: input.correlation,
|
|
476
|
+
scope: { nativeSessionId: this.nativeSessionId },
|
|
477
|
+
}),
|
|
435
478
|
);
|
|
436
479
|
} catch (error) {
|
|
437
480
|
// A dead stdin means the process is gone: the turn never started.
|
|
@@ -445,7 +488,12 @@ class TurnSessionImpl implements TurnSession {
|
|
|
445
488
|
if (!turn.outcomeResolved) {
|
|
446
489
|
turn.cancelRequested = true;
|
|
447
490
|
try {
|
|
448
|
-
this.process.writeStdin(
|
|
491
|
+
this.process.writeStdin(
|
|
492
|
+
this.driver.encodeCancel(reason, {
|
|
493
|
+
nativeSessionId: this.nativeSessionId,
|
|
494
|
+
nativeTurnId: turn.nativeTurnId,
|
|
495
|
+
}),
|
|
496
|
+
);
|
|
449
497
|
} catch {
|
|
450
498
|
// stdin gone — the exit handler settles deterministically.
|
|
451
499
|
}
|
|
@@ -465,7 +513,12 @@ class TurnSessionImpl implements TurnSession {
|
|
|
465
513
|
if (turn !== undefined && !turn.outcomeResolved) {
|
|
466
514
|
turn.cancelRequested = true;
|
|
467
515
|
try {
|
|
468
|
-
this.process.writeStdin(
|
|
516
|
+
this.process.writeStdin(
|
|
517
|
+
this.driver.encodeCancel('session closing', {
|
|
518
|
+
nativeSessionId: this.nativeSessionId,
|
|
519
|
+
nativeTurnId: turn.nativeTurnId,
|
|
520
|
+
}),
|
|
521
|
+
);
|
|
469
522
|
} catch {
|
|
470
523
|
// stdin gone
|
|
471
524
|
}
|
|
@@ -504,10 +557,16 @@ class TurnSessionImpl implements TurnSession {
|
|
|
504
557
|
if (wire.type === 'terminal' && wire.terminal !== undefined) {
|
|
505
558
|
// Decoder terminals carry their own pre-acceptance classification (`not-started`);
|
|
506
559
|
// cancel precedence still wins over whatever the wire reported.
|
|
560
|
+
// Cancel precedence: a caller-requested cancel is `interrupted` whatever the wire said;
|
|
561
|
+
// otherwise the wire kind passes through, including a NATIVE `interrupted` (1278).
|
|
507
562
|
const kind: TurnOutcomeKind = turn.cancelRequested ? 'interrupted' : wire.terminal.kind;
|
|
508
563
|
turn.settle({
|
|
509
564
|
kind,
|
|
510
|
-
...(wire.terminal.nativeTurnId !== undefined
|
|
565
|
+
...(wire.terminal.nativeTurnId !== undefined
|
|
566
|
+
? { nativeTurnId: wire.terminal.nativeTurnId }
|
|
567
|
+
: turn.nativeTurnId !== undefined
|
|
568
|
+
? { nativeTurnId: turn.nativeTurnId }
|
|
569
|
+
: {}),
|
|
511
570
|
...(wire.terminal.nativeSessionId !== undefined
|
|
512
571
|
? { nativeSessionId: wire.terminal.nativeSessionId }
|
|
513
572
|
: {}),
|
|
@@ -523,8 +582,11 @@ class TurnSessionImpl implements TurnSession {
|
|
|
523
582
|
return;
|
|
524
583
|
}
|
|
525
584
|
if (wire.type === 'accepted') {
|
|
585
|
+
if (wire.nativeTurnId !== undefined && turn.nativeTurnId === undefined)
|
|
586
|
+
turn.nativeTurnId = wire.nativeTurnId;
|
|
526
587
|
if (turn.acceptedAt === undefined) {
|
|
527
|
-
|
|
588
|
+
// `markAccepted` owns the `acceptedAt` write — setting it first would make its own
|
|
589
|
+
// idempotence guard skip `resolveAccepted`, leaving the `accepted` promise pending.
|
|
528
590
|
turn.markAccepted();
|
|
529
591
|
turn.emit({ type: 'accepted' });
|
|
530
592
|
} else {
|
|
@@ -544,7 +606,12 @@ class TurnSessionImpl implements TurnSession {
|
|
|
544
606
|
const context: TurnDecodeContext | undefined =
|
|
545
607
|
active === undefined
|
|
546
608
|
? undefined
|
|
547
|
-
: {
|
|
609
|
+
: {
|
|
610
|
+
turnId: active.turnId,
|
|
611
|
+
accepted: active.acceptedAt !== undefined,
|
|
612
|
+
...(active.nativeTurnId !== undefined ? { nativeTurnId: active.nativeTurnId } : {}),
|
|
613
|
+
...(this.nativeSessionId !== undefined ? { nativeSessionId: this.nativeSessionId } : {}),
|
|
614
|
+
};
|
|
548
615
|
const wires = this.driver.decode(line, context);
|
|
549
616
|
for (const wire of wires) this.route(wire);
|
|
550
617
|
}
|
|
@@ -628,7 +695,7 @@ export async function openTurnSessionWithDriver(options: {
|
|
|
628
695
|
let handshakeResult: TurnHandshake = null;
|
|
629
696
|
if (driver.handshake !== undefined) {
|
|
630
697
|
// A handshake that loses the race (or throws) must not surface as an unhandled rejection.
|
|
631
|
-
const handshake = driver.handshake(pull).catch(() => null);
|
|
698
|
+
const handshake = driver.handshake(pull, (line) => process.writeStdin(line)).catch(() => null);
|
|
632
699
|
try {
|
|
633
700
|
handshakeResult = await Promise.race([handshake, delay(handshakeTimeoutMs)]);
|
|
634
701
|
} catch {
|