@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
package/dist/merge.js ADDED
@@ -0,0 +1,209 @@
1
+ // What a run did to a copy of a directory, carried back into the directory.
2
+ //
3
+ // It is apart from the reading and the copying (tree.ts) because it is long,
4
+ // and it is in parts because it is done in parts, each of which can be read
5
+ // without the others. What a merge is given, and what its parts have between
6
+ // them, is merge-shared.ts: what the run changed, what is told of it, what
7
+ // the run left, and the directories opened. With those, what is to be done is
8
+ // found out before anything is (merge-deeds.ts: it looks, and opens a
9
+ // directory to look; no more); what follows from what does not arrive is
10
+ // followed up (merge-settle.ts: it touches nothing); and it is done
11
+ // (merge-doing.ts: all that is made, moved or removed in the real directory
12
+ // is there). Here is what all of it comes to, and the order of it.
13
+ import { chmodSync } from "fs";
14
+ import { realRootOf } from "./path-guard.js";
15
+ import { messageOf } from "./errors.js";
16
+ import { ITSELF, entryAt, walk } from "./tree.js";
17
+ import { changesOf, leftBy, opening, telling } from "./merge-shared.js";
18
+ import { deedsOf } from "./merge-deeds.js";
19
+ import { followingUp } from "./merge-settle.js";
20
+ import { carryOut } from "./merge-doing.js";
21
+ /**
22
+ * Carry what a run did to a copy back into the directory it is a copy of.
23
+ *
24
+ * @param stagedDir - the copy, as the run left it
25
+ * @param realDir - the directory it was copied from
26
+ * @param before - the copy as it was before the run (readTree)
27
+ * @param seed - the real directory as it was when the copy was made (copyTree)
28
+ * @param together - things that are one thing to the caller: each list the
29
+ * `id`s (see Entry) of the files, links and directories that are one
30
+ *
31
+ * What the run did is where the copy differs from what it was: a file, a
32
+ * directory or a link made, removed, changed, or put where something of
33
+ * another kind was; permissions changed — those of the directory itself
34
+ * among them, which is a directory like any in it: only that it is neither
35
+ * made nor removed. Each difference is carried over on
36
+ * one condition: the place in the real directory is still as it was when the
37
+ * copy was made — and so is the directory it is in. If not, somebody else —
38
+ * the user, another run of the same project — has been there since, and
39
+ * theirs is kept. A place that already holds what the run left needs nothing
40
+ * done, whoever made it so.
41
+ *
42
+ * There is no path this leaves out. Where the caller has itself put
43
+ * something into the real directory since the copy was made, it says so in
44
+ * `seed`: the place is then as the seed has it, and what the run did there is
45
+ * carried over like anything else.
46
+ *
47
+ * All of that is found out before anything is done. What cannot arrive is
48
+ * then left alone, with everything under it; and a directory the run removed,
49
+ * or put something else in the place of, goes only if all that is in it goes
50
+ * — if anything in it stays, or it holds something the run never saw, the
51
+ * directory stays whole. What the run moved — a file, a link, a directory —
52
+ * goes from where it was only if it arrives where the run moved it: what it
53
+ * holds is not to be in neither place. (What was moved is known by its `id`,
54
+ * see Entry. What the run copied and then removed is a new file, and is not
55
+ * known to be the old one's.) And what the caller says is one thing — a
56
+ * link, say, with the file that makes it lead somewhere: the things in one
57
+ * list of `together`, each known by what it is, at every path where the copy
58
+ * had it before the run or has it now — arrives together or not at all: if
59
+ * one of those paths is left alone, nothing is done at any of them. A part
60
+ * the run left as it was has nothing to arrive, but the rest leans on it: if
61
+ * it is not, in the project, as it was when the copy was made, that is told
62
+ * of it, and the rest does not arrive. (So that all this holds where the
63
+ * system refuses in the doing, what is done at such a path is only what can
64
+ * be taken back: a file there is not written into but has the new one put in
65
+ * its place, and what is to go from there is moved aside first, as what is
66
+ * taken the place of is. A directory among them that stays a directory is
67
+ * not left alone with the rest — what else the run did in it could not be
68
+ * taken for undone with it — but what it was to be left allowing does not
69
+ * arrive either, and that is told of it. And a part the run left as it was,
70
+ * and that is not so in the project, is told of besides, as that: nothing
71
+ * under it is left alone for it — and nothing is told of it where nothing is
72
+ * held back for it.) So what is returned as not arrived is as it
73
+ * was, at that path and under it. That holds where the system refuses, in
74
+ * the doing, what had been found possible — see how it is done, below — as
75
+ * long as it does not also refuse to put back what was moved aside; then
76
+ * the report says where that is.
77
+ *
78
+ * Some things are told of besides, which are not that. What was moved aside
79
+ * to go, or made ready and not needed, and which the system will not have
80
+ * removed, is told of at the name it is left under — a path that is none of
81
+ * the run's. A directory the run removed which the system will not remove,
82
+ * or not with all that was in it, holds what is left, as it would had the
83
+ * run removed it there, and is told of so. A directory or a file that could
84
+ * not be given, at the end, what it is to allow is told of for that: what
85
+ * it holds has arrived, unless that is told of itself. A file that could not
86
+ * be written into, and had a new one put in its place, is told of for that.
87
+ * (If the system will not have the new one put there either, the file did
88
+ * not arrive, and the report says that what it held may be damaged, and
89
+ * where what it was to hold is.)
90
+ *
91
+ * Finding out is looking, and a directory that is closed cannot be looked
92
+ * into. One of the real directory's — or the directory itself — is opened
93
+ * for it, as it is for what is then done in it, and one of the copy's is
94
+ * opened to be read: both are this merge's to open. Each is left, at the end,
95
+ * allowing what the run left it allowing — or, if that did not arrive, what
96
+ * it allowed. (One that somebody else gave other permissions since the copy
97
+ * was made is theirs, and is not opened: nothing is made or removed in it.)
98
+ *
99
+ * A path is a name, and the real directory has the last word on its names:
100
+ * its file system may take "Notes.txt" and "notes.txt" for one. A path of
101
+ * the tree whose place holds something, though the directory does not list
102
+ * the name as the tree spells it, is such a second spelling — the run
103
+ * spelled a name anew, or made one beside another on a file system that
104
+ * tells them apart. To a tree that is one entry removed and another made; in
105
+ * the real directory the two are one place, and removing the one would
106
+ * remove the other. Neither is touched: nothing is done to what is there
107
+ * under any name the run changed, and each is told of as not arrived. (What
108
+ * is there is known by what it is. All the names of a file that has several
109
+ * are therefore left, where one would have done.) If what is there is a
110
+ * directory, nothing is done in it either: a path through it is a path
111
+ * through the other, and what the run left under the two names is in one
112
+ * place. And two names the run made where nothing was, which the directory
113
+ * turns out to take for one when the second is put there: neither is put.
114
+ * (That can only be seen in the putting. If the first was not put, for a
115
+ * reason of its own, the second is — and what is told of the first is then
116
+ * true of the name as the run spelled it, not as the directory takes it.)
117
+ * The same is asked of the way to a path: a directory on it that the real
118
+ * one no longer lists as the tree spells it — somebody spelled it anew — is
119
+ * not the tree's directory any more, and nothing is done in it.
120
+ *
121
+ * What is to be done is done so that nothing is lost by its being done in
122
+ * part. A file or a link that is to be where something is, is made beside
123
+ * the place first. Then what the run made is made, a directory before what
124
+ * goes in it. What is in the place of it is not removed but moved aside,
125
+ * under a name of its own beside the place, and what was made beside the
126
+ * place is moved in. (Only a directory that stays a directory, and a file
127
+ * the run wrote into that can be written into, stay and are changed where
128
+ * they are. A file that is written into has what it is to hold made beside
129
+ * it first all the same: if the system will not have the writing — which it
130
+ * may have begun — that takes its place.) Where the system will not have a thing done, that
131
+ * thing is left alone like what was found impossible beforehand, with what
132
+ * follows from it — and what follows may be that something already done is
133
+ * not to stand: what the run moved from there did not arrive where it went.
134
+ * Then what was put there is removed again, and what was moved aside comes
135
+ * back. Only when all that is settled does what was moved aside go for good,
136
+ * and what the run removed, where it is. (A runner that is stopped in the
137
+ * middle leaves what it had moved aside, or made ready, where it is: under
138
+ * names that begin with .trama-tmp-.) It is where the run ended that is
139
+ * carried over, not the steps by which it got there.
140
+ *
141
+ * A file the run wrote into is written into, if it may be, and stays the
142
+ * file it is — as does one that holds what the run left already, and has
143
+ * only what it allows changed. Where the run put another file in the place,
144
+ * or the file may not be written into, or the system will not have it
145
+ * written into after all, a new one is put in its place — and then a second
146
+ * name of the old file is none of the new one, and holds whatever the
147
+ * writing left. A link is written as the run wrote it
148
+ * — the run took its copy for the directory itself — unless its way comes to
149
+ * the copy from outside: by the copy's full path, or out of the copy and
150
+ * back in by its name. What such a link says from there on is said of the
151
+ * real directory, wherever that leads from there. So a link the copy
152
+ * was given in other words than the directory's own (see copyTree), if the
153
+ * run moved it, is merged in those words: it names what the run found it to
154
+ * name, which is not always what the directory's own words would name from
155
+ * the new place. And a link the run made that climbs out of its directory
156
+ * with ".." and does not come back says the same in the real directory, and
157
+ * names from there what it names from there.
158
+ *
159
+ * Nothing is thrown. What could not be carried over is returned, each path
160
+ * with the reason, so that a run whose work did not all arrive is not passed
161
+ * off as one whose work did. Under a path that did not arrive, what was not
162
+ * looked at for that reason is not listed: it is as it was, with the path.
163
+ */
164
+ export function mergeTree(stagedDir, realDir, before, seed, together = []) {
165
+ let copy;
166
+ let real;
167
+ const after = new Map();
168
+ try {
169
+ real = realRootOf(realDir);
170
+ // The directory is the one that was copied — which the seed knows by what it is. Where it is gone, or another
171
+ // is at its path by now, there is nothing here that the run's work is the work on.
172
+ const itself = entryAt(real), copied = seed.get(ITSELF);
173
+ if (itself?.kind !== "dir")
174
+ return [{ path: ITSELF, why: "the project is no longer there; nothing was merged into it" }];
175
+ if (copied?.kind === "dir" && copied.id !== itself.id) {
176
+ return [{ path: ITSELF, why: "another directory is at the project's path than the one that was copied; nothing was merged into it" }];
177
+ }
178
+ }
179
+ catch (err) {
180
+ return [{ path: ITSELF, why: `the project could not be come to (${messageOf(err)}); nothing was merged into it` }];
181
+ }
182
+ try {
183
+ copy = realRootOf(stagedDir);
184
+ walk(copy, (path, entry, at) => {
185
+ after.set(path, entry); // as the run left it
186
+ if (entry.kind === "dir" && (entry.mode & 0o500) !== 0o500)
187
+ chmodSync(at, entry.mode | 0o500);
188
+ });
189
+ }
190
+ catch (err) {
191
+ // What the run left cannot be told. Nothing is merged — least of all as a removal of what cannot be seen.
192
+ return [{ path: ITSELF, why: `what the run left could not be read (${messageOf(err)}); none of it was merged` }];
193
+ }
194
+ const given = { copy, real, before, after, seed };
195
+ const changes = changesOf(before, after, together);
196
+ const told = telling();
197
+ const left = leftBy(given);
198
+ const doors = opening(real);
199
+ // --- What is to be done, found out before anything is ---
200
+ const { deeds, amiss } = deedsOf(given, changes, told, left, doors);
201
+ const settling = followingUp(deeds, amiss, given, changes, told);
202
+ // --- Doing it ---
203
+ carryOut(deeds, given, changes, told, left, doors, settling);
204
+ const { refused, besides } = told;
205
+ // What is told: what did not arrive, and what there is to say besides. (Every path that was left alone by
206
+ // itself, with its reason: where two of them are a directory and a path in it, each is the other's reason
207
+ // as often as not, and neither is left out for the other.)
208
+ return [...refused, ...besides].map(([path, why]) => ({ path, why }));
209
+ }
@@ -21,7 +21,9 @@
21
21
  // Three things are here: the one that asks (createModelRelay), and the two
