@gobing-ai/ts-ai-runner 0.5.33 → 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,452 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
/** Thrown by `TurnSessionDriver.decode` on a malformed frame — settles the turn `contract-violation`. */
|
|
3
|
+
export class TurnProtocolError extends Error {
|
|
4
|
+
constructor(message) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = 'TurnProtocolError';
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
/** Built-in driver registry. Empty in 0.x by design — real drivers land with qualification evidence. */
|
|
10
|
+
export const TURN_SESSION_DRIVERS = new Map();
|
|
11
|
+
/** How long `cancel()` waits for native terminal evidence before resolving `outcome-unknown`. */
|
|
12
|
+
export const TURN_CANCEL_GRACE_MS = 5_000;
|
|
13
|
+
/** Handshake bound for `openTurnSession`. */
|
|
14
|
+
export const TURN_HANDSHAKE_TIMEOUT_MS = 10_000;
|
|
15
|
+
/** Max buffered stdout line; overflow is a protocol contract violation. */
|
|
16
|
+
export const TURN_MAX_LINE_BYTES = 1024 * 1024;
|
|
17
|
+
/** `startTurn` while another turn is active — no hidden queue, by design. */
|
|
18
|
+
export class TurnSessionBusyError extends Error {
|
|
19
|
+
constructor(turnId) {
|
|
20
|
+
super(`turn session busy: turn ${turnId} is still active`);
|
|
21
|
+
this.name = 'TurnSessionBusyError';
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/** `startTurn` on a closed session. */
|
|
25
|
+
export class TurnSessionClosedError extends Error {
|
|
26
|
+
constructor() {
|
|
27
|
+
super('turn session is closed');
|
|
28
|
+
this.name = 'TurnSessionClosedError';
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/** sha256 over the canonical JSON (recursively sorted keys) of the policy — stable digest contract. */
|
|
32
|
+
export function turnSessionPolicyDigest(policy) {
|
|
33
|
+
const canonical = (value) => {
|
|
34
|
+
if (Array.isArray(value))
|
|
35
|
+
return value.map(canonical);
|
|
36
|
+
if (value !== null && typeof value === 'object') {
|
|
37
|
+
return Object.fromEntries(Object.entries(value)
|
|
38
|
+
.sort(([a], [b]) => (a < b ? -1 : 1))
|
|
39
|
+
.map(([key, item]) => [key, canonical(item)]));
|
|
40
|
+
}
|
|
41
|
+
return value;
|
|
42
|
+
};
|
|
43
|
+
return createHash('sha256')
|
|
44
|
+
.update(JSON.stringify(canonical(policy)))
|
|
45
|
+
.digest('hex');
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Line-buffered stdout reader with the bounded-buffer invariant (overflow invokes `onOverflow`
|
|
49
|
+
* and ends the iteration). The single reader of the process stdout stream — both the handshake
|
|
50
|
+
* and the session pump pull from the SAME generator.
|
|
51
|
+
*/
|
|
52
|
+
export async function* readLines(stream) {
|
|
53
|
+
const decoder = new TextDecoder();
|
|
54
|
+
let buffer = '';
|
|
55
|
+
const reader = stream.getReader();
|
|
56
|
+
try {
|
|
57
|
+
while (true) {
|
|
58
|
+
const chunk = await reader.read();
|
|
59
|
+
if (chunk.done)
|
|
60
|
+
break;
|
|
61
|
+
buffer += decoder.decode(chunk.value, { stream: true });
|
|
62
|
+
for (;;) {
|
|
63
|
+
const newline = buffer.indexOf('\n');
|
|
64
|
+
if (newline === -1)
|
|
65
|
+
break;
|
|
66
|
+
const line = buffer.slice(0, newline);
|
|
67
|
+
buffer = buffer.slice(newline + 1);
|
|
68
|
+
if (Buffer.byteLength(line, 'utf8') > TURN_MAX_LINE_BYTES) {
|
|
69
|
+
throw new TurnProtocolError(`stdout line exceeded ${TURN_MAX_LINE_BYTES} bytes`);
|
|
70
|
+
}
|
|
71
|
+
yield line;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
const tail = buffer + decoder.decode();
|
|
75
|
+
if (tail.length > 0)
|
|
76
|
+
yield tail;
|
|
77
|
+
}
|
|
78
|
+
finally {
|
|
79
|
+
reader.releaseLock();
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
function delay(ms) {
|
|
83
|
+
return new Promise((resolve) => {
|
|
84
|
+
setTimeout(() => resolve(null), ms);
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
/** Per-turn state: deferred accepted/outcome promises, event queue, exactly-once settlement. */
|
|
88
|
+
class ActiveTurn {
|
|
89
|
+
turnId;
|
|
90
|
+
correlation;
|
|
91
|
+
startedAt = new Date().toISOString();
|
|
92
|
+
acceptedAt;
|
|
93
|
+
firstOutputAt;
|
|
94
|
+
outcomeResolved = false;
|
|
95
|
+
cancelRequested = false;
|
|
96
|
+
accepted;
|
|
97
|
+
outcome;
|
|
98
|
+
events;
|
|
99
|
+
cancelHook;
|
|
100
|
+
acceptResolve;
|
|
101
|
+
outcomeResolve;
|
|
102
|
+
settledResolve;
|
|
103
|
+
queue = [];
|
|
104
|
+
eventWake;
|
|
105
|
+
eventsClosed = false;
|
|
106
|
+
sessionNativeSessionId;
|
|
107
|
+
settledPromiseField;
|
|
108
|
+
constructor(init) {
|
|
109
|
+
this.turnId = init.turnId;
|
|
110
|
+
this.correlation = init.correlation;
|
|
111
|
+
this.sessionNativeSessionId = init.nativeSessionId;
|
|
112
|
+
this.accepted = new Promise((resolve) => {
|
|
113
|
+
this.acceptResolve = resolve;
|
|
114
|
+
});
|
|
115
|
+
this.outcome = new Promise((resolve) => {
|
|
116
|
+
this.outcomeResolve = resolve;
|
|
117
|
+
});
|
|
118
|
+
const settledPromise = new Promise((resolve) => {
|
|
119
|
+
this.settledResolve = resolve;
|
|
120
|
+
});
|
|
121
|
+
const self = this;
|
|
122
|
+
this.events = {
|
|
123
|
+
async *[Symbol.asyncIterator]() {
|
|
124
|
+
while (true) {
|
|
125
|
+
while (self.queue.length > 0) {
|
|
126
|
+
const event = self.queue.shift();
|
|
127
|
+
if (event !== undefined)
|
|
128
|
+
yield event;
|
|
129
|
+
}
|
|
130
|
+
if (self.eventsClosed)
|
|
131
|
+
return;
|
|
132
|
+
await new Promise((resolve) => {
|
|
133
|
+
self.eventWake = resolve;
|
|
134
|
+
});
|
|
135
|
+
self.eventWake = undefined;
|
|
136
|
+
}
|
|
137
|
+
},
|
|
138
|
+
};
|
|
139
|
+
this.settledPromiseField = settledPromise;
|
|
140
|
+
}
|
|
141
|
+
get settled() {
|
|
142
|
+
return this.settledPromiseField;
|
|
143
|
+
}
|
|
144
|
+
emit(event) {
|
|
145
|
+
this.queue.push({ ...event, turnId: this.turnId, at: new Date().toISOString() });
|
|
146
|
+
this.eventWake?.();
|
|
147
|
+
}
|
|
148
|
+
resolveAccepted(value) {
|
|
149
|
+
this.acceptResolve?.(value);
|
|
150
|
+
this.acceptResolve = undefined;
|
|
151
|
+
}
|
|
152
|
+
/** The agent accepted the turn — resolves the `accepted` promise (idempotent). */
|
|
153
|
+
markAccepted() {
|
|
154
|
+
if (this.acceptedAt !== undefined)
|
|
155
|
+
return;
|
|
156
|
+
this.acceptedAt = new Date().toISOString();
|
|
157
|
+
this.resolveAccepted({ acceptedAt: this.acceptedAt });
|
|
158
|
+
}
|
|
159
|
+
/** Exactly-once settlement: the first call wins; the outcome never upgrades afterwards. */
|
|
160
|
+
settle(partial) {
|
|
161
|
+
if (this.outcomeResolved)
|
|
162
|
+
return;
|
|
163
|
+
this.outcomeResolved = true;
|
|
164
|
+
this.eventsClosed = true;
|
|
165
|
+
this.eventWake?.();
|
|
166
|
+
this.resolveAccepted(this.acceptedAt === undefined ? null : { acceptedAt: this.acceptedAt });
|
|
167
|
+
const outcome = {
|
|
168
|
+
kind: partial.kind,
|
|
169
|
+
turnId: this.turnId,
|
|
170
|
+
correlation: this.correlation,
|
|
171
|
+
startedAt: this.startedAt,
|
|
172
|
+
terminalAt: new Date().toISOString(),
|
|
173
|
+
...(this.acceptedAt !== undefined ? { acceptedAt: this.acceptedAt } : {}),
|
|
174
|
+
...(this.firstOutputAt !== undefined ? { firstOutputAt: this.firstOutputAt } : {}),
|
|
175
|
+
...(partial.nativeSessionId !== undefined
|
|
176
|
+
? { nativeSessionId: partial.nativeSessionId }
|
|
177
|
+
: this.sessionNativeSessionId !== undefined
|
|
178
|
+
? { nativeSessionId: this.sessionNativeSessionId }
|
|
179
|
+
: {}),
|
|
180
|
+
...(partial.nativeTurnId !== undefined ? { nativeTurnId: partial.nativeTurnId } : {}),
|
|
181
|
+
...(partial.reason !== undefined ? { reason: partial.reason } : {}),
|
|
182
|
+
...(partial.finalText !== undefined ? { finalText: partial.finalText } : {}),
|
|
183
|
+
};
|
|
184
|
+
this.emit({ type: 'terminal', outcome });
|
|
185
|
+
this.outcomeResolve?.(outcome);
|
|
186
|
+
this.settledResolve?.(true);
|
|
187
|
+
}
|
|
188
|
+
async cancel(reason, options) {
|
|
189
|
+
return await (this.cancelHook?.(reason, options?.graceMs ?? TURN_CANCEL_GRACE_MS) ?? this.outcome);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
/** The one session implementation: one active turn, deterministic settlement, diagnostics for stray frames. */
|
|
193
|
+
class TurnSessionImpl {
|
|
194
|
+
agent;
|
|
195
|
+
policyDigest;
|
|
196
|
+
nativeSessionId;
|
|
197
|
+
state = 'ready';
|
|
198
|
+
process;
|
|
199
|
+
driver;
|
|
200
|
+
lines;
|
|
201
|
+
active;
|
|
202
|
+
/** Most recent turn — kept so frames arriving after settlement surface as diagnostics. */
|
|
203
|
+
lastTurn;
|
|
204
|
+
constructor(options) {
|
|
205
|
+
this.agent = options.agent;
|
|
206
|
+
this.process = options.process;
|
|
207
|
+
this.driver = options.driver;
|
|
208
|
+
this.policyDigest = turnSessionPolicyDigest(options.policy);
|
|
209
|
+
this.nativeSessionId = options.nativeSessionId;
|
|
210
|
+
this.lines = options.lines;
|
|
211
|
+
void this.pump();
|
|
212
|
+
void this.process.exited.then(() => {
|
|
213
|
+
this.onExit();
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
startTurn(input) {
|
|
217
|
+
if (this.state === 'closed')
|
|
218
|
+
throw new TurnSessionClosedError();
|
|
219
|
+
if (this.active !== undefined)
|
|
220
|
+
throw new TurnSessionBusyError(this.active.turnId);
|
|
221
|
+
const turnId = randomUUID();
|
|
222
|
+
const turn = new ActiveTurn({
|
|
223
|
+
turnId,
|
|
224
|
+
correlation: input.correlation,
|
|
225
|
+
nativeSessionId: this.nativeSessionId,
|
|
226
|
+
});
|
|
227
|
+
turn.cancelHook = (reason, graceMs) => this.cancelTurn(turn, reason, graceMs);
|
|
228
|
+
this.active = turn;
|
|
229
|
+
this.state = 'busy';
|
|
230
|
+
try {
|
|
231
|
+
this.process.writeStdin(this.driver.encodeTurn({ turnId, prompt: input.prompt, correlation: input.correlation }));
|
|
232
|
+
}
|
|
233
|
+
catch (error) {
|
|
234
|
+
// A dead stdin means the process is gone: the turn never started.
|
|
235
|
+
turn.settle({ kind: 'not-started', reason: error instanceof Error ? error.message : String(error) });
|
|
236
|
+
}
|
|
237
|
+
return turn;
|
|
238
|
+
}
|
|
239
|
+
/** Send the cancel frame; wait at most `graceMs` for native terminal evidence, else leave it to the exit path. */
|
|
240
|
+
async cancelTurn(turn, reason, graceMs) {
|
|
241
|
+
if (!turn.outcomeResolved) {
|
|
242
|
+
turn.cancelRequested = true;
|
|
243
|
+
try {
|
|
244
|
+
this.process.writeStdin(this.driver.encodeCancel(reason));
|
|
245
|
+
}
|
|
246
|
+
catch {
|
|
247
|
+
// stdin gone — the exit handler settles deterministically.
|
|
248
|
+
}
|
|
249
|
+
await Promise.race([turn.settled, delay(graceMs)]);
|
|
250
|
+
if (!turn.outcomeResolved)
|
|
251
|
+
turn.settle({
|
|
252
|
+
kind: 'outcome-unknown',
|
|
253
|
+
reason: `cancel grace (${graceMs}ms) expired without native terminal evidence`,
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
return await turn.outcome;
|
|
257
|
+
}
|
|
258
|
+
async close() {
|
|
259
|
+
if (this.state === 'closed')
|
|
260
|
+
return;
|
|
261
|
+
const turn = this.active;
|
|
262
|
+
if (turn !== undefined && !turn.outcomeResolved) {
|
|
263
|
+
turn.cancelRequested = true;
|
|
264
|
+
try {
|
|
265
|
+
this.process.writeStdin(this.driver.encodeCancel('session closing'));
|
|
266
|
+
}
|
|
267
|
+
catch {
|
|
268
|
+
// stdin gone
|
|
269
|
+
}
|
|
270
|
+
await Promise.race([turn.settled, delay(TURN_CANCEL_GRACE_MS)]);
|
|
271
|
+
turn.settle({
|
|
272
|
+
kind: turn.acceptedAt === undefined ? 'not-started' : 'outcome-unknown',
|
|
273
|
+
reason: 'session closed',
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
this.state = 'closed';
|
|
277
|
+
this.active = undefined;
|
|
278
|
+
try {
|
|
279
|
+
this.process.endStdin();
|
|
280
|
+
}
|
|
281
|
+
catch {
|
|
282
|
+
// already dead
|
|
283
|
+
}
|
|
284
|
+
this.process.kill('SIGTERM');
|
|
285
|
+
const gone = await Promise.race([this.process.exited, delay(5_000)]);
|
|
286
|
+
if (gone === null)
|
|
287
|
+
this.process.kill('SIGKILL');
|
|
288
|
+
}
|
|
289
|
+
/** Route decoded frames; foreign or late frames become diagnostics on the recent turn. */
|
|
290
|
+
route(wire) {
|
|
291
|
+
const turn = this.active ?? this.lastTurn;
|
|
292
|
+
if (turn === undefined)
|
|
293
|
+
return; // nowhere to surface a frame without a turn
|
|
294
|
+
if (wire.turnId !== turn.turnId || turn.outcomeResolved) {
|
|
295
|
+
turn.emit({ type: 'diagnostic', data: wire });
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
const at = new Date().toISOString();
|
|
299
|
+
if (wire.type === 'output') {
|
|
300
|
+
turn.firstOutputAt ??= at;
|
|
301
|
+
turn.emit({ type: 'output', data: wire.data });
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
if (wire.type === 'terminal' && wire.terminal !== undefined) {
|
|
305
|
+
const kind = turn.cancelRequested
|
|
306
|
+
? 'interrupted'
|
|
307
|
+
: wire.terminal.kind === 'success'
|
|
308
|
+
? 'success'
|
|
309
|
+
: 'failure';
|
|
310
|
+
turn.settle({
|
|
311
|
+
kind,
|
|
312
|
+
...(wire.terminal.nativeTurnId !== undefined ? { nativeTurnId: wire.terminal.nativeTurnId } : {}),
|
|
313
|
+
...(wire.terminal.nativeSessionId !== undefined
|
|
314
|
+
? { nativeSessionId: wire.terminal.nativeSessionId }
|
|
315
|
+
: {}),
|
|
316
|
+
...(wire.terminal.finalText !== undefined ? { finalText: wire.terminal.finalText } : {}),
|
|
317
|
+
...(wire.terminal.reason !== undefined ? { reason: wire.terminal.reason } : {}),
|
|
318
|
+
});
|
|
319
|
+
// Turn complete: keep the reference for late-frame diagnostics, admit the next turn.
|
|
320
|
+
this.lastTurn = turn;
|
|
321
|
+
if (this.active === turn) {
|
|
322
|
+
this.active = undefined;
|
|
323
|
+
if (this.state === 'busy')
|
|
324
|
+
this.state = 'ready';
|
|
325
|
+
}
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
if (wire.type === 'accepted') {
|
|
329
|
+
if (turn.acceptedAt === undefined) {
|
|
330
|
+
turn.acceptedAt = at;
|
|
331
|
+
turn.markAccepted();
|
|
332
|
+
turn.emit({ type: 'accepted' });
|
|
333
|
+
}
|
|
334
|
+
else {
|
|
335
|
+
turn.emit({ type: 'diagnostic', data: wire });
|
|
336
|
+
}
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
turn.emit({ type: 'diagnostic', data: wire });
|
|
340
|
+
}
|
|
341
|
+
async pump() {
|
|
342
|
+
// The reader itself can throw (line overflow → TurnProtocolError) — either way the turn
|
|
343
|
+
// settles contract-violation.
|
|
344
|
+
try {
|
|
345
|
+
for await (const line of this.lines) {
|
|
346
|
+
const wires = this.driver.decode(line);
|
|
347
|
+
for (const wire of wires)
|
|
348
|
+
this.route(wire);
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
catch (error) {
|
|
352
|
+
this.active?.settle({
|
|
353
|
+
kind: 'contract-violation',
|
|
354
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
/** Deterministic settlement when the process dies: before acceptance → not-started, after → unknown. */
|
|
359
|
+
onExit() {
|
|
360
|
+
const turn = this.active;
|
|
361
|
+
this.state = 'closed';
|
|
362
|
+
if (turn === undefined)
|
|
363
|
+
return;
|
|
364
|
+
if (!turn.outcomeResolved) {
|
|
365
|
+
if (turn.acceptedAt === undefined)
|
|
366
|
+
turn.settle({ kind: 'not-started', reason: 'process exited before acceptance' });
|
|
367
|
+
else
|
|
368
|
+
turn.settle({ kind: 'outcome-unknown', reason: 'process exited without a native terminal' });
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
/**
|
|
373
|
+
* Open a turn session: driver lookup → qualification → spawn → handshake → session. Expected
|
|
374
|
+
* refusals are typed values, never throws (R1). `resolveBinary`/`resolveDriver` are seams:
|
|
375
|
+
* `AiRunner.openTurnSession` binds them to its agent resolution; tests bind the fake driver.
|
|
376
|
+
*/
|
|
377
|
+
export async function openTurnSessionWithDriver(options) {
|
|
378
|
+
const { agent, driver, policy, binary, processExecutor } = options;
|
|
379
|
+
if (driver === undefined) {
|
|
380
|
+
return {
|
|
381
|
+
ok: false,
|
|
382
|
+
reason: 'unsupported-agent',
|
|
383
|
+
detail: `no turn-session driver registered for agent '${agent}' (registry: ${[...TURN_SESSION_DRIVERS.keys()].join(', ') || 'empty'})`,
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
const handshakeTimeoutMs = options.handshakeTimeoutMs ?? TURN_HANDSHAKE_TIMEOUT_MS;
|
|
387
|
+
const qualification = driver.qualify(binary);
|
|
388
|
+
if (!qualification.qualified) {
|
|
389
|
+
return {
|
|
390
|
+
ok: false,
|
|
391
|
+
reason: 'unqualified-version',
|
|
392
|
+
detail: `${agent} ${binary.version ?? '<no version>'}: ${qualification.reason}`,
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
const argv = driver.spawnArgv(binary, policy);
|
|
396
|
+
let process;
|
|
397
|
+
try {
|
|
398
|
+
process = processExecutor.runStreaming({
|
|
399
|
+
command: argv.command,
|
|
400
|
+
args: argv.args,
|
|
401
|
+
label: `turn-session.${agent}`,
|
|
402
|
+
cwd: policy.workspace,
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
catch (error) {
|
|
406
|
+
return { ok: false, reason: 'spawn-failed', detail: error instanceof Error ? error.message : String(error) };
|
|
407
|
+
}
|
|
408
|
+
if (process.stdout === null) {
|
|
409
|
+
void process.kill('SIGTERM');
|
|
410
|
+
return {
|
|
411
|
+
ok: false,
|
|
412
|
+
reason: 'handshake-failed',
|
|
413
|
+
detail: `${agent} process has no stdout to speak the turn protocol`,
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
const lines = readLines(process.stdout);
|
|
417
|
+
const iterator = lines[Symbol.asyncIterator]();
|
|
418
|
+
// Handshake pulls lines one at a time with its own timeout; a timeout or EOF yields null.
|
|
419
|
+
// The line lost to a timeout is irrelevant: a timeout fails the handshake and kills the process.
|
|
420
|
+
const pull = (timeoutMs) => Promise.race([iterator.next().then((step) => (step.done ? null : step.value)), delay(timeoutMs)]);
|
|
421
|
+
let handshakeResult = null;
|
|
422
|
+
if (driver.handshake !== undefined) {
|
|
423
|
+
// A handshake that loses the race (or throws) must not surface as an unhandled rejection.
|
|
424
|
+
const handshake = driver.handshake(pull).catch(() => null);
|
|
425
|
+
try {
|
|
426
|
+
handshakeResult = await Promise.race([handshake, delay(handshakeTimeoutMs)]);
|
|
427
|
+
}
|
|
428
|
+
catch {
|
|
429
|
+
void process.kill('SIGTERM');
|
|
430
|
+
return { ok: false, reason: 'handshake-failed', detail: `${agent} handshake failed` };
|
|
431
|
+
}
|
|
432
|
+
if (handshakeResult === null) {
|
|
433
|
+
void process.kill('SIGTERM');
|
|
434
|
+
return {
|
|
435
|
+
ok: false,
|
|
436
|
+
reason: 'handshake-failed',
|
|
437
|
+
detail: `${agent} did not become ready within ${handshakeTimeoutMs}ms`,
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
return {
|
|
442
|
+
ok: true,
|
|
443
|
+
session: new TurnSessionImpl({
|
|
444
|
+
agent,
|
|
445
|
+
process,
|
|
446
|
+
driver,
|
|
447
|
+
policy,
|
|
448
|
+
nativeSessionId: handshakeResult?.nativeSessionId,
|
|
449
|
+
lines,
|
|
450
|
+
}),
|
|
451
|
+
};
|
|
452
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gobing-ai/ts-ai-runner",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "@gobing-ai/ts-ai-runner — Coding-agent shims, detection, doctor checks, and prompt execution.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"typescript",
|
|
@@ -28,6 +28,10 @@
|
|
|
28
28
|
".": {
|
|
29
29
|
"types": "./dist/index.d.ts",
|
|
30
30
|
"import": "./dist/index.js"
|
|
31
|
+
},
|
|
32
|
+
"./testing": {
|
|
33
|
+
"types": "./dist/testing/fake-turn-driver.d.ts",
|
|
34
|
+
"import": "./dist/testing/fake-turn-driver.js"
|
|
31
35
|
}
|
|
32
36
|
},
|
|
33
37
|
"files": [
|
|
@@ -47,12 +51,12 @@
|
|
|
47
51
|
"release": "echo 'Manual publish is disabled. Releases go through GitHub Actions via Trusted Publishing — push a tag: git tag @gobing-ai/ts-ai-runner-v<version> && git push --tags' && exit 1"
|
|
48
52
|
},
|
|
49
53
|
"dependencies": {
|
|
50
|
-
"@gobing-ai/ts-infra": "^0.
|
|
51
|
-
"@gobing-ai/ts-runtime": "^0.
|
|
54
|
+
"@gobing-ai/ts-infra": "^0.6.0",
|
|
55
|
+
"@gobing-ai/ts-runtime": "^0.6.0"
|
|
52
56
|
},
|
|
53
57
|
"devDependencies": {
|
|
54
58
|
"@types/bun": "1.4.3",
|
|
55
|
-
"@gobing-ai/ts-db": "^0.
|
|
59
|
+
"@gobing-ai/ts-db": "^0.6.0"
|
|
56
60
|
},
|
|
57
61
|
"publishConfig": {
|
|
58
62
|
"access": "public"
|
package/src/ai-runner.ts
CHANGED
|
@@ -17,6 +17,14 @@ import {
|
|
|
17
17
|
QuotaObservationProducer,
|
|
18
18
|
} from './quota';
|
|
19
19
|
import { translateSlashCommand } from './slash-command';
|
|
20
|
+
import {
|
|
21
|
+
type OpenTurnSessionResult,
|
|
22
|
+
openTurnSessionWithDriver,
|
|
23
|
+
TURN_SESSION_DRIVERS,
|
|
24
|
+
type TurnBinary,
|
|
25
|
+
type TurnSessionDriver,
|
|
26
|
+
type TurnSessionPolicy,
|
|
27
|
+
} from './turn-session';
|
|
20
28
|
|
|
21
29
|
/** Result returned by every AI runner dispatch method. */
|
|
22
30
|
export interface AgentRunResult {
|
|
@@ -220,6 +228,53 @@ export class AiRunner {
|
|
|
220
228
|
return command === null ? null : this.invoke(agent, 'auth', command, options, true);
|
|
221
229
|
}
|
|
222
230
|
|
|
231
|
+
/** Open a correlated warm-turn session (task 1284). Expected refusals are typed, never throws. */
|
|
232
|
+
async openTurnSession(
|
|
233
|
+
agent: AgentName,
|
|
234
|
+
options: {
|
|
235
|
+
policy: TurnSessionPolicy;
|
|
236
|
+
/** Test/injection seam; defaults to the built-in registry (empty in 0.x). */
|
|
237
|
+
driver?: TurnSessionDriver;
|
|
238
|
+
/** Pre-resolved binary identity; defaults to probing the shim's version command. */
|
|
239
|
+
binary?: TurnBinary;
|
|
240
|
+
handshakeTimeoutMs?: number;
|
|
241
|
+
},
|
|
242
|
+
): Promise<OpenTurnSessionResult> {
|
|
243
|
+
// Driver lookup BEFORE any binary probe: an unsupported agent must not spawn (AC1).
|
|
244
|
+
const driver = options.driver ?? TURN_SESSION_DRIVERS.get(agent);
|
|
245
|
+
if (driver === undefined) {
|
|
246
|
+
return {
|
|
247
|
+
ok: false,
|
|
248
|
+
reason: 'unsupported-agent',
|
|
249
|
+
detail: `no turn-session driver registered for agent '${agent}' (registry: ${[...TURN_SESSION_DRIVERS.keys()].join(', ') || 'empty'})`,
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
const binary = options.binary ?? (await this.resolveTurnBinary(agent));
|
|
253
|
+
return await openTurnSessionWithDriver({
|
|
254
|
+
agent,
|
|
255
|
+
driver,
|
|
256
|
+
policy: options.policy,
|
|
257
|
+
binary,
|
|
258
|
+
processExecutor: this.processExecutor,
|
|
259
|
+
...(options.handshakeTimeoutMs !== undefined ? { handshakeTimeoutMs: options.handshakeTimeoutMs } : {}),
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Probe the agent binary for qualification: path + best-effort semver from the version command. */
|
|
264
|
+
private async resolveTurnBinary(agent: AgentName): Promise<TurnBinary> {
|
|
265
|
+
const command = getAgentShim(agent).getVersionCommand();
|
|
266
|
+
const result = await this.processExecutor.run({
|
|
267
|
+
command: command.command,
|
|
268
|
+
args: command.args,
|
|
269
|
+
label: `ai-runner.${agent}.version`,
|
|
270
|
+
rejectOnError: false,
|
|
271
|
+
forceBuffered: true,
|
|
272
|
+
...(this.defaultCwd !== undefined ? { cwd: this.defaultCwd } : {}),
|
|
273
|
+
});
|
|
274
|
+
const match = /[0-9]+\.[0-9]+\.[0-9]+[^\s]*/.exec(result.stdout);
|
|
275
|
+
return { path: command.command, version: match?.[0] ?? null };
|
|
276
|
+
}
|
|
277
|
+
|
|
223
278
|
private async invoke(
|
|
224
279
|
agent: AgentName,
|
|
225
280
|
operation: string,
|
package/src/index.ts
CHANGED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Scripted fake turn agent for turn-session tests (task 1284). A REAL child process: it speaks a
|
|
3
|
+
* JSONL protocol over stdin/stdout, replaying a script passed as `argv[2]` (JSON array). Only for
|
|
4
|
+
* tests via `./testing` — never imported by library code.
|
|
5
|
+
*
|
|
6
|
+
* Protocol (parent → child):
|
|
7
|
+
* {"type":"turn","turnId":...,"prompt":...,"correlation":{...}} start replaying the script
|
|
8
|
+
* {"type":"cancel","reason":...} flush pending sleeps (unless ignored)
|
|
9
|
+
* Protocol (child → parent):
|
|
10
|
+
* {"ctl":"ready","nativeSessionId":...} handshake (auto-emitted at startup)
|
|
11
|
+
* {"turn":T,"type":"accepted"} | {"turn":T,"type":"output","data":...}
|
|
12
|
+
* {"turn":T,"type":"terminal","kind":"success"|"failure",...}
|
|
13
|
+
* {"ctl":"exit"} echoes are the raw scripted `stray` lines.
|
|
14
|
+
*/
|
|
15
|
+
import { createInterface } from 'node:readline';
|
|
16
|
+
|
|
17
|
+
interface FakeAction {
|
|
18
|
+
op: 'ready' | 'accept' | 'output' | 'terminal' | 'stray' | 'sleep' | 'ignore-cancel' | 'flood' | 'exit';
|
|
19
|
+
nativeSessionId?: string;
|
|
20
|
+
data?: string;
|
|
21
|
+
kind?: 'success' | 'failure';
|
|
22
|
+
nativeTurnId?: string;
|
|
23
|
+
finalText?: string;
|
|
24
|
+
line?: Record<string, unknown>;
|
|
25
|
+
ms?: number;
|
|
26
|
+
code?: number;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const script: FakeAction[] = JSON.parse(process.argv[2] ?? '[]');
|
|
30
|
+
const readyAction = script.find((action) => action.op === 'ready');
|
|
31
|
+
const turnActions = script.filter((action) => action.op !== 'ready');
|
|
32
|
+
/** Skip the startup ready frame when the script dies immediately (broken-agent handshake test). */
|
|
33
|
+
const startsWithExit = script[0]?.op === 'exit';
|
|
34
|
+
|
|
35
|
+
let currentTurnId: string | null = null;
|
|
36
|
+
let ignoreCancel = false;
|
|
37
|
+
let flushing = false;
|
|
38
|
+
/** Pending sleep timers mapped to their resolvers so a cancel can wake them (not just clear them). */
|
|
39
|
+
const sleepers = new Map<NodeJS.Timeout, () => void>();
|
|
40
|
+
|
|
41
|
+
function send(line: Record<string, unknown>): void {
|
|
42
|
+
process.stdout.write(`${JSON.stringify(line)}\n`);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Parent may drop stdout (kill/close) while frames are in flight — exit instead of crashing on EPIPE.
|
|
46
|
+
process.stdout.on('error', () => process.exit(0));
|
|
47
|
+
|
|
48
|
+
// Handshake: explicit ready action first (nativeSessionId control), else the default.
|
|
49
|
+
if (readyAction !== undefined) {
|
|
50
|
+
send({
|
|
51
|
+
ctl: 'ready',
|
|
52
|
+
...(readyAction.nativeSessionId !== undefined ? { nativeSessionId: readyAction.nativeSessionId } : {}),
|
|
53
|
+
});
|
|
54
|
+
} else if (!startsWithExit) {
|
|
55
|
+
send({ ctl: 'ready', nativeSessionId: 'fake-session-1' });
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function sleep(ms: number): Promise<void> {
|
|
59
|
+
return new Promise((resolve) => {
|
|
60
|
+
const timer = setTimeout(() => {
|
|
61
|
+
sleepers.delete(timer);
|
|
62
|
+
resolve();
|
|
63
|
+
}, ms);
|
|
64
|
+
sleepers.set(timer, resolve);
|
|
65
|
+
if (flushing) {
|
|
66
|
+
clearTimeout(timer);
|
|
67
|
+
sleepers.delete(timer);
|
|
68
|
+
resolve();
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function replay(): Promise<void> {
|
|
74
|
+
for (const action of turnActions) {
|
|
75
|
+
if (action.op === 'accept') send({ turn: currentTurnId, type: 'accepted' });
|
|
76
|
+
else if (action.op === 'output') send({ turn: currentTurnId, type: 'output', data: action.data ?? '' });
|
|
77
|
+
else if (action.op === 'terminal')
|
|
78
|
+
send({
|
|
79
|
+
turn: currentTurnId,
|
|
80
|
+
type: 'terminal',
|
|
81
|
+
kind: action.kind ?? 'success',
|
|
82
|
+
...(action.nativeTurnId !== undefined ? { nativeTurnId: action.nativeTurnId } : {}),
|
|
83
|
+
...(action.finalText !== undefined ? { finalText: action.finalText } : {}),
|
|
84
|
+
});
|
|
85
|
+
else if (action.op === 'stray' && action.line !== undefined) send(action.line);
|
|
86
|
+
else if (action.op === 'flood')
|
|
87
|
+
// Written by the child so the >1MiB line never passes through argv (macOS E2BIG limit).
|
|
88
|
+
send({ turn: currentTurnId, type: 'output', data: 'x'.repeat(1024 * 1024 + 64) });
|
|
89
|
+
else if (action.op === 'sleep') await sleep(action.ms ?? 0);
|
|
90
|
+
else if (action.op === 'ignore-cancel') ignoreCancel = true;
|
|
91
|
+
else if (action.op === 'exit') process.exit(action.code ?? 0);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const rl = createInterface({ input: process.stdin });
|
|
96
|
+
rl.on('line', (raw) => {
|
|
97
|
+
let frame: Record<string, unknown>;
|
|
98
|
+
try {
|
|
99
|
+
frame = JSON.parse(raw) as Record<string, unknown>;
|
|
100
|
+
} catch {
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
if (frame.type === 'turn' && typeof frame.turnId === 'string') {
|
|
104
|
+
currentTurnId = frame.turnId;
|
|
105
|
+
flushing = false;
|
|
106
|
+
void replay();
|
|
107
|
+
} else if (frame.type === 'cancel') {
|
|
108
|
+
if (ignoreCancel) return;
|
|
109
|
+
// Answering cancel: wake pending sleeps so the scripted terminal arrives promptly.
|
|
110
|
+
flushing = true;
|
|
111
|
+
for (const [timer, resolve] of sleepers) {
|
|
112
|
+
clearTimeout(timer);
|
|
113
|
+
resolve();
|
|
114
|
+
}
|
|
115
|
+
sleepers.clear();
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
rl.on('close', () => {
|
|
119
|
+
process.exit(0);
|
|
120
|
+
});
|
|
121
|
+
// Scripts that lead with `exit` run at startup (direct child drives and handshake tests);
|
|
122
|
+
// turn-dependent actions replay with a null turnId in that mode.
|
|
123
|
+
if (startsWithExit) void replay();
|