@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
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
+ }
@@ -17,6 +17,15 @@ export interface RelayRequest {
17
17
  by?: RelayWay;
18
18
  /** The model, as the session that asks has it. */
19
19
  model: RelayModel;
20
+ /**
21
+ * The model by name, "provider/model", where no session asks that has it:
22
+ * it is then the relay's own by that name — and where the relay has none
23
+ * such, has no key for it, or the model does not think as the request
24
+ * would have it, the reply says so, as one that was not asked for (see
25
+ * `unasked`). Such a request is never one for whoever sent it to ask
26
+ * itself: it has nothing to ask by.
27
+ */
28
+ named?: string;
20
29
  /** What the model is to be sent: as pi hands it to a provider. */
21
30
  context: unknown;
22
31
  /** The options of the request that are data (see `dataOf`). */
@@ -111,6 +120,16 @@ export declare function usageAtEnd(event: RelayEvent): ReplyUsage | undefined;
111
120
  * the conversation up — and a request that is not to be made is neither.)
112
121
  */
113
122
  export declare function notAsked(model: RelayModel, why: string, as?: "aborted" | "error"): RelayEvent;
123
+ /** Why a model that was asked for by name was not asked: which of the things a request by name is refused for. */
124
+ export type Unasked = "model" | "key" | "thinking";
125
+ /**
126
+ * A model by the name a call gives it, "provider/model", among those `models`
127
+ * has: the provider's name ends at a stroke, and either name may have more of
128
+ * them — so each stroke is tried, the first first.
129
+ */
130
+ export declare function modelNamed<M>(models: {
131
+ getModel(provider: string, id: string): M | undefined;
132
+ }, name: string): M | undefined;
114
133
  /**
115
134
  * Makes of a reply's events the events as they are sent: without the reply
116
135
  * so far. (One for each reply: it keeps how much of each tool call has been
@@ -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";
@@ -174,6 +176,33 @@ export function notAsked(model, why, as = "aborted") {
174
176
  },
175
177
  };
176
178
  }
179
+ /** The reply of a request by name that was not made (see RelayRequest.named): one event, that says why — and of which kind the reason is. */
180
+ async function* unasked(model, kind, why) {
181
+ yield { ...notAsked(model, why, "error"), unasked: kind };
182
+ }
183
+ /**
184
+ * A model by the name a call gives it, "provider/model", among those `models`
185
+ * has: the provider's name ends at a stroke, and either name may have more of
186
+ * them — so each stroke is tried, the first first.
187
+ */
188
+ export function modelNamed(models, name) {
189
+ for (const { index } of name.matchAll(/\//g)) {
190
+ const model = models.getModel(name.slice(0, index), name.slice(index + 1));
191
+ if (model)
192
+ return model;
193
+ }
194
+ return undefined;
195
+ }
196
+ /** The levels a model thinks at, as pi-ai has them of it. (pi-ai's own, had by its file: pi hands it to nobody.) */
197
+ async function levelsOf(model) {
198
+ try {
199
+ const { getSupportedThinkingLevels } = await import(pathToFileURL(inPisAi("./models")).href);
200
+ return getSupportedThinkingLevels?.(model);
201
+ }
202
+ catch {
203
+ return undefined;
204
+ }
205
+ }
177
206
  // --- An event without the reply so far, and with it again ---
178
207
  // Every event of a reply but the last carries `partial`: the whole reply so
179
208
  // far. Sent as they are, a reply's events grow with the square of its length.
@@ -242,11 +271,35 @@ export function whole(event, state) {
242
271
  return { ...rest, partial };
243
272
  }
244
273
  // --- The one that asks ---
274
+ /**
275
+ * Where pi's own pi-ai keeps what it exports by a name: looked for where pi
276
+ * would look for the package (beside it, then in each `node_modules` above),
277
+ * and read from what the package says it exports to an `import`. Not by
278
+ * `require.resolve`: pi-ai is a package to be imported and nothing else, and
279
+ * asked for as one to be required it is not found — which is how nothing was
280
+ * let go of, with no word of it, in 0.6.0 and 0.6.1.
281
+ */
282
+ function inPisAi(name) {
283
+ const lookedIn = createRequire(import.meta.resolve("@earendil-works/pi-coding-agent")).resolve.paths("@earendil-works/pi-ai") ?? [];
284
+ for (const dir of lookedIn) {
285
+ const root = join(dir, "@earendil-works", "pi-ai");
286
+ let exported;
287
+ try {
288
+ exported = JSON.parse(readFileSync(join(root, "package.json"), "utf-8")).exports?.[name]?.import;
289
+ }
290
+ catch {
291
+ continue; // not here: pi's is further up
292
+ }
293
+ if (typeof exported === "string")
294
+ return join(root, exported);
295
+ break;
296
+ }
297
+ throw new Error(`pi-ai exports no ${name}`);
298
+ }
245
299
  /** 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
300
  async function letGoOf(sessions) {
247
301
  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);
302
+ const { cleanupSessionResources } = await import(pathToFileURL(inPisAi("./compat")).href);
250
303
  for (const session of sessions)
251
304
  cleanupSessionResources?.(session);
252
305
  }
@@ -266,6 +319,9 @@ export function createModelRelay() {
266
319
  async ask(request, signal) {
267
320
  let reply;
268
321
  const stop = new AbortController();
322
+ // (Cancelled before it was asked: nothing is asked.)
323
+ if (signal?.aborted)
324
+ return (async function* () { yield notAsked(request.model, "Aborted"); })();
269
325
  try {
270
326
  const found = await (models ??= loadPi().then(pi => pi.ModelRuntime.create()));
271
327
  const { provider, id } = request.model;
@@ -274,14 +330,39 @@ export function createModelRelay() {
274
330
  const way = WAYS.get(by);
275
331
  if (!way)
276
332
  return undefined;
277
- const own = way.of === "chat" ? found.getModel(provider, id) : found.getModelOfType(way.of, provider, id);
278
- // The same model, to the letter, with a key to ask it by — and a provider nobody has had a hand in.
279
- if (!own || JSON.stringify(own) !== JSON.stringify(request.model) || !found.hasConfiguredAuth(provider))
280
- return undefined;
281
333
  // (What goes with a request is held to here as where it was sent from: whoever sent it may not be who should have.)
282
334
  const options = dataOf(request.options);
283
335
  if (!options)
284
336
  return undefined;
337
+ let own;
338
+ if (request.named !== undefined) {
339
+ // By name: this relay's own model of that name, or none — and what stands against asking it is said.
340
+ const name = request.named;
341
+ const mine = way.of === "chat" ? modelNamed(found, name) : undefined;
342
+ if (!mine)
343
+ return unasked(request.model, "model", `Unknown model "${name}". A model is named "provider/model", as pi's model catalog has it.`);
344
+ if (!found.hasConfiguredAuth(mine.provider))
345
+ return unasked(request.model, "key", `The model ${name} cannot be asked: pi has no key for the provider "${mine.provider}".`);
346
+ if (options.reasoning !== undefined) {
347
+ // (pi gives the level it has that is nearest, without a word: a request is to have what it asked for, or fail.)
348
+ const levels = await levelsOf(mine);
349
+ if (!levels)
350
+ return unasked(request.model, "thinking", `Whether the model ${name} thinks at level "${String(options.reasoning)}" cannot be told: pi's list of a model's levels was not found.`);
351
+ if (!levels.includes(String(options.reasoning))) {
352
+ return unasked(request.model, "thinking", `The model ${name} does not think at level "${String(options.reasoning)}". Its levels: ${levels.join(", ")}.`);
353
+ }
354
+ // (Not at all is how a model is asked without a word of it.)
355
+ if (options.reasoning === "off")
356
+ delete options.reasoning;
357
+ }
358
+ own = mine;
359
+ }
360
+ else {
361
+ own = way.of === "chat" ? found.getModel(provider, id) : found.getModelOfType(way.of, provider, id);
362
+ // The same model, to the letter, with a key to ask it by — and a provider nobody has had a hand in.
363
+ if (!own || JSON.stringify(own) !== JSON.stringify(request.model) || !found.hasConfiguredAuth(provider))
364
+ return undefined;
365
+ }
285
366
  if (typeof options.sessionId === "string")
286
367
  sessions.add(options.sessionId);
287
368
  // (pi's models, asked by the name of the way: each takes the model, what it is to be sent, and the options.)
@@ -369,11 +450,12 @@ export function relayClient(send) {
369
450
  heard(answer) {
370
451
  if ("event" in answer)
371
452
  return add(answer.event);
372
- // (Not one the other end can serve: nothing was asked.)
453
+ // (Not one the other end can serve: nothing was asked. Said of a reply that had begun, it is the reply's end.)
454
+ if (begun)
455
+ return add(notAsked(request.model, "The process that was asking the model ended the reply before it was whole.", "error"));
373
456
  off();
374
457
  waiting.delete(id);
375
- if (!begun)
376
- resolve(undefined);
458
+ resolve(undefined);
377
459
  },
378
460
  end: () => add(notAsked(request.model, "The process that was asking the model ended before the reply had come.", "error")),
379
461
  });
@@ -0,0 +1,9 @@
1
+ import { type ModelAsk } from "./agent-backend.js";
2
+ /** What a request may hold, as a program names it. */
3
+ export declare const REQUEST_FIELDS: readonly ["messages", "system", "tools", "model", "thinking", "maxTokens", "temperature", "toolChoice", "timeout"];
4
+ /**
5
+ * A request as a program gave it, held to what one is: returns it as a
6
+ * backend is handed it. Throws with what is wrong, in words for whoever
7
+ * wrote it. (What is given as null is not given: it is how JSON says so.)
8
+ */
9
+ export declare function requestOf(given: unknown): ModelAsk;
@@ -0,0 +1,185 @@
1
+ // One request to a model, as a program makes it — held to its shape.
2
+ //
3
+ // A program that is its own harness keeps the conversation and asks a model
4
+ // one reply at a time (`agent.complete`). What it asks with comes over the
5
+ // bridge as JSON, and nothing behind the bridge holds it to anything: pi sends
6
+ // a provider what it is handed, and a conversation that is none comes back as
7
+ // the provider's complaint, or as pi's own failure half-way through reading
8
+ // it. So it is read here first, and what is wrong with it is said in the
9
+ // program's words — which message, which part, what was expected.
10
+ //
11
+ // What a program writes is three kinds of message: the user's, a tool's
12
+ // result, and a reply — the last as `complete` returned it, and sent back as
13
+ // it came: a reply holds what its provider needs to see again (a signature on
14
+ // what the model thought, an id of its own), and none of that is a program's
15
+ // to know or to mend. Of a reply only what could not be one is refused.
16
+ import { IMAGE_KINDS } from "./agent-backend.js";
17
+ import { messageOf } from "./errors.js";
18
+ import { toolsOf } from "./own-tools.js";
19
+ import { isJsonObject } from "./serializable.js";
20
+ /** What a request may hold, as a program names it. */
21
+ export const REQUEST_FIELDS = ["messages", "system", "tools", "model", "thinking", "maxTokens", "temperature", "toolChoice", "timeout"];
22
+ /** A value as it is said back to whoever gave it: what it is, where that is short to say — or what kind of thing. */
23
+ function got(value) {
24
+ if (typeof value === "string")
25
+ return JSON.stringify(value.length > 60 ? `${value.slice(0, 60)}…` : value);
26
+ if (typeof value === "number" || typeof value === "boolean")
27
+ return String(value);
28
+ if (Array.isArray(value))
29
+ return value.length === 0 ? "an empty list" : "a list";
30
+ return value === null ? "null" : typeof value === "object" ? "an object" : typeof value;
31
+ }
32
+ /** A field a thing does not take, if it has one. */
33
+ const beside = (given, takes) => Object.keys(given).find(field => !takes.includes(field));
34
+ const IMAGES = new Set(IMAGE_KINDS);
35
+ const BASE64 = /^[A-Za-z0-9+/]+={0,2}$/;
36
+ /** What a user's message says, or a tool's result: text, or parts of text and images — as it is to be sent. */
37
+ function saidOf(content, at) {
38
+ if (typeof content === "string")
39
+ return content;
40
+ if (!Array.isArray(content) || content.length === 0)
41
+ throw new Error(`${at} is text, or a list of parts — text and images: got ${got(content)}`);
42
+ return content.map((part, index) => {
43
+ const here = `${at}[${index}]`;
44
+ const isPart = isJsonObject(part) && (part.type === "text" || part.type === "image");
45
+ if (!isPart) {
46
+ throw new Error(`${here} is a part — { type: "text", text } or { type: "image", mimeType, data }: got ${isJsonObject(part) && part.type !== undefined ? `one of type ${got(part.type)}` : got(part)}`);
47
+ }
48
+ if (part.type === "text") {
49
+ if (typeof part.text !== "string")
50
+ throw new Error(`${here}.text is text: got ${got(part.text)}`);
51
+ const more = beside(part, ["type", "text"]);
52
+ if (more !== undefined)
53
+ throw new Error(`${here} has a field a part of text does not take: ${more} (it takes: type, text)`);
54
+ return { type: "text", text: part.text };
55
+ }
56
+ const { mimeType, data } = part;
57
+ if (typeof mimeType !== "string" || !IMAGES.has(mimeType) || typeof data !== "string" || !BASE64.test(data) || beside(part, ["type", "mimeType", "data"]) !== undefined) {
58
+ throw new Error(`${here} is an image of a kind a model is shown — ${IMAGE_KINDS.join(", ")} — with its data in base64`);
59
+ }
60
+ return { type: "image", mimeType, data };
61
+ });
62
+ }
63
+ /** A reply, as it came: held to nothing but what every reply is. */
64
+ function replyOf(message, at) {
65
+ const { content } = message;
66
+ if (!Array.isArray(content))
67
+ throw new Error(`${at}.content is a reply's parts, as the reply came: got ${got(content)}`);
68
+ for (const [index, part] of content.entries()) {
69
+ const here = `${at}.content[${index}]`;
70
+ if (!isJsonObject(part))
71
+ throw new Error(`${here} is a part of a reply, as the reply came: got ${got(part)}`);
72
+ if (typeof part.type !== "string")
73
+ throw new Error(`${here} is a part of a reply, as the reply came: it has no type`);
74
+ if (part.type === "toolCall" && (typeof part.id !== "string" || typeof part.name !== "string" || !isJsonObject(part.arguments))) {
75
+ throw new Error(`${here} is a tool's call — its id, the tool's name, and its arguments — as the reply came`);
76
+ }
77
+ }
78
+ return message;
79
+ }
80
+ const ROLES = `"user", "assistant" or "toolResult"`;
81
+ function messageOfAConversation(message, at) {
82
+ if (!isJsonObject(message))
83
+ throw new Error(`${at} is a message — from the user, a reply as it came, or a tool's result: got ${got(message)}`);
84
+ const { role } = message;
85
+ if (role === "user") {
86
+ const content = saidOf(message.content, `${at}.content`);
87
+ const more = beside(message, ["role", "content"]);
88
+ if (more !== undefined)
89
+ throw new Error(`${at} has a field a user's message does not take: ${more} (it takes: role, content)`);
90
+ return { role, content };
91
+ }
92
+ if (role === "assistant")
93
+ return replyOf(message, at);
94
+ if (role === "toolResult") {
95
+ const { toolCallId, toolName, isError } = message;
96
+ if (typeof toolCallId !== "string" || toolCallId === "")
97
+ throw new Error(`${at}.toolCallId is the id of the call it answers, as the reply had it: got ${got(toolCallId)}`);
98
+ if (typeof toolName !== "string" || toolName === "")
99
+ throw new Error(`${at}.toolName is the name of the tool that was called: got ${got(toolName)}`);
100
+ const said = saidOf(message.content, `${at}.content`);
101
+ if (isError != null && typeof isError !== "boolean")
102
+ throw new Error(`${at}.isError is true or false: got ${got(isError)}`);
103
+ const more = beside(message, ["role", "toolCallId", "toolName", "content", "isError"]);
104
+ if (more !== undefined)
105
+ throw new Error(`${at} has a field a tool's result does not take: ${more} (it takes: role, toolCallId, toolName, content, isError)`);
106
+ // (As a provider is sent one: its words as parts, and whether it failed said either way.)
107
+ return { role, toolCallId, toolName, content: typeof said === "string" ? [{ type: "text", text: said }] : said, isError: isError === true };
108
+ }
109
+ throw new Error(`${at}: a message's role is ${ROLES}, not ${got(role)}${role === "system" ? " (what a model is told to be is the request's `system`)" : ""}`);
110
+ }
111
+ /** The tools a model is told of: each declared, as a program declares a tool of its own to an agent — and none named. */
112
+ function declaredOf(tools) {
113
+ if (!Array.isArray(tools))
114
+ throw new Error(`tools is a list of tools, each declared: got ${got(tools)}`);
115
+ const named = tools.findIndex(tool => typeof tool === "string");
116
+ if (named !== -1) {
117
+ throw new Error(`tools[${named}]: a tool is declared here — its name, its description, its parameters — and not named: no agent is asked, whose tool ${JSON.stringify(tools[named])} would be`);
118
+ }
119
+ try {
120
+ // (Whether one may run beside another, or ends anything, is a question for whoever runs tools: here nobody does.)
121
+ return toolsOf(tools).declared.map(({ name, description, parameters }) => ({ name, description, parameters }));
122
+ }
123
+ catch (err) {
124
+ throw new Error(`tools: ${messageOf(err)}`);
125
+ }
126
+ }
127
+ /**
128
+ * A request as a program gave it, held to what one is: returns it as a
129
+ * backend is handed it. Throws with what is wrong, in words for whoever
130
+ * wrote it. (What is given as null is not given: it is how JSON says so.)
131
+ */
132
+ export function requestOf(given) {
133
+ if (!isJsonObject(given))
134
+ throw new Error(`a request is an object — the conversation so far (messages), and what goes with it: got ${got(given)}`);
135
+ const unknown = beside(given, REQUEST_FIELDS);
136
+ if (unknown !== undefined)
137
+ throw new Error(`a request has no ${unknown}: it has ${REQUEST_FIELDS.join(", ")}`);
138
+ const { messages, system, tools, model, thinking, maxTokens, temperature, toolChoice, timeout } = given;
139
+ if (!Array.isArray(messages) || messages.length === 0)
140
+ throw new Error(`messages is the conversation so far, a list of messages with at least one in it: got ${got(messages)}`);
141
+ const context = { messages: messages.map((message, index) => messageOfAConversation(message, `messages[${index}]`)) };
142
+ if (system != null) {
143
+ if (typeof system !== "string")
144
+ throw new Error(`system is text: got ${got(system)}`);
145
+ context.systemPrompt = system;
146
+ }
147
+ if (tools != null) {
148
+ const declared = declaredOf(tools);
149
+ if (declared.length > 0)
150
+ context.tools = declared;
151
+ }
152
+ const asked = { context };
153
+ if (model != null) {
154
+ // (Which of its strokes parts the provider from the model is for whoever has the models to say.)
155
+ if (typeof model !== "string" || !/^[^/]+\/./.test(model))
156
+ throw new Error(`model is a model by name, "provider/model": got ${got(model)}`);
157
+ asked.model = model;
158
+ }
159
+ if (thinking != null) {
160
+ if (typeof thinking !== "string" || thinking === "")
161
+ throw new Error(`thinking is a level by name: got ${got(thinking)}`);
162
+ asked.thinking = thinking;
163
+ }
164
+ if (maxTokens != null) {
165
+ if (typeof maxTokens !== "number" || !Number.isInteger(maxTokens) || maxTokens <= 0)
166
+ throw new Error(`maxTokens is a whole number above 0: got ${got(maxTokens)}`);
167
+ asked.maxTokens = maxTokens;
168
+ }
169
+ if (temperature != null) {
170
+ if (typeof temperature !== "number" || !Number.isFinite(temperature) || temperature < 0)
171
+ throw new Error(`temperature is a number that is not negative: got ${got(temperature)}`);
172
+ asked.temperature = temperature;
173
+ }
174
+ if (toolChoice != null) {
175
+ if (toolChoice !== "auto" && toolChoice !== "none")
176
+ throw new Error(`toolChoice is "auto" or "none": got ${got(toolChoice)}`);
177
+ asked.toolChoice = toolChoice;
178
+ }
179
+ if (timeout != null) {
180
+ if (typeof timeout !== "number" || !Number.isFinite(timeout) || timeout <= 0)
181
+ throw new Error(`timeout is milliseconds, a number above 0: got ${got(timeout)}`);
182
+ asked.timeout = timeout;
183
+ }
184
+ return asked;
185
+ }
@@ -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 {};