jackline 0.0.0-stage → 0.1.0-alpha.2

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/dist/run.js ADDED
@@ -0,0 +1,1168 @@
1
+ /**
2
+ * Runs, handles, tools, capabilities, budgets and the effect protocol.
3
+ *
4
+ * Every interaction with the outside world goes through `Run`. Each one is
5
+ * proposed to the kernel, which checks it (capability, policy, budget) and
6
+ * records it. It runs only if allowed, and its outcome is recorded with
7
+ * labels. In replay, nothing is executed: recorded outcomes (and refusals)
8
+ * are returned.
9
+ *
10
+ * This is a port of `python/jackline/_run.py`. Where it deliberately differs,
11
+ * the comment says so; docs/typescript/api.md lists every difference.
12
+ */
13
+ import { AsyncLocalStorage } from "node:async_hooks";
14
+ import { execFileSync } from "node:child_process";
15
+ import { randomBytes, randomUUID } from "node:crypto";
16
+ import { inspect } from "node:util";
17
+ import { approvalRequestFromKernel, ask, } from "./approvals.js";
18
+ import { DeadlineExceeded, Divergence, EffectFailed, HandleMisuse, Refused, StepLimit, refusedError, } from "./errors.js";
19
+ import { openJournal } from "./journal.js";
20
+ import { manifestDigest, modelMessage } from "./native.js";
21
+ import { readers } from "./policy.js";
22
+ import { strictSchema, validate } from "./schema.js";
23
+ // The current task path, e.g. "root" or "root/0/1". Async work inherits it.
24
+ const taskPath = new AsyncLocalStorage();
25
+ function currentPath() {
26
+ return taskPath.getStore() ?? "root";
27
+ }
28
+ /** Unwinds the agent when a human's decision is needed and the approver chose to pause. */
29
+ class Paused extends Error {
30
+ request;
31
+ constructor(request) {
32
+ super(`paused for approval of \`${request.tool}\``);
33
+ this.request = request;
34
+ this.name = "Paused";
35
+ }
36
+ }
37
+ /** Unwinds the agent when an irreversible call's outcome is unknown after a crash. */
38
+ class InDoubtSignal extends Error {
39
+ info;
40
+ constructor(info) {
41
+ super(`in doubt: ${info.target} at ${info.identity}`);
42
+ this.info = info;
43
+ this.name = "InDoubt";
44
+ }
45
+ }
46
+ /** The name of an error's type, like Python's `type(exc).__name__`. */
47
+ function errorType(err) {
48
+ if (err instanceof Error) {
49
+ if (err.name && err.name !== "Error")
50
+ return err.name;
51
+ return err.constructor?.name || "Error";
52
+ }
53
+ return typeof err;
54
+ }
55
+ function errorMessage(err) {
56
+ return err instanceof Error ? err.message : String(err);
57
+ }
58
+ // ---------------------------------------------------------------- shared run state
59
+ /** Everything a run and its sub-runs share. */
60
+ class RunState {
61
+ kernel;
62
+ runId;
63
+ key;
64
+ mode;
65
+ approver;
66
+ /** A pause or in-doubt signal. Sticky: agent code that catches it can't continue. */
67
+ interrupt = null;
68
+ /** Sticky as well: a replay that diverged stays diverged. */
69
+ divergence = null;
70
+ counters = new Map();
71
+ tails = new Map();
72
+ constructor(kernel, runId, key, mode, approver) {
73
+ this.kernel = kernel;
74
+ this.runId = runId;
75
+ this.key = key;
76
+ this.mode = mode;
77
+ this.approver = approver;
78
+ }
79
+ next(kind, parent) {
80
+ const key = `${kind}:${parent}`;
81
+ const n = this.counters.get(key) ?? 0;
82
+ this.counters.set(key, n + 1);
83
+ return n;
84
+ }
85
+ /**
86
+ * Take a place in line on a task path. The kernel numbers calls on a path in
87
+ * the order they are proposed, so proposals are made in the order calls
88
+ * were *invoked*: a call's identity is fixed synchronously, when
89
+ * `run.call(...)` is called, whatever order earlier calls' asynchronous
90
+ * preparation (such as counting tokens) finishes in.
91
+ */
92
+ enter(path) {
93
+ const prev = this.tails.get(path) ?? null;
94
+ let release;
95
+ const mine = new Promise((resolve) => (release = resolve));
96
+ const tail = prev ? prev.then(() => mine) : mine;
97
+ this.tails.set(path, tail);
98
+ void tail.then(() => {
99
+ if (this.tails.get(path) === tail)
100
+ this.tails.delete(path);
101
+ });
102
+ return { wait: prev, release };
103
+ }
104
+ /** Throw a pending signal again, so agent code can't carry on past it. */
105
+ check() {
106
+ if (this.interrupt)
107
+ throw this.interrupt;
108
+ if (this.divergence)
109
+ throw this.divergence;
110
+ }
111
+ /** Call the kernel, remembering a divergence. */
112
+ guard(fn) {
113
+ try {
114
+ return fn();
115
+ }
116
+ catch (err) {
117
+ if (err instanceof Divergence)
118
+ this.divergence ??= err;
119
+ throw err;
120
+ }
121
+ }
122
+ }
123
+ // ---------------------------------------------------------------- values and handles
124
+ const HANDLE_TYPE = Symbol("jackline.HandleType");
125
+ class HandleImpl {
126
+ run;
127
+ valueId;
128
+ path;
129
+ constructor(run, valueId, path = []) {
130
+ this.run = run;
131
+ this.valueId = valueId;
132
+ this.path = path;
133
+ }
134
+ /** Labels are kept per top-level field. */
135
+ labelField() {
136
+ const first = this.path[0];
137
+ return typeof first === "string" ? first : null;
138
+ }
139
+ ref() {
140
+ return [this.valueId, this.labelField()];
141
+ }
142
+ navigate(value, start) {
143
+ let v = value;
144
+ for (const key of this.path.slice(start)) {
145
+ v = v === null || v === undefined ? undefined : v[key];
146
+ }
147
+ return v;
148
+ }
149
+ /** Read for the library itself (building a request). Labels are unchanged. */
150
+ resolve() {
151
+ const s = this.run._state;
152
+ const value = s.guard(() => s.kernel.value(s.key, this.valueId));
153
+ return this.navigate(value, 0);
154
+ }
155
+ label() {
156
+ const s = this.run._state;
157
+ return s.kernel.label(s.key, this.valueId, this.labelField());
158
+ }
159
+ repr() {
160
+ const path = this.path.map((k) => `[${JSON.stringify(k)}]`).join("");
161
+ return `<jackline.Handle value#${this.valueId}${path} (use run.reveal() to read)>`;
162
+ }
163
+ }
164
+ const HANDLES = new WeakMap();
165
+ function handleImpl(value) {
166
+ return value !== null && (typeof value === "object" || typeof value === "function") ? HANDLES.get(value) : undefined;
167
+ }
168
+ /** True if `value` is a Jackline handle. */
169
+ export function isHandle(value) {
170
+ return handleImpl(value) !== undefined;
171
+ }
172
+ function misuse() {
173
+ throw new HandleMisuse("this is a jackline Handle, not a plain value; read it with run.reveal(handle)");
174
+ }
175
+ const INDEX = /^(0|[1-9][0-9]*)$/;
176
+ function makeHandle(run, valueId, path = []) {
177
+ const impl = new HandleImpl(run, valueId, path);
178
+ const field = (key) => makeHandle(run, valueId, [...path, key]);
179
+ const proxy = new Proxy(Object.create(null), {
180
+ get(_target, prop) {
181
+ if (typeof prop === "symbol") {
182
+ if (prop === Symbol.toPrimitive || prop === Symbol.iterator || prop === Symbol.asyncIterator) {
183
+ return misuse;
184
+ }
185
+ if (prop === inspect.custom)
186
+ return () => impl.repr();
187
+ if (prop === Symbol.toStringTag)
188
+ return "jackline.Handle";
189
+ return undefined;
190
+ }
191
+ switch (prop) {
192
+ case "field":
193
+ return field;
194
+ case "label":
195
+ return impl.label();
196
+ // Not thenable: `await handle` and `return handle` keep the handle.
197
+ case "then":
198
+ return undefined;
199
+ case "toString":
200
+ case "valueOf":
201
+ case "toJSON":
202
+ return misuse;
203
+ default:
204
+ return field(INDEX.test(prop) ? Number(prop) : prop);
205
+ }
206
+ },
207
+ set() {
208
+ throw new HandleMisuse("handles are read-only");
209
+ },
210
+ has() {
211
+ return false;
212
+ },
213
+ ownKeys() {
214
+ return [];
215
+ },
216
+ });
217
+ HANDLES.set(proxy, impl);
218
+ return proxy;
219
+ }
220
+ /**
221
+ * Convert a value to plain recordable data. Handles are resolved, and a
222
+ * reference to each is collected into `inputs`, so the kernel knows what
223
+ * flows into an effect.
224
+ *
225
+ * Numbers: an integral value with magnitude at most 2^53 - 1 is recorded as
226
+ * an integer, any other number as a 64-bit float. NaN and infinities can't be
227
+ * recorded.
228
+ */
229
+ function toData(value, run, inputs) {
230
+ const h = handleImpl(value);
231
+ if (h) {
232
+ if (run === null || h.run._state.key !== run._state.key) {
233
+ throw new HandleMisuse("a handle can only be used inside the run that produced it");
234
+ }
235
+ inputs?.push(h.ref());
236
+ return h.resolve();
237
+ }
238
+ if (value === null || value === undefined)
239
+ return null;
240
+ switch (typeof value) {
241
+ case "boolean":
242
+ case "string":
243
+ return value;
244
+ case "number":
245
+ if (!Number.isFinite(value))
246
+ throw new TypeError("NaN and infinity can't be recorded");
247
+ return Object.is(value, -0) ? 0 : value;
248
+ case "object":
249
+ break;
250
+ default:
251
+ throw new TypeError(`can't record a value of type ${typeof value}; use plain data`);
252
+ }
253
+ if (Array.isArray(value))
254
+ return value.map((v) => toData(v, run, inputs));
255
+ const obj = value;
256
+ if (typeof obj.toJSON === "function")
257
+ return toData(obj.toJSON(), run, inputs);
258
+ const proto = Object.getPrototypeOf(obj);
259
+ if (proto !== Object.prototype && proto !== null) {
260
+ const name = obj.constructor?.name ?? "object";
261
+ throw new TypeError(`can't record a value of type ${name}; use plain data (objects, arrays, strings, numbers, booleans, null)`);
262
+ }
263
+ const out = {};
264
+ for (const [k, v] of Object.entries(obj)) {
265
+ if (v !== undefined)
266
+ out[k] = toData(v, run, inputs);
267
+ }
268
+ return out;
269
+ }
270
+ function budgetToKernel(b, nowMs) {
271
+ const wall = (b.minutes ?? 0) * 60 + (b.seconds ?? 0);
272
+ return {
273
+ usd_micros: b.usd == null ? null : Math.round(b.usd * 1_000_000),
274
+ input_tokens: b.inputTokens ?? null,
275
+ output_tokens: b.outputTokens ?? null,
276
+ steps: b.steps ?? null,
277
+ deadline_ms: b.minutes || b.seconds ? nowMs + Math.round(wall * 1000) : null,
278
+ max_call_input_tokens: b.contextTokens ?? null,
279
+ max_tool_result_tokens: b.maxToolResultTokens ?? null,
280
+ max_approvals: b.approvals ?? null,
281
+ approval_ttl_ms: b.approvalTtlSeconds == null ? null : Math.round(b.approvalTtlSeconds * 1000),
282
+ };
283
+ }
284
+ function spendFromKernel(c) {
285
+ const usd = c.usd_micros;
286
+ return {
287
+ usd: usd == null ? null : usd / 1_000_000,
288
+ inputTokens: c.input_tokens ?? null,
289
+ outputTokens: c.output_tokens ?? null,
290
+ steps: c.steps ?? null,
291
+ };
292
+ }
293
+ /* eslint-enable @typescript-eslint/no-explicit-any */
294
+ /** A function declared as a tool with `tool(...)`. */
295
+ export class Tool {
296
+ name;
297
+ description;
298
+ effect;
299
+ costUsd;
300
+ output;
301
+ reconcile;
302
+ parameters;
303
+ /** For tools with a manifest (MCP): returns the current manifest, for pinning. */
304
+ manifest;
305
+ fn;
306
+ constructor(options, fn) {
307
+ const effect = options.effect ?? "irreversible";
308
+ if (!["read_only", "idempotent", "irreversible"].includes(effect)) {
309
+ throw new TypeError("effect must be read_only, idempotent or irreversible");
310
+ }
311
+ if (!options.name)
312
+ throw new TypeError("a tool needs a name");
313
+ this.name = options.name;
314
+ this.description = options.description ?? "";
315
+ this.effect = effect;
316
+ this.costUsd = options.cost ?? 0;
317
+ this.output = options.output ?? null;
318
+ this.reconcile = options.reconcile ?? null;
319
+ this.parameters = options.parameters ?? null;
320
+ this.manifest = options.manifest ?? null;
321
+ this.fn = fn;
322
+ }
323
+ /** @internal */
324
+ manifestDigest() {
325
+ return this.manifest === null ? null : manifestDigest(this.manifest());
326
+ }
327
+ /** JSON Schema for the tool's arguments, shown to models in `run.agent()`. */
328
+ inputSchema() {
329
+ if (this.manifest !== null)
330
+ return this.manifest().input_schema ?? { type: "object" };
331
+ return this.parameters ?? { type: "object" };
332
+ }
333
+ }
334
+ /**
335
+ * Declare a function as a tool. It is called with one arguments object and an
336
+ * `EffectContext`.
337
+ *
338
+ * ```ts
339
+ * const getOrder = jl.tool(
340
+ * { name: "get_order", effect: "read_only", output: jl.trusted() },
341
+ * async ({ orderId }: { orderId: string }) => orders[orderId],
342
+ * );
343
+ * ```
344
+ */
345
+ export function tool(options, fn) {
346
+ return new Tool(options, fn);
347
+ }
348
+ /**
349
+ * Permission to call one tool, possibly narrowed (spec G3). Get one with
350
+ * `run.grant(tool)`; narrow it with `.narrow(...)`. Narrowing can only remove
351
+ * permissions: every ancestor's limits still apply.
352
+ */
353
+ export class Capability {
354
+ run;
355
+ id;
356
+ tool;
357
+ hostApproval;
358
+ /** @internal */
359
+ constructor(run, id, tool, hostApproval = false) {
360
+ this.run = run;
361
+ this.id = id;
362
+ this.tool = tool;
363
+ this.hostApproval = hostApproval;
364
+ }
365
+ /** The same capability, but every call asks a human first (spec G5). */
366
+ requiringApproval() {
367
+ return new Capability(this.run, this.id, this.tool, true);
368
+ }
369
+ /** A narrower capability. */
370
+ narrow(options = {}) {
371
+ const constraints = {};
372
+ for (const [k, v] of Object.entries(options.args ?? {}))
373
+ constraints[k] = Array.isArray(v) ? v : [v];
374
+ const s = this.run._state;
375
+ const id = s.kernel.narrow(s.key, this.run._account, this.id, {
376
+ maxCalls: options.maxCalls,
377
+ expiresMs: options.expiresInSeconds == null ? undefined : Date.now() + Math.round(options.expiresInSeconds * 1000),
378
+ constraints,
379
+ });
380
+ return new Capability(this.run, id, this.tool);
381
+ }
382
+ [inspect.custom]() {
383
+ return `<jackline.Capability #${this.id} for ${this.tool.name}>`;
384
+ }
385
+ }
386
+ export function user(content) {
387
+ return { role: "user", content };
388
+ }
389
+ export function assistant(content) {
390
+ return { role: "assistant", content };
391
+ }
392
+ export function system(content) {
393
+ return { role: "system", content };
394
+ }
395
+ /** Usage as model APIs report it (`input_tokens`, ...) to `Usage`. */
396
+ export function usageFromApi(u, servedModel) {
397
+ if (u === null || u === undefined || typeof u !== "object")
398
+ return null;
399
+ const r = u;
400
+ return {
401
+ inputTokens: r.input_tokens ?? 0,
402
+ outputTokens: r.output_tokens ?? 0,
403
+ cacheWriteTokens: r.cache_write_tokens ?? r.cache_creation_input_tokens ?? 0,
404
+ cacheReadTokens: r.cache_read_tokens ?? r.cache_read_input_tokens ?? 0,
405
+ ...(servedModel !== undefined ? { servedModel } : {}),
406
+ };
407
+ }
408
+ /**
409
+ * A safe upper bound on a request's input tokens: one token per byte of its
410
+ * JSON, plus overhead for message framing. Real tokens are several bytes
411
+ * each, so this overestimates; adapters with exact counting can do better.
412
+ */
413
+ export function estimateInputTokens(request) {
414
+ const messages = request.messages ?? [];
415
+ const text = JSON.stringify(messages) +
416
+ (typeof request.system === "string" ? request.system : JSON.stringify(request.system ?? ""));
417
+ return Buffer.byteLength(text, "utf8") + 16 * messages.length + 256;
418
+ }
419
+ /**
420
+ * Base class for model adapters.
421
+ *
422
+ * `request` turns messages and options into the plain data that gets
423
+ * recorded and hashed. `costRequest` says what the call may cost at most,
424
+ * `execute` sends it, and `usage` reads what it actually cost.
425
+ */
426
+ export class Model {
427
+ target = "model";
428
+ mocked = false;
429
+ /** Price-table key, e.g. `claude-opus-5-5`. `null` means no money cost. */
430
+ priceKey = null;
431
+ defaultMaxTokens = 4096;
432
+ request(messages, options) {
433
+ return { messages, ...options };
434
+ }
435
+ costRequest(request) {
436
+ return {
437
+ model: this.priceKey,
438
+ inputTokens: estimateInputTokens(request),
439
+ outputTokens: Math.trunc(Number(request.max_tokens ?? this.defaultMaxTokens)),
440
+ fallback: Boolean(request.fallbacks),
441
+ };
442
+ }
443
+ usage(result) {
444
+ return usageFromApi(result.usage);
445
+ }
446
+ }
447
+ function costToKernel(c) {
448
+ return {
449
+ model: c.model ?? null,
450
+ input_tokens: c.inputTokens,
451
+ output_tokens: c.outputTokens,
452
+ fallback: c.fallback ?? false,
453
+ };
454
+ }
455
+ function usageToKernel(u) {
456
+ if (u === null)
457
+ return null;
458
+ return {
459
+ input_tokens: u.inputTokens ?? 0,
460
+ output_tokens: u.outputTokens ?? 0,
461
+ cache_write_tokens: u.cacheWriteTokens ?? 0,
462
+ cache_read_tokens: u.cacheReadTokens ?? 0,
463
+ served_model: u.servedModel ?? null,
464
+ };
465
+ }
466
+ function toolResult(toolUseId, content, isError) {
467
+ const block = { type: "tool_result", tool_use_id: toolUseId, content };
468
+ if (isError)
469
+ block.is_error = true;
470
+ return block;
471
+ }
472
+ const DEADLINE = Symbol("deadline");
473
+ function deadlineRefusal(message) {
474
+ return { code: "deadline", message, model_message: modelMessage("deadline") };
475
+ }
476
+ // ---------------------------------------------------------------- runs
477
+ /** One execution of an agent function. The only door to the outside world. */
478
+ export class Run {
479
+ /** @internal */
480
+ _state;
481
+ /** @internal */
482
+ _account;
483
+ rootPath;
484
+ implicit = new Map();
485
+ /** @internal */
486
+ constructor(state, account = 0, rootPath = null) {
487
+ this._state = state;
488
+ this._account = account;
489
+ this.rootPath = rootPath;
490
+ }
491
+ get runId() {
492
+ return this._state.runId;
493
+ }
494
+ /** `live`, `replay` or `resume`. */
495
+ get mode() {
496
+ return this._state.mode;
497
+ }
498
+ // -- task paths
499
+ /** The current task path. A sub-run's effects stay under its own root. */
500
+ path() {
501
+ const cur = currentPath();
502
+ const root = this.rootPath;
503
+ if (root !== null && cur !== root && !cur.startsWith(root + "/"))
504
+ return root;
505
+ return cur;
506
+ }
507
+ // -- the effect protocol
508
+ finish(proposal, result, usage) {
509
+ const s = this._state;
510
+ try {
511
+ const data = toData(result, this);
512
+ const u = usage ? usage(result) : null;
513
+ return s.kernel.completeOk(s.key, proposal.effect_id, data, u);
514
+ }
515
+ catch (err) {
516
+ this.fail(proposal, err);
517
+ throw new EffectFailed(errorType(err), errorMessage(err), proposal.identity, { cause: err });
518
+ }
519
+ }
520
+ fail(proposal, err) {
521
+ const s = this._state;
522
+ s.kernel.completeError(s.key, proposal.effect_id, errorType(err), errorMessage(err), null);
523
+ }
524
+ /** Throw for refusals and replayed failures. True if the result was replayed. */
525
+ static checkProposal(proposal) {
526
+ const status = proposal.status;
527
+ if (status === "refused")
528
+ throw refusedError(proposal.refusal, proposal.identity);
529
+ if (status === "replayed_error") {
530
+ const message = proposal.message;
531
+ if (proposal.error_type === "DeadlineExceeded") {
532
+ throw new DeadlineExceeded(deadlineRefusal(message), proposal.identity);
533
+ }
534
+ throw new EffectFailed(proposal.error_type, message, proposal.identity);
535
+ }
536
+ return status === "replayed";
537
+ }
538
+ /**
539
+ * Propose an effect. Everything up to taking a place in line runs
540
+ * synchronously, so the call's identity is fixed when it is invoked.
541
+ */
542
+ async propose(kind, target, args, effectClass, o) {
543
+ const s = this._state;
544
+ const path = this.path();
545
+ const ticket = s.enter(path);
546
+ try {
547
+ s.check();
548
+ const inputs = [...(o.inputs ?? [])];
549
+ const data = toData(args, this, inputs);
550
+ let cost = null;
551
+ if (o.cost && s.mode !== "replay") {
552
+ const c = o.cost();
553
+ cost = c instanceof Promise ? await c : c;
554
+ }
555
+ if (ticket.wait)
556
+ await ticket.wait;
557
+ s.check();
558
+ const proposal = s.guard(() => s.kernel.propose(s.key, path, kind, target, data, {
559
+ effectClass,
560
+ mocked: o.mocked ?? false,
561
+ account: this._account,
562
+ cost,
563
+ inputs,
564
+ nowMs: Date.now(),
565
+ capability: o.capability,
566
+ argSources: o.argSources,
567
+ outputLabel: o.outputLabel ? o.outputLabel.toKernel() : null,
568
+ manifestDigest: o.manifestDigest ?? undefined,
569
+ hostApproval: o.hostApproval ?? false,
570
+ proposedBy: o.proposedBy ?? null,
571
+ }));
572
+ return { proposal, data };
573
+ }
574
+ finally {
575
+ ticket.release();
576
+ }
577
+ }
578
+ async effect(kind, target, args, execute, effectClass, o = {}) {
579
+ const s = this._state;
580
+ const proposed = await this.propose(kind, target, args, effectClass, o);
581
+ const proposal = await this.settle(proposed.proposal, o.reconcile ?? null);
582
+ if (Run.checkProposal(proposal))
583
+ return makeHandle(this, proposal.value_id);
584
+ const controller = new AbortController();
585
+ const ctx = Object.freeze({
586
+ identity: proposal.identity,
587
+ idempotencyKey: proposal.idempotency_key,
588
+ effectId: proposal.effect_id,
589
+ signal: controller.signal,
590
+ });
591
+ const deadline = proposal.deadline_ms;
592
+ let timer;
593
+ let result;
594
+ try {
595
+ const work = Promise.resolve().then(() => execute(ctx));
596
+ if (deadline == null) {
597
+ result = await work;
598
+ }
599
+ else {
600
+ const timeout = new Promise((resolve) => {
601
+ timer = setTimeout(() => resolve(DEADLINE), Math.max(0, deadline - Date.now()));
602
+ });
603
+ const outcome = await Promise.race([work.then((value) => ({ value })), timeout]);
604
+ if (outcome === DEADLINE) {
605
+ // The run's deadline, not the tool's own error: a tool that throws a
606
+ // TimeoutError fails with EffectFailed("TimeoutError") instead.
607
+ // (Python's `except TimeoutError` conflates the two.)
608
+ void work.catch(() => undefined);
609
+ const message = `\`${target}\` was still running at the run's deadline`;
610
+ const err = new DeadlineExceeded(deadlineRefusal(message), proposal.identity);
611
+ controller.abort(err);
612
+ s.kernel.completeError(s.key, proposal.effect_id, "DeadlineExceeded", message, null);
613
+ throw err;
614
+ }
615
+ result = outcome.value;
616
+ }
617
+ }
618
+ catch (err) {
619
+ if (err instanceof DeadlineExceeded && controller.signal.aborted)
620
+ throw err;
621
+ this.fail(proposal, err);
622
+ throw new EffectFailed(errorType(err), errorMessage(err), proposal.identity, { cause: err });
623
+ }
624
+ finally {
625
+ if (timer)
626
+ clearTimeout(timer);
627
+ }
628
+ return makeHandle(this, this.finish(proposal, result, o.usage));
629
+ }
630
+ /** Resolve approvals and in-doubt calls until the kernel's answer is final. */
631
+ async settle(proposal, reconcile) {
632
+ const s = this._state;
633
+ for (;;) {
634
+ if (proposal.status === "needs_approval") {
635
+ const req = approvalRequestFromKernel(proposal.request);
636
+ if (s.mode === "replay" || s.approver === null)
637
+ throw (s.interrupt = new Paused(req));
638
+ const decision = await ask(s.approver, req);
639
+ if (decision.kind === "pause")
640
+ throw (s.interrupt = new Paused(req));
641
+ s.check();
642
+ proposal = s.guard(() => s.kernel.decide(s.key, req.id, decision.kind === "approve", {
643
+ by: decision.by,
644
+ reason: decision.reason,
645
+ nowMs: Date.now(),
646
+ }));
647
+ }
648
+ else if (proposal.status === "in_doubt") {
649
+ const info = {
650
+ identity: proposal.identity,
651
+ target: proposal.target,
652
+ args: proposal.args ?? {},
653
+ idempotencyKey: proposal.idempotency_key,
654
+ };
655
+ const receipt = reconcile ? await reconcile({ ...info.args }, info.idempotencyKey) : null;
656
+ if (!receipt || receipt.kind === "unknown")
657
+ throw (s.interrupt = new InDoubtSignal(info));
658
+ const isCommitted = receipt.kind === "committed";
659
+ const value = isCommitted ? toData(receipt.value, this) : null;
660
+ proposal = s.guard(() => s.kernel.resolveInDoubt(s.key, info.identity, isCommitted, {
661
+ value,
662
+ by: "reconcile",
663
+ }));
664
+ }
665
+ else {
666
+ return proposal;
667
+ }
668
+ }
669
+ }
670
+ async hostEffect(target, produce) {
671
+ const s = this._state;
672
+ const { proposal } = await this.propose("host", target, {}, "read_only", {});
673
+ if (Run.checkProposal(proposal))
674
+ return s.kernel.value(s.key, proposal.value_id, null);
675
+ const value = produce();
676
+ this.finish(proposal, value);
677
+ return value;
678
+ }
679
+ // -- public API: models and tools
680
+ /**
681
+ * Call a model. Returns a handle to `{ text, stop_reason, model, usage, content, tool_calls, raw }`.
682
+ *
683
+ * With `output` (a JSON Schema), the model must return that shape
684
+ * (structured output), and the handle points at the parsed, validated
685
+ * value. The result carries the labels of everything the model read (spec G4).
686
+ */
687
+ async llm(model, messages, options = {}) {
688
+ const { output, validate: check, ...rest } = options;
689
+ const inputs = [];
690
+ const dataOptions = toData(rest, this, inputs);
691
+ if (output !== undefined)
692
+ dataOptions.output_schema = strictSchema(output);
693
+ const request = model.request(toData(messages, this, inputs), dataOptions);
694
+ const execute = async () => {
695
+ const result = await model.execute(request);
696
+ if (output === undefined)
697
+ return result;
698
+ let parsed = result.parsed ?? JSON.parse(result.text || "null");
699
+ validate(parsed, output);
700
+ if (check)
701
+ parsed = check(parsed);
702
+ return { ...result, parsed };
703
+ };
704
+ const handle = await this.effect("llm", model.target, request, execute, "read_only", {
705
+ mocked: model.mocked,
706
+ cost: () => {
707
+ const c = model.costRequest(request);
708
+ return c instanceof Promise ? c.then(costToKernel) : costToKernel(c);
709
+ },
710
+ usage: (r) => usageToKernel(model.usage(r)),
711
+ inputs,
712
+ });
713
+ return (output !== undefined ? handle.field("parsed") : handle);
714
+ }
715
+ /**
716
+ * Permission to call a tool (spec G3). Only tools allowed by
717
+ * `start(..., { grants })` can be granted, and only by the top-level run;
718
+ * sub-runs use the capabilities passed to them.
719
+ */
720
+ grant(t) {
721
+ const s = this._state;
722
+ const id = s.kernel.grant(s.key, this._account, t.name, t.manifestDigest());
723
+ return new Capability(this, id, t);
724
+ }
725
+ /**
726
+ * Call a tool through a capability. Passing a tool grants it first. Each
727
+ * argument that is an unmodified handle keeps its own label; anything else
728
+ * carries the run's context label.
729
+ */
730
+ call(t, args = {}) {
731
+ return this.callTool(t, args, null);
732
+ }
733
+ /**
734
+ * A tool-using loop: the model calls tools until it answers.
735
+ *
736
+ * Every call the model proposes goes through the kernel like any other,
737
+ * but it carries the label of everything the model has read (spec G4): a
738
+ * model that read an attacker's email can't trigger a tool your policy
739
+ * reserves for trusted decisions. When a call is refused, the model is told
740
+ * so in fixed words that never repeat the arguments. Returns a handle to
741
+ * the final reply. Throws `StepLimit` after `maxSteps` model calls.
742
+ */
743
+ async agent(model, prompt, options = {}) {
744
+ const { tools = [], maxSteps = 10, system: systemPrompt, ...rest } = options;
745
+ const caps = tools.map((t) => (t instanceof Capability ? t : this.capability(t)));
746
+ const byName = new Map();
747
+ const defs = [];
748
+ for (const cap of caps) {
749
+ const name = cap.tool.name.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64);
750
+ byName.set(name, cap);
751
+ defs.push({
752
+ name,
753
+ description: cap.tool.description || cap.tool.name,
754
+ input_schema: cap.tool.inputSchema(),
755
+ });
756
+ }
757
+ const messages = Array.isArray(prompt) ? [...prompt] : [user(prompt)];
758
+ if (systemPrompt !== undefined)
759
+ messages.unshift(system(systemPrompt));
760
+ for (let step = 0; step < maxSteps; step++) {
761
+ const reply = defs.length
762
+ ? await this.llm(model, messages, { ...rest, tools: defs })
763
+ : await this.llm(model, messages, rest);
764
+ const calls = handleImpl(reply).resolve().tool_calls ?? [];
765
+ if (calls.length === 0)
766
+ return reply;
767
+ messages.push(assistant(reply.content));
768
+ const results = [];
769
+ for (const call of calls) {
770
+ const cap = byName.get(call.name);
771
+ if (!cap) {
772
+ results.push(toolResult(call.id, "Refused: that tool isn't available.", true));
773
+ continue;
774
+ }
775
+ try {
776
+ const out = await this.callTool(cap, { ...(call.input ?? {}) }, reply);
777
+ results.push(toolResult(call.id, out, false));
778
+ }
779
+ catch (err) {
780
+ if (err instanceof Refused)
781
+ results.push(toolResult(call.id, err.modelMessage, true));
782
+ // Only the error type: the message may contain outside content.
783
+ else if (err instanceof EffectFailed) {
784
+ results.push(toolResult(call.id, `The tool failed (${err.errorType}).`, true));
785
+ }
786
+ else
787
+ throw err;
788
+ }
789
+ }
790
+ messages.push(user(results));
791
+ }
792
+ throw new StepLimit(`run.agent() made ${maxSteps} model calls and the model was still calling tools`);
793
+ }
794
+ capability(t) {
795
+ let cap = this.implicit.get(t.name);
796
+ if (!cap) {
797
+ cap = this.grant(t);
798
+ this.implicit.set(t.name, cap);
799
+ }
800
+ return cap;
801
+ }
802
+ /** @internal */
803
+ _setImplicit(cap) {
804
+ this.implicit.set(cap.tool.name, cap);
805
+ }
806
+ async callTool(t, kwargs, proposedBy) {
807
+ let cap;
808
+ if (t instanceof Capability)
809
+ cap = t;
810
+ else if (t instanceof Tool)
811
+ cap = this.capability(t);
812
+ else
813
+ throw new TypeError("run.call() takes a tool declared with jl.tool(), or a capability");
814
+ const tl = cap.tool;
815
+ const args = {};
816
+ const sources = {};
817
+ for (const [name, value] of Object.entries(kwargs)) {
818
+ if (value === undefined)
819
+ continue;
820
+ const nested = [];
821
+ args[name] = toData(value, this, nested);
822
+ const h = handleImpl(value);
823
+ if (h)
824
+ sources[name] = { bare: h.ref(), nested: [] };
825
+ else if (nested.length)
826
+ sources[name] = { bare: null, nested };
827
+ }
828
+ const usdMicros = Math.round(tl.costUsd * 1_000_000);
829
+ return this.effect("tool", tl.name, args, (ctx) => tl.fn({ ...args }, ctx), tl.effect, {
830
+ cost: () => ({ usd_micros: usdMicros }),
831
+ capability: cap.id,
832
+ argSources: sources,
833
+ outputLabel: tl.output,
834
+ manifestDigest: tl.manifestDigest(),
835
+ hostApproval: cap.hostApproval,
836
+ reconcile: tl.reconcile,
837
+ proposedBy: proposedBy === null ? null : handleImpl(proposedBy).ref(),
838
+ });
839
+ }
840
+ // -- public API: labels
841
+ /**
842
+ * Read a handle's value as plain data.
843
+ *
844
+ * Revealing untrusted data makes every later call of this run carry that
845
+ * label, because your code may now be steered by it (spec G4). Prefer
846
+ * passing handles along unrevealed where you can.
847
+ */
848
+ reveal(handle) {
849
+ const h = handleImpl(handle);
850
+ if (!h)
851
+ throw new TypeError("run.reveal() takes a Handle");
852
+ if (h.run._state.key !== this._state.key)
853
+ throw new HandleMisuse("this handle belongs to a different run");
854
+ const s = this._state;
855
+ const field = h.labelField();
856
+ const value = s.kernel.reveal(s.key, this._account, h.valueId, field);
857
+ return h.navigate(value, field !== null ? 1 : 0);
858
+ }
859
+ /**
860
+ * Mark a value as trusted, after checking it (spec G4).
861
+ *
862
+ * With `check`, the tool is called with `args` (which may include the
863
+ * handle) and must return `true` with a trusted label; declare it
864
+ * `output: trusted({ independentOfArgs: true })`. Without `check`, your
865
+ * code vouches for the value. Either way, it's journaled.
866
+ */
867
+ async endorse(handle, options) {
868
+ const h = handleImpl(handle);
869
+ if (!h)
870
+ throw new TypeError("run.endorse() takes a Handle");
871
+ let evidence = null;
872
+ if (options.check) {
873
+ const verdict = handleImpl(await this.call(options.check, options.args ?? {}));
874
+ if (verdict.path.length)
875
+ throw new TypeError("the check must return its verdict as a plain true or false");
876
+ evidence = verdict.valueId;
877
+ }
878
+ const field = h.labelField();
879
+ const rest = field !== null ? h.path.slice(1) : [...h.path];
880
+ const s = this._state;
881
+ const vid = s.kernel.endorse(s.key, this._account, h.valueId, field, rest, evidence, options.reason);
882
+ return makeHandle(this, vid);
883
+ }
884
+ /** Lower a value's sensitivity: set who may read it and drop its tags. Journaled. */
885
+ declassify(handle, options) {
886
+ const h = handleImpl(handle);
887
+ if (!h)
888
+ throw new TypeError("run.declassify() takes a Handle");
889
+ const field = h.labelField();
890
+ const rest = field !== null ? h.path.slice(1) : [...h.path];
891
+ const s = this._state;
892
+ const vid = s.kernel.declassify(s.key, this._account, h.valueId, field, rest, options.to ?? readers.public, options.reason);
893
+ return makeHandle(this, vid);
894
+ }
895
+ /** Everything this run's code has revealed, combined. Every tool call carries it. */
896
+ get contextLabel() {
897
+ const s = this._state;
898
+ return s.kernel.accountStatus(s.key, this._account).context;
899
+ }
900
+ // -- public API: time and randomness
901
+ /** The current time in milliseconds since the epoch. Recorded, so replays see the same clock. */
902
+ now() {
903
+ return this.hostEffect("now", () => Date.now());
904
+ }
905
+ /** A random number in [0, 1). Recorded, so replays see the same number. */
906
+ random() {
907
+ return this.hostEffect("random", () => Math.random());
908
+ }
909
+ /** A random UUID string. Recorded, so replays see the same value. */
910
+ uuid() {
911
+ return this.hostEffect("uuid", () => randomUUID());
912
+ }
913
+ /**
914
+ * Wait for several effects running concurrently, with stable call identities.
915
+ *
916
+ * - A promise from `run.call(...)`, `run.llm(...)` or `run.spawn(...)` already
917
+ * has its identity: it was fixed when the call was made.
918
+ * - A function `() => Promise` runs as its own branch with its own task path
919
+ * (`parent/n/i`), so every call inside it, however many and whatever order
920
+ * branches finish in, keeps the same identity in a replay. Use this form
921
+ * for branches that make more than one call.
922
+ */
923
+ async gather(items) {
924
+ const parent = this.path();
925
+ const n = this._state.next("gather", parent);
926
+ const promises = items.map((item, i) => typeof item === "function"
927
+ ? taskPath.run(`${parent}/${n}/${i}`, () => Promise.resolve().then(item))
928
+ : item);
929
+ return (await Promise.all(promises));
930
+ }
931
+ // -- public API: budgets and sub-runs
932
+ /**
933
+ * What's left: `usd`, `inputTokens`, `outputTokens`, `steps` (`null` =
934
+ * unlimited) and `seconds` until the deadline.
935
+ */
936
+ get remaining() {
937
+ const s = this._state;
938
+ const status = s.kernel.accountStatus(s.key, this._account);
939
+ const deadline = status.deadline_ms;
940
+ return {
941
+ ...spendFromKernel(status.remaining),
942
+ seconds: deadline == null ? null : Math.max(0, (deadline - Date.now()) / 1000),
943
+ };
944
+ }
945
+ /** What this run (or sub-run) has spent so far. */
946
+ get spent() {
947
+ const s = this._state;
948
+ return spendFromKernel(s.kernel.accountStatus(s.key, this._account).spent);
949
+ }
950
+ async spawn(budget, optionsOrFn, maybeFn) {
951
+ const fn = typeof optionsOrFn === "function" ? optionsOrFn : maybeFn;
952
+ const grants = typeof optionsOrFn === "function" ? [] : (optionsOrFn.grants ?? []);
953
+ if (!fn)
954
+ throw new TypeError("run.spawn() needs a function to run as the sub-run");
955
+ const s = this._state;
956
+ const parent = this.path();
957
+ const n = s.next("spawn", parent);
958
+ const ticket = s.enter(parent);
959
+ let account;
960
+ try {
961
+ if (ticket.wait)
962
+ await ticket.wait;
963
+ s.check();
964
+ account = s.guard(() => s.kernel.spawn(s.key, parent, this._account, budgetToKernel(budget, Date.now()), grants.map((c) => c.id)));
965
+ }
966
+ finally {
967
+ ticket.release();
968
+ }
969
+ const child = new SubRun(this, account, `${parent}/s${n}`);
970
+ for (const c of grants)
971
+ child._setImplicit(new Capability(child, c.id, c.tool));
972
+ try {
973
+ return await fn(child);
974
+ }
975
+ finally {
976
+ child.end();
977
+ }
978
+ }
979
+ }
980
+ /** A run inside a run, with its own budget slice and capabilities. */
981
+ export class SubRun extends Run {
982
+ ended = false;
983
+ /** @internal */
984
+ constructor(parent, account, rootPath) {
985
+ super(parent._state, account, rootPath);
986
+ }
987
+ /** End the sub-run early. Unused budget returns to the parent. Returns what it spent. */
988
+ end() {
989
+ if (this.ended)
990
+ return this.spent;
991
+ this.ended = true;
992
+ const s = this._state;
993
+ return spendFromKernel(s.kernel.endSubRun(s.key, this._account));
994
+ }
995
+ }
996
+ function resolveCodeVersion(codeVersion) {
997
+ if (codeVersion !== "git")
998
+ return codeVersion;
999
+ try {
1000
+ const sha = execFileSync("git", ["rev-parse", "HEAD"], {
1001
+ encoding: "utf8",
1002
+ stdio: ["ignore", "pipe", "ignore"],
1003
+ });
1004
+ return `git:${sha.trim()}`;
1005
+ }
1006
+ catch {
1007
+ return undefined;
1008
+ }
1009
+ }
1010
+ function result(status, runId, spent, extra = {}) {
1011
+ return {
1012
+ value: null,
1013
+ status,
1014
+ runId,
1015
+ error: null,
1016
+ spent: spendFromKernel(spent),
1017
+ pending: [],
1018
+ inDoubt: [],
1019
+ mismatches: [],
1020
+ ...extra,
1021
+ };
1022
+ }
1023
+ async function drive(run, agent, args) {
1024
+ const s = run._state;
1025
+ const { kernel, key, runId } = s;
1026
+ let value;
1027
+ let error;
1028
+ let failed = false;
1029
+ try {
1030
+ value = await taskPath.run("root", () => agent(run, ...args));
1031
+ }
1032
+ catch (err) {
1033
+ error = err;
1034
+ failed = true;
1035
+ }
1036
+ const close = () => kernel.close(key);
1037
+ // A divergence, pause or in-doubt call decides the outcome even if agent
1038
+ // code caught it. (Python's are BaseExceptions agent code rarely catches;
1039
+ // JS has no equivalent, so they are sticky instead.)
1040
+ const divergence = s.divergence ?? (failed && error instanceof Divergence ? error : null);
1041
+ if (divergence) {
1042
+ close();
1043
+ throw divergence;
1044
+ }
1045
+ try {
1046
+ if (s.interrupt instanceof Paused) {
1047
+ const spent = kernel.endRun(key, "paused", null, null);
1048
+ return result("paused", runId, spent, { pending: [s.interrupt.request] });
1049
+ }
1050
+ if (s.interrupt instanceof InDoubtSignal) {
1051
+ const { info } = s.interrupt;
1052
+ const spent = kernel.endRun(key, "in_doubt", null, `in doubt: ${info.target} at ${info.identity}`);
1053
+ return result("in_doubt", runId, spent, { inDoubt: [info] });
1054
+ }
1055
+ if (failed) {
1056
+ const spent = kernel.endRun(key, "failed", null, `${errorType(error)}: ${errorMessage(error)}`);
1057
+ return result("failed", runId, spent, { error });
1058
+ }
1059
+ let output;
1060
+ try {
1061
+ output = toData(value, run);
1062
+ }
1063
+ catch (err) {
1064
+ const spent = kernel.endRun(key, "failed", null, `unrecordable return value: ${errorMessage(err)}`);
1065
+ return result("failed", runId, spent, { error: err });
1066
+ }
1067
+ const spent = kernel.endRun(key, "completed", output, null);
1068
+ const mismatches = s.mode === "resume" ? kernel.mismatches(key) : [];
1069
+ return result("completed", runId, spent, { value: value, mismatches });
1070
+ }
1071
+ finally {
1072
+ close();
1073
+ }
1074
+ }
1075
+ export async function start(agent, argsOrOptions, maybeOptions) {
1076
+ const args = Array.isArray(argsOrOptions) ? argsOrOptions : [];
1077
+ const options = (Array.isArray(argsOrOptions) ? maybeOptions : argsOrOptions) ?? {};
1078
+ const { kernel } = openJournal(options.journal);
1079
+ const runId = options.runId ?? `run-${randomBytes(6).toString("hex")}`;
1080
+ const now = Date.now();
1081
+ const prices = options.prices
1082
+ ? Object.fromEntries(Object.entries(options.prices).map(([model, p]) => [
1083
+ model,
1084
+ {
1085
+ input: p.input,
1086
+ output: p.output,
1087
+ cache_write: p.cacheWrite ?? null,
1088
+ cache_read: p.cacheRead ?? null,
1089
+ },
1090
+ ]))
1091
+ : undefined;
1092
+ kernel.startRun(runId, { args: toData(args, null) }, {
1093
+ codeVersion: resolveCodeVersion(options.codeVersion),
1094
+ nowMs: now,
1095
+ budget: budgetToKernel(options.budget ?? {}, now),
1096
+ prices,
1097
+ policy: options.policy ? options.policy.toJSON() : null,
1098
+ allowedTools: options.grants?.map((g) => (g instanceof Tool ? g.name : String(g))),
1099
+ approvalsEnabled: options.approver !== undefined,
1100
+ });
1101
+ const state = new RunState(kernel, runId, runId, "live", options.approver ?? null);
1102
+ return drive(new Run(state), agent, args);
1103
+ }
1104
+ /**
1105
+ * Re-run a recorded run offline: zero model or tool calls.
1106
+ *
1107
+ * Budget and policy decisions are replayed from the recording, including
1108
+ * refusals. Throws `Divergence` at the first call that doesn't match the
1109
+ * recording, or at the end if recorded calls were never made or the result differs.
1110
+ */
1111
+ export async function replay(agent, // eslint-disable-line @typescript-eslint/no-explicit-any
1112
+ runId, options = {}) {
1113
+ const { kernel } = openJournal(options.journal);
1114
+ const key = `replay:${runId}:${randomBytes(4).toString("hex")}`;
1115
+ const recorded = kernel.openReplay(runId, key);
1116
+ const state = new RunState(kernel, runId, key, "replay", null);
1117
+ return drive(new Run(state), agent, [...recorded.args]);
1118
+ }
1119
+ /**
1120
+ * Continue a run that crashed, paused for approval, or stopped in doubt (spec G8).
1121
+ *
1122
+ * The agent runs again from the start: completed calls return their recorded
1123
+ * results instantly and budgets continue where they were. Then:
1124
+ *
1125
+ * - read-only and idempotent calls cut off by the crash run again (same idempotency key);
1126
+ * - an irreversible call cut off by the crash is never re-run automatically.
1127
+ * Its tool's `reconcile` is asked whether it went through; without an
1128
+ * answer, the run stops with status `"in_doubt"` (settle it with `resolve`);
1129
+ * - `approvals` maps approval IDs (from `result.pending`) to decisions. Each
1130
+ * applies only if the call is exactly what the human saw.
1131
+ *
1132
+ * If `codeVersion` differs from the recorded one, resuming is refused unless
1133
+ * `allowCodeChange` is set; calls that no longer match are then run live and
1134
+ * listed in `result.mismatches` (spec G9).
1135
+ */
1136
+ export async function resume(agent, // eslint-disable-line @typescript-eslint/no-explicit-any
1137
+ runId, options = {}) {
1138
+ const { kernel } = openJournal(options.journal);
1139
+ const recorded = kernel.openResume(runId, {
1140
+ codeVersion: resolveCodeVersion(options.codeVersion),
1141
+ allowCodeChange: options.allowCodeChange ?? false,
1142
+ nowMs: Date.now(),
1143
+ });
1144
+ for (const [approvalId, decision] of Object.entries(options.approvals ?? {})) {
1145
+ if (decision.kind !== "pause") {
1146
+ kernel.supplyDecision(runId, approvalId, decision.kind === "approve", {
1147
+ by: decision.by,
1148
+ reason: decision.reason,
1149
+ });
1150
+ }
1151
+ }
1152
+ const state = new RunState(kernel, runId, runId, "resume", options.approver ?? null);
1153
+ return drive(new Run(state), agent, [...recorded.args]);
1154
+ }
1155
+ /**
1156
+ * Settle an in-doubt call by hand, for example after checking with the
1157
+ * payment provider (spec G8). `identity` comes from `result.inDoubt`. The next
1158
+ * `resume` uses the answer: `committed: true` reuses `value` as the call's
1159
+ * result; `committed: false` lets it run again.
1160
+ */
1161
+ export function resolve(runId, identity, options) {
1162
+ const { kernel } = openJournal(options.journal);
1163
+ kernel.resolveOffline(runId, identity, options.committed, {
1164
+ value: toData(options.value, null),
1165
+ by: options.by ?? "",
1166
+ });
1167
+ }
1168
+ //# sourceMappingURL=run.js.map