22
22
  // ends of a channel between it and a session (relayClient, relayServer).
23
23
  import { randomUUID } from "crypto";
24
+ import { readFileSync } from "fs";
24
25
  import { createRequire } from "module";
26
+ import { join } from "path";
25
27
  import { pathToFileURL } from "url";
26
28
  import { onAbort } from "./abort.js";
27
29
  import { messageOf } from "./errors.js";
@@ -242,11 +244,35 @@ export function whole(event, state) {
242
244
  return { ...rest, partial };
243
245
  }
244
246
  // --- The one that asks ---
247
+ /**
248
+ * Where pi's own pi-ai keeps what it exports by a name: looked for where pi
249
+ * would look for the package (beside it, then in each `node_modules` above),
250
+ * and read from what the package says it exports to an `import`. Not by
251
+ * `require.resolve`: pi-ai is a package to be imported and nothing else, and
252
+ * asked for as one to be required it is not found — which is how nothing was
253
+ * let go of, with no word of it, in 0.6.0 and 0.6.1.
254
+ */
255
+ function inPisAi(name) {
256
+ const lookedIn = createRequire(import.meta.resolve("@earendil-works/pi-coding-agent")).resolve.paths("@earendil-works/pi-ai") ?? [];
257
+ for (const dir of lookedIn) {
258
+ const root = join(dir, "@earendil-works", "pi-ai");
259
+ let exported;
260
+ try {
261
+ exported = JSON.parse(readFileSync(join(root, "package.json"), "utf-8")).exports?.[name]?.import;
262
+ }
263
+ catch {
264
+ continue; // not here: pi's is further up
265
+ }
266
+ if (typeof exported === "string")
267
+ return join(root, exported);
268
+ break;
269
+ }
270
+ throw new Error(`pi-ai exports no ${name}`);
271
+ }
245
272
  /** What pi keeps for a session where its model is asked, let go of. (pi's own, had by its file: it is no part of what pi exports.) */
