@trama-dev/runtime 0.6.1 → 0.8.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.
Files changed (64) hide show
  1. package/dist/agent-backend.d.ts +100 -0
  2. package/dist/agent-backend.js +4 -0
  3. package/dist/agent-host.d.ts +46 -7
  4. package/dist/agent-host.js +59 -19
  5. package/dist/agent-hosts.d.ts +8 -0
  6. package/dist/agent-hosts.js +123 -56
  7. package/dist/agent.d.ts +18 -5
  8. package/dist/agent.js +23 -64
  9. package/dist/bridge-client.d.ts +6 -2
  10. package/dist/bridge-client.js +7 -1
  11. package/dist/budget.d.ts +6 -0
  12. package/dist/budget.js +1 -0
  13. package/dist/client.d.ts +3 -2
  14. package/dist/client.js +146 -2
  15. package/dist/context.js +3 -2
  16. package/dist/history.d.ts +9 -0
  17. package/dist/history.js +98 -0
  18. package/dist/index.d.ts +2 -0
  19. package/dist/index.js +73 -41
  20. package/dist/ipc-server.d.ts +2 -3
  21. package/dist/ipc-server.js +99 -38
  22. package/dist/journal-view.d.ts +8 -0
  23. package/dist/journal-view.js +63 -11
  24. package/dist/journal.d.ts +10 -4
  25. package/dist/journal.js +73 -7
  26. package/dist/merge-deeds.d.ts +22 -0
  27. package/dist/merge-deeds.js +201 -0
  28. package/dist/merge-doing.d.ts +9 -0
  29. package/dist/merge-doing.js +410 -0
  30. package/dist/merge-settle.d.ts +14 -0
  31. package/dist/merge-settle.js +166 -0
  32. package/dist/merge-shared.d.ts +64 -0
  33. package/dist/merge-shared.js +159 -0
  34. package/dist/merge.d.ts +150 -0
  35. package/dist/merge.js +209 -0
  36. package/dist/model-relay.d.ts +19 -0
  37. package/dist/model-relay.js +91 -9
  38. package/dist/model-request.d.ts +9 -0
  39. package/dist/model-request.js +185 -0
  40. package/dist/own-tools.d.ts +60 -0
  41. package/dist/own-tools.js +209 -0
  42. package/dist/path-guard.js +8 -6
  43. package/dist/pi-adapter.d.ts +32 -9
  44. package/dist/pi-adapter.js +198 -51
  45. package/dist/project.d.ts +39 -0
  46. package/dist/project.js +270 -0
  47. package/dist/replace-file.d.ts +13 -2
  48. package/dist/replace-file.js +23 -6
  49. package/dist/runner-backend.d.ts +43 -0
  50. package/dist/runner-backend.js +149 -0
  51. package/dist/runner-types.d.ts +26 -0
  52. package/dist/runner.d.ts +10 -125
  53. package/dist/runner.js +148 -461
  54. package/dist/schema.d.ts +45 -0
  55. package/dist/schema.js +113 -0
  56. package/dist/stopping.js +2 -3
  57. package/dist/tools.d.ts +8 -1
  58. package/dist/tools.js +36 -10
  59. package/dist/tree.d.ts +33 -149
  60. package/dist/tree.js +43 -1077
  61. package/dist/types.d.ts +182 -2
  62. package/dist/workspace.d.ts +28 -1
  63. package/dist/workspace.js +88 -13
  64. package/package.json +2 -2
