@trama-dev/runtime 0.6.0 → 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 (57) 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.d.ts +63 -5
  33. package/dist/model-relay.js +206 -23
  34. package/dist/own-tools.d.ts +60 -0
  35. package/dist/own-tools.js +209 -0
  36. package/dist/path-guard.js +8 -6
  37. package/dist/pi-adapter.d.ts +22 -0
  38. package/dist/pi-adapter.js +294 -72
  39. package/dist/project.d.ts +31 -0
  40. package/dist/project.js +253 -0
  41. package/dist/replace-file.d.ts +13 -2
  42. package/dist/replace-file.js +23 -6
  43. package/dist/runner-backend.d.ts +43 -0
  44. package/dist/runner-backend.js +125 -0
  45. package/dist/runner-types.d.ts +8 -0
  46. package/dist/runner.d.ts +8 -123
  47. package/dist/runner.js +57 -453
  48. package/dist/schema.d.ts +38 -0
  49. package/dist/schema.js +104 -0
  50. package/dist/stopping.js +2 -3
  51. package/dist/tools.js +31 -7
  52. package/dist/tree.d.ts +33 -149
  53. package/dist/tree.js +43 -1077
  54. package/dist/types.d.ts +54 -2
  55. package/dist/workspace.d.ts +20 -0
  56. package/dist/workspace.js +76 -12
  57. 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
+ }
@@ -4,8 +4,17 @@ export type RelayModel = {
4
4
  id: string;
5
5
  api?: string;
6
6
  } & Record<string, unknown>;
7
+ /**
8
+ * The ways pi has of asking a model, that a relay asks by: for a reply, as
9
+ * pi's agent asks (by options that are any provider's) or by the options of
10
+ * the model's own provider; for images; for what a classifier makes of a
11
+ * state. Each is a method of pi's models by that name.
12
+ */
13
+ export type RelayWay = "streamSimple" | "stream" | "generateImages" | "classify";
7
14
  /** A request of a model: plain data, all of it. */
