@gobing-ai/ts-ai-runner 0.5.32 → 0.6.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 +6 -2
- package/dist/ai-runner.d.ts +12 -0
- package/dist/ai-runner.d.ts.map +1 -1
- package/dist/ai-runner.js +36 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/testing/fake-turn-agent.d.ts +2 -0
- package/dist/testing/fake-turn-agent.d.ts.map +1 -0
- package/dist/testing/fake-turn-agent.js +114 -0
- package/dist/testing/fake-turn-driver.d.ts +22 -0
- package/dist/testing/fake-turn-driver.d.ts.map +1 -0
- package/dist/testing/fake-turn-driver.js +66 -0
- package/dist/turn-session.d.ts +201 -0
- package/dist/turn-session.d.ts.map +1 -0
- package/dist/turn-session.js +452 -0
- package/package.json +8 -4
- package/src/ai-runner.ts +55 -0
- package/src/index.ts +1 -0
- package/src/testing/fake-turn-agent.ts +123 -0
- package/src/testing/fake-turn-driver.ts +99 -0
- package/src/turn-session.ts +627 -0
|
@@ -0,0 +1,627 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import type { PipeProcess, ProcessExecutor } from '@gobing-ai/ts-runtime';
|
|
3
|
+
import type { AgentName } from './agents/shims';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Correlated warm-turn session facade (task 1284, design `fleet-task-turn-execution.md` §4–5,
|
|
7
|
+
* ADR-145): ts-ai-runner owns the process/protocol mechanics of one long-lived agent session;
|
|
8
|
+
* consumers (Spur) own policy, receipts and validation. 0.x ships the CONTRACT with no
|
|
9
|
+
* real-agent driver registered — claude/pi/codex drivers land with their qualification
|
|
10
|
+
* evidence in Spur tasks 1276–1278.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** Terminal classification of one turn. Exactly one outcome per turn, never upgraded after resolution. */
|
|
14
|
+
export type TurnOutcomeKind =
|
|
15
|
+
| 'success'
|
|
16
|
+
| 'failure'
|
|
17
|
+
| 'interrupted'
|
|
18
|
+
| 'not-started'
|
|
19
|
+
| 'outcome-unknown'
|
|
20
|
+
| 'contract-violation';
|
|
21
|
+
|
|
22
|
+
/** Correlation carried on every turn: the runner-level ids plus the caller's per-request identity. */
|
|
23
|
+
export interface TurnCorrelation {
|
|
24
|
+
readonly runId: string;
|
|
25
|
+
readonly executionId: string;
|
|
26
|
+
readonly requestId: string;
|
|
27
|
+
readonly attempt: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Durable session placement; digested into `policyDigest` for consumer-side reuse checks. */
|
|
31
|
+
export interface TurnSessionPolicy {
|
|
32
|
+
workspace: string;
|
|
33
|
+
role: string;
|
|
34
|
+
model?: string;
|
|
35
|
+
provider?: string;
|
|
36
|
+
reasoning?: string;
|
|
37
|
+
tools?: readonly string[];
|
|
38
|
+
permissions?: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** One resolved turn. `nativeSessionId`/`nativeTurnId` are present only when the driver observed them. */
|
|
42
|
+
export interface TurnOutcome {
|
|
43
|
+
kind: TurnOutcomeKind;
|
|
44
|
+
turnId: string;
|
|
45
|
+
correlation: TurnCorrelation;
|
|
46
|
+
nativeSessionId?: string;
|
|
47
|
+
nativeTurnId?: string;
|
|
48
|
+
reason?: string;
|
|
49
|
+
finalText?: string;
|
|
50
|
+
startedAt: string;
|
|
51
|
+
acceptedAt?: string;
|
|
52
|
+
firstOutputAt?: string;
|
|
53
|
+
terminalAt: string;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Turn progress events surfaced live on a handle; `terminal` is the last event. */
|
|
57
|
+
export type TurnEvent =
|
|
58
|
+
| { type: 'accepted'; turnId: string; at: string }
|
|
59
|
+
| { type: 'output'; turnId: string; at: string; data?: unknown }
|
|
60
|
+
| { type: 'diagnostic'; turnId: string; at: string; data?: unknown }
|
|
61
|
+
| { type: 'terminal'; turnId: string; at: string; outcome: TurnOutcome };
|
|
62
|
+
|
|
63
|
+
/** One started turn: acceptance and outcome are SEPARATE promises (acceptance ≠ completion). */
|
|
64
|
+
export interface TurnHandle {
|
|
65
|
+
readonly turnId: string;
|
|
66
|
+
/** Resolves once the agent accepted the turn; `null` when the process died before acceptance. */
|
|
67
|
+
readonly accepted: Promise<{ acceptedAt: string } | null>;
|
|
68
|
+
/** Resolves exactly once to the terminal outcome. */
|
|
69
|
+
readonly outcome: Promise<TurnOutcome>;
|
|
70
|
+
/** Live event stream; completes when the outcome resolves. */
|
|
71
|
+
readonly events: AsyncIterable<TurnEvent>;
|
|
72
|
+
/** Request cancellation; resolves with the final outcome (deterministic, bounded by the grace). */
|
|
73
|
+
cancel(reason: string, options?: { graceMs?: number }): Promise<TurnOutcome>;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** An open session over one agent process. Admits ONE active turn; busy is an error, not a queue. */
|
|
77
|
+
export interface TurnSession {
|
|
78
|
+
readonly agent: AgentName;
|
|
79
|
+
/** sha256 of the canonical-JSON policy (stable key order) — consumers compare digests for reuse. */
|
|
80
|
+
readonly policyDigest: string;
|
|
81
|
+
readonly nativeSessionId?: string;
|
|
82
|
+
readonly state: 'ready' | 'busy' | 'closed';
|
|
83
|
+
startTurn(input: {
|
|
84
|
+
prompt: string;
|
|
85
|
+
correlation: TurnCorrelation;
|
|
86
|
+
timeoutMs?: number;
|
|
87
|
+
signal?: AbortSignal;
|
|
88
|
+
}): TurnHandle;
|
|
89
|
+
close(): Promise<void>;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Resolved agent binary identity a driver qualifies and spawns. */
|
|
93
|
+
export interface TurnBinary {
|
|
94
|
+
path: string;
|
|
95
|
+
/** `null` when the version could not be probed — drivers decide whether that qualifies. */
|
|
96
|
+
version: string | null;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** A wire-level terminal extracted from one decoded line. */
|
|
100
|
+
export interface TurnWireTerminal {
|
|
101
|
+
kind: 'success' | 'failure';
|
|
102
|
+
nativeTurnId?: string;
|
|
103
|
+
nativeSessionId?: string;
|
|
104
|
+
finalText?: string;
|
|
105
|
+
reason?: string;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** One decoded protocol frame routed by `turnId` (`null` = foreign/unattributable → diagnostic). */
|
|
109
|
+
export interface TurnWireEvent {
|
|
110
|
+
turnId: string | null;
|
|
111
|
+
type: 'accepted' | 'output' | 'diagnostic' | 'terminal';
|
|
112
|
+
data?: unknown;
|
|
113
|
+
terminal?: TurnWireTerminal;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Thrown by `TurnSessionDriver.decode` on a malformed frame — settles the turn `contract-violation`. */
|
|
117
|
+
export class TurnProtocolError extends Error {
|
|
118
|
+
constructor(message: string) {
|
|
119
|
+
super(message);
|
|
120
|
+
this.name = 'TurnProtocolError';
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Handshake result: the native session id when the agent reported one during startup. */
|
|
125
|
+
export type TurnHandshake = { nativeSessionId?: string } | null;
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Per-agent driver behind the session facade. Real drivers are registered only with recorded
|
|
129
|
+
* `verifiedAgainst` qualification evidence (anti-pattern: registration without evidence).
|
|
130
|
+
*/
|
|
131
|
+
export interface TurnSessionDriver {
|
|
132
|
+
readonly agent: AgentName;
|
|
133
|
+
qualify(binary: TurnBinary): { qualified: true } | { qualified: false; reason: string };
|
|
134
|
+
spawnArgv(binary: TurnBinary, policy: TurnSessionPolicy): { command: string; args: string[] };
|
|
135
|
+
/**
|
|
136
|
+
* Consume startup lines until the agent is ready; reject/throw on a bad handshake. Absent =
|
|
137
|
+
* no handshake. Pull via `pull(timeoutMs)` — NOT `for await` over a stream — because an
|
|
138
|
+
* early `return`/`break` in a for-await CLOSES the shared iterator the session pump needs.
|
|
139
|
+
*/
|
|
140
|
+
handshake?(pull: (timeoutMs: number) => Promise<string | null>): Promise<TurnHandshake>;
|
|
141
|
+
encodeTurn(input: { turnId: string; prompt: string; correlation: TurnCorrelation }): string;
|
|
142
|
+
/** Decode one stdout line into zero or more frames; throws {@link TurnProtocolError} on malformed input. */
|
|
143
|
+
decode(line: string): TurnWireEvent[];
|
|
144
|
+
encodeCancel(reason: string): string;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Outcome of {@link AiRunner.openTurnSession}: an open session or a typed failure reason. */
|
|
148
|
+
export type OpenTurnSessionResult =
|
|
149
|
+
| { ok: true; session: TurnSession }
|
|
150
|
+
| {
|
|
151
|
+
ok: false;
|
|
152
|
+
reason: 'unsupported-agent' | 'unqualified-version' | 'spawn-failed' | 'handshake-failed';
|
|
153
|
+
detail: string;
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
/** Built-in driver registry. Empty in 0.x by design — real drivers land with qualification evidence. */
|
|
157
|
+
export const TURN_SESSION_DRIVERS: ReadonlyMap<AgentName, TurnSessionDriver> = new Map();
|
|
158
|
+
|
|
159
|
+
/** How long `cancel()` waits for native terminal evidence before resolving `outcome-unknown`. */
|
|
160
|
+
export const TURN_CANCEL_GRACE_MS = 5_000;
|
|
161
|
+
/** Handshake bound for `openTurnSession`. */
|
|
162
|
+
export const TURN_HANDSHAKE_TIMEOUT_MS = 10_000;
|
|
163
|
+
/** Max buffered stdout line; overflow is a protocol contract violation. */
|
|
164
|
+
export const TURN_MAX_LINE_BYTES = 1024 * 1024;
|
|
165
|
+
|
|
166
|
+
/** `startTurn` while another turn is active — no hidden queue, by design. */
|
|
167
|
+
export class TurnSessionBusyError extends Error {
|
|
168
|
+
constructor(turnId: string) {
|
|
169
|
+
super(`turn session busy: turn ${turnId} is still active`);
|
|
170
|
+
this.name = 'TurnSessionBusyError';
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** `startTurn` on a closed session. */
|
|
175
|
+
export class TurnSessionClosedError extends Error {
|
|
176
|
+
constructor() {
|
|
177
|
+
super('turn session is closed');
|
|
178
|
+
this.name = 'TurnSessionClosedError';
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** sha256 over the canonical JSON (recursively sorted keys) of the policy — stable digest contract. */
|
|
183
|
+
export function turnSessionPolicyDigest(policy: TurnSessionPolicy): string {
|
|
184
|
+
const canonical = (value: unknown): unknown => {
|
|
185
|
+
if (Array.isArray(value)) return value.map(canonical);
|
|
186
|
+
if (value !== null && typeof value === 'object') {
|
|
187
|
+
return Object.fromEntries(
|
|
188
|
+
Object.entries(value as Record<string, unknown>)
|
|
189
|
+
.sort(([a], [b]) => (a < b ? -1 : 1))
|
|
190
|
+
.map(([key, item]) => [key, canonical(item)]),
|
|
191
|
+
);
|
|
192
|
+
}
|
|
193
|
+
return value;
|
|
194
|
+
};
|
|
195
|
+
return createHash('sha256')
|
|
196
|
+
.update(JSON.stringify(canonical(policy)))
|
|
197
|
+
.digest('hex');
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Line-buffered stdout reader with the bounded-buffer invariant (overflow invokes `onOverflow`
|
|
202
|
+
* and ends the iteration). The single reader of the process stdout stream — both the handshake
|
|
203
|
+
* and the session pump pull from the SAME generator.
|
|
204
|
+
*/
|
|
205
|
+
export async function* readLines(stream: ReadableStream<Uint8Array>): AsyncGenerator<string> {
|
|
206
|
+
const decoder = new TextDecoder();
|
|
207
|
+
let buffer = '';
|
|
208
|
+
const reader = stream.getReader();
|
|
209
|
+
try {
|
|
210
|
+
while (true) {
|
|
211
|
+
const chunk = await reader.read();
|
|
212
|
+
if (chunk.done) break;
|
|
213
|
+
buffer += decoder.decode(chunk.value, { stream: true });
|
|
214
|
+
for (;;) {
|
|
215
|
+
const newline = buffer.indexOf('\n');
|
|
216
|
+
if (newline === -1) break;
|
|
217
|
+
const line = buffer.slice(0, newline);
|
|
218
|
+
buffer = buffer.slice(newline + 1);
|
|
219
|
+
if (Buffer.byteLength(line, 'utf8') > TURN_MAX_LINE_BYTES) {
|
|
220
|
+
throw new TurnProtocolError(`stdout line exceeded ${TURN_MAX_LINE_BYTES} bytes`);
|
|
221
|
+
}
|
|
222
|
+
yield line;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
const tail = buffer + decoder.decode();
|
|
226
|
+
if (tail.length > 0) yield tail;
|
|
227
|
+
} finally {
|
|
228
|
+
reader.releaseLock();
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function delay(ms: number): Promise<null> {
|
|
233
|
+
return new Promise((resolve) => {
|
|
234
|
+
setTimeout(() => resolve(null), ms);
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** Per-turn state: deferred accepted/outcome promises, event queue, exactly-once settlement. */
|
|
239
|
+
class ActiveTurn implements TurnHandle {
|
|
240
|
+
readonly turnId: string;
|
|
241
|
+
readonly correlation: TurnCorrelation;
|
|
242
|
+
readonly startedAt = new Date().toISOString();
|
|
243
|
+
acceptedAt: string | undefined;
|
|
244
|
+
firstOutputAt: string | undefined;
|
|
245
|
+
outcomeResolved = false;
|
|
246
|
+
cancelRequested = false;
|
|
247
|
+
readonly accepted: Promise<{ acceptedAt: string } | null>;
|
|
248
|
+
readonly outcome: Promise<TurnOutcome>;
|
|
249
|
+
readonly events: AsyncIterable<TurnEvent>;
|
|
250
|
+
cancelHook: ((reason: string, graceMs: number) => Promise<TurnOutcome>) | undefined;
|
|
251
|
+
|
|
252
|
+
private acceptResolve: ((value: { acceptedAt: string } | null) => void) | undefined;
|
|
253
|
+
private outcomeResolve: ((outcome: TurnOutcome) => void) | undefined;
|
|
254
|
+
private settledResolve: ((settled: boolean) => void) | undefined;
|
|
255
|
+
private readonly queue: TurnEvent[] = [];
|
|
256
|
+
private eventWake: (() => void) | undefined;
|
|
257
|
+
private eventsClosed = false;
|
|
258
|
+
private sessionNativeSessionId: string | undefined;
|
|
259
|
+
private readonly settledPromiseField: Promise<boolean>;
|
|
260
|
+
|
|
261
|
+
constructor(init: ActiveTurnInit) {
|
|
262
|
+
this.turnId = init.turnId;
|
|
263
|
+
this.correlation = init.correlation;
|
|
264
|
+
this.sessionNativeSessionId = init.nativeSessionId;
|
|
265
|
+
this.accepted = new Promise((resolve) => {
|
|
266
|
+
this.acceptResolve = resolve;
|
|
267
|
+
});
|
|
268
|
+
this.outcome = new Promise((resolve) => {
|
|
269
|
+
this.outcomeResolve = resolve;
|
|
270
|
+
});
|
|
271
|
+
const settledPromise = new Promise<boolean>((resolve) => {
|
|
272
|
+
this.settledResolve = resolve;
|
|
273
|
+
});
|
|
274
|
+
const self = this;
|
|
275
|
+
this.events = {
|
|
276
|
+
async *[Symbol.asyncIterator]() {
|
|
277
|
+
while (true) {
|
|
278
|
+
while (self.queue.length > 0) {
|
|
279
|
+
const event = self.queue.shift();
|
|
280
|
+
if (event !== undefined) yield event;
|
|
281
|
+
}
|
|
282
|
+
if (self.eventsClosed) return;
|
|
283
|
+
await new Promise<void>((resolve) => {
|
|
284
|
+
self.eventWake = resolve;
|
|
285
|
+
});
|
|
286
|
+
self.eventWake = undefined;
|
|
287
|
+
}
|
|
288
|
+
},
|
|
289
|
+
};
|
|
290
|
+
this.settledPromiseField = settledPromise;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
get settled(): Promise<boolean> {
|
|
294
|
+
return this.settledPromiseField;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
emit(event: DistributiveOmit<TurnEvent, 'turnId' | 'at'>): void {
|
|
298
|
+
this.queue.push({ ...event, turnId: this.turnId, at: new Date().toISOString() } as TurnEvent);
|
|
299
|
+
this.eventWake?.();
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
private resolveAccepted(value: { acceptedAt: string } | null): void {
|
|
303
|
+
this.acceptResolve?.(value);
|
|
304
|
+
this.acceptResolve = undefined;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** The agent accepted the turn — resolves the `accepted` promise (idempotent). */
|
|
308
|
+
markAccepted(): void {
|
|
309
|
+
if (this.acceptedAt !== undefined) return;
|
|
310
|
+
this.acceptedAt = new Date().toISOString();
|
|
311
|
+
this.resolveAccepted({ acceptedAt: this.acceptedAt });
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** Exactly-once settlement: the first call wins; the outcome never upgrades afterwards. */
|
|
315
|
+
settle(
|
|
316
|
+
partial: Omit<TurnOutcome, 'turnId' | 'correlation' | 'startedAt' | 'terminalAt'> & { kind: TurnOutcomeKind },
|
|
317
|
+
): void {
|
|
318
|
+
if (this.outcomeResolved) return;
|
|
319
|
+
this.outcomeResolved = true;
|
|
320
|
+
this.eventsClosed = true;
|
|
321
|
+
this.eventWake?.();
|
|
322
|
+
this.resolveAccepted(this.acceptedAt === undefined ? null : { acceptedAt: this.acceptedAt });
|
|
323
|
+
const outcome: TurnOutcome = {
|
|
324
|
+
kind: partial.kind,
|
|
325
|
+
turnId: this.turnId,
|
|
326
|
+
correlation: this.correlation,
|
|
327
|
+
startedAt: this.startedAt,
|
|
328
|
+
terminalAt: new Date().toISOString(),
|
|
329
|
+
...(this.acceptedAt !== undefined ? { acceptedAt: this.acceptedAt } : {}),
|
|
330
|
+
...(this.firstOutputAt !== undefined ? { firstOutputAt: this.firstOutputAt } : {}),
|
|
331
|
+
...(partial.nativeSessionId !== undefined
|
|
332
|
+
? { nativeSessionId: partial.nativeSessionId }
|
|
333
|
+
: this.sessionNativeSessionId !== undefined
|
|
334
|
+
? { nativeSessionId: this.sessionNativeSessionId }
|
|
335
|
+
: {}),
|
|
336
|
+
...(partial.nativeTurnId !== undefined ? { nativeTurnId: partial.nativeTurnId } : {}),
|
|
337
|
+
...(partial.reason !== undefined ? { reason: partial.reason } : {}),
|
|
338
|
+
...(partial.finalText !== undefined ? { finalText: partial.finalText } : {}),
|
|
339
|
+
};
|
|
340
|
+
this.emit({ type: 'terminal', outcome });
|
|
341
|
+
this.outcomeResolve?.(outcome);
|
|
342
|
+
this.settledResolve?.(true);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
async cancel(reason: string, options?: { graceMs?: number }): Promise<TurnOutcome> {
|
|
346
|
+
return await (this.cancelHook?.(reason, options?.graceMs ?? TURN_CANCEL_GRACE_MS) ?? this.outcome);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
interface ActiveTurnInit {
|
|
351
|
+
turnId: string;
|
|
352
|
+
correlation: TurnCorrelation;
|
|
353
|
+
nativeSessionId: string | undefined;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** Omit distributes over unions — `Omit<TurnEvent, …>` alone collapses the union. */
|
|
357
|
+
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
|
|
358
|
+
|
|
359
|
+
/** The one session implementation: one active turn, deterministic settlement, diagnostics for stray frames. */
|
|
360
|
+
class TurnSessionImpl implements TurnSession {
|
|
361
|
+
readonly agent: AgentName;
|
|
362
|
+
readonly policyDigest: string;
|
|
363
|
+
nativeSessionId: string | undefined;
|
|
364
|
+
state: 'ready' | 'busy' | 'closed' = 'ready';
|
|
365
|
+
private readonly process: PipeProcess;
|
|
366
|
+
private readonly driver: TurnSessionDriver;
|
|
367
|
+
private readonly lines: AsyncIterable<string>;
|
|
368
|
+
private active: ActiveTurn | undefined;
|
|
369
|
+
/** Most recent turn — kept so frames arriving after settlement surface as diagnostics. */
|
|
370
|
+
private lastTurn: ActiveTurn | undefined;
|
|
371
|
+
|
|
372
|
+
constructor(options: {
|
|
373
|
+
agent: AgentName;
|
|
374
|
+
process: PipeProcess;
|
|
375
|
+
driver: TurnSessionDriver;
|
|
376
|
+
policy: TurnSessionPolicy;
|
|
377
|
+
nativeSessionId: string | undefined;
|
|
378
|
+
lines: AsyncIterable<string>;
|
|
379
|
+
}) {
|
|
380
|
+
this.agent = options.agent;
|
|
381
|
+
this.process = options.process;
|
|
382
|
+
this.driver = options.driver;
|
|
383
|
+
this.policyDigest = turnSessionPolicyDigest(options.policy);
|
|
384
|
+
this.nativeSessionId = options.nativeSessionId;
|
|
385
|
+
this.lines = options.lines;
|
|
386
|
+
void this.pump();
|
|
387
|
+
void this.process.exited.then(() => {
|
|
388
|
+
this.onExit();
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
startTurn(input: { prompt: string; correlation: TurnCorrelation }): TurnHandle {
|
|
393
|
+
if (this.state === 'closed') throw new TurnSessionClosedError();
|
|
394
|
+
if (this.active !== undefined) throw new TurnSessionBusyError(this.active.turnId);
|
|
395
|
+
const turnId = randomUUID();
|
|
396
|
+
const turn = new ActiveTurn({
|
|
397
|
+
turnId,
|
|
398
|
+
correlation: input.correlation,
|
|
399
|
+
nativeSessionId: this.nativeSessionId,
|
|
400
|
+
});
|
|
401
|
+
turn.cancelHook = (reason, graceMs) => this.cancelTurn(turn, reason, graceMs);
|
|
402
|
+
this.active = turn;
|
|
403
|
+
this.state = 'busy';
|
|
404
|
+
try {
|
|
405
|
+
this.process.writeStdin(
|
|
406
|
+
this.driver.encodeTurn({ turnId, prompt: input.prompt, correlation: input.correlation }),
|
|
407
|
+
);
|
|
408
|
+
} catch (error) {
|
|
409
|
+
// A dead stdin means the process is gone: the turn never started.
|
|
410
|
+
turn.settle({ kind: 'not-started', reason: error instanceof Error ? error.message : String(error) });
|
|
411
|
+
}
|
|
412
|
+
return turn;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/** Send the cancel frame; wait at most `graceMs` for native terminal evidence, else leave it to the exit path. */
|
|
416
|
+
private async cancelTurn(turn: ActiveTurn, reason: string, graceMs: number): Promise<TurnOutcome> {
|
|
417
|
+
if (!turn.outcomeResolved) {
|
|
418
|
+
turn.cancelRequested = true;
|
|
419
|
+
try {
|
|
420
|
+
this.process.writeStdin(this.driver.encodeCancel(reason));
|
|
421
|
+
} catch {
|
|
422
|
+
// stdin gone — the exit handler settles deterministically.
|
|
423
|
+
}
|
|
424
|
+
await Promise.race([turn.settled, delay(graceMs)]);
|
|
425
|
+
if (!turn.outcomeResolved)
|
|
426
|
+
turn.settle({
|
|
427
|
+
kind: 'outcome-unknown',
|
|
428
|
+
reason: `cancel grace (${graceMs}ms) expired without native terminal evidence`,
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
return await turn.outcome;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
async close(): Promise<void> {
|
|
435
|
+
if (this.state === 'closed') return;
|
|
436
|
+
const turn = this.active;
|
|
437
|
+
if (turn !== undefined && !turn.outcomeResolved) {
|
|
438
|
+
turn.cancelRequested = true;
|
|
439
|
+
try {
|
|
440
|
+
this.process.writeStdin(this.driver.encodeCancel('session closing'));
|
|
441
|
+
} catch {
|
|
442
|
+
// stdin gone
|
|
443
|
+
}
|
|
444
|
+
await Promise.race([turn.settled, delay(TURN_CANCEL_GRACE_MS)]);
|
|
445
|
+
turn.settle({
|
|
446
|
+
kind: turn.acceptedAt === undefined ? 'not-started' : 'outcome-unknown',
|
|
447
|
+
reason: 'session closed',
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
this.state = 'closed';
|
|
451
|
+
this.active = undefined;
|
|
452
|
+
try {
|
|
453
|
+
this.process.endStdin();
|
|
454
|
+
} catch {
|
|
455
|
+
// already dead
|
|
456
|
+
}
|
|
457
|
+
this.process.kill('SIGTERM');
|
|
458
|
+
const gone = await Promise.race([this.process.exited, delay(5_000)]);
|
|
459
|
+
if (gone === null) this.process.kill('SIGKILL');
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/** Route decoded frames; foreign or late frames become diagnostics on the recent turn. */
|
|
463
|
+
private route(wire: TurnWireEvent): void {
|
|
464
|
+
const turn = this.active ?? this.lastTurn;
|
|
465
|
+
if (turn === undefined) return; // nowhere to surface a frame without a turn
|
|
466
|
+
if (wire.turnId !== turn.turnId || turn.outcomeResolved) {
|
|
467
|
+
turn.emit({ type: 'diagnostic', data: wire });
|
|
468
|
+
return;
|
|
469
|
+
}
|
|
470
|
+
const at = new Date().toISOString();
|
|
471
|
+
if (wire.type === 'output') {
|
|
472
|
+
turn.firstOutputAt ??= at;
|
|
473
|
+
turn.emit({ type: 'output', data: wire.data });
|
|
474
|
+
return;
|
|
475
|
+
}
|
|
476
|
+
if (wire.type === 'terminal' && wire.terminal !== undefined) {
|
|
477
|
+
const kind: TurnOutcomeKind = turn.cancelRequested
|
|
478
|
+
? 'interrupted'
|
|
479
|
+
: wire.terminal.kind === 'success'
|
|
480
|
+
? 'success'
|
|
481
|
+
: 'failure';
|
|
482
|
+
turn.settle({
|
|
483
|
+
kind,
|
|
484
|
+
...(wire.terminal.nativeTurnId !== undefined ? { nativeTurnId: wire.terminal.nativeTurnId } : {}),
|
|
485
|
+
...(wire.terminal.nativeSessionId !== undefined
|
|
486
|
+
? { nativeSessionId: wire.terminal.nativeSessionId }
|
|
487
|
+
: {}),
|
|
488
|
+
...(wire.terminal.finalText !== undefined ? { finalText: wire.terminal.finalText } : {}),
|
|
489
|
+
...(wire.terminal.reason !== undefined ? { reason: wire.terminal.reason } : {}),
|
|
490
|
+
});
|
|
491
|
+
// Turn complete: keep the reference for late-frame diagnostics, admit the next turn.
|
|
492
|
+
this.lastTurn = turn;
|
|
493
|
+
if (this.active === turn) {
|
|
494
|
+
this.active = undefined;
|
|
495
|
+
if (this.state === 'busy') this.state = 'ready';
|
|
496
|
+
}
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
if (wire.type === 'accepted') {
|
|
500
|
+
if (turn.acceptedAt === undefined) {
|
|
501
|
+
turn.acceptedAt = at;
|
|
502
|
+
turn.markAccepted();
|
|
503
|
+
turn.emit({ type: 'accepted' });
|
|
504
|
+
} else {
|
|
505
|
+
turn.emit({ type: 'diagnostic', data: wire });
|
|
506
|
+
}
|
|
507
|
+
return;
|
|
508
|
+
}
|
|
509
|
+
turn.emit({ type: 'diagnostic', data: wire });
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
private async pump(): Promise<void> {
|
|
513
|
+
// The reader itself can throw (line overflow → TurnProtocolError) — either way the turn
|
|
514
|
+
// settles contract-violation.
|
|
515
|
+
try {
|
|
516
|
+
for await (const line of this.lines) {
|
|
517
|
+
const wires = this.driver.decode(line);
|
|
518
|
+
for (const wire of wires) this.route(wire);
|
|
519
|
+
}
|
|
520
|
+
} catch (error) {
|
|
521
|
+
this.active?.settle({
|
|
522
|
+
kind: 'contract-violation',
|
|
523
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
524
|
+
});
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/** Deterministic settlement when the process dies: before acceptance → not-started, after → unknown. */
|
|
529
|
+
private onExit(): void {
|
|
530
|
+
const turn = this.active;
|
|
531
|
+
this.state = 'closed';
|
|
532
|
+
if (turn === undefined) return;
|
|
533
|
+
if (!turn.outcomeResolved) {
|
|
534
|
+
if (turn.acceptedAt === undefined)
|
|
535
|
+
turn.settle({ kind: 'not-started', reason: 'process exited before acceptance' });
|
|
536
|
+
else turn.settle({ kind: 'outcome-unknown', reason: 'process exited without a native terminal' });
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* Open a turn session: driver lookup → qualification → spawn → handshake → session. Expected
|
|
543
|
+
* refusals are typed values, never throws (R1). `resolveBinary`/`resolveDriver` are seams:
|
|
544
|
+
* `AiRunner.openTurnSession` binds them to its agent resolution; tests bind the fake driver.
|
|
545
|
+
*/
|
|
546
|
+
export async function openTurnSessionWithDriver(options: {
|
|
547
|
+
agent: AgentName;
|
|
548
|
+
driver: TurnSessionDriver | undefined;
|
|
549
|
+
policy: TurnSessionPolicy;
|
|
550
|
+
binary: TurnBinary;
|
|
551
|
+
processExecutor: ProcessExecutor;
|
|
552
|
+
handshakeTimeoutMs?: number;
|
|
553
|
+
}): Promise<OpenTurnSessionResult> {
|
|
554
|
+
const { agent, driver, policy, binary, processExecutor } = options;
|
|
555
|
+
if (driver === undefined) {
|
|
556
|
+
return {
|
|
557
|
+
ok: false,
|
|
558
|
+
reason: 'unsupported-agent',
|
|
559
|
+
detail: `no turn-session driver registered for agent '${agent}' (registry: ${[...TURN_SESSION_DRIVERS.keys()].join(', ') || 'empty'})`,
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
const handshakeTimeoutMs = options.handshakeTimeoutMs ?? TURN_HANDSHAKE_TIMEOUT_MS;
|
|
563
|
+
const qualification = driver.qualify(binary);
|
|
564
|
+
if (!qualification.qualified) {
|
|
565
|
+
return {
|
|
566
|
+
ok: false,
|
|
567
|
+
reason: 'unqualified-version',
|
|
568
|
+
detail: `${agent} ${binary.version ?? '<no version>'}: ${qualification.reason}`,
|
|
569
|
+
};
|
|
570
|
+
}
|
|
571
|
+
const argv = driver.spawnArgv(binary, policy);
|
|
572
|
+
let process: PipeProcess;
|
|
573
|
+
try {
|
|
574
|
+
process = processExecutor.runStreaming({
|
|
575
|
+
command: argv.command,
|
|
576
|
+
args: argv.args,
|
|
577
|
+
label: `turn-session.${agent}`,
|
|
578
|
+
cwd: policy.workspace,
|
|
579
|
+
});
|
|
580
|
+
} catch (error) {
|
|
581
|
+
return { ok: false, reason: 'spawn-failed', detail: error instanceof Error ? error.message : String(error) };
|
|
582
|
+
}
|
|
583
|
+
if (process.stdout === null) {
|
|
584
|
+
void process.kill('SIGTERM');
|
|
585
|
+
return {
|
|
586
|
+
ok: false,
|
|
587
|
+
reason: 'handshake-failed',
|
|
588
|
+
detail: `${agent} process has no stdout to speak the turn protocol`,
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
const lines = readLines(process.stdout);
|
|
592
|
+
const iterator = lines[Symbol.asyncIterator]();
|
|
593
|
+
// Handshake pulls lines one at a time with its own timeout; a timeout or EOF yields null.
|
|
594
|
+
// The line lost to a timeout is irrelevant: a timeout fails the handshake and kills the process.
|
|
595
|
+
const pull = (timeoutMs: number): Promise<string | null> =>
|
|
596
|
+
Promise.race([iterator.next().then((step) => (step.done ? null : step.value)), delay(timeoutMs)]);
|
|
597
|
+
let handshakeResult: TurnHandshake = null;
|
|
598
|
+
if (driver.handshake !== undefined) {
|
|
599
|
+
// A handshake that loses the race (or throws) must not surface as an unhandled rejection.
|
|
600
|
+
const handshake = driver.handshake(pull).catch(() => null);
|
|
601
|
+
try {
|
|
602
|
+
handshakeResult = await Promise.race([handshake, delay(handshakeTimeoutMs)]);
|
|
603
|
+
} catch {
|
|
604
|
+
void process.kill('SIGTERM');
|
|
605
|
+
return { ok: false, reason: 'handshake-failed', detail: `${agent} handshake failed` };
|
|
606
|
+
}
|
|
607
|
+
if (handshakeResult === null) {
|
|
608
|
+
void process.kill('SIGTERM');
|
|
609
|
+
return {
|
|
610
|
+
ok: false,
|
|
611
|
+
reason: 'handshake-failed',
|
|
612
|
+
detail: `${agent} did not become ready within ${handshakeTimeoutMs}ms`,
|
|
613
|
+
};
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
return {
|
|
617
|
+
ok: true,
|
|
618
|
+
session: new TurnSessionImpl({
|
|
619
|
+
agent,
|
|
620
|
+
process,
|
|
621
|
+
driver,
|
|
622
|
+
policy,
|
|
623
|
+
nativeSessionId: handshakeResult?.nativeSessionId,
|
|
624
|
+
lines,
|
|
625
|
+
}),
|
|
626
|
+
};
|
|
627
|
+
}
|