@@ -30,37 +30,63 @@ function saidBy(message) {
30
30
  if (typeof message !== "object" || message === null)
31
31
  return undefined;
32
32
  const said = message;
33
- const counted = (usage) => typeof usage === "object" && usage !== null;
33
+ const held = (value) => typeof value === "object" && value !== null;
34
34
  if (said.ready === true)
35
35
  return { ready: true };
36
- if (counted(said.sofar))
37
- return { sofar: said.sofar, ...(said.answered === true && { answered: true }) };
38
- if (counted(said.had))
39
- return { had: said.had };
40
- if (counted(said.used))
41
- return { used: said.used };
42
- if (typeof said.answer === "string")
43
- return { answer: said.answer };
44
- if (typeof said.cutOff === "string")
45
- return { cutOff: said.cutOff };
46
- if (typeof said.error === "string")
47
- return { error: said.error };
36
+ // What is said of a call: by the call's number.
37
+ const { of } = said;
38
+ if (typeof of === "number") {
39
+ const sofar = countOf(said.sofar), had = countOf(said.had), used = countOf(said.used);
40
+ if (sofar)
41
+ return { of, sofar, ...(said.answered === true && { answered: true }) };
42
+ if (had)
43
+ return { of, had };
44
+ if (used)
45
+ return { of, used };
46
+ if (typeof said.answer === "string")
47
+ return { of, answer: said.answer };
48
+ if (typeof said.cutOff === "string")
49
+ return { of, cutOff: said.cutOff };
50
+ if (typeof said.error === "string")
51
+ return { of, error: said.error };
52
+ // That a tool of the caller's own is called.
53
+ const { tool } = said;
54
+ if (held(tool) && typeof tool.key === "string" && typeof tool.name === "string" && typeof tool.id === "string") {
55
+ return { of, tool: { key: tool.key, name: tool.name, id: tool.id, args: tool.args } };
56
+ }
57
+ }
48
58
  // What a call would have a model asked, and what a model answered (see model-relay.ts).
49
- const held = (value) => typeof value === "object" && value !== null;
50
59
  const { relay, relayAbort, relayed } = said;
51
60
  if (held(relay) && typeof relay.id === "number" && held(relay.request)) {
52
61
  const { model, options } = relay.request;
53
62
  if (held(model) && typeof model.provider === "string" && typeof model.id === "string" && held(options))
54
- return { relay };
63
+ return { relay, ...(typeof of === "number" && { of }) };
55
64
  }
56
65
  if (typeof relayAbort === "number")
57
- return { relayAbort };
66
+ return { relayAbort, ...(typeof of === "number" && { of }) };
58
67
  if (held(relayed) && typeof relayed.id === "number" && (relayed.not === true || (held(relayed.event) && typeof relayed.event.type === "string")))
59
68
  return { relayed };
60
69
  return undefined;
61
70
  }
62
- /** Of a call, what can be sent to another process. */
63
- const sendable = ({ signal: _signal, used: _used, sofar: _sofar, had: _had, relay: _relay, ...call }) => call;
71
+ /**
72
+ * A count a host said, if it is one: every figure of it a number, and none
73
+ * less than nothing. What is anything else is no count — and is not to be
74
+ * reckoned with as one: a figure that is no number would make no number of
75
+ * what the runner itself saw the call use.
76
+ */
77
+ function countOf(said) {
78
+ if (typeof said !== "object" || said === null)
79
+ return undefined;
80
+ const { model, input, output, cacheRead, cacheWrite, cost } = said;
81
+ const figures = [input, output, cacheRead, cacheWrite, cost];
82
+ if (!figures.every((figure) => typeof figure === "number" && Number.isFinite(figure) && figure >= 0))
83
+ return undefined;
84
+ if (model !== undefined && typeof model !== "string")
85
+ return undefined;
86
+ return { ...(model !== undefined && { model }), input: figures[0], output: figures[1], cacheRead: figures[2], cacheWrite: figures[3], cost: figures[4] };
87
+ }
88
+ /** Of a call, what can be sent to another process: of a tool of its caller's own, all it declares — the function stays here. */
89
+ const sendable = ({ signal: _signal, used: _used, sofar: _sofar, had: _had, relay: _relay, ownTools, ...call }) => ({ ...call, ...(ownTools && { ownTools: ownTools.map(({ run: _run, ...declared }) => declared) }) });
64
90
  /**
65
91
  * The hosts of one runner's calls. `env`: variables the hosts are started
66
92
  * with, over this process's own — a run's, whose agents are then that run's
@@ -69,6 +95,14 @@ const sendable = ({ signal: _signal, used: _used, sofar: _sofar, had: _had, rela
69
95
  export function createAgentHosts(env) {
70
96
  /** The hosts that are there: those serving a call, and those free to serve one. */
71
97
  const all = new Set(), free = [];
98
+ /** How many calls were handed to a host: each is known to its host, and in what the host says of it, by its number. */
99
+ let calls = 0;
100
+ /** A host that is ending, or has ended, is no longer one to hand a call. */
101
+ const notFree = (host) => {
102
+ const at = free.indexOf(host);
103
+ if (at !== -1)
104
+ free.splice(at, 1);
105
+ };
72
106
  /** Put an end to a host, and to what it has under it. Resolves when they are gone. */
73
107
  const end = async (host) => {
74
108
  // Whoever waits for a host to be gone is held until it is seen to be. (A free host keeps nobody waiting —
@@ -78,9 +112,7 @@ export function createAgentHosts(env) {
78
112
  host.process.ref();
79
113
  if (!host.gone) {
80
114
  host.gone = true;
81
- const at = free.indexOf(host);
82
- if (at !== -1)
83
- free.splice(at, 1);
115
+ notFree(host);
84
116
  // (Its process leads a group of its own; what it started in groups of their own is looked for first, while it is there to be asked of.)
85
117
  const { pid } = host.process;
86
118
  if (pid !== undefined)
@@ -119,9 +151,7 @@ export function createAgentHosts(env) {
119
151
  const over = () => {
120
152
  host.gone = true;
121
153
  all.delete(host);
122
- const at = free.indexOf(host);
123
- if (at !== -1)
124
- free.splice(at, 1);
154
+ notFree(host);
125
155
  watched();
126
156
  resolve();
127
157
  };
@@ -174,13 +204,16 @@ export function createAgentHosts(env) {
174
204
  },
175
205
  };
176
206
  return {
207
+ asks: apart,
177
208
  async ask(config, prompt, call) {
178
209
  throwIfAborted(call.signal);
179
210
  const host = free.pop() ?? start();
180
211
  const child = host.process;
212
+ const id = ++calls;
181
213
  // (While it serves a call it is this process's to wait for; free, it keeps nobody waiting.)
182
214
  child.ref();
183
215
  child.channel?.ref();
216
+ let kept = false;
184
217
  /** The host goes back among the free ones: it has answered, or was never asked. */
185
218
  const release = () => {
186
219
  kept = true;
@@ -188,7 +221,6 @@ export function createAgentHosts(env) {
188
221
  child.channel?.unref();
189
222
  free.push(host);
190
223
  };
191
- let kept = false;
192
224
  try {
193
225
  await host.ready;
194
226
  return await new Promise((resolve, reject) => {
@@ -205,6 +237,33 @@ export function createAgentHosts(env) {
205
237
  let replies = 0, told = 0, noMore = false;
206
238
  let asksHere;
207
239
  let asked;
240
+ // What says to the caller's own tools, run from here for the host, that they are to go no further: the
241
+ // call is over — answered, failed, or cancelled and let go of.
242
+ const tooling = new AbortController();
243
+ /**
244
+ * Tell the call what it has used by now, and hear what it says to that — which, of a call that is
245
+ * over (`answered`), is whether anything more may be asked on its account: a no is one from then on.
246
+ */
247
+ const tell = (answered) => {
248
+ told = replies;
249
+ const sofar = atLeast(last, seen);
250
+ return Promise.resolve(sofar && call.sofar?.(sofar, answered)).then((go) => {
251
+ if (go === false && answered)
252
+ noMore = true;
253
+ return go;
254
+ });
255
+ };
256
+ /** Say what the call has used, to whoever counts: as a reply came, and — once — in the end. */
257
+ const sayHad = () => {
258
+ const had = atLeast(last, seen);
259
+ if (had)
260
+ call.had?.(had);
261
+ };
262
+ const sayUsed = (said) => {
263
+ const used = atLeast(said, seen);
264
+ if (used)
265
+ call.used?.(used);
266
+ };
208
267
  const asking = () => asked ??= relayServer(env ? apart : asksHere = createModelRelay(), (answer) => { if (child.connected)
209
268
  child.send(answer, () => { }); }, {
210
269
  // A model is not asked for a call that has not been told of all it was seen to use: the host says
@@ -214,20 +273,14 @@ export function createAgentHosts(env) {
214
273
  // after and whatever it says of itself. And a call that is cancelled, or done with, has its model
215
274
  // asked no more, whatever in its host would have it asked.
216
275
  async refuse(request) {
217
- if (!noMore && replies !== told) {
218
- told = replies;
219
- const sofar = atLeast(last, seen), answered = request.answered === true;
220
- if (sofar && await call.sofar?.(sofar, answered) === false && answered)
221
- noMore = true;
222
- }
276
+ if (!noMore && replies !== told)
277
+ await tell(request.answered === true);
223
278
  return noMore || isOver || call.signal?.aborted === true;
224
279
  },
225
280
  replied(used) {
226
281
  addReply(seen, used);
227
282
  replies += 1;
228
- const had = atLeast(last, seen);
229
- if (had)
230
- call.had?.(had);
283
+ sayHad();
231
284
  },
232
285
  });
233
286
  /** The call is over: by an answer of the host's, which is then free again — or without one, and the host is ended. */
@@ -235,6 +288,8 @@ export function createAgentHosts(env) {
235
288
  if (isOver)
236
289
  return;
237
290
  isOver = true;
291
+ // (A tool of the caller's own that is still running is told that its call is over.)
292
+ tooling.abort();
238
293
  offAbort();
239
294
  clearTimeout(giveUp);
240
295
  child.off("message", heard);
@@ -247,42 +302,49 @@ export function createAgentHosts(env) {
247
302
  // it last said the call had used — and what was seen of it here — is then all that is
248
303
  // known of it, and what the call is taken to have used. (And a host that is well and
249
304
  // says nothing, of a call whose model was asked from here, is not taken at its silence.)
250
- if (!usedSaid) {
251
- const used = atLeast(last, seen);
252
- if (used)
253
- call.used?.(used);
254
- }
305
+ if (!usedSaid)
306
+ sayUsed(last);
255
307
  settle();
256
308
  };
257
309
  const heard = (word) => {
258
310
  const message = saidBy(word);
259
311
  if (!message)
260
312
  return;
313
+ // (Of another call than this: a word that waited on the channel since, or was never the host's.)
314
+ if (!("of" in message) || message.of !== id)
315
+ return;
261
316
  if ("relay" in message || "relayAbort" in message)
262
317
  return asking().heard(message);
318
+ // The call's model has called a tool of the caller's own: it is run from here, where the caller's
319
+ // tools are, and the host is told what it answered. (One the call has not got is not run. Whoever
320
+ // has the tool holds what it is called with to what it declared: a host's word is not taken for it.)
321
+ if ("tool" in message) {
322
+ const { key, name, id, args } = message.tool;
323
+ const tool = call.ownTools?.find(own => own.name === name);
324
+ const answering = tool ? tool.run(args, id, tooling.signal) : Promise.resolve({ text: `Tool ${name} not found`, failed: true });
325
+ void answering.catch((err) => ({ text: messageOf(err), failed: true })).then((answer) => {
326
+ if (!tooling.signal.aborted && child.connected)
327
+ child.send({ tooled: { key, answer } }, () => { });
328
+ });
329
+ return;
330
+ }
263
331
  if ("sofar" in message) {
264
- const sofar = atLeast(last = message.sofar, seen);
265
- told = replies;
332
+ last = message.sofar;
266
333
  // The host waits to hear whether the call is to go on — or, of a call that has its answer, whether
267
334
  // what would be asked beside it may be. (Where hearing what it used cancelled the call, the host
268
335
  // has been told that first, below: this then tells it nothing.)
269
- void Promise.resolve(sofar && call.sofar?.(sofar, message.answered === true)).then((go) => {
270
- if (go === false && message.answered === true)
271
- noMore = true;
336
+ void tell(message.answered === true).then((go) => {
272
337
  if (!isOver && child.connected)
273
- child.send({ go: go !== false }, () => { });
338
+ child.send({ go: go !== false, of: id }, () => { });
274
339
  });
275
340
  }
276
341
  else if ("had" in message) {
277
- const had = atLeast(last = message.had, seen);
278
- if (had)
279
- call.had?.(had);
342
+ last = message.had;
343
+ sayHad();
280
344
  }
281
345
  else if ("used" in message) {
282
346
  usedSaid = true;
283
- const used = atLeast(message.used, seen);
284
- if (used)
285
- call.used?.(used);
347
+ sayUsed(message.used);
286
348
  }
287
349
  else if ("answer" in message)
288
350
  over(() => resolve(message.answer), true);
@@ -294,16 +356,21 @@ export function createAgentHosts(env) {
294
356
  const exited = (code, signal) => over(() => reject(new Error(`The agent's process ended before it had answered (${signal ?? `exit code ${code}`}): the call was not finished.`)), false);
295
357
  child.on("message", heard);
296
358
  child.once("exit", exited);
297
- child.send({ ask: { config, prompt, call: sendable(call) } }, (err) => {
298
- if (err)
299
- over(() => reject(new Error(`The agent's process could not be asked: ${err.message}`)), false);
300
- });
359
+ const notAsked = (err) => over(() => reject(new Error(`The agent's process could not be asked: ${err.message}`)), false);
360
+ // (What cannot be sent at all — a call that holds what no channel carries — is refused as it is handed over, and not later.)
361
+ try {
362
+ child.send({ ask: { id, config, prompt, call: sendable(call) } }, (err) => { if (err)
363
+ notAsked(err); });
364
+ }
365
+ catch (err) {
366
+ notAsked(err instanceof Error ? err : new Error(String(err)));
367
+ }
301
368
  // A cancelled call is asked to stop where it is, and waited for no longer than anything asked to stop is.
302
369
  offAbort = onAbort(call.signal, () => {
303
370
  // (What its model is being asked from here is asked no further, whether or not its host hears.)
304
371
  asked?.close();
305
372
  if (child.connected)
306
- child.send({ abort: true }, () => { });
373
+ child.send({ abort: true, of: id }, () => { });
307
374
  giveUp = setTimeout(() => over(() => reject(new Error("Aborted")), false), KILL_GRACE_MS);
308
375
  });
309
376
  });
package/dist/agent.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import type { Agent } from "./types.js";
2
- import { type AgentBackend, type AgentCall } from "./agent-backend.js";
1
+ import type { AgentOptions, Schema } from "./types.js";
2
+ import { type AgentBackend, type AgentCall, type ModelAsk, type OwnTool } from "./agent-backend.js";
3
3
  /**
4
4
  * The program in an LLM reply that was asked to contain nothing else: the last
5
5
  * fenced block if there is one (models add explanations, or show a "before"
@@ -23,10 +23,23 @@ import { type AgentBackend, type AgentCall } from "./agent-backend.js";
23
23
  export declare function stripCodeFences(text: string): string;
24
24
  /** Hears what a call used — each time its backend was asked: a `generate` that had to ask again is heard twice. */
25
25
  type Used = AgentCall["used"];
26
- /** The runner's side of a program's `agent`: its calls, and for each a place to say what it used. */
26
+ /** How a call is served, as its runner has it: the agent's tools by name — the program's own are given beside (`ownTools`). */
27
+ type Served = Omit<AgentOptions, "tools"> & {
28
+ tools?: string[];
29
+ };
30
+ /**
31
+ * The runner's side of a program's `agent`: its calls, and for each a place
32
+ * to say what it used — and the tools of the program's that the agent has
33
+ * for it, each a way to ask the program.
34
+ */
27
35
  export interface RunnerAgent {
28
- instruct(prompt: string, options?: Parameters<Agent["instruct"]>[1], used?: Used): Promise<string>;
29
- generate<T>(input: Parameters<Agent["generate"]>[0], used?: Used): Promise<T>;
36
+ instruct(prompt: string, options?: Served, used?: Used, ownTools?: OwnTool[]): Promise<string>;
37
+ generate<T>(input: Omit<Served, "templates"> & {
38
+ prompt: string;
39
+ schema: Schema;
40
+ }, used?: Used, ownTools?: OwnTool[]): Promise<T>;
41
+ /** One request to the model, held to its shape already (see model-request.ts), and its one reply. */
42
+ complete(request: ModelAsk, used?: Used): Promise<Record<string, unknown>>;
30
43
  }
31
44
  /**
32
45
  * The `agent` a program talks to: its calls, served by `backend` working in
package/dist/agent.js CHANGED
@@ -1,4 +1,8 @@
1
+ // What a program's `agent` is to its runner: its calls, each made a request
2
+ // of the backend — and, of a reply that was to be a program and nothing
3
+ // else, the program in it.
1
4
  import { CutOff } from "./agent-backend.js";
5
+ import { conform, hasList, shapeOf } from "./schema.js";
2
6
  import { isJsonObject } from "./serializable.js";
3
7
  const NAMED = /[\w.+#-]*\s*\n/y;
4
8
  /** The fences of a text, in the order they stand in. */
@@ -82,62 +86,6 @@ export function stripCodeFences(text) {
82
86
  }
83
87
  return last ?? reply;
84
88
  }
85
- const SCHEMA_PRIMITIVES = new Set(["string", "number", "boolean"]);
86
- /** How the two shapes that are not named in a word are written, for whoever named them in one. */
87
- const HOW_WRITTEN = `a list is written as the shape of its items, in brackets: ["string"]; an object as its fields: { name: "string" }`;
88
- const fieldOf = (where, key) => (where === null ? key : `${where}.${key}`);
89
- /**
90
- * Read the caller's schema declaration, up front: what the value at `where`
91
- * is to be. In words — "string", "number", "boolean", where what follows a
92
- * ":" describes the value to the model and is not read here — or an object
93
- * of such, or a list of one element: the shape of every item.
94
- */
95
- function shapeOf(declared, where) {
96
- if (Array.isArray(declared)) {
97
- if (declared.length !== 1) {
98
- throw new Error(`Schema validation failed: the list at "${where}" is written with ${declared.length} elements — it takes one, the shape of every item`);
99
- }
100
- return { items: shapeOf(declared[0], `${where}[]`) };
101
- }
102
- if (isJsonObject(declared)) {
103
- return { fields: Object.entries(declared).map(([key, value]) => [key, shapeOf(value, fieldOf(where, key))]) };
104
- }
105
- // (Anything else says nothing that is supported — and is said back as JSON would write it, which is no word for a kind.)
106
- const named = typeof declared === "string" ? declared.split(":")[0].trim() : JSON.stringify(declared);
107
- if (!SCHEMA_PRIMITIVES.has(named)) {
108
- throw new Error(`Schema validation failed: unsupported schema type "${named}" for key "${where}" (${HOW_WRITTEN})`);
109
- }
110
- return named;
111
- }
112
- const hasList = (shape) => typeof shape !== "string" && ("items" in shape || shape.fields.some(([, field]) => hasList(field)));
113
- /** What a value is, said as a reply is told of it. */
114
- const said = (value) => value === null ? "null" : Array.isArray(value) ? "a list" : typeof value === "number" ? String(value) : typeof value;
115
- /**
116
- * Shape validation and projection: verifies that the value at `where` is of
117
- * the shape declared — every field there, every item of a list — and returns
118
- * it holding the declared fields and no others.
119
- */
120
- function conform(value, shape, where) {
121
- const mismatch = (expected) => new Error(`Schema validation failed: ${where}: expected ${expected}, got ${said(value)}`);
122
- if (typeof shape === "string") {
123
- if (typeof value !== shape || (shape === "number" && !Number.isFinite(value)))
124
- throw mismatch(shape);
125
- return value;
126
- }
127
- if ("items" in shape) {
128
- if (!Array.isArray(value))
129
- throw mismatch("a list");
130
- return value.map((item, index) => conform(item, shape.items, `${where}[${index}]`));
131
- }
132
- if (!isJsonObject(value))
133
- throw where === null ? new Error("Schema validation failed: response is not an object") : mismatch("an object");
134
- return Object.fromEntries(shape.fields.map(([key, field]) => {
135
- // (A field is the reply's own: what every object has by birth is not something a reply said.)
136
- if (!Object.hasOwn(value, key))
137
- throw new Error(`Schema validation failed: missing key: ${fieldOf(where, key)}`);
138
- return [key, conform(value[key], field, fieldOf(where, key))];
139
- }));
140
- }
141
89
  /** Of what a call may ask for, what it did ask for: a backend is not handed a thing nobody named. */
142
90
  const asked = (options) => Object.fromEntries(Object.entries(options).filter(([, value]) => value !== undefined));
143
91
  /**
@@ -164,21 +112,22 @@ export function createAgent(backend, cwd, signal) {
164
112
  }
165
113
  };
166
114
  return {
167
- async instruct(prompt, options, used) {
115
+ async instruct(prompt, options, used, ownTools) {
168
116
  const { system, model, thinking, tools, skills, templates, extensions, cutOff } = options ?? {};
169
- return ask(prompt, { cwd, system, signal, ...asked({ model, thinking, tools, skills, templates, extensions, used }) }, cutOff);
117
+ return ask(prompt, { cwd, system, signal, ...asked({ model, thinking, tools, ownTools, skills, templates, extensions, used }) }, cutOff);
170
118
  },
171
- async generate(input, used) {
119
+ complete: (request, used) => backend.complete(request, { signal, ...(used && { used }) }),
120
+ async generate(input, used, ownTools) {
172
121
  if (!isJsonObject(input.schema))
173
122
  throw new Error("Schema validation failed: a schema is an object of the fields the answer is to have");
174
- const shape = shapeOf(input.schema, null);
123
+ const shape = shapeOf(input.schema);
175
124
  const schemaInstruction = `Respond with ONLY a JSON object matching this shape:\n${JSON.stringify(input.schema, null, 2)}\n${hasList(shape) ? "Where the shape shows a list, it shows one item: answer with as many as there are, each of that shape.\n" : ""}No markdown. No explanation. Just the JSON.`;
176
125
  const fullPrompt = `${input.prompt}\n\n${schemaInstruction}`;
177
126
  const { system, model, thinking, tools, skills, extensions, cutOff } = input;
178
127
  // The prompt of a typed answer is text, whatever it begins with: what says how to answer follows it, and a
179
128
  // skill called up by name, or a command, would take that for its own — and would not be there at a second asking.
180
129
  const asText = skills !== undefined || extensions !== undefined ? true : undefined;
181
- const call = { cwd, system, signal, ...asked({ model, thinking, tools, skills, extensions, asText, used }) };
130
+ const call = { cwd, system, signal, ...asked({ model, thinking, tools, ownTools, skills, extensions, asText, used }) };
182
131
  const parseAndValidate = (response) => {
183
132
  const trimmed = response.trim();
184
133
  // Try raw parse first — avoids mangling valid JSON that contains
@@ -188,10 +137,20 @@ export function createAgent(backend, cwd, signal) {
188
137
  parsed = JSON.parse(trimmed);
189
138
  }
190
139
  catch {
191
- const fenceMatch = trimmed.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);
192
- parsed = JSON.parse(fenceMatch ? fenceMatch[1].trim() : trimmed);
140
+ // Fenced: what stands between the first fence and the last — an answer may hold fences of its own,
141
+ // in what it says — or, where that is not JSON (more blocks than one), what the first block holds.
142
+ const whole = trimmed.match(/```(?:json)?\s*\n?([\s\S]*)\n?\s*```/);
143
+ try {
144
+ if (!whole)
145
+ throw new SyntaxError("not fenced");
146
+ parsed = JSON.parse(whole[1].trim());
147
+ }
148
+ catch {
149
+ const first = trimmed.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);
150
+ parsed = JSON.parse(first ? first[1].trim() : trimmed);
151
+ }
193
152
  }
194
- return conform(parsed, shape, null);
153
+ return conform(parsed, shape);
195
154
  };
196
155
  // First attempt — backend errors (network/auth) propagate immediately.
197
156
  // Only parse/validation failures trigger a retry.
@@ -2,8 +2,12 @@ import type { Workspace } from "./types.js";
2
2
  export interface Bridge {
3
3
  /** What the runner handed the program when it started it — the bridge secret among it. */
4
4
  init: Record<string, any>;
5
- /** POST one call to the runner and return its result. */
6
- call(endpoint: string, body: unknown): Promise<any>;
5
+ /**
6
+ * POST one call to the runner and return its result. With `signal`, the
7
+ * call can be given up: its connection is closed — which is how the runner
8
+ * hears of it — and it rejects.
9
+ */
10
+ call(endpoint: string, body: unknown, signal?: AbortSignal): Promise<any>;
7
11
  }
8
12
  /**
9
13
  * The body of a call that takes options: what the call is made with, and the
@@ -2,6 +2,7 @@
2
2
  // reaches the runner that started it (ipc-server.ts is the other end).
3
3
  import { readFileSync } from "fs";
4
4
  import { Agent, request } from "http";
5
+ import { onAbort } from "./abort.js";
5
6
  import { messageOf } from "./errors.js";
6
7
  let cached;
7
8
  /**
@@ -53,8 +54,10 @@ export function openBridge(port, initPath) {
53
54
  // A call lasts as long as the work behind it — an agent run, or the whole
54
55
  // run of another program — so this uses node:http, which sets no deadline
55
56
  // for the response. (fetch gives up after five minutes without response headers.)
56
- const call = (endpoint, body) => new Promise((resolve, reject) => {
57
+ const call = (endpoint, body, signal) => new Promise((resolve, reject) => {
57
58
  const payload = encode(endpoint, body);
59
+ if (signal?.aborted)
60
+ return reject(new Error(`${endpoint} was given up`));
58
61
  const req = request({
59
62
  host: "127.0.0.1",
60
63
  port,
@@ -85,6 +88,8 @@ export function openBridge(port, initPath) {
85
88
  });
86
89
  });
87
90
  req.on("error", reject);
91
+ const off = onAbort(signal, () => req.destroy(new Error(`${endpoint} was given up`)));
92
+ req.on("close", off);
88
93
  req.end(payload);
89
94
  });
90
95
  const bridge = { init, call };
@@ -120,5 +125,6 @@ export function remoteWorkspace(call, dir) {
120
125
  write: (path, content) => call("/workspace/write", { dir, path, content }),
121
126
  list: (pattern) => call("/workspace/list", { dir, pattern }),
122
127
  observe: async (pattern, options) => call("/workspace/observe", withOptions({ dir, pattern }, options)),
128
+ shell: async (command, options) => call("/workspace/shell", withOptions({ dir, command }, options)),
123
129
  };
124
130
  }
package/dist/budget.d.ts CHANGED
@@ -42,6 +42,12 @@ export interface Meter {
42
42
  reached(): string | undefined;
43
43
  /** Add to the count, here and above: calls taken on, and what calls used — more than was said of them before, or less. */
44
44
  count(calls: number, cost: number, tokens: number): void;
45
+ /** What it has counted so far: the calls taken on, and what they have said they used. */
46
+ counted(): {
47
+ calls: number;
48
+ cost: number;
49
+ tokens: number;
50
+ };
45
51
  }
46
52
  /**
47
53
  * The count of what a run uses, held to `limit`. What it counts is counted
package/dist/budget.js CHANGED
@@ -92,6 +92,7 @@ export function createMeter(limit = {}, above) {
92
92
  tokens += read;
93
93
  above?.count(more, dollars, read);
94
94
  },
95
+ counted: () => ({ calls, cost, tokens }),
95
96
  admit() {
96
97
  const refusal = meter.spent();
97
98
  if (refusal !== undefined)
package/dist/client.d.ts CHANGED
@@ -1,7 +1,8 @@
1
- import type { Ctx, Agent, AgentOptions, Thinking, Schema, SchemaField, ShellResult, Tools, ObserveResult, Workspace } from "./types.js";
2
- export type { Ctx, Agent, AgentOptions, Thinking, Schema, SchemaField, ShellResult, Tools, ObserveResult, Workspace };
1
+ import type { Ctx, Agent, AgentOptions, AgentTool, Thinking, Schema, SchemaField, ShellResult, Tools, ObserveResult, Workspace, ModelRequest, ModelReply, ModelMessage, TextPart, ImagePart, ThinkingPart, ToolCallPart } from "./types.js";
2
+ export type { Ctx, Agent, AgentOptions, AgentTool, Thinking, Schema, SchemaField, ShellResult, Tools, ObserveResult, Workspace, ModelRequest, ModelReply, ModelMessage, TextPart, ImagePart, ThinkingPart, ToolCallPart };
3
3
  export declare const ctx: Ctx;
4
4
  export declare const agent: Agent;
5
5
  export declare const tools: Tools;
6
6
  /** workspace.* exists only inside a session — everywhere else it fails clearly, without a round trip. */
7
7
  export declare const workspace: Workspace;
8
+ export { heldTo } from "./schema.js";