246
273
  async function letGoOf(sessions) {
247
274
  try {
248
- const kept = createRequire(import.meta.resolve("@earendil-works/pi-coding-agent")).resolve("@earendil-works/pi-ai/compat");
249
- const { cleanupSessionResources } = await import(pathToFileURL(kept).href);
275
+ const { cleanupSessionResources } = await import(pathToFileURL(inPisAi("./compat")).href);
250
276
  for (const session of sessions)
251
277
  cleanupSessionResources?.(session);
252
278
  }
@@ -266,6 +292,9 @@ export function createModelRelay() {
266
292
  async ask(request, signal) {
267
293
  let reply;
268
294
  const stop = new AbortController();
295
+ // (Cancelled before it was asked: nothing is asked.)
296
+ if (signal?.aborted)
297
+ return (async function* () { yield notAsked(request.model, "Aborted"); })();
269
298
  try {
270
299
  const found = await (models ??= loadPi().then(pi => pi.ModelRuntime.create()));
271
300
  const { provider, id } = request.model;
@@ -369,11 +398,12 @@ export function relayClient(send) {
369
398
  heard(answer) {
370
399
  if ("event" in answer)
371
400
  return add(answer.event);
372
- // (Not one the other end can serve: nothing was asked.)
401
+ // (Not one the other end can serve: nothing was asked. Said of a reply that had begun, it is the reply's end.)
402
+ if (begun)
403
+ return add(notAsked(request.model, "The process that was asking the model ended the reply before it was whole.", "error"));
373
404
  off();
374
405
  waiting.delete(id);
375
- if (!begun)
376
- resolve(undefined);
406
+ resolve(undefined);
377
407
  },
378
408
  end: () => add(notAsked(request.model, "The process that was asking the model ended before the reply had come.", "error")),
379
409
  });
@@ -0,0 +1,60 @@
1
+ import { type OwnTool, type ToolAnswer, type ToolImage } from "./agent-backend.js";
2
+ /**
3
+ * A tool of a program's, as the program declared it: all of it but the
4
+ * function — and what holds a use of it to the parameters it declared
5
+ * (returning the declared fields, or throwing what is wrong: see argumentsOf).
6
+ */
7
+ export type DeclaredTool = Omit<OwnTool, "run"> & {
8
+ held(args: unknown): unknown;
9
+ };
10
+ /**
11
+ * The images a tool answered with, as its program's client sent them: each
12
+ * its kind and its bytes in base64, and nothing else. (pi hands a model
13
+ * whatever it is given by that name; what is no image is refused here.)
14
+ */
15
+ export declare function imagesOf(given: unknown): ToolImage[] | undefined;
16
+ /**
17
+ * A call's `tools` as its program wrote them: the agent's own by name, and
18
+ * the program's, each read for what it declares. What is wrong with one is
19
+ * thrown, in words for whoever wrote it.
20
+ */
21
+ export declare function toolsOf(tools: unknown[]): {
22
+ names: string[];
23
+ declared: DeclaredTool[];
24
+ };
25
+ /**
26
+ * What a program is told while an agent call of its is under way: that a
27
+ * tool of its is called — `key` is how it says what the tool answered — or
28
+ * that one it is running is to go no further.
29
+ */
30
+ export type ToolEvent = {
31
+ key: string;
32
+ name: string;
33
+ args: unknown;
34
+ } | {
35
+ stop: string;
36
+ };
37
+ /** Writes down that a tool was asked, and returns what writes down its answer. */
38
+ type Recorder = (id: string, name: string, args: unknown) => (answer: ToolAnswer) => void;
39
+ export interface ToolAsks {
40
+ /**
41
+ * Open the way for the tools of one agent call, under the id its program
42
+ * gave it: the tools as the call's backend is to have them, each asking
43
+ * the program — and what closes the way, when the call is over.
44
+ */
45
+ open(of: string, declared: DeclaredTool[], record: Recorder): {
46
+ tools: OwnTool[];
47
+ close(): void;
48
+ };
49
+ /**
50
+ * The next thing the program is to hear of the tools of the call `of`.
51
+ * Null where there is to be none: the call is over — or whoever asked is
52
+ * gone (`gone`), and is told nothing.
53
+ */
54
+ next(of: string, gone: Promise<void>): Promise<ToolEvent | null>;
55
+ /** What the program says a tool answered. (Of a use nobody waits for any more, it is said to nobody.) */
56
+ answered(of: string, key: string, answer: ToolAnswer): void;
57
+ }
58
+ /** The tools of one program's agent calls: how each is asked, and how the program comes to hear of it. */
59
+ export declare function createToolAsks(): ToolAsks;
60
+ export {};
@@ -0,0 +1,209 @@
1
+ // A program's own tools, on the runner's side of the bridge.
2
+ //
3
+ // A program hands an agent call tools that are functions of its own. The
4
+ // functions stay where they are, in the program's process: what crosses the
5
+ // bridge with the call is what each is called and called with, and the
6
+ // runner makes of that a tool whose every use asks the program. The bridge
7
+ // only carries calls from a program to its runner, so the program asks for
8
+ // them: beside the agent call it makes another, which the runner holds until
9
+ // a tool of the call's is used, and it says what the tool answered by a third.
10
+ // Nothing listens in the program, and what a tool was asked and answered is
11
+ // seen where everything a program is told is seen.
12
+ import { IMAGE_KINDS, NOT_WAITED_FOR } from "./agent-backend.js";
13
+ import { argumentsOf } from "./schema.js";
14
+ import { onAbort } from "./abort.js";
15
+ import { messageOf } from "./errors.js";
16
+ import { describeJson, isJsonObject } from "./serializable.js";
17
+ /** What a tool's name may be: what every provider takes for one. */
18
+ const NAME = /^[A-Za-z0-9_-]{1,64}$/;
19
+ const DECLARED = ["name", "description", "parameters", "parallel", "ends"];
20
+ const IMAGES = new Set(IMAGE_KINDS);
21
+ /**
22
+ * The images a tool answered with, as its program's client sent them: each
23
+ * its kind and its bytes in base64, and nothing else. (pi hands a model
24
+ * whatever it is given by that name; what is no image is refused here.)
25
+ */
26
+ export function imagesOf(given) {
27
+ if (given == null)
28
+ return undefined;
29
+ const isImage = (image) => isJsonObject(image) && Object.keys(image).length === 2
30
+ && typeof image.mimeType === "string" && IMAGES.has(image.mimeType)
31
+ && typeof image.data === "string" && image.data !== "" && /^[A-Za-z0-9+/]*={0,2}$/.test(image.data);
32
+ if (!Array.isArray(given) || !given.every(isImage)) {
33
+ throw new Error(`Invalid field: images (expected a list of images, each its mimeType — ${[...IMAGES].join(", ")} — and its data, in base64)`);
34
+ }
35
+ return given.length > 0 ? given.map(({ mimeType, data }) => ({ mimeType, data })) : undefined;
36
+ }
37
+ /**
38
+ * A call's `tools` as its program wrote them: the agent's own by name, and
39
+ * the program's, each read for what it declares. What is wrong with one is
40
+ * thrown, in words for whoever wrote it.
41
+ */
42
+ export function toolsOf(tools) {
43
+ const names = [], declared = [];
44
+ // A tool of the program's is nobody else's by its name: not another of the program's, and not one of the
45
+ // agent's that the call names. (A name of the agent's said twice is the agent's tool twice named, which is
46
+ // the backend's to read — as a list of names and nothing else is.)
47
+ const own = new Set();
48
+ const take = (name) => {
49
+ if (own.has(name) || names.includes(name))
50
+ throw new Error(`Two tools are named ${JSON.stringify(name)}: a tool is called by its name`);
51
+ own.add(name);
52
+ };
53
+ for (const tool of tools) {
54
+ if (typeof tool === "string") {
55
+ if (own.has(tool))
56
+ throw new Error(`Two tools are named ${JSON.stringify(tool)}: a tool is called by its name`);
57
+ names.push(tool);
58
+ continue;
59
+ }
60
+ if (!isJsonObject(tool))
61
+ throw new Error(`A tool is a name, or an object with a name, a description and a run: not ${describeJson(tool)}`);
62
+ const { name, description, parameters, parallel, ends } = tool;
63
+ if (typeof name !== "string" || !NAME.test(name)) {
64
+ throw new Error(`A tool's name is letters, digits, "_" and "-", 64 of them at most: not ${typeof name === "string" ? JSON.stringify(name) : describeJson(name)}`);
65
+ }
66
+ const unknown = Object.keys(tool).find(field => !DECLARED.includes(field));
67
+ if (unknown !== undefined)
68
+ throw new Error(`The tool ${JSON.stringify(name)} has a field a tool does not take: ${unknown} (a tool takes: ${DECLARED.join(", ")}, run)`);
69
+ if (typeof description !== "string" || description.trim() === "") {
70
+ throw new Error(`The tool ${JSON.stringify(name)} has no description: it is all a model is told of what the tool is for`);
71
+ }
72
+ for (const [option, value] of Object.entries({ parallel, ends })) {
73
+ if (value != null && typeof value !== "boolean")
74
+ throw new Error(`The tool ${JSON.stringify(name)}: ${option} is true or false, not ${describeJson(value)}`);
75
+ }
76
+ let called;
77
+ try {
78
+ called = argumentsOf(parameters ?? {});
79
+ }
80
+ catch (err) {
81
+ throw new Error(`The tool ${JSON.stringify(name)}: ${messageOf(err)}`);
82
+ }
83
+ take(name);
84
+ declared.push({ name, description, parameters: called.schema, ...(parallel === true && { parallel }), ...(ends === true && { ends }), held: called.held });
85
+ }
86
+ return { names, declared };
87
+ }
88
+ /** How many calls that are over are remembered as that. */
89
+ const MAX_CLOSED = 1024;
90
+ /** The tools of one program's agent calls: how each is asked, and how the program comes to hear of it. */
91
+ export function createToolAsks() {
92
+ const ways = new Map();
93
+ /**
94
+ * The calls that are over, by their ids — the latest of them: whoever asks what is next of one is told
95
+ * that nothing is, and is not taken for one who asks ahead of a call to come.
96
+ */
97
+ const closed = new Set();
98
+ /** Whoever asked of a call that is not here yet: it and the asking were sent together, and either may be first. */
99
+ const early = new Map();
100
+ const tell = (way, event) => {
101
+ const waiting = way.waiting.shift();
102
+ if (waiting)
103
+ waiting(event);
104
+ else
105
+ way.events.push(event);
106
+ };
107
+ return {
108
+ open(of, declared, record) {
109
+ if (of === "")
110
+ throw new Error("Invalid field: toolsId (expected a non-empty string)");
111
+ if (ways.has(of) || closed.has(of))
112
+ throw new Error(`Duplicate toolsId: ${of}`);
113
+ const way = { events: [], waiting: [], pending: new Map(), uses: 0, closed: false };
114
+ ways.set(of, way);
115
+ for (const wake of early.get(of) ?? [])
116
+ wake();
117
+ early.delete(of);
118
+ const tools = declared.map(({ held, ...tool }) => ({
119
+ ...tool,
120
+ run: (given, id, signal) => new Promise((resolve) => {
121
+ if (way.closed || signal?.aborted)
122
+ return resolve(NOT_WAITED_FOR);
123
+ // A backend holds a model's call to the tool's parameters before it asks; what asks here may be
124
+ // somebody else's word of what a backend said (a process that serves the call, with other code in it).
125
+ // The program is asked with what its tool declared, or not at all.
126
+ let args;
127
+ try {
128
+ args = held(given);
129
+ }
130
+ catch (err) {
131
+ return resolve({ text: `The tool ${JSON.stringify(tool.name)} was called with what its parameters do not allow: ${messageOf(err).replace(/^Schema validation failed: /, "")}`, failed: true });
132
+ }
133
+ const key = String(++way.uses);
134
+ const answered = record(id, tool.name, args);
135
+ let off = () => { };
136
+ // (An answer the program gave is written down. One that was not waited for is no answer: such a use has none on record.)
137
+ way.pending.set(key, (answer) => {
138
+ way.pending.delete(key);
139
+ off();
140
+ if (answer)
141
+ answered(answer);
142
+ resolve(answer ?? NOT_WAITED_FOR);
143
+ });
144
+ off = onAbort(signal, () => {
145
+ const waiting = way.pending.get(key);
146
+ if (!waiting)
147
+ return;
148
+ waiting(null);
149
+ tell(way, { stop: key });
150
+ });
151
+ tell(way, { key, name: tool.name, args });
152
+ }),
153
+ }));
154
+ return {
155
+ tools,
156
+ close() {
157
+ // (A use that is still waiting for the program is waited for by nobody: its call is over. It has
158
+ // the answer of one that was not waited for, and none on record.)
159
+ way.closed = true;
160
+ ways.delete(of);
161
+ if (closed.size >= MAX_CLOSED)
162
+ closed.delete(closed.values().next().value);
163
+ closed.add(of);
164
+ for (const settle of [...way.pending.values()])
165
+ settle(null);
166
+ for (const waiting of way.waiting.splice(0))
167
+ waiting(null);
168
+ },
169
+ };
170
+ },
171
+ async next(of, gone) {
172
+ if (closed.has(of))
173
+ return null;
174
+ if (!ways.has(of)) {
175
+ const opened = await new Promise((resolve) => {
176
+ const wake = () => resolve(true);
177
+ const waiting = early.get(of) ?? new Set();
178
+ early.set(of, waiting.add(wake));
179
+ void gone.then(() => {
180
+ if (waiting.delete(wake) && waiting.size === 0 && early.get(of) === waiting)
181
+ early.delete(of);
182
+ resolve(false);
183
+ });
184
+ });
185
+ if (!opened)
186
+ return null;
187
+ }
188
+ const way = ways.get(of);
189
+ if (!way)
190
+ return null;
191
+ const told = way.events.shift();
192
+ if (told)
193
+ return told;
194
+ return new Promise((resolve) => {
195
+ way.waiting.push(resolve);
196
+ void gone.then(() => {
197
+ const at = way.waiting.indexOf(resolve);
198
+ if (at === -1)
199
+ return;
200
+ way.waiting.splice(at, 1);
201
+ resolve(null);
202
+ });
203
+ });
204
+ },
205
+ answered(of, key, answer) {
206
+ ways.get(of)?.pending.get(key)?.(answer);
207
+ },
208
+ };
209
+ }
@@ -19,6 +19,9 @@ import { dirname, isAbsolute, join, parse, resolve, sep } from "path";
19
19
  */
20
20
  const MAX_LINKS = 32;
21
21
  const tooManyLinks = (path) => new Error(`Too many levels of symbolic links: ${path}`);
22
+ /** Nothing lies beyond what is not a directory: the system refuses to go on from one, in these words. */
23
+ const notADirectory = (at, path) => Object.assign(new Error(`ENOTDIR: not a directory, ${at} (on the way to ${path})`), { code: "ENOTDIR" });
24
+ const saysNothing = (link) => new Error(`Path cannot be followed: ${link} (it links to nothing, or to what is not readable as text)`);
22
25
  /**
23
26
  * A step that is not a name: what the walk has come to must be a directory.
24
27
  * A path says so by ending in a slash. (It is not the same as a last step of
@@ -122,7 +125,7 @@ function follow(path, from, watch = {}) {
122
125
  // Nothing lies beyond a file — not a name, and not "." or ".." either.
123
126
  // The system refuses to go on, and so does this.
124
127
  if (!stat.isDirectory() && steps.length > 0) {
125
- throw Object.assign(new Error(`ENOTDIR: not a directory, ${next} (on the way to ${path})`), { code: "ENOTDIR" });
128
+ throw notADirectory(next, path);
126
129
  }
127
130
  at = next;
128
131
  continue;
@@ -134,16 +137,15 @@ function follow(path, from, watch = {}) {
134
137
  ({ at, missing } = instead);
135
138
  // As where a file is come to by a step: nothing lies beyond one.
136
139
  if (steps.length > 0 && !missing && !lstatSync(at).isDirectory()) {
137
- throw Object.assign(new Error(`ENOTDIR: not a directory, ${at} (on the way to ${path})`), { code: "ENOTDIR" });
140
+ throw notADirectory(at, path);
138
141
  }
139
142
  continue;
140
143
  }
141
144
  if (++links > MAX_LINKS)
142
145
  throw tooManyLinks(path);
143
146
  const target = linkText(next);
144
- if (target === undefined) {
145
- throw new Error(`Path cannot be followed: ${next} (it links to nothing, or to what is not readable as text)`);
146
- }
147
+ if (target === undefined)
148
+ throw saysNothing(next);
147
149
  if (isAbsolute(target))
148
150
  at = parse(target).root;
149
151
  steps = [...stepsOf(target), ...steps];
@@ -233,7 +235,7 @@ export function linksOf(root) {
233
235
  try {
234
236
  const text = linkText(link);
235
237
  if (text === undefined)
236
- throw new Error(`Path cannot be followed: ${link} (it links to nothing, or to what is not readable as text)`);
238
+ throw saysNothing(link);
237
239
  const { place } = lead(dirname(link), text);
238
240
  named.set(link, place);
239
241
  return place;
@@ -2,6 +2,28 @@ import { type AgentBackend, type AgentCall } from "./agent-backend.js";
2
2
  import type { ModelConfig } from "./runner-types.js";
3
3
  /** The pi version this runtime is built against (recorded in each project's meta.json). */
4
4
  export declare const piVersion: () => Promise<string>;
5
+ /** What an extension may have a hand in, of a request to a provider: a session where one does asks its model itself. */
6
+ export declare const HANDS_IN: string[];
7
+ /**
8
+ * What pi's agent has every request of its own go with, to be told of what
9
+ * a provider is sent and answers: pi's own, which do nothing where no
10
+ * extension has a hand in (HANDS_IN). A request that goes with all of them,
11
+ * by the way the agent asks, is one the agent makes for itself — or one made
12
+ * with all the agent's was made with, which is the same to a provider.
13
+ */
14
+ export declare const HOOKS: string[];
15
+ /**
16
+ * What else goes with a request the agent makes for itself, and is nothing
17
+ * a provider is handed: what the agent's loop calls as a turn goes, which pi
18
+ * passes along with what a provider is to have. (The functions of
19
+ * pi-agent-core's `createLoopConfig` that pi sets, less the hooks above. The
20
+ * rest of what a loop is set up by is data, and goes as any data.) Named,
21
+ * because it cannot be told otherwise: a function of the loop's is a
22
+ * function like one an asker might mean a provider to have. A pi whose loop
23
+ * is set up by a function more has its agent's requests asked where the call
24
+ * is served, until it is named here.
25
+ */
26
+ export declare const LOOPS: string[];
5
27
  /**
6
28
  * The pi coding agent: a fresh in-memory session for every call — in this
7
29
  * process, or in a process of its own (see agent-host.ts). A call that has