8
15
  export interface RelayRequest {
16
+ /** The way the model is asked: as pi's agent asks, where it is not said. */
17
+ by?: RelayWay;
9
18
  /** The model, as the session that asks has it. */
10
19
  model: RelayModel;
11
20
  /** What the model is to be sent: as pi hands it to a provider. */
@@ -15,7 +24,13 @@ export interface RelayRequest {
15
24
  /** Whether it is asked beside a call that is over — one that has its answer, or has failed (see AgentCall.sofar). */
16
25
  answered?: true;
17
26
  }
18
- /** An event of a reply, as pi's stream of it has them. The last is of type "done" or "error", and has the reply whole. */
27
+ /**
28
+ * An event of a reply, as pi's stream of it has them. The last is of type
29
+ * "done" or "error", and has the reply whole. What comes all at once —
30
+ * images, a classifier's answers — comes as a reply of one event, "done",
31
+ * with it as its `message`: so that it is counted, and waited for, as any
32
+ * reply is (see `wholeOf`).
33
+ */
19
34
  export type RelayEvent = {
20
35
  type: string;
21
36
  } & Record<string, unknown>;
@@ -28,12 +43,54 @@ export interface ModelRelay {
28
43
  ask(request: RelayRequest, signal?: AbortSignal): Promise<AsyncIterable<RelayEvent> | undefined>;
29
44
  }
30
45
  /**
31
- * Of the options a session asks with, those that go with a relayed request —
32
- * or undefined where one is there that cannot go, and would be missed: a key
33
- * of the asker's own, a way of its own to reach the provider, a reply that is
34
- * to be fetched later.
46
+ * Whether a value is data: what it is on the other side of a channel is what
47
+ * it is here. Text, numbers that are numbers, yes and no, nothing; and lists
48
+ * and plain records of those. Not a function, nor anything that is of a kind
49
+ * of its own (a date, a signal, bytes; a list or a record that is more than
50
+ * one), nor what holds itself, nor what says of itself something other than
51
+ * it shows. (What a record has by a symbol, or has and does not show, is no
52
+ * part of it on any channel, and a provider is sent none of it either: pi's
53
+ * schemas have such.)
54
+ */
55
+ export declare function isData(value: unknown, within?: Set<object>): boolean;
56
+ /**
57
+ * The options a session asks with, as those that go with a relayed request —
58
+ * or undefined where one is there that cannot go, and would be missed.
59
+ *
60
+ * What goes is whatever is data, by whatever name: a provider's own options
61
+ * are its own, and are not known here by name. What cannot go: a key of the
62
+ * asker's own, a way of its own to reach the provider, a span to report to,
63
+ * a reply that is to be fetched later (it is fetched where it was asked
64
+ * for) — and anything else that is not data: a provider may read whatever
65
+ * it is given, and what goes with a request is its asker's to mean something
66
+ * by. (What whoever hands a request over knows to be nothing a provider is
67
+ * handed, they leave out first: see `account`, pi-adapter.ts.) The word to
68
+ * stop by is no option here: it goes beside the request.
35
69
  */
36
70
  export declare function dataOf(options?: Record<string, unknown>): Record<string, unknown> | undefined;
71
+ /**
72
+ * Data as it goes on a channel, where a record in it has nothing under a
73
+ * name. A channel carries no such name — and to have nothing under a name is
74
+ * not to be without it, where records are laid one over another, name by
75
+ * name and in the order of their names (as pi lays a request's headers, and
76
+ * what a model is sampled by, over the model's own). So a word is put under
77
+ * each such name, that is nothing else: said beside the data (`mark`), and
78
+ * taken out again where the data is had (`unmarked`). The name then stands
79
+ * where it stood, with nothing under it.
80
+ */
81
+ export declare function marked<T>(data: T): {
82
+ data: T;
83
+ mark?: string;
84
+ };
85
+ /** Data that came by a channel (see `marked`), with nothing under the names of its records that the mark is under. (In a list the mark is a word like any: nothing is ever marked there.) */
86
+ export declare function unmarked<T>(data: T, mark: unknown): T;
87
+ /**
88
+ * What came of asking a model, of a reply that is gone through to its end:
89
+ * the reply whole — or, of a request that failed before it was one, its
90
+ * failure thrown (as pi's own `generateImages` and `classify` have what a
91
+ * provider throws, and make of it what they give back).
92
+ */
93
+ export declare function wholeOf(reply: AsyncIterable<RelayEvent>): Promise<unknown>;
37
94
  /** What a reply used, as pi has it on the reply. */
38
95
  export interface ReplyUsage {
39
96
  input: number;
@@ -87,6 +144,7 @@ export type RelayAsked = {
87
144
  relay: {
88
145
  id: number;
89
146
  request: RelayRequest;
147
+ mark?: string;
90
148
  };
91
149
  } | {
92
150
  relayAbort: number;
@@ -14,29 +14,144 @@
14
14
  // asks its model itself, as it always did — and what it used is what its
15
15
  // process says. This is not a wall: pi does not hold an extension to it.
16
16
  //
17
+ // A model: one that is asked for a reply as pi's agent asks, or by its
18
+ // provider's own options (which is how an extension asks that would have the
19
+ // whole answer: pi's `complete`), one that makes images, one that classifies.
20
+ //
17
21
  // Three things are here: the one that asks (createModelRelay), and the two
18
22
  // ends of a channel between it and a session (relayClient, relayServer).
23
+ import { randomUUID } from "crypto";
24
+ import { readFileSync } from "fs";
19
25
  import { createRequire } from "module";
26
+ import { join } from "path";
20
27
  import { pathToFileURL } from "url";
21
28
  import { onAbort } from "./abort.js";
22
29
  import { messageOf } from "./errors.js";
23
30
  const loadPi = () => import("@earendil-works/pi-coding-agent");
24
- /** The options of a request that are data, and mean something to a provider. (The rest is pi's agent's own, and functions.) */
25
- const DATA_OPTIONS = [
26
- "temperature", "samplingParams", "maxTokens", "transport", "cacheRetention", "sessionId", "disableContinuation",
27
- "websocketConnectTimeoutMs", "metadata", "toolChoice", "reasoning", "thinkingBudgets", "env", "headers", "identity",
28
- "timeoutMs", "maxRetries", "maxRetryDelayMs",
29
- ];
31
+ /** Of each way: the type of model it asks, as pi's catalog has them — and whether what comes of it comes as the events of a reply (and not all at once). */
32
+ const WAYS = new Map([
33
+ ["streamSimple", { of: "chat", events: true }],
34
+ ["stream", { of: "chat", events: true }],
35
+ ["generateImages", { of: "image", events: false }],
36
+ ["classify", { of: "classifier", events: false }],
37
+ ]);
30
38
  /**
31
- * Of the options a session asks with, those that go with a relayed request —
32
- * or undefined where one is there that cannot go, and would be missed: a key
33
- * of the asker's own, a way of its own to reach the provider, a reply that is
34
- * to be fetched later.
39
+ * Whether a value is data: what it is on the other side of a channel is what
40
+ * it is here. Text, numbers that are numbers, yes and no, nothing; and lists
41
+ * and plain records of those. Not a function, nor anything that is of a kind
42
+ * of its own (a date, a signal, bytes; a list or a record that is more than
43
+ * one), nor what holds itself, nor what says of itself something other than
44
+ * it shows. (What a record has by a symbol, or has and does not show, is no
45
+ * part of it on any channel, and a provider is sent none of it either: pi's
46
+ * schemas have such.)
47
+ */
48
+ export function isData(value, within = new Set()) {
49
+ if (value === null || typeof value === "string" || typeof value === "boolean")
50
+ return true;
51
+ if (typeof value === "number")
52
+ return Number.isFinite(value);
53
+ if (typeof value !== "object" || within.has(value))
54
+ return false;
55
+ // (A list or a record, and of no kind of its own: nor one that would be said otherwise than it shows.)
56
+ const kind = Object.getPrototypeOf(value);
57
+ if (Array.isArray(value) ? kind !== Array.prototype : kind !== Object.prototype && kind !== null)
58
+ return false;
59
+ if (typeof value.toJSON === "function")
60
+ return false;
61
+ within.add(value);
62
+ try {
63
+ // (A place of a list that has nothing is something else on the other side; a name of a record that has nothing is no
64
+ // name there. A list is gone through place by place, as a channel goes through it — not as it would have itself gone through.)
65
+ if (Array.isArray(value))
66
+ return Array.from({ length: value.length }, (_, at) => value[at]).every(one => isData(one, within));
67
+ return Object.values(value).every(one => one === undefined || isData(one, within));
68
+ }
69
+ finally {
70
+ within.delete(value);
71
+ }
72
+ }
73
+ /**
74
+ * The options a session asks with, as those that go with a relayed request —
75
+ * or undefined where one is there that cannot go, and would be missed.
76
+ *
77
+ * What goes is whatever is data, by whatever name: a provider's own options
78
+ * are its own, and are not known here by name. What cannot go: a key of the
79
+ * asker's own, a way of its own to reach the provider, a span to report to,
80
+ * a reply that is to be fetched later (it is fetched where it was asked
81
+ * for) — and anything else that is not data: a provider may read whatever
82
+ * it is given, and what goes with a request is its asker's to mean something
83
+ * by. (What whoever hands a request over knows to be nothing a provider is
84
+ * handed, they leave out first: see `account`, pi-adapter.ts.) The word to
85
+ * stop by is no option here: it goes beside the request.
35
86
  */
36
87
  export function dataOf(options = {}) {
37
88
  if (["apiKey", "fetch", "telemetry", "deferred"].some(key => options[key] !== undefined))
38
89
  return undefined;
39
- return Object.fromEntries(DATA_OPTIONS.filter(key => options[key] !== undefined).map(key => [key, options[key]]));
90
+ const data = Object.entries(options).filter(([key]) => key !== "signal");
91
+ if (data.some(([, value]) => value !== undefined && !isData(value)))
92
+ return undefined;
93
+ // (Each under its own name, whatever the name: none of them is taken for anything else.)
94
+ return Object.fromEntries(data);
95
+ }
96
+ /**
97
+ * Data as it goes on a channel, where a record in it has nothing under a
98
+ * name. A channel carries no such name — and to have nothing under a name is
99
+ * not to be without it, where records are laid one over another, name by
100
+ * name and in the order of their names (as pi lays a request's headers, and
101
+ * what a model is sampled by, over the model's own). So a word is put under
102
+ * each such name, that is nothing else: said beside the data (`mark`), and
103
+ * taken out again where the data is had (`unmarked`). The name then stands
104
+ * where it stood, with nothing under it.
105
+ */
106
+ export function marked(data) {
107
+ const mark = `nothing:${randomUUID()}`;
108
+ let found = false;
109
+ const copy = (value) => {
110
+ if (Array.isArray(value))
111
+ return value.map(copy);
112
+ if (value === null || typeof value !== "object")
113
+ return value;
114
+ return Object.fromEntries(Object.entries(value).map(([name, one]) => {
115
+ if (one !== undefined)
116
+ return [name, copy(one)];
117
+ found = true;
118
+ return [name, mark];
119
+ }));
120
+ };
121
+ const made = copy(data);
122
+ // (A copy either way: what goes on the channel is what the data shows, name by name, whatever else it has.)
123
+ return found ? { data: made, mark } : { data: made };
124
+ }
125
+ /** Data that came by a channel (see `marked`), with nothing under the names of its records that the mark is under. (In a list the mark is a word like any: nothing is ever marked there.) */
126
+ export function unmarked(data, mark) {
127
+ if (typeof mark !== "string" || mark === "")
128
+ return data;
129
+ const clear = (value) => {
130
+ if (value === null || typeof value !== "object")
131
+ return;
132
+ for (const [name, one] of Object.entries(value)) {
133
+ if (one === mark && !Array.isArray(value))
134
+ value[name] = undefined;
135
+ else
136
+ clear(one);
137
+ }
138
+ };
139
+ clear(data);
140
+ return data;
141
+ }
142
+ /**
143
+ * What came of asking a model, of a reply that is gone through to its end:
144
+ * the reply whole — or, of a request that failed before it was one, its
145
+ * failure thrown (as pi's own `generateImages` and `classify` have what a
146
+ * provider throws, and make of it what they give back).
147
+ */
148
+ export async function wholeOf(reply) {
149
+ let last;
150
+ for await (const event of reply)
151
+ last = event;
152
+ if (last?.type === "done")
153
+ return last.message;
154
+ throw new Error(String(last?.error?.errorMessage ?? "The model was not asked."));
40
155
  }
41
156
  /** What the reply an event is the last of used — undefined of any other event. */
42
157
  export function usageAtEnd(event) {
@@ -129,11 +244,35 @@ export function whole(event, state) {
129
244
  return { ...rest, partial };
130
245
  }
131
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
+ }
132
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.) */
133
273
  async function letGoOf(sessions) {
134
274
  try {
135
- const kept = createRequire(import.meta.resolve("@earendil-works/pi-coding-agent")).resolve("@earendil-works/pi-ai/compat");
136
- const { cleanupSessionResources } = await import(pathToFileURL(kept).href);
275
+ const { cleanupSessionResources } = await import(pathToFileURL(inPisAi("./compat")).href);
137
276
  for (const session of sessions)
138
277
  cleanupSessionResources?.(session);
139
278
  }
@@ -153,10 +292,18 @@ export function createModelRelay() {
153
292
  async ask(request, signal) {
154
293
  let reply;
155
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"); })();
156
298
  try {
157
299
  const found = await (models ??= loadPi().then(pi => pi.ModelRuntime.create()));
158
300
  const { provider, id } = request.model;
159
- const own = found.getModel(provider, id);
301
+ const by = request.by ?? "streamSimple";
302
+ // (A way that is none of these is not one to ask by, whatever pi's models have by that name.)
303
+ const way = WAYS.get(by);
304
+ if (!way)
305
+ return undefined;
306
+ const own = way.of === "chat" ? found.getModel(provider, id) : found.getModelOfType(way.of, provider, id);
160
307
  // The same model, to the letter, with a key to ask it by — and a provider nobody has had a hand in.
161
308
  if (!own || JSON.stringify(own) !== JSON.stringify(request.model) || !found.hasConfiguredAuth(provider))
162
309
  return undefined;
@@ -166,7 +313,10 @@ export function createModelRelay() {
166
313
  return undefined;
167
314
  if (typeof options.sessionId === "string")
168
315
  sessions.add(options.sessionId);
169
- reply = found.streamSimple(own, request.context, { ...options, signal: stop.signal });
316
+ // (pi's models, asked by the name of the way: each takes the model, what it is to be sent, and the options.)
317
+ const ask = found[by].bind(found);
318
+ const asked = ask(own, request.context, { ...options, signal: stop.signal });
319
+ reply = way.events ? asked : (async function* () { yield { type: "done", message: await asked }; })();
170
320
  }
171
321
  catch {
172
322
  // (A pi that cannot be had here is not one to ask by: whoever asked asks itself.)
@@ -248,16 +398,19 @@ export function relayClient(send) {
248
398
  heard(answer) {
249
399
  if ("event" in answer)
250
400
  return add(answer.event);
251
- // (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"));
252
404
  off();
253
405
  waiting.delete(id);
254
- if (!begun)
255
- resolve(undefined);
406
+ resolve(undefined);
256
407
  },
257
408
  end: () => add(notAsked(request.model, "The process that was asking the model ended before the reply had come.", "error")),
258
409
  });
259
410
  try {
260
- send({ relay: { id, request } });
411
+ // (Where its options have nothing under a name, that is said: the channel would not say it.)
412
+ const { data: options, mark } = marked(request.options);
413
+ send({ relay: { id, request: { ...request, options }, mark } });
261
414
  }
262
415
  catch {
263
416
  // (A request that cannot be put on the channel — something in it is not data — is one nobody served.)
@@ -286,10 +439,23 @@ export function relayClient(send) {
286
439
  */
287
440
  export function relayServer(relay, send, on = {}) {
288
441
  const asking = new Map();
442
+ // What cannot be said — the channel will not carry it, or is gone — is not said: whoever asks for others
443
+ // is not failed by one of them.
444
+ const say = (answer) => {
445
+ try {
446
+ send(answer);
447
+ }
448
+ catch { /* (Nobody is there to hear it.) */ }
449
+ };
289
450
  const serve = async (id, request, stop) => {
451
+ // Of a request that is not asked, what is said back of its model is its names: whatever else came as
452
+ // the model may be nothing the channel will carry.
453
+ let model = { provider: "", id: "" };
290
454
  try {
455
+ const { provider, id: name, api } = request.model;
456
+ model = { provider: String(provider), id: String(name), ...(typeof api === "string" && { api }) };
291
457
  if (await on.refuse?.(request))
292
- return send({ relayed: { id, event: notAsked(request.model, "The call is to ask no more.") } });
458
+ return send({ relayed: { id, event: notAsked(model, "The call is to ask no more.") } });
293
459
  const events = await relay.ask(request, stop.signal);
294
460
  if (!events)
295
461
  return send({ relayed: { id, not: true } });
@@ -301,7 +467,13 @@ export function relayServer(relay, send, on = {}) {
301
467
  }
302
468
  }
303
469
  catch (err) {
304
- send({ relayed: { id, event: notAsked(request.model, `The model could not be asked: ${messageOf(err)}`, "error") } });
470
+ // (Whatever was thrown, and whether or not it can be said what.)
471
+ let why = "it cannot be said why";
472
+ try {
473
+ why = messageOf(err);
474
+ }
475
+ catch { /* (As it is.) */ }
476
+ say({ relayed: { id, event: notAsked(model, `The model could not be asked: ${why}`, "error") } });
305
477
  }
306
478
  finally {
307
479
  asking.delete(id);
@@ -311,10 +483,21 @@ export function relayServer(relay, send, on = {}) {
311
483
  heard(message) {
312
484
  if ("relayAbort" in message)
313
485
  return asking.get(message.relayAbort)?.abort();
314
- const { id, request } = message.relay;
486
+ const { id, request, mark } = message.relay;
487
+ // (A request by a number another is being asked by is nobody's: what would stop it would stop the other.)
488
+ if (asking.has(id))
489
+ return;
490
+ let asked;
491
+ try {
492
+ asked = { ...request, options: unmarked(request.options, mark) };
493
+ }
494
+ catch {
495
+ // (What cannot be gone through — it goes deeper than anything a request goes with — is not one to serve.)
496
+ return say({ relayed: { id, not: true } });
497
+ }
315
498
  const stop = new AbortController();
316
499
  asking.set(id, stop);
317
- void serve(id, request, stop);
500
+ void serve(id, asked, stop);
318
501
  },
319
502
  close() {
320
503
  for (const stop of asking.values())