@trama-dev/runtime 0.6.1 → 0.7.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 (56) hide show
  1. package/dist/agent-backend.d.ts +51 -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.js +122 -56
  6. package/dist/agent.d.ts +16 -5
  7. package/dist/agent.js +22 -64
  8. package/dist/bridge-client.d.ts +6 -2
  9. package/dist/bridge-client.js +6 -1
  10. package/dist/client.d.ts +2 -2
  11. package/dist/client.js +126 -2
  12. package/dist/context.js +3 -2
  13. package/dist/history.d.ts +9 -0
  14. package/dist/history.js +98 -0
  15. package/dist/index.d.ts +1 -0
  16. package/dist/index.js +70 -41
  17. package/dist/ipc-server.d.ts +2 -3
  18. package/dist/ipc-server.js +93 -37
  19. package/dist/journal-view.js +19 -9
  20. package/dist/journal.d.ts +10 -4
  21. package/dist/journal.js +28 -6
  22. package/dist/merge-deeds.d.ts +22 -0
  23. package/dist/merge-deeds.js +201 -0
  24. package/dist/merge-doing.d.ts +9 -0
  25. package/dist/merge-doing.js +410 -0
  26. package/dist/merge-settle.d.ts +14 -0
  27. package/dist/merge-settle.js +166 -0
  28. package/dist/merge-shared.d.ts +64 -0
  29. package/dist/merge-shared.js +159 -0
  30. package/dist/merge.d.ts +150 -0
  31. package/dist/merge.js +209 -0
  32. package/dist/model-relay.js +35 -5
  33. package/dist/own-tools.d.ts +60 -0
  34. package/dist/own-tools.js +209 -0
  35. package/dist/path-guard.js +8 -6
  36. package/dist/pi-adapter.d.ts +22 -0
  37. package/dist/pi-adapter.js +147 -46
  38. package/dist/project.d.ts +31 -0
  39. package/dist/project.js +253 -0
  40. package/dist/replace-file.d.ts +13 -2
  41. package/dist/replace-file.js +23 -6
  42. package/dist/runner-backend.d.ts +43 -0
  43. package/dist/runner-backend.js +125 -0
  44. package/dist/runner-types.d.ts +8 -0
  45. package/dist/runner.d.ts +8 -123
  46. package/dist/runner.js +57 -453
  47. package/dist/schema.d.ts +38 -0
  48. package/dist/schema.js +104 -0
  49. package/dist/stopping.js +2 -3
  50. package/dist/tools.js +31 -7
  51. package/dist/tree.d.ts +33 -149
  52. package/dist/tree.js +43 -1077
  53. package/dist/types.d.ts +54 -2
  54. package/dist/workspace.d.ts +20 -0
  55. package/dist/workspace.js +76 -12
  56. package/package.json +2 -2
@@ -43,6 +43,51 @@ export declare function addReply(tally: Tally, used: {
43
43
  export declare function atLeast(usage: AgentUsage | undefined, seen?: Tally): AgentUsage | undefined;
44
44
  /** Of a report, what a report is declared to hold — whatever else a backend put beside it. */
45
45
  export declare const declaredUsage: ({ model, input, output, cacheRead, cacheWrite, cost }: AgentUsage) => AgentUsage;
46
+ /** The kinds of image a model is shown. */
47
+ export declare const IMAGE_KINDS: readonly ["image/png", "image/jpeg", "image/gif", "image/webp"];
48
+ export type ImageKind = (typeof IMAGE_KINDS)[number];
49
+ /** An image, as it is handed about: what kind it is, and its bytes in base64. */
50
+ export interface ToolImage {
51
+ mimeType: string;
52
+ data: string;
53
+ }
54
+ /**
55
+ * What a tool that was asked says: what the model is to read — and to be
56
+ * shown, where the tool has images for it — and whether that is how it failed.
57
+ */
58
+ export interface ToolAnswer {
59
+ text: string;
60
+ images?: ToolImage[];
61
+ failed?: boolean;
62
+ }
63
+ /** What a tool is taken to have said where it was not waited for: its call was to go no further. (Nobody reads it: the call is over.) */
64
+ export declare const NOT_WAITED_FOR: ToolAnswer;
65
+ /**
66
+ * A tool that is not the backend's: whoever makes the call has it, and is
67
+ * asked by `run` each time the model calls it.
68
+ */
69
+ export interface OwnTool {
70
+ /** As the model calls it. Nobody else's name: not a tool of the backend's, nor of anything the backend loads. */
71
+ name: string;
72
+ /** What it is for, as the model is told. */
73
+ description: string;
74
+ /** What it is called with: the JSON Schema of an object. A backend holds a call's arguments to it before it asks. */
75
+ parameters: Record<string, unknown>;
76
+ /** It may be run while another tool is. Without it, of the tools a model calls in one reply, one is run after the other. */
77
+ parallel?: boolean;
78
+ /**
79
+ * What it answers, where it does not fail, is the end of the agent's work
80
+ * and the answer of the call: the model is not asked again. (Unless the
81
+ * model called, in the same reply, a tool that does not end it.)
82
+ */
83
+ ends?: boolean;
84
+ /**
85
+ * Have it run: `id` is the model's call of it. It does not reject — a
86
+ * tool's failure is an answer, for the model to read — and where `signal`
87
+ * says the call is to go no further it is not waited for.
88
+ */
89
+ run(args: unknown, id: string, signal?: AbortSignal): Promise<ToolAnswer>;
90
+ }
46
91
  export interface AgentCall {
47
92
  /** The directory the agent works in: what its tools read is here, and what they write lands here. */
48
93
  cwd: string;
@@ -54,6 +99,12 @@ export interface AgentCall {
54
99
  thinking?: string;
55
100
  /** The agent's tools for this call, by name: these and no others. Without it, the agent's own choice. */
56
101
  tools?: string[];
102
+ /**
103
+ * Tools of the caller's own, which the agent has beside those: each to be
104
+ * the agent's as it is written, or the call rejects — a name that is
105
+ * another tool's is not taken over, and not passed over.
106
+ */
107
+ ownTools?: OwnTool[];
57
108
  /**
58
109
  * The skills the agent has for this call, of those the backend finds for
59
110
  * the user and where it works: all of them, or the ones named. Without it,
@@ -32,6 +32,10 @@ export function atLeast(usage, seen) {
32
32
  }
33
33
  /** Of a report, what a report is declared to hold — whatever else a backend put beside it. */
34
34
  export const declaredUsage = ({ model, input, output, cacheRead, cacheWrite, cost }) => ({ model, input, output, cacheRead, cacheWrite, cost });
35
+ /** The kinds of image a model is shown. */
36
+ export const IMAGE_KINDS = ["image/png", "image/jpeg", "image/gif", "image/webp"];
37
+ /** What a tool is taken to have said where it was not waited for: its call was to go no further. (Nobody reads it: the call is over.) */
38
+ export const NOT_WAITED_FOR = { text: "The call was stopped before the tool had answered.", failed: true };
35
39
  /**
36
40
  * A reply that ended at the model's output limit, and not where the model
37
41
  * would have ended it. It is not the answer — the call fails with this —
@@ -1,26 +1,48 @@
1
- import { type AgentCall, type AgentUsage } from "./agent-backend.js";
1
+ import { type AgentCall, type AgentUsage, type OwnTool, type ToolAnswer } from "./agent-backend.js";
2
2
  import type { ModelConfig } from "./runner-types.js";
3
3
  import { type RelayAnswered, type RelayAsked } from "./model-relay.js";
4
- /** What a call is made of that can be sent: all of it but where to say what it used, and what cancels it. */
5
- export type SentCall = Omit<AgentCall, "signal" | "used" | "sofar" | "had" | "relay">;
4
+ /**
5
+ * What a call is made of that can be sent: all of it but where to say what
6
+ * it used, and what cancels it — and, of the tools of its caller's own, what
7
+ * each declares: to have one run, a host asks its runner (below).
8
+ */
9
+ export type SentCall = Omit<AgentCall, "signal" | "used" | "sofar" | "had" | "relay" | "ownTools"> & {
10
+ ownTools?: Array<Omit<OwnTool, "run">>;
11
+ };
12
+ /** A use of a tool of the caller's own, as a host asks its runner for it: `key` is how the two speak of it. */
13
+ export interface ToolAsked {
14
+ key: string;
15
+ name: string;
16
+ id: string;
17
+ args: unknown;
18
+ }
6
19
  /**
7
20
  * What a runner says to a host: a call to serve; that the call it is serving
8
21
  * may go on, having said what it has used so far; that it is cancelled; and
9
22
  * what a model answers that the call had asked by its runner (see
10
23
  * model-relay.ts). And to a host that serves no call, but asks models for
11
24
  * the calls of others — the runner's own, where the run was given variables,
12
- * which a process is to be started with to ask by them: what to ask.
25
+ * which a process is to be started with to ask by them: what to ask. And
26
+ * what a tool of the caller's own answered, that the call's model had called.
13
27
  */
14
28
  export type ToHost = {
15
29
  ask: {
30
+ id: number;
16
31
  config: ModelConfig;
17
32
  prompt: string;
18
33
  call: SentCall;
19
34
  };
20
35
  } | {
21
36
  go: boolean;
37
+ of: number;
22
38
  } | {
23
39
  abort: true;
40
+ of: number;
41
+ } | {
42
+ tooled: {
43
+ key: string;
44
+ answer: ToolAnswer;
45
+ };
24
46
  } | RelayAnswered | RelayAsked;
25
47
  /**
26
48
  * What a host says to its runner: that it is there; what the call has used
@@ -30,11 +52,26 @@ export type ToHost = {
30
52
  * process has to be ended); what it used in the end; how the call ended —
31
53
  * its answer, an answer cut off at the output limit (with what there was of
32
54
  * it), or its failure; and what the call would have a model asked (or, of a
33
- * host that asks for others: what the model answered).
55
+ * host that asks for others: what the model answered). And that the call's
56
+ * model has called a tool of the caller's own — which is the runner's to
57
+ * have run. (That such a use is to go no further is not said: it is when the
58
+ * call is cancelled, or over, and the runner knows of both.)
59
+ *
60
+ * What is said of a call is said with the call's number (`of`), as the
61
+ * runner gave it — what the call would have a model asked too. A host
62
+ * serves one call after another, and what it says while nobody listens
63
+ * waits on the channel for whoever listens next: a word that comes late, or
64
+ * was not the host's at all, is not to be the next call's.
34
65
  */
35
66
  export type FromHost = {
36
67
  ready: true;
37
- } | {
68
+ } | OfCall | (RelayAsked & {
69
+ of?: number;
70
+ }) | RelayAnswered;
71
+ /** What a host says of the call it is serving. */
72
+ export type OfCall = {
73
+ of: number;
74
+ } & ({
38
75
  sofar: AgentUsage;
39
76
  answered?: true;
40
77
  } | {
@@ -47,4 +84,6 @@ export type FromHost = {
47
84
  cutOff: string;
48
85
  } | {
49
86
  error: string;
50
- } | RelayAsked | RelayAnswered;
87
+ } | {
88
+ tool: ToolAsked;
89
+ });
@@ -15,12 +15,14 @@ import { PiAdapter } from "./pi-adapter.js";
15
15
  import { CutOff } from "./agent-backend.js";
16
16
  import { messageOf } from "./errors.js";
17
17
  import { createModelRelay, relayClient, relayServer, withRepliesWhole } from "./model-relay.js";
18
- import { groupsUnder, signalGroup } from "./stopping.js";
18
+ import { groupsUnder, stopGroups } from "./stopping.js";
19
19
  const say = (message) => {
20
20
  // (A runner that is gone is told nothing: this process is on its way out with it.)
21
21
  if (process.connected)
22
22
  process.send?.(message);
23
23
  };
24
+ /** The call being served, by the number its runner gave it — none, while this process is free. */
25
+ let serving;
24
26
  /** Cancels the call being served. */
25
27
  let cancel;
26
28
  /**
@@ -33,19 +35,44 @@ const answered = (go) => {
33
35
  goOn?.(go);
34
36
  goOn = undefined;
35
37
  };
36
- /** The end that asks, of what the call being served has its model asked by: this process's runner. */
37
- const asks = relayClient(say);
38
+ /** The end that asks, of what the call being served has its model asked by: this process's runner — told which call it is for. */
39
+ const asks = relayClient((asked) => say(serving === undefined ? asked : { ...asked, of: serving }));
38
40
  /** The end that answers, where this process is one that asks models for the calls of others: with its own pi, and the keys it was started with. */
39
41
  let answers;
42
+ /** The uses of the caller's own tools that the call being served waits for, each by its key. */
43
+ const uses = new Map();
44
+ let used = 0;
45
+ /**
46
+ * A tool of the caller's own, as this process has it: each use is asked of
47
+ * the runner, which has the tool. (A use whose call is cancelled meanwhile
48
+ * is not waited for by whoever asked it here — see asPisTool — and its
49
+ * answer, should one come, is nobody's.)
50
+ */
51
+ const askedOfRunner = (of) => (tool) => ({
52
+ ...tool,
53
+ run: (args, id) => new Promise((resolve) => {
54
+ const key = String(++used);
55
+ uses.set(key, resolve);
56
+ say({ of, tool: { key, name: tool.name, id, args } });
57
+ }),
58
+ });
40
59
  /** Whether this process has been told to end. What it was serving is then stopped, and how that ended is not said: its runner hears that the process did. */
41
60
  let leaving = false;
42
61
  process.on("message", (message) => {
62
+ // (What is said of a call that is not the one being served — it is over here, and its runner had not heard — is said of nothing.)
43
63
  if ("go" in message)
44
- return answered(message.go);
64
+ return message.of === serving ? answered(message.go) : undefined;
45
65
  if ("abort" in message) {
66
+ if (message.of !== serving)
67
+ return;
46
68
  cancel?.abort();
47
69
  return answered(false);
48
70
  }
71
+ if ("tooled" in message) {
72
+ uses.get(message.tooled.key)?.(message.tooled.answer);
73
+ uses.delete(message.tooled.key);
74
+ return;
75
+ }
49
76
  if ("relayed" in message)
50
77
  return asks.heard(message.relayed);
51
78
  if ("relay" in message || "relayAbort" in message)
@@ -53,45 +80,58 @@ process.on("message", (message) => {
53
80
  // (A process that has been told to end serves nothing more: whoever asked hears that it ended.)
54
81
  if (leaving)
55
82
  return;
56
- const { config, prompt, call } = message.ask;
57
- const serving = cancel = new AbortController();
83
+ // A runner asks a host that is free, and a host is free when it has said how its call ended. Asked while it is
84
+ // at a call's work still, something else in this process said that for it — an extension, which has the same
85
+ // channel: this is no process to serve a call by, and it ends. (Whoever asked hears that it did.)
86
+ if (serving !== undefined)
87
+ return leave();
88
+ const { id: of, config, prompt, call } = message.ask;
89
+ const stop = cancel = new AbortController();
90
+ serving = of;
91
+ goOn = undefined;
92
+ uses.clear();
93
+ /** The call is over here: how it ended is said, and this process is free. */
94
+ const over = (how) => {
95
+ serving = undefined;
96
+ if (!leaving)
97
+ say({ of, ...how });
98
+ };
58
99
  new PiAdapter(config).serve(prompt, {
59
100
  ...call,
60
- signal: serving.signal,
61
- used: (usage) => say({ used: usage }),
62
- had: (usage) => say({ had: usage }),
101
+ ownTools: call.ownTools?.map(askedOfRunner(of)),
102
+ signal: stop.signal,
103
+ used: (usage) => say({ of, used: usage }),
104
+ had: (usage) => say({ of, had: usage }),
63
105
  relay: withRepliesWhole(asks.relay),
64
106
  sofar: (usage, has) => new Promise((resolve) => {
65
107
  goOn = resolve;
66
- say({ sofar: usage, ...(has && { answered: true }) });
108
+ say({ of, sofar: usage, ...(has && { answered: true }) });
67
109
  }),
68
- }).then((answer) => { if (!leaving)
69
- say({ answer }); }, (err) => { if (!leaving)
70
- say(err instanceof CutOff ? { cutOff: err.text } : { error: messageOf(err) }); });
110
+ }).then((answer) => over({ answer }), (err) => over(err instanceof CutOff ? { cutOff: err.text } : { error: messageOf(err) }));
71
111
  });
72
112
  // The runner is gone, or has no more use for this process — it says so, or its watchdog does, by asking
73
113
  // this process to end: there is nothing left to serve. What this process has under it in groups of their
74
114
  // own — an MCP server, what an agent was running — goes first: nobody else knows of it, once this process
75
- // is gone. (This process's own group is its runner's to end, or the watchdog's; and a process that cannot
115
+ // is gone. It is stopped as anything is: asked, given its time, and only then ended. (Whoever asked this
116
+ // process to end may have asked those groups too, having looked for them first: such a group is asked twice.)
117
+ // (This process's own group is its runner's to end, or the watchdog's; and a process that cannot
76
118
  // hear either is ended without being asked again, when the time anything asked to stop is given is up.)
77
119
  // And the call it is serving is stopped first, where it is: the system takes a moment to say what is
78
120
  // under this process, and in that moment the call is not to go on — to ask its model again, or to answer.
79
- const leave = (asked) => {
121
+ function leave(asked) {
80
122
  if (leaving)
81
123
  return;
82
124
  leaving = true;
83
125
  cancel?.abort();
84
126
  answered(false);
85
- void groupsUnder(process.pid).then((groups) => {
86
- for (const group of groups)
87
- signalGroup(group, "SIGKILL");
127
+ void groupsUnder(process.pid).then(stopGroups).then(() => {
88
128
  // (Asked to end, it ends as what was asked to: whoever waits for it is told how it went.)
89
129
  if (!asked)
90
130
  process.exit(0);
91
131
  process.removeAllListeners(asked);
92
132
  process.kill(process.pid, asked);
93
133
  });
94
- };
134
+ }
95
135
  process.on("disconnect", () => leave());
96
136
  process.on("SIGTERM", leave);
97
137
  say({ ready: true });
@@ -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
  };
@@ -178,9 +208,11 @@ export function createAgentHosts(env) {
178
208
  throwIfAborted(call.signal);
179
209
  const host = free.pop() ?? start();
180
210
  const child = host.process;
211
+ const id = ++calls;
181
212
  // (While it serves a call it is this process's to wait for; free, it keeps nobody waiting.)
182
213
  child.ref();
183
214
  child.channel?.ref();
215
+ let kept = false;
184
216
  /** The host goes back among the free ones: it has answered, or was never asked. */
185
217
  const release = () => {
186
218
  kept = true;
@@ -188,7 +220,6 @@ export function createAgentHosts(env) {
188
220
  child.channel?.unref();
189
221
  free.push(host);
190
222
  };
191
- let kept = false;
192
223
  try {
193
224
  await host.ready;
194
225
  return await new Promise((resolve, reject) => {
@@ -205,6 +236,33 @@ export function createAgentHosts(env) {
205
236
  let replies = 0, told = 0, noMore = false;
206
237
  let asksHere;
207
238
  let asked;
239
+ // What says to the caller's own tools, run from here for the host, that they are to go no further: the
240
+ // call is over — answered, failed, or cancelled and let go of.
241
+ const tooling = new AbortController();
242
+ /**
243
+ * Tell the call what it has used by now, and hear what it says to that — which, of a call that is
244
+ * over (`answered`), is whether anything more may be asked on its account: a no is one from then on.
245
+ */
246
+ const tell = (answered) => {
247
+ told = replies;
248
+ const sofar = atLeast(last, seen);
249
+ return Promise.resolve(sofar && call.sofar?.(sofar, answered)).then((go) => {
250
+ if (go === false && answered)
251
+ noMore = true;
252
+ return go;
253
+ });
254
+ };
255
+ /** Say what the call has used, to whoever counts: as a reply came, and — once — in the end. */
256
+ const sayHad = () => {
257
+ const had = atLeast(last, seen);
258
+ if (had)
259
+ call.had?.(had);
260
+ };
261
+ const sayUsed = (said) => {
262
+ const used = atLeast(said, seen);
263
+ if (used)
264
+ call.used?.(used);
265
+ };
208
266
  const asking = () => asked ??= relayServer(env ? apart : asksHere = createModelRelay(), (answer) => { if (child.connected)
209
267
  child.send(answer, () => { }); }, {
210
268
  // 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 +272,14 @@ export function createAgentHosts(env) {
214
272
  // after and whatever it says of itself. And a call that is cancelled, or done with, has its model
215
273
  // asked no more, whatever in its host would have it asked.
216
274
  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
- }
275
+ if (!noMore && replies !== told)
276
+ await tell(request.answered === true);
223
277
  return noMore || isOver || call.signal?.aborted === true;
224
278
  },
225
279
  replied(used) {
226
280
  addReply(seen, used);
227
281
  replies += 1;
228
- const had = atLeast(last, seen);
229
- if (had)
230
- call.had?.(had);
282
+ sayHad();
231
283
  },
232
284
  });
233
285
  /** 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 +287,8 @@ export function createAgentHosts(env) {
235
287
  if (isOver)
236
288
  return;
237
289
  isOver = true;
290
+ // (A tool of the caller's own that is still running is told that its call is over.)
291
+ tooling.abort();
238
292
  offAbort();
239
293
  clearTimeout(giveUp);
240
294
  child.off("message", heard);
@@ -247,42 +301,49 @@ export function createAgentHosts(env) {
247
301
  // it last said the call had used — and what was seen of it here — is then all that is
248
302
  // known of it, and what the call is taken to have used. (And a host that is well and
249
303
  // 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
- }
304
+ if (!usedSaid)
305
+ sayUsed(last);
255
306
  settle();
256
307
  };
257
308
  const heard = (word) => {
258
309
  const message = saidBy(word);
259
310
  if (!message)
260
311
  return;
312
+ // (Of another call than this: a word that waited on the channel since, or was never the host's.)
313
+ if (!("of" in message) || message.of !== id)
314
+ return;
261
315
  if ("relay" in message || "relayAbort" in message)
262
316
  return asking().heard(message);
317
+ // The call's model has called a tool of the caller's own: it is run from here, where the caller's
318
+ // tools are, and the host is told what it answered. (One the call has not got is not run. Whoever
319
+ // has the tool holds what it is called with to what it declared: a host's word is not taken for it.)
320
+ if ("tool" in message) {
321
+ const { key, name, id, args } = message.tool;
322
+ const tool = call.ownTools?.find(own => own.name === name);
323
+ const answering = tool ? tool.run(args, id, tooling.signal) : Promise.resolve({ text: `Tool ${name} not found`, failed: true });
324
+ void answering.catch((err) => ({ text: messageOf(err), failed: true })).then((answer) => {
325
+ if (!tooling.signal.aborted && child.connected)
326
+ child.send({ tooled: { key, answer } }, () => { });
327
+ });
328
+ return;
329
+ }
263
330
  if ("sofar" in message) {
264
- const sofar = atLeast(last = message.sofar, seen);
265
- told = replies;
331
+ last = message.sofar;
266
332
  // The host waits to hear whether the call is to go on — or, of a call that has its answer, whether
267
333
  // what would be asked beside it may be. (Where hearing what it used cancelled the call, the host
268
334
  // 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;
335
+ void tell(message.answered === true).then((go) => {
272
336
  if (!isOver && child.connected)
273
- child.send({ go: go !== false }, () => { });
337
+ child.send({ go: go !== false, of: id }, () => { });
274
338
  });
275
339
  }
276
340
  else if ("had" in message) {
277
- const had = atLeast(last = message.had, seen);
278
- if (had)
279
- call.had?.(had);
341
+ last = message.had;
342
+ sayHad();
280
343
  }
281
344
  else if ("used" in message) {
282
345
  usedSaid = true;
283
- const used = atLeast(message.used, seen);
284
- if (used)
285
- call.used?.(used);
346
+ sayUsed(message.used);
286
347
  }
287
348
  else if ("answer" in message)
288
349
  over(() => resolve(message.answer), true);
@@ -294,16 +355,21 @@ export function createAgentHosts(env) {
294
355
  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
356
  child.on("message", heard);
296
357
  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
- });
358
+ const notAsked = (err) => over(() => reject(new Error(`The agent's process could not be asked: ${err.message}`)), false);
359
+ // (What cannot be sent at all — a call that holds what no channel carries — is refused as it is handed over, and not later.)
360
+ try {
361
+ child.send({ ask: { id, config, prompt, call: sendable(call) } }, (err) => { if (err)
362
+ notAsked(err); });
363
+ }
364
+ catch (err) {
365
+ notAsked(err instanceof Error ? err : new Error(String(err)));
366
+ }
301
367
  // A cancelled call is asked to stop where it is, and waited for no longer than anything asked to stop is.
302
368
  offAbort = onAbort(call.signal, () => {
303
369
  // (What its model is being asked from here is asked no further, whether or not its host hears.)
304
370
  asked?.close();
305
371
  if (child.connected)
306
- child.send({ abort: true }, () => { });
372
+ child.send({ abort: true, of: id }, () => { });
307
373
  giveUp = setTimeout(() => over(() => reject(new Error("Aborted")), false), KILL_GRACE_MS);
308
374
  });
309
375
  });
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 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,21 @@ 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>;
30
41
  }
31
42
  /**
32
43
  * The `agent` a program talks to: its calls, served by `backend` working in