megacode-agent-sdk 0.0.0-stage → 0.31.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/LICENSE-APACHE +176 -0
- package/LICENSE-MIT +23 -0
- package/README.md +38 -2
- package/dist/binary/archive.d.ts +7 -0
- package/dist/binary/archive.js +215 -0
- package/dist/binary/cache.d.ts +21 -0
- package/dist/binary/cache.js +256 -0
- package/dist/binary/download.d.ts +16 -0
- package/dist/binary/download.js +174 -0
- package/dist/binary/index.d.ts +49 -0
- package/dist/binary/index.js +160 -0
- package/dist/client.d.ts +94 -0
- package/dist/client.js +868 -0
- package/dist/errors.d.ts +58 -0
- package/dist/errors.js +97 -0
- package/dist/index.d.ts +52 -0
- package/dist/index.js +42 -0
- package/dist/options.d.ts +48 -0
- package/dist/options.js +49 -0
- package/dist/pins.d.ts +5 -0
- package/dist/pins.js +22 -0
- package/dist/process.d.ts +72 -0
- package/dist/process.js +255 -0
- package/dist/tools.d.ts +74 -0
- package/dist/tools.js +256 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +3 -0
- package/dist/wire.d.ts +241 -0
- package/dist/wire.js +620 -0
- package/package.json +33 -4
package/dist/client.js
ADDED
|
@@ -0,0 +1,868 @@
|
|
|
1
|
+
// A session (spec slice-ar R8.1, R8.5, R8.6): one process, one reader (the
|
|
2
|
+
// stdout `data` handler, which never awaits the program), one writer (a
|
|
3
|
+
// queue drained in order), and the handle a program holds. The reader's
|
|
4
|
+
// state owns the turn, its aborts and the pending `(command, id)` slots;
|
|
5
|
+
// Node runs it on one thread, so a method that reads and changes that state
|
|
6
|
+
// without awaiting between is atomic with respect to the reader.
|
|
7
|
+
import { locate } from "./binary/index.js";
|
|
8
|
+
import { HandshakeError, ProtocolError, Refused, SdkError, SessionEnded, SlowConsumer, TurnInProgress } from "./errors.js";
|
|
9
|
+
import { fileJson } from "./options.js";
|
|
10
|
+
import { LineSplitter, OptionsFile, spawn } from "./process.js";
|
|
11
|
+
import { checkArguments, debugQuoted, errorLine, failureText, isAbort, resultLine, shown, toToolOutput, typeName, } from "./tools.js";
|
|
12
|
+
import { VERSION } from "./version.js";
|
|
13
|
+
import { compactedOf, cut, decode, encode, REASON_LIMIT, snippet, stateFrom, wellFormedJson, } from "./wire.js";
|
|
14
|
+
/** How long a start waits for `init` (R6.2). */
|
|
15
|
+
export const INIT_TIMEOUT_MS = 60_000;
|
|
16
|
+
/** A turn's unread events past this end the session (R8.5.5). */
|
|
17
|
+
export const UNREAD_LIMIT = 10_000;
|
|
18
|
+
/** How long `close` waits for the exit after `quit` (R8.6.2). */
|
|
19
|
+
export const QUIT_WAIT_MS = 5000;
|
|
20
|
+
/** How long `close` waits for handler and callback tasks before it stops
|
|
21
|
+
* waiting for them (R8.6.2). */
|
|
22
|
+
export const TASK_WAIT_MS = 5000;
|
|
23
|
+
/** How long the reader keeps reading stdout once the process has exited: its
|
|
24
|
+
* last lines are already in the pipe, while a descendant holding the pipe
|
|
25
|
+
* open may never end it. */
|
|
26
|
+
export const DRAIN_AFTER_EXIT_MS = 500;
|
|
27
|
+
let initTimeoutMs = INIT_TIMEOUT_MS;
|
|
28
|
+
/** Test support: shortens the wait for `init`. Not part of the API. */
|
|
29
|
+
export function setInitTimeoutMs(ms) {
|
|
30
|
+
initTimeoutMs = ms;
|
|
31
|
+
}
|
|
32
|
+
const noop = () => { };
|
|
33
|
+
/** A stream's queue: the reader pushes, the stream reads. Events queue
|
|
34
|
+
* without blocking the reader. Internal: a program holds only the `Events`
|
|
35
|
+
* that reads it. */
|
|
36
|
+
class Queue {
|
|
37
|
+
items = [];
|
|
38
|
+
waiter = null;
|
|
39
|
+
done = false;
|
|
40
|
+
ended = false;
|
|
41
|
+
error = null;
|
|
42
|
+
overflowed = false;
|
|
43
|
+
dropped = false;
|
|
44
|
+
/** Queues `event`; `false` once more than `UNREAD_LIMIT` are unread. A
|
|
45
|
+
* dropped or finished stream discards it. */
|
|
46
|
+
push(event) {
|
|
47
|
+
if (this.dropped || this.done || this.ended || this.error !== null)
|
|
48
|
+
return true;
|
|
49
|
+
this.items.push(event);
|
|
50
|
+
this.wake();
|
|
51
|
+
if (this.items.length > UNREAD_LIMIT) {
|
|
52
|
+
this.overflowed = true;
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
return true;
|
|
56
|
+
}
|
|
57
|
+
/** Ends the stream after the events already queued. */
|
|
58
|
+
end() {
|
|
59
|
+
this.ended = true;
|
|
60
|
+
this.wake();
|
|
61
|
+
}
|
|
62
|
+
/** Ends the stream with `error` after the events already queued. */
|
|
63
|
+
fail(error) {
|
|
64
|
+
if (this.error === null && !this.ended)
|
|
65
|
+
this.error = error;
|
|
66
|
+
this.wake();
|
|
67
|
+
}
|
|
68
|
+
take() {
|
|
69
|
+
if (this.done)
|
|
70
|
+
return { done: true, value: undefined };
|
|
71
|
+
if (this.overflowed) {
|
|
72
|
+
this.done = true;
|
|
73
|
+
this.items = [];
|
|
74
|
+
return new SlowConsumer();
|
|
75
|
+
}
|
|
76
|
+
const item = this.items.shift();
|
|
77
|
+
if (item !== undefined)
|
|
78
|
+
return { done: false, value: item };
|
|
79
|
+
if (this.error !== null) {
|
|
80
|
+
this.done = true;
|
|
81
|
+
return this.error.clone();
|
|
82
|
+
}
|
|
83
|
+
if (this.ended) {
|
|
84
|
+
this.done = true;
|
|
85
|
+
return { done: true, value: undefined };
|
|
86
|
+
}
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
wake() {
|
|
90
|
+
const waiter = this.waiter;
|
|
91
|
+
if (waiter === null)
|
|
92
|
+
return;
|
|
93
|
+
const got = this.take();
|
|
94
|
+
if (got === null)
|
|
95
|
+
return;
|
|
96
|
+
this.waiter = null;
|
|
97
|
+
if (got instanceof SdkError)
|
|
98
|
+
waiter.reject(got);
|
|
99
|
+
else
|
|
100
|
+
waiter.resolve(got);
|
|
101
|
+
}
|
|
102
|
+
next() {
|
|
103
|
+
if (this.waiter !== null)
|
|
104
|
+
return Promise.reject(new Error("next() called while a previous next() is pending"));
|
|
105
|
+
const got = this.take();
|
|
106
|
+
if (got instanceof SdkError)
|
|
107
|
+
return Promise.reject(got);
|
|
108
|
+
if (got !== null)
|
|
109
|
+
return Promise.resolve(got);
|
|
110
|
+
return new Promise((resolve, reject) => {
|
|
111
|
+
this.waiter = { resolve, reject };
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
return() {
|
|
115
|
+
this.dropped = true;
|
|
116
|
+
this.done = true;
|
|
117
|
+
this.items = [];
|
|
118
|
+
const waiter = this.waiter;
|
|
119
|
+
this.waiter = null;
|
|
120
|
+
waiter?.resolve({ done: true, value: undefined });
|
|
121
|
+
return Promise.resolve({ done: true, value: undefined });
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/** Each stream's queue; the reader's side, out of a program's reach. */
|
|
125
|
+
const queues = new WeakMap();
|
|
126
|
+
function sink(events) {
|
|
127
|
+
return queues.get(events);
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* A stream of events, a turn's or the session's between turns. An error ends
|
|
131
|
+
* the stream (thrown by `next`). `return()` (a `break` out of `for await`)
|
|
132
|
+
* drops the stream: the rest of its events are discarded.
|
|
133
|
+
*/
|
|
134
|
+
export class Events {
|
|
135
|
+
constructor() {
|
|
136
|
+
queues.set(this, new Queue());
|
|
137
|
+
}
|
|
138
|
+
next() {
|
|
139
|
+
return sink(this).next();
|
|
140
|
+
}
|
|
141
|
+
return() {
|
|
142
|
+
return sink(this).return();
|
|
143
|
+
}
|
|
144
|
+
[Symbol.asyncIterator]() {
|
|
145
|
+
return this;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
/** One turn's events, `user` to `result`. It ends after `result`, or with
|
|
149
|
+
* no event once an abort took its queued prompt back (`dequeued`). */
|
|
150
|
+
export class TurnStream extends Events {
|
|
151
|
+
}
|
|
152
|
+
/** A waiting command's key: the command and its `id`, as its `response`
|
|
153
|
+
* echoes both, so an `approval` and a `client_tool_result` that share an id
|
|
154
|
+
* never answer each other. */
|
|
155
|
+
const key = (command, id) => `${command}\u0000${id}`;
|
|
156
|
+
const CLOSE = Symbol("close stdin");
|
|
157
|
+
/** What the reader, the writer and every method share. */
|
|
158
|
+
class Session {
|
|
159
|
+
proc;
|
|
160
|
+
tools;
|
|
161
|
+
onApproval;
|
|
162
|
+
pending = new Map();
|
|
163
|
+
turn = null;
|
|
164
|
+
loose = null;
|
|
165
|
+
looseGiven = false;
|
|
166
|
+
ended = null;
|
|
167
|
+
calls = new Map();
|
|
168
|
+
tasks = new Set();
|
|
169
|
+
nextId = 1;
|
|
170
|
+
queue = [];
|
|
171
|
+
writing = false;
|
|
172
|
+
stdinClosed = false;
|
|
173
|
+
phase = "init";
|
|
174
|
+
/** The SDK ended the session: the rest of stdout is read and dropped, so
|
|
175
|
+
* the process is never held writing while it stops. */
|
|
176
|
+
stopped = false;
|
|
177
|
+
readDone = false;
|
|
178
|
+
initWake = null;
|
|
179
|
+
initEarly = null;
|
|
180
|
+
stopping = null;
|
|
181
|
+
constructor(proc, tools, onApproval) {
|
|
182
|
+
this.proc = proc;
|
|
183
|
+
this.tools = tools;
|
|
184
|
+
this.onApproval = onApproval;
|
|
185
|
+
const splitter = new LineSplitter();
|
|
186
|
+
const stdout = proc.child.stdout;
|
|
187
|
+
const onLine = (line) => this.onLine(line);
|
|
188
|
+
stdout.on("data", (chunk) => splitter.push(chunk, onLine));
|
|
189
|
+
// At the end of stdout an unterminated last line is read too; a read the
|
|
190
|
+
// drain cut short (below) is not.
|
|
191
|
+
stdout.on("end", () => {
|
|
192
|
+
splitter.end(onLine);
|
|
193
|
+
this.finishReading();
|
|
194
|
+
});
|
|
195
|
+
stdout.on("close", () => this.finishReading());
|
|
196
|
+
proc.onExit(() => {
|
|
197
|
+
const timer = setTimeout(() => {
|
|
198
|
+
stdout.destroy();
|
|
199
|
+
this.finishReading();
|
|
200
|
+
}, DRAIN_AFTER_EXIT_MS);
|
|
201
|
+
stdout.once("close", () => clearTimeout(timer));
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
newId() {
|
|
205
|
+
return `sdk-${this.nextId++}`;
|
|
206
|
+
}
|
|
207
|
+
/** Waits for `init` (at most the init timeout), checked by `check`. */
|
|
208
|
+
awaitInit(check, ms) {
|
|
209
|
+
this.check = check;
|
|
210
|
+
if (this.initEarly !== null)
|
|
211
|
+
return Promise.resolve(this.initEarly);
|
|
212
|
+
return new Promise((resolve) => {
|
|
213
|
+
const timer = setTimeout(() => {
|
|
214
|
+
this.initWake = null;
|
|
215
|
+
this.phase = "failed";
|
|
216
|
+
this.stopped = true;
|
|
217
|
+
resolve({ failure: new HandshakeError(`no init within ${Math.floor(ms / 1000)} s`) });
|
|
218
|
+
}, ms);
|
|
219
|
+
this.initWake = (o) => {
|
|
220
|
+
clearTimeout(timer);
|
|
221
|
+
this.initWake = null;
|
|
222
|
+
resolve(o);
|
|
223
|
+
};
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
check = () => null;
|
|
227
|
+
settleInit(o) {
|
|
228
|
+
if (this.initWake !== null)
|
|
229
|
+
this.initWake(o);
|
|
230
|
+
else
|
|
231
|
+
this.initEarly = o;
|
|
232
|
+
}
|
|
233
|
+
onLine(bytes) {
|
|
234
|
+
if (this.stopped)
|
|
235
|
+
return;
|
|
236
|
+
if (this.phase === "init") {
|
|
237
|
+
let decoded;
|
|
238
|
+
try {
|
|
239
|
+
decoded = decode(utf8(bytes));
|
|
240
|
+
}
|
|
241
|
+
catch (e) {
|
|
242
|
+
this.phase = "failed";
|
|
243
|
+
this.stopped = true;
|
|
244
|
+
this.settleInit({ failure: new HandshakeError(e instanceof Error ? e.message : String(e)) });
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
const line = decoded.line;
|
|
248
|
+
if (line === null)
|
|
249
|
+
return;
|
|
250
|
+
if (line.type !== "init") {
|
|
251
|
+
this.phase = "failed";
|
|
252
|
+
this.stopped = true;
|
|
253
|
+
this.settleInit({ failure: new HandshakeError(`the first line was not init: ${snippet(bytes)}`) });
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
const { type: _type, ...info } = line;
|
|
257
|
+
const why = this.check(info, decoded.v ?? 0);
|
|
258
|
+
if (why !== null) {
|
|
259
|
+
this.phase = "failed";
|
|
260
|
+
this.stopped = true;
|
|
261
|
+
this.settleInit({ failure: new HandshakeError(why) });
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
this.phase = "running";
|
|
265
|
+
this.settleInit({ info });
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
if (this.phase !== "running")
|
|
269
|
+
return;
|
|
270
|
+
try {
|
|
271
|
+
const { line } = decode(utf8(bytes), (id, decision) => this.respond(id, decision));
|
|
272
|
+
if (line !== null)
|
|
273
|
+
this.route(line);
|
|
274
|
+
}
|
|
275
|
+
catch (e) {
|
|
276
|
+
this.stopWith(e instanceof SdkError ? e : new ProtocolError(e instanceof Error ? e.message : String(e)));
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
/** stdout ended, or the drain after the exit ran out: the session ends. */
|
|
280
|
+
finishReading() {
|
|
281
|
+
if (this.readDone)
|
|
282
|
+
return;
|
|
283
|
+
this.readDone = true;
|
|
284
|
+
if (this.phase === "init") {
|
|
285
|
+
this.phase = "failed";
|
|
286
|
+
this.settleInit({ ended: true });
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
void this.proc.diagnostics().then((d) => this.end(new SessionEnded(d)));
|
|
290
|
+
}
|
|
291
|
+
/** Ends the session with `cause`: every stream and waiting command gets
|
|
292
|
+
* it, every running call's signal fires. The first cause wins. */
|
|
293
|
+
end(cause) {
|
|
294
|
+
if (this.ended !== null)
|
|
295
|
+
return;
|
|
296
|
+
this.ended = cause;
|
|
297
|
+
this.turn?.events.fail(cause);
|
|
298
|
+
this.turn = null;
|
|
299
|
+
this.loose?.fail(cause);
|
|
300
|
+
this.loose = null;
|
|
301
|
+
const waiting = [...this.pending.values()];
|
|
302
|
+
this.pending.clear();
|
|
303
|
+
for (const w of waiting)
|
|
304
|
+
w.reject(cause.clone());
|
|
305
|
+
this.cancelCalls();
|
|
306
|
+
}
|
|
307
|
+
cancelCalls() {
|
|
308
|
+
for (const c of this.calls.values())
|
|
309
|
+
c.abort();
|
|
310
|
+
this.calls.clear();
|
|
311
|
+
}
|
|
312
|
+
/** Ends the session for `cause` and stops the process (R8.6). */
|
|
313
|
+
stopWith(cause) {
|
|
314
|
+
this.end(cause);
|
|
315
|
+
this.stopped = true;
|
|
316
|
+
void this.shutDown();
|
|
317
|
+
}
|
|
318
|
+
/** Queues `line` whole; `false` once stdin is closed. Lines keep their
|
|
319
|
+
* order, and a caller that stops waiting never leaves a part of one. */
|
|
320
|
+
write(line) {
|
|
321
|
+
if (this.stdinClosed)
|
|
322
|
+
return false;
|
|
323
|
+
this.queue.push(line);
|
|
324
|
+
if (!this.writing)
|
|
325
|
+
void this.pump();
|
|
326
|
+
return true;
|
|
327
|
+
}
|
|
328
|
+
/** The writer: writes each queued line, waiting until it was handed to the
|
|
329
|
+
* pipe, until `CLOSE` or a failed write; then stdin is closed. A failed
|
|
330
|
+
* write ends the session at once and kills the process, whether or not
|
|
331
|
+
* its stdout ever ends (a descendant can hold it open). */
|
|
332
|
+
async pump() {
|
|
333
|
+
this.writing = true;
|
|
334
|
+
const stdin = this.proc.child.stdin;
|
|
335
|
+
while (this.queue.length > 0) {
|
|
336
|
+
const item = this.queue.shift();
|
|
337
|
+
if (item === CLOSE) {
|
|
338
|
+
this.stdinClosed = true;
|
|
339
|
+
this.queue.length = 0;
|
|
340
|
+
stdin.end();
|
|
341
|
+
break;
|
|
342
|
+
}
|
|
343
|
+
const ok = await new Promise((resolve) => {
|
|
344
|
+
try {
|
|
345
|
+
stdin.write(item, (err) => resolve(err === null || err === undefined));
|
|
346
|
+
}
|
|
347
|
+
catch {
|
|
348
|
+
resolve(false);
|
|
349
|
+
}
|
|
350
|
+
});
|
|
351
|
+
if (!ok) {
|
|
352
|
+
this.stdinClosed = true;
|
|
353
|
+
this.queue.length = 0;
|
|
354
|
+
this.end(new SessionEnded());
|
|
355
|
+
this.proc.signal("SIGKILL");
|
|
356
|
+
break;
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
this.writing = false;
|
|
360
|
+
}
|
|
361
|
+
/** Queues an encoded `command` line and waits for its `response`. */
|
|
362
|
+
sendLine(command, id, line) {
|
|
363
|
+
if (this.ended !== null)
|
|
364
|
+
return Promise.reject(this.ended.clone());
|
|
365
|
+
const k = key(command, id);
|
|
366
|
+
if (this.pending.has(k)) {
|
|
367
|
+
return Promise.reject(new Refused("bad_argument", `an answer to ${id} is already waiting for its response`));
|
|
368
|
+
}
|
|
369
|
+
if (!this.write(line))
|
|
370
|
+
return Promise.reject(new SessionEnded());
|
|
371
|
+
return this.waitFor(k);
|
|
372
|
+
}
|
|
373
|
+
/** Registers the slot `k` and waits for its response: `Refused` when it
|
|
374
|
+
* is an error, the session's end when it never comes. */
|
|
375
|
+
waitFor(k) {
|
|
376
|
+
return new Promise((resolve, reject) => {
|
|
377
|
+
this.pending.set(k, { resolve, reject });
|
|
378
|
+
}).then((r) => {
|
|
379
|
+
if (r.ok)
|
|
380
|
+
return r;
|
|
381
|
+
throw new Refused(r.error?.code ?? "", r.error?.message ?? "");
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
command(command, body) {
|
|
385
|
+
const id = this.newId();
|
|
386
|
+
return this.commandWithId(command, { ...body, id }, id);
|
|
387
|
+
}
|
|
388
|
+
commandWithId(command, body, id) {
|
|
389
|
+
let line;
|
|
390
|
+
try {
|
|
391
|
+
line = encode({ type: command, ...body });
|
|
392
|
+
}
|
|
393
|
+
catch (e) {
|
|
394
|
+
return Promise.reject(e);
|
|
395
|
+
}
|
|
396
|
+
return this.sendLine(command, id, line);
|
|
397
|
+
}
|
|
398
|
+
/** Answers the approval request `requestId` (R8.3.3). `approval`'s `id`
|
|
399
|
+
* names the request, so the answer is matched by it, and a second answer
|
|
400
|
+
* while one is in flight is refused before it is sent. */
|
|
401
|
+
async respond(requestId, decision) {
|
|
402
|
+
const plain = plainDecision(decision);
|
|
403
|
+
if (plain === null)
|
|
404
|
+
throw new TypeError(`a decision is allow_once, allow_for_turn, deny or deny_and_stop, not ${shown(decision)}`);
|
|
405
|
+
await this.sendLine("approval", requestId, approvalLine(requestId, plain));
|
|
406
|
+
}
|
|
407
|
+
/** The stop of R8.6.2: `quit` and the end of stdin are queued, then the
|
|
408
|
+
* exit is awaited, escalating to signals whether or not the writer got
|
|
409
|
+
* them through. */
|
|
410
|
+
shutDown() {
|
|
411
|
+
if (this.stopping === null) {
|
|
412
|
+
this.write(encode({ type: "quit", id: this.newId() }));
|
|
413
|
+
this.write(CLOSE);
|
|
414
|
+
this.stopping = this.proc.stop(QUIT_WAIT_MS);
|
|
415
|
+
}
|
|
416
|
+
return this.stopping;
|
|
417
|
+
}
|
|
418
|
+
track(task) {
|
|
419
|
+
this.tasks.add(task);
|
|
420
|
+
void task.finally(() => this.tasks.delete(task));
|
|
421
|
+
}
|
|
422
|
+
/** Waits up to `TASK_WAIT_MS` for the handler and callback tasks, those
|
|
423
|
+
* started meanwhile included; then stops waiting (their results are
|
|
424
|
+
* dropped, their signals fired). */
|
|
425
|
+
async finishTasks() {
|
|
426
|
+
const deadline = Date.now() + TASK_WAIT_MS;
|
|
427
|
+
while (this.tasks.size > 0) {
|
|
428
|
+
const left = deadline - Date.now();
|
|
429
|
+
if (left <= 0) {
|
|
430
|
+
// Past the wait, the tasks still running are no longer waited for,
|
|
431
|
+
// so a later call waits only for tasks started after this one.
|
|
432
|
+
this.tasks.clear();
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
let timer;
|
|
436
|
+
await Promise.race([
|
|
437
|
+
Promise.allSettled([...this.tasks]),
|
|
438
|
+
new Promise((resolve) => {
|
|
439
|
+
timer = setTimeout(resolve, left);
|
|
440
|
+
}),
|
|
441
|
+
]);
|
|
442
|
+
clearTimeout(timer);
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
/** One line's effect. Throws `SlowConsumer` when a queue overflowed. */
|
|
446
|
+
route(line) {
|
|
447
|
+
switch (line.type) {
|
|
448
|
+
case "client_tool_call":
|
|
449
|
+
this.startCall(line);
|
|
450
|
+
return;
|
|
451
|
+
case "client_tool_cancel":
|
|
452
|
+
// The call is over: its entry goes now, even if its handler never settles.
|
|
453
|
+
this.calls.get(line.id)?.abort();
|
|
454
|
+
this.calls.delete(line.id);
|
|
455
|
+
return;
|
|
456
|
+
case "response": {
|
|
457
|
+
const id = line.id;
|
|
458
|
+
if (id === null)
|
|
459
|
+
return;
|
|
460
|
+
const turn = this.turn;
|
|
461
|
+
// A refused prompt takes no turn, whether or not `send` still waits.
|
|
462
|
+
if (line.command === "prompt" && !line.ok && turn?.promptId === id) {
|
|
463
|
+
turn.events.end();
|
|
464
|
+
this.turn = null;
|
|
465
|
+
}
|
|
466
|
+
// A prompt an abort took back never runs: its turn ends here.
|
|
467
|
+
if (line.command === "abort" && line.disposition === "dequeued" && turn !== null && turn.aborts.has(id)) {
|
|
468
|
+
turn.events.end();
|
|
469
|
+
this.turn = null;
|
|
470
|
+
}
|
|
471
|
+
const k = key(line.command, id);
|
|
472
|
+
const waiting = this.pending.get(k);
|
|
473
|
+
if (waiting !== undefined) {
|
|
474
|
+
this.pending.delete(k);
|
|
475
|
+
waiting.resolve(line);
|
|
476
|
+
}
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
case "init":
|
|
480
|
+
return;
|
|
481
|
+
default:
|
|
482
|
+
this.routeEvent(line);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
routeEvent(event) {
|
|
486
|
+
if (event.type === "approval_request" && this.onApproval !== undefined) {
|
|
487
|
+
this.startApproval(this.onApproval, event);
|
|
488
|
+
return;
|
|
489
|
+
}
|
|
490
|
+
const turn = this.turn;
|
|
491
|
+
// The program's turn opens at its prompt's `user` line: the one prompt
|
|
492
|
+
// in flight is the program's, so the first prompt-kind `user` line is
|
|
493
|
+
// its own, and the next `result` ends it.
|
|
494
|
+
if (turn !== null)
|
|
495
|
+
turn.opened ||= event.type === "user" && event.kind === "message";
|
|
496
|
+
if (turn !== null && turn.opened) {
|
|
497
|
+
const kept = turn.events.push(event);
|
|
498
|
+
if (event.type === "result") {
|
|
499
|
+
turn.events.end();
|
|
500
|
+
this.turn = null;
|
|
501
|
+
}
|
|
502
|
+
if (!kept)
|
|
503
|
+
throw new SlowConsumer();
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
if (this.loose !== null && !this.loose.push(event))
|
|
507
|
+
throw new SlowConsumer();
|
|
508
|
+
}
|
|
509
|
+
/** Runs a `client_tool_call` (R8.4) as its own task: the arguments'
|
|
510
|
+
* check, the handler, then the result, unless the call's signal fired
|
|
511
|
+
* first (R8.4.4). Whatever the handler throws, returns or rejects with is
|
|
512
|
+
* an outcome, never the program's crash. A `bad_argument` refusal is
|
|
513
|
+
* followed by an `is_error` result with its message (R8.4.5). */
|
|
514
|
+
startCall(call) {
|
|
515
|
+
const fire = new AbortController();
|
|
516
|
+
if (this.ended !== null)
|
|
517
|
+
fire.abort();
|
|
518
|
+
this.calls.set(call.id, fire);
|
|
519
|
+
const tool = this.tools.get(call.name);
|
|
520
|
+
const run = async () => {
|
|
521
|
+
let outcome;
|
|
522
|
+
if (call.tooDeep === true)
|
|
523
|
+
outcome = { error: "the arguments are nested too deeply" };
|
|
524
|
+
else if (tool === undefined)
|
|
525
|
+
outcome = { error: `this program has no tool named ${debugQuoted(call.name)}` };
|
|
526
|
+
else
|
|
527
|
+
outcome = await runHandler(tool, call, fire.signal);
|
|
528
|
+
await this.answerCall(call.id, outcome, fire.signal);
|
|
529
|
+
};
|
|
530
|
+
this.track(run()
|
|
531
|
+
.catch(noop)
|
|
532
|
+
.finally(() => {
|
|
533
|
+
if (this.calls.get(call.id) === fire)
|
|
534
|
+
this.calls.delete(call.id);
|
|
535
|
+
}));
|
|
536
|
+
}
|
|
537
|
+
/** Sends the call's one answer, unless its signal fired. A line that
|
|
538
|
+
* cannot be built answers `is_error` with the reason, so no call is left to
|
|
539
|
+
* harness's timeout. */
|
|
540
|
+
async answerCall(id, outcome, signal) {
|
|
541
|
+
if (signal.aborted)
|
|
542
|
+
return;
|
|
543
|
+
const command = "client_tool_result";
|
|
544
|
+
let line;
|
|
545
|
+
try {
|
|
546
|
+
line = resultLine(id, outcome);
|
|
547
|
+
}
|
|
548
|
+
catch (e) {
|
|
549
|
+
line = errorLine(id, failureText(e));
|
|
550
|
+
}
|
|
551
|
+
try {
|
|
552
|
+
await this.sendLine(command, id, line);
|
|
553
|
+
}
|
|
554
|
+
catch (e) {
|
|
555
|
+
if (e instanceof Refused && e.code === "bad_argument" && !signal.aborted) {
|
|
556
|
+
await this.sendLine(command, id, errorLine(id, e.message)).catch(noop);
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
/** Runs the approval callback on `request` as its own task (R8.3.2) and
|
|
561
|
+
* answers with its decision; a callback that throws or rejects, returns no
|
|
562
|
+
* promise, or gives no decision or one not among the request's choices,
|
|
563
|
+
* answers `deny` with the failure as the reason. */
|
|
564
|
+
startApproval(callback, request) {
|
|
565
|
+
const run = async () => {
|
|
566
|
+
const decision = await decide(callback, request);
|
|
567
|
+
// Built here, synchronously: a line that cannot be built answers a plain `deny`.
|
|
568
|
+
let line;
|
|
569
|
+
try {
|
|
570
|
+
line = approvalLine(request.id, decision);
|
|
571
|
+
}
|
|
572
|
+
catch {
|
|
573
|
+
line = approvalLine(request.id, { kind: "deny" });
|
|
574
|
+
}
|
|
575
|
+
await this.sendLine("approval", request.id, line);
|
|
576
|
+
};
|
|
577
|
+
this.track(run().catch(noop));
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
/** A handler's outcome: its output, or the error the call answers. */
|
|
581
|
+
async function runHandler(tool, call, signal) {
|
|
582
|
+
try {
|
|
583
|
+
const why = checkArguments(tool.inputSchema, call.input);
|
|
584
|
+
if (why !== null)
|
|
585
|
+
return { error: `invalid arguments: ${why}` };
|
|
586
|
+
const running = tool.handler(call.input, { callId: call.id, signal });
|
|
587
|
+
if (!isThenable(running))
|
|
588
|
+
return { error: `the tool's handler returned ${typeName(running)}, not a Promise` };
|
|
589
|
+
const out = await running;
|
|
590
|
+
if (typeof out === "string")
|
|
591
|
+
return { ok: { text: out } };
|
|
592
|
+
const output = toToolOutput(out);
|
|
593
|
+
if (output !== null)
|
|
594
|
+
return { ok: output };
|
|
595
|
+
return { error: `the tool's handler returned ${typeName(out)}, not string or ToolOutput` };
|
|
596
|
+
}
|
|
597
|
+
catch (e) {
|
|
598
|
+
return { error: isAbort(e) ? "the tool's handler was stopped" : failureText(e) };
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
const DECISIONS = ["allow_once", "allow_for_turn", "deny", "deny_and_stop"];
|
|
602
|
+
/** The approval callback's decision, or the `deny` its failure answers. */
|
|
603
|
+
async function decide(callback, request) {
|
|
604
|
+
try {
|
|
605
|
+
const running = callback(request);
|
|
606
|
+
if (!isThenable(running))
|
|
607
|
+
return { kind: "deny", reason: `the approval callback returned ${shown(running)}, which is not a Promise` };
|
|
608
|
+
const chosen = await running;
|
|
609
|
+
const decision = plainDecision(chosen);
|
|
610
|
+
if (decision === null)
|
|
611
|
+
return { kind: "deny", reason: `the approval callback returned ${shown(chosen)}, which is not a decision` };
|
|
612
|
+
if (!request.choices.includes(decision.kind)) {
|
|
613
|
+
return {
|
|
614
|
+
kind: "deny",
|
|
615
|
+
reason: `the approval callback chose ${decision.kind}, which is not among the choices offered (${request.choices.join(", ")})`,
|
|
616
|
+
};
|
|
617
|
+
}
|
|
618
|
+
return decision;
|
|
619
|
+
}
|
|
620
|
+
catch (e) {
|
|
621
|
+
return { kind: "deny", reason: isAbort(e) ? "the approval callback was stopped" : `the approval callback panicked: ${failureText(e)}` };
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
function isThenable(v) {
|
|
625
|
+
return (typeof v === "object" || typeof v === "function") && v !== null && typeof v.then === "function";
|
|
626
|
+
}
|
|
627
|
+
/** `v` read into a fresh plain decision, or `null` when it is not one.
|
|
628
|
+
* `kind` is read once, and a `deny`'s `reason` once, so a getter cannot
|
|
629
|
+
* answer one thing to the check and another to the line. */
|
|
630
|
+
function plainDecision(v) {
|
|
631
|
+
if (typeof v !== "object" || v === null)
|
|
632
|
+
return null;
|
|
633
|
+
const kind = v.kind;
|
|
634
|
+
if (typeof kind !== "string" || !DECISIONS.includes(kind))
|
|
635
|
+
return null;
|
|
636
|
+
if (kind !== "deny")
|
|
637
|
+
return { kind };
|
|
638
|
+
const reason = v.reason;
|
|
639
|
+
if (reason === undefined)
|
|
640
|
+
return { kind };
|
|
641
|
+
return typeof reason === "string" ? { kind, reason } : null;
|
|
642
|
+
}
|
|
643
|
+
/** The `approval` line answering `requestId` with `decision`, its reason
|
|
644
|
+
* cut to `REASON_LIMIT` bytes; each field of `decision` is read once. */
|
|
645
|
+
function approvalLine(requestId, decision) {
|
|
646
|
+
const kind = decision.kind;
|
|
647
|
+
const body = { type: "approval", id: requestId, decision: kind };
|
|
648
|
+
const reason = kind === "deny" ? decision.reason : undefined;
|
|
649
|
+
if (reason !== undefined)
|
|
650
|
+
body["reason"] = cut(reason, REASON_LIMIT);
|
|
651
|
+
return encode(body);
|
|
652
|
+
}
|
|
653
|
+
const strict = new TextDecoder("utf-8", { fatal: true });
|
|
654
|
+
/** A line's text; bytes that are not UTF-8 are a protocol error, as serde
|
|
655
|
+
* reads them. */
|
|
656
|
+
function utf8(bytes) {
|
|
657
|
+
try {
|
|
658
|
+
return strict.decode(bytes);
|
|
659
|
+
}
|
|
660
|
+
catch {
|
|
661
|
+
throw new ProtocolError(`a line that is not JSON (invalid UTF-8): ${snippet(bytes)}`);
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
/** The major.minor of a version. */
|
|
665
|
+
function minor(version) {
|
|
666
|
+
return version.split(".").slice(0, 2).join(".");
|
|
667
|
+
}
|
|
668
|
+
/** R6.2: protocol `v` 1, a harness of this SDK's major.minor, and
|
|
669
|
+
* `client_tool_result` among the commands when the session has tools. */
|
|
670
|
+
function check(info, v, tools) {
|
|
671
|
+
if (v !== 1)
|
|
672
|
+
return `the session speaks protocol v${v}; this SDK speaks v1`;
|
|
673
|
+
if (minor(info.harnessVersion) !== minor(VERSION)) {
|
|
674
|
+
return `harness ${info.harnessVersion} does not match this SDK (${VERSION}); it needs harness ${minor(VERSION)}.x`;
|
|
675
|
+
}
|
|
676
|
+
if (tools > 0 && !info.commands.includes("client_tool_result")) {
|
|
677
|
+
return `harness ${info.harnessVersion} does not take client_tool_result, and the session has tools`;
|
|
678
|
+
}
|
|
679
|
+
return null;
|
|
680
|
+
}
|
|
681
|
+
/** A session: every method usable while a turn's stream is read (R8.1.2). */
|
|
682
|
+
export class Client {
|
|
683
|
+
session;
|
|
684
|
+
info;
|
|
685
|
+
closing = null;
|
|
686
|
+
constructor(session,
|
|
687
|
+
/** `init`'s data. */
|
|
688
|
+
info) {
|
|
689
|
+
this.session = session;
|
|
690
|
+
this.info = info;
|
|
691
|
+
}
|
|
692
|
+
/** The session's id. */
|
|
693
|
+
get id() {
|
|
694
|
+
return this.info.sessionId;
|
|
695
|
+
}
|
|
696
|
+
/** Starts a session and reads its `init`. */
|
|
697
|
+
static start(options = {}) {
|
|
698
|
+
return Client.open(null, options);
|
|
699
|
+
}
|
|
700
|
+
/** Continues the session `sessionId` (R2.5): the options send only what
|
|
701
|
+
* a resume may give, and the same tools. */
|
|
702
|
+
static resume(sessionId, options = {}) {
|
|
703
|
+
return Client.open(sessionId, options);
|
|
704
|
+
}
|
|
705
|
+
static async open(resume, options) {
|
|
706
|
+
const binary = await locate(options);
|
|
707
|
+
let file;
|
|
708
|
+
try {
|
|
709
|
+
file = OptionsFile.write(wellFormedJson(fileJson(options, resume !== null)));
|
|
710
|
+
}
|
|
711
|
+
catch (e) {
|
|
712
|
+
throw new HandshakeError(`cannot write the options file: ${e instanceof Error ? e.message : String(e)}`);
|
|
713
|
+
}
|
|
714
|
+
let proc;
|
|
715
|
+
try {
|
|
716
|
+
proc = await spawn({ binary, resume, mock: options.mock, cwd: options.cwd, env: options.env, options: file });
|
|
717
|
+
}
|
|
718
|
+
catch (e) {
|
|
719
|
+
file.remove();
|
|
720
|
+
throw e;
|
|
721
|
+
}
|
|
722
|
+
const tools = new Map((options.tools ?? []).map((t) => [t.name, t]));
|
|
723
|
+
const session = new Session(proc, tools, options.onApproval);
|
|
724
|
+
const got = await session.awaitInit((info, v) => check(info, v, tools.size), initTimeoutMs);
|
|
725
|
+
let failure;
|
|
726
|
+
if ("info" in got) {
|
|
727
|
+
file.remove();
|
|
728
|
+
return new Client(session, got.info);
|
|
729
|
+
}
|
|
730
|
+
else if ("failure" in got) {
|
|
731
|
+
failure = got.failure;
|
|
732
|
+
}
|
|
733
|
+
else {
|
|
734
|
+
const d = await proc.diagnostics();
|
|
735
|
+
// harness refused its flags or options, in one stderr line naming the
|
|
736
|
+
// field (R2.1).
|
|
737
|
+
failure =
|
|
738
|
+
d.exitStatus === 2 ? new Refused("bad_argument", d.stderrTail[d.stderrTail.length - 1] ?? "") : new SessionEnded(d);
|
|
739
|
+
}
|
|
740
|
+
// R8.6.4: stdin closed, the process stopped and reaped, the options file
|
|
741
|
+
// removed, then the error.
|
|
742
|
+
session.write(CLOSE);
|
|
743
|
+
await proc.stop(QUIT_WAIT_MS);
|
|
744
|
+
file.remove();
|
|
745
|
+
session.end(failure);
|
|
746
|
+
throw failure;
|
|
747
|
+
}
|
|
748
|
+
/** Starts a turn with `prompt` and returns its events, `user` to
|
|
749
|
+
* `result`. One turn at a time: until the wire's `result` (whether or not
|
|
750
|
+
* the stream is read), or an abort that took the prompt back, another
|
|
751
|
+
* `send` is `TurnInProgress`. */
|
|
752
|
+
async send(prompt) {
|
|
753
|
+
const s = this.session;
|
|
754
|
+
const id = s.newId();
|
|
755
|
+
const line = encode({ type: "prompt", id, text: prompt });
|
|
756
|
+
if (s.ended !== null)
|
|
757
|
+
throw s.ended.clone();
|
|
758
|
+
if (s.turn !== null)
|
|
759
|
+
throw new TurnInProgress();
|
|
760
|
+
const events = new TurnStream();
|
|
761
|
+
s.turn = { promptId: id, opened: false, aborts: new Set(), events: sink(events) };
|
|
762
|
+
if (!s.write(line)) {
|
|
763
|
+
s.turn = null;
|
|
764
|
+
throw new SessionEnded();
|
|
765
|
+
}
|
|
766
|
+
await s.waitFor(key("prompt", id));
|
|
767
|
+
return events;
|
|
768
|
+
}
|
|
769
|
+
/** Joins the running turn at its next landing point. */
|
|
770
|
+
async steer(text) {
|
|
771
|
+
return (await this.session.command("steer", { text })).disposition ?? "";
|
|
772
|
+
}
|
|
773
|
+
/** Interrupts the program's turn, naming its prompt: a running one is
|
|
774
|
+
* `interrupting`; one still `queued` is taken back, `dequeued`, never runs,
|
|
775
|
+
* and its stream ends with no `result`. With no turn of the program's,
|
|
776
|
+
* whatever runs is interrupted. */
|
|
777
|
+
async abort() {
|
|
778
|
+
const s = this.session;
|
|
779
|
+
const id = s.newId();
|
|
780
|
+
if (s.ended !== null)
|
|
781
|
+
throw s.ended.clone();
|
|
782
|
+
const turn = s.turn;
|
|
783
|
+
const body = { type: "abort", id };
|
|
784
|
+
if (turn !== null)
|
|
785
|
+
body["prompt_id"] = turn.promptId;
|
|
786
|
+
// The turn read, the abort registered with it and the line queued with
|
|
787
|
+
// no await between: the abort names the prompt that precedes it.
|
|
788
|
+
if (!s.write(encode(body)))
|
|
789
|
+
throw new SessionEnded();
|
|
790
|
+
turn?.aborts.add(id);
|
|
791
|
+
const r = await s.waitFor(key("abort", id));
|
|
792
|
+
return r.disposition ?? "";
|
|
793
|
+
}
|
|
794
|
+
/** Compacts the context: at once when idle, after the turn when one runs.
|
|
795
|
+
* `done` carries the compaction its own response names; every `compacted`
|
|
796
|
+
* line goes to the running turn's stream or `sessionEvents()`. */
|
|
797
|
+
async compact() {
|
|
798
|
+
const r = await this.session.command("compact", {});
|
|
799
|
+
if (r.disposition === "queued")
|
|
800
|
+
return { queued: true };
|
|
801
|
+
return { done: compactedOf(r.data) };
|
|
802
|
+
}
|
|
803
|
+
/** Puts the running or next task away, or ends away. */
|
|
804
|
+
async away(on) {
|
|
805
|
+
return (await this.session.command("away", { on })).disposition ?? "";
|
|
806
|
+
}
|
|
807
|
+
/** The session's state. */
|
|
808
|
+
async state() {
|
|
809
|
+
return stateFrom((await this.session.command("get_state", {})).data);
|
|
810
|
+
}
|
|
811
|
+
/** Answers the approval request `requestId` (R8.3.3). */
|
|
812
|
+
respond(requestId, decision) {
|
|
813
|
+
return this.session.respond(requestId, decision);
|
|
814
|
+
}
|
|
815
|
+
/** The events that arrive while no turn's stream is open; the first call
|
|
816
|
+
* takes the stream, later calls get `null`. Until it is taken, those
|
|
817
|
+
* events are dropped. */
|
|
818
|
+
sessionEvents() {
|
|
819
|
+
const s = this.session;
|
|
820
|
+
if (s.looseGiven)
|
|
821
|
+
return null;
|
|
822
|
+
s.looseGiven = true;
|
|
823
|
+
const events = new Events();
|
|
824
|
+
if (s.ended !== null)
|
|
825
|
+
sink(events).fail(s.ended);
|
|
826
|
+
else
|
|
827
|
+
s.loose = sink(events);
|
|
828
|
+
return events;
|
|
829
|
+
}
|
|
830
|
+
/** Ends the session (R8.6.2): every running call's signal fires; `quit`,
|
|
831
|
+
* up to 5 s for the exit, SIGTERM, up to 5 s more, SIGKILL, the process
|
|
832
|
+
* reaped; meanwhile up to 5 s for handler and callback tasks, then they
|
|
833
|
+
* are no longer waited for. Returns within about 15 s. A `close()` never
|
|
834
|
+
* awaited still kills the process at this process's exit. */
|
|
835
|
+
close() {
|
|
836
|
+
if (this.closing === null) {
|
|
837
|
+
const s = this.session;
|
|
838
|
+
s.cancelCalls();
|
|
839
|
+
this.closing = Promise.all([s.shutDown(), s.finishTasks()])
|
|
840
|
+
.then(() => s.finishTasks())
|
|
841
|
+
.catch(noop);
|
|
842
|
+
}
|
|
843
|
+
return this.closing;
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
if (typeof Symbol.asyncDispose === "symbol") {
|
|
847
|
+
Object.defineProperty(Client.prototype, Symbol.asyncDispose, {
|
|
848
|
+
value: function () {
|
|
849
|
+
return this.close();
|
|
850
|
+
},
|
|
851
|
+
writable: true,
|
|
852
|
+
configurable: true,
|
|
853
|
+
});
|
|
854
|
+
}
|
|
855
|
+
/** Starts a session, sends `prompt`, and yields `init` and then that turn's
|
|
856
|
+
* events up to its `result`; then the session is closed (R8.1.1). Leaving
|
|
857
|
+
* the loop early closes it too. */
|
|
858
|
+
export async function* query(prompt, options = {}) {
|
|
859
|
+
const client = await Client.start(options);
|
|
860
|
+
try {
|
|
861
|
+
const turn = await client.send(prompt);
|
|
862
|
+
yield { type: "init", ...client.info };
|
|
863
|
+
yield* turn;
|
|
864
|
+
}
|
|
865
|
+
finally {
|
|
866
|
+
await client.close();
|
|
867
|
+
}
|
|
868
|
+
}
|