@trama-dev/runtime 0.5.0 → 0.6.1
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.
- package/dist/agent-backend.d.ts +127 -1
- package/dist/agent-backend.js +41 -2
- package/dist/agent-host.d.ts +50 -0
- package/dist/agent-host.js +97 -0
- package/dist/agent-hosts.d.ts +14 -0
- package/dist/agent-hosts.js +321 -0
- package/dist/agent.d.ts +10 -2
- package/dist/agent.js +85 -36
- package/dist/bridge-client.d.ts +6 -0
- package/dist/bridge-client.js +31 -8
- package/dist/budget.d.ts +52 -0
- package/dist/budget.js +118 -0
- package/dist/child-process.d.ts +18 -0
- package/dist/child-process.js +29 -0
- package/dist/client.d.ts +2 -2
- package/dist/client.js +4 -4
- package/dist/index.d.ts +3 -1
- package/dist/index.js +191 -56
- package/dist/ipc-server.d.ts +11 -2
- package/dist/ipc-server.js +104 -41
- package/dist/journal-view.d.ts +2 -0
- package/dist/journal-view.js +41 -4
- package/dist/journal.d.ts +12 -4
- package/dist/journal.js +7 -2
- package/dist/model-relay.d.ts +188 -0
- package/dist/model-relay.js +492 -0
- package/dist/pi-adapter.d.ts +34 -9
- package/dist/pi-adapter.js +978 -47
- package/dist/runner-types.d.ts +35 -0
- package/dist/runner.d.ts +190 -4
- package/dist/runner.js +652 -189
- package/dist/stopping.d.ts +33 -2
- package/dist/stopping.js +119 -11
- package/dist/tools.d.ts +2 -1
- package/dist/tools.js +52 -13
- package/dist/tree.d.ts +9 -2
- package/dist/tree.js +25 -3
- package/dist/types.d.ts +100 -12
- package/package.json +1 -1
|
@@ -0,0 +1,492 @@
|
|
|
1
|
+
// Asking a model for a session that is in another process.
|
|
2
|
+
//
|
|
3
|
+
// A call that has extensions is served by pi in a process of its own (see
|
|
4
|
+
// agent-host.ts), and what an extension is free to do there it can do to what
|
|
5
|
+
// that process says of itself: what the call used, among it. So where it can
|
|
6
|
+
// be, the model is asked by a process no extension is in — the runner, or a
|
|
7
|
+
// process of the runner's that was started with the variables of the run —
|
|
8
|
+
// and the session is handed the reply as it comes. What the reply used is
|
|
9
|
+
// then read where it was asked for, and is nobody's word.
|
|
10
|
+
//
|
|
11
|
+
// Where it can be: the model has to be the same to both, and the request one
|
|
12
|
+
// that is made of plain data. A session whose model the other side has not
|
|
13
|
+
// got as the session has it, or whose request an extension has a hand in,
|
|
14
|
+
// asks its model itself, as it always did — and what it used is what its
|
|
15
|
+
// process says. This is not a wall: pi does not hold an extension to it.
|
|
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
|
+
//
|
|
21
|
+
// Three things are here: the one that asks (createModelRelay), and the two
|
|
22
|
+
// ends of a channel between it and a session (relayClient, relayServer).
|
|
23
|
+
import { randomUUID } from "crypto";
|
|
24
|
+
import { createRequire } from "module";
|
|
25
|
+
import { pathToFileURL } from "url";
|
|
26
|
+
import { onAbort } from "./abort.js";
|
|
27
|
+
import { messageOf } from "./errors.js";
|
|
28
|
+
const loadPi = () => import("@earendil-works/pi-coding-agent");
|
|
29
|
+
/** 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). */
|
|
30
|
+
const WAYS = new Map([
|
|
31
|
+
["streamSimple", { of: "chat", events: true }],
|
|
32
|
+
["stream", { of: "chat", events: true }],
|
|
33
|
+
["generateImages", { of: "image", events: false }],
|
|
34
|
+
["classify", { of: "classifier", events: false }],
|
|
35
|
+
]);
|
|
36
|
+
/**
|
|
37
|
+
* Whether a value is data: what it is on the other side of a channel is what
|
|
38
|
+
* it is here. Text, numbers that are numbers, yes and no, nothing; and lists
|
|
39
|
+
* and plain records of those. Not a function, nor anything that is of a kind
|
|
40
|
+
* of its own (a date, a signal, bytes; a list or a record that is more than
|
|
41
|
+
* one), nor what holds itself, nor what says of itself something other than
|
|
42
|
+
* it shows. (What a record has by a symbol, or has and does not show, is no
|
|
43
|
+
* part of it on any channel, and a provider is sent none of it either: pi's
|
|
44
|
+
* schemas have such.)
|
|
45
|
+
*/
|
|
46
|
+
export function isData(value, within = new Set()) {
|
|
47
|
+
if (value === null || typeof value === "string" || typeof value === "boolean")
|
|
48
|
+
return true;
|
|
49
|
+
if (typeof value === "number")
|
|
50
|
+
return Number.isFinite(value);
|
|
51
|
+
if (typeof value !== "object" || within.has(value))
|
|
52
|
+
return false;
|
|
53
|
+
// (A list or a record, and of no kind of its own: nor one that would be said otherwise than it shows.)
|
|
54
|
+
const kind = Object.getPrototypeOf(value);
|
|
55
|
+
if (Array.isArray(value) ? kind !== Array.prototype : kind !== Object.prototype && kind !== null)
|
|
56
|
+
return false;
|
|
57
|
+
if (typeof value.toJSON === "function")
|
|
58
|
+
return false;
|
|
59
|
+
within.add(value);
|
|
60
|
+
try {
|
|
61
|
+
// (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
|
|
62
|
+
// name there. A list is gone through place by place, as a channel goes through it — not as it would have itself gone through.)
|
|
63
|
+
if (Array.isArray(value))
|
|
64
|
+
return Array.from({ length: value.length }, (_, at) => value[at]).every(one => isData(one, within));
|
|
65
|
+
return Object.values(value).every(one => one === undefined || isData(one, within));
|
|
66
|
+
}
|
|
67
|
+
finally {
|
|
68
|
+
within.delete(value);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* The options a session asks with, as those that go with a relayed request —
|
|
73
|
+
* or undefined where one is there that cannot go, and would be missed.
|
|
74
|
+
*
|
|
75
|
+
* What goes is whatever is data, by whatever name: a provider's own options
|
|
76
|
+
* are its own, and are not known here by name. What cannot go: a key of the
|
|
77
|
+
* asker's own, a way of its own to reach the provider, a span to report to,
|
|
78
|
+
* a reply that is to be fetched later (it is fetched where it was asked
|
|
79
|
+
* for) — and anything else that is not data: a provider may read whatever
|
|
80
|
+
* it is given, and what goes with a request is its asker's to mean something
|
|
81
|
+
* by. (What whoever hands a request over knows to be nothing a provider is
|
|
82
|
+
* handed, they leave out first: see `account`, pi-adapter.ts.) The word to
|
|
83
|
+
* stop by is no option here: it goes beside the request.
|
|
84
|
+
*/
|
|
85
|
+
export function dataOf(options = {}) {
|
|
86
|
+
if (["apiKey", "fetch", "telemetry", "deferred"].some(key => options[key] !== undefined))
|
|
87
|
+
return undefined;
|
|
88
|
+
const data = Object.entries(options).filter(([key]) => key !== "signal");
|
|
89
|
+
if (data.some(([, value]) => value !== undefined && !isData(value)))
|
|
90
|
+
return undefined;
|
|
91
|
+
// (Each under its own name, whatever the name: none of them is taken for anything else.)
|
|
92
|
+
return Object.fromEntries(data);
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Data as it goes on a channel, where a record in it has nothing under a
|
|
96
|
+
* name. A channel carries no such name — and to have nothing under a name is
|
|
97
|
+
* not to be without it, where records are laid one over another, name by
|
|
98
|
+
* name and in the order of their names (as pi lays a request's headers, and
|
|
99
|
+
* what a model is sampled by, over the model's own). So a word is put under
|
|
100
|
+
* each such name, that is nothing else: said beside the data (`mark`), and
|
|
101
|
+
* taken out again where the data is had (`unmarked`). The name then stands
|
|
102
|
+
* where it stood, with nothing under it.
|
|
103
|
+
*/
|
|
104
|
+
export function marked(data) {
|
|
105
|
+
const mark = `nothing:${randomUUID()}`;
|
|
106
|
+
let found = false;
|
|
107
|
+
const copy = (value) => {
|
|
108
|
+
if (Array.isArray(value))
|
|
109
|
+
return value.map(copy);
|
|
110
|
+
if (value === null || typeof value !== "object")
|
|
111
|
+
return value;
|
|
112
|
+
return Object.fromEntries(Object.entries(value).map(([name, one]) => {
|
|
113
|
+
if (one !== undefined)
|
|
114
|
+
return [name, copy(one)];
|
|
115
|
+
found = true;
|
|
116
|
+
return [name, mark];
|
|
117
|
+
}));
|
|
118
|
+
};
|
|
119
|
+
const made = copy(data);
|
|
120
|
+
// (A copy either way: what goes on the channel is what the data shows, name by name, whatever else it has.)
|
|
121
|
+
return found ? { data: made, mark } : { data: made };
|
|
122
|
+
}
|
|
123
|
+
/** 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.) */
|
|
124
|
+
export function unmarked(data, mark) {
|
|
125
|
+
if (typeof mark !== "string" || mark === "")
|
|
126
|
+
return data;
|
|
127
|
+
const clear = (value) => {
|
|
128
|
+
if (value === null || typeof value !== "object")
|
|
129
|
+
return;
|
|
130
|
+
for (const [name, one] of Object.entries(value)) {
|
|
131
|
+
if (one === mark && !Array.isArray(value))
|
|
132
|
+
value[name] = undefined;
|
|
133
|
+
else
|
|
134
|
+
clear(one);
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
clear(data);
|
|
138
|
+
return data;
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* What came of asking a model, of a reply that is gone through to its end:
|
|
142
|
+
* the reply whole — or, of a request that failed before it was one, its
|
|
143
|
+
* failure thrown (as pi's own `generateImages` and `classify` have what a
|
|
144
|
+
* provider throws, and make of it what they give back).
|
|
145
|
+
*/
|
|
146
|
+
export async function wholeOf(reply) {
|
|
147
|
+
let last;
|
|
148
|
+
for await (const event of reply)
|
|
149
|
+
last = event;
|
|
150
|
+
if (last?.type === "done")
|
|
151
|
+
return last.message;
|
|
152
|
+
throw new Error(String(last?.error?.errorMessage ?? "The model was not asked."));
|
|
153
|
+
}
|
|
154
|
+
/** What the reply an event is the last of used — undefined of any other event. */
|
|
155
|
+
export function usageAtEnd(event) {
|
|
156
|
+
const reply = event.type === "done" ? event.message : event.type === "error" ? event.error : undefined;
|
|
157
|
+
return reply?.usage;
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* The event that ends a reply the model was not asked for: as pi makes the
|
|
161
|
+
* reply of a request that was cancelled before it was sent. (Said as one that
|
|
162
|
+
* was cancelled, whyever it was: pi reads the words of a reply that failed —
|
|
163
|
+
* for a number that looks like a server's, to try again; for a limit, to sum
|
|
164
|
+
* the conversation up — and a request that is not to be made is neither.)
|
|
165
|
+
*/
|
|
166
|
+
export function notAsked(model, why, as = "aborted") {
|
|
167
|
+
return {
|
|
168
|
+
type: "error",
|
|
169
|
+
reason: as,
|
|
170
|
+
error: {
|
|
171
|
+
role: "assistant", content: [], api: model.api, provider: model.provider, model: model.id,
|
|
172
|
+
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
|
|
173
|
+
stopReason: as, errorMessage: why, timestamp: Date.now(),
|
|
174
|
+
},
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
// --- An event without the reply so far, and with it again ---
|
|
178
|
+
// Every event of a reply but the last carries `partial`: the whole reply so
|
|
179
|
+
// far. Sent as they are, a reply's events grow with the square of its length.
|
|
180
|
+
// And `partial` is one object that pi goes on changing: read a moment late,
|
|
181
|
+
// it holds what later events bring. So an event is sent with what it adds —
|
|
182
|
+
// text and thinking as their delta, anything else as the one block it is of
|
|
183
|
+
// (see `leaner`) — and the reply so far is put together again where it is
|
|
184
|
+
// wanted.
|
|
185
|
+
const wordsOf = (type) => type.startsWith("text_") ? "text" : type.startsWith("thinking_") ? "thinking" : undefined;
|
|
186
|
+
/** How much of a tool call's arguments is sent whole with every piece of them, before it is sent whole only as it grows by half again. */
|
|
187
|
+
const SMALL = 8 * 1024;
|
|
188
|
+
/**
|
|
189
|
+
* Makes of a reply's events the events as they are sent: without the reply
|
|
190
|
+
* so far. (One for each reply: it keeps how much of each tool call has been
|
|
191
|
+
* sent.) What an event adds is sent with it — but a tool call's arguments,
|
|
192
|
+
* which pi puts together from their pieces in its own way for each kind of
|
|
193
|
+
* provider, can only be sent whole: so they are, with every piece while they
|
|
194
|
+
* are short, and after that each time they have grown by half — and whole at
|
|
195
|
+
* their end. Whoever is shown a long tool call as it comes is shown its
|
|
196
|
+
* arguments as they were a little while before.
|
|
197
|
+
*/
|
|
198
|
+
export function leaner() {
|
|
199
|
+
const grown = new Map(), sent = new Map();
|
|
200
|
+
return (event) => {
|
|
201
|
+
if (event.type === "done" || event.type === "error")
|
|
202
|
+
return event;
|
|
203
|
+
const { partial, ...rest } = event;
|
|
204
|
+
const { content, ...top } = partial;
|
|
205
|
+
if (event.type === "start")
|
|
206
|
+
return { ...rest, top };
|
|
207
|
+
const at = rest.contentIndex, kind = wordsOf(event.type);
|
|
208
|
+
if (!kind) {
|
|
209
|
+
const now = (grown.get(at) ?? 0) + (typeof rest.delta === "string" ? rest.delta.length : 0);
|
|
210
|
+
grown.set(at, now);
|
|
211
|
+
const whole = !event.type.endsWith("_delta") || now <= SMALL || now >= (sent.get(at) ?? 0) * 1.5;
|
|
212
|
+
if (!whole)
|
|
213
|
+
return { ...rest, top };
|
|
214
|
+
sent.set(at, now);
|
|
215
|
+
return { ...rest, top, block: content[at] };
|
|
216
|
+
}
|
|
217
|
+
if (event.type.endsWith("_delta"))
|
|
218
|
+
return { ...rest, top };
|
|
219
|
+
// (Its beginning and its end: the block without its words, which are had from the deltas, or from `content`.)
|
|
220
|
+
const { [kind]: _words, ...around } = content[at] ?? {};
|
|
221
|
+
return { ...rest, top, around };
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
/** An event that was sent without the reply so far (see `leaner`), with it. */
|
|
225
|
+
export function whole(event, state) {
|
|
226
|
+
if (event.type === "done" || event.type === "error")
|
|
227
|
+
return event;
|
|
228
|
+
const { top, block, around, ...rest } = event;
|
|
229
|
+
const partial = state.partial = { ...state.partial, ...top, content: [...(state.partial?.content ?? [])] };
|
|
230
|
+
if (event.type === "start")
|
|
231
|
+
return { ...rest, partial };
|
|
232
|
+
const at = rest.contentIndex, was = partial.content[at] ?? {};
|
|
233
|
+
const kind = wordsOf(event.type);
|
|
234
|
+
if (!kind)
|
|
235
|
+
partial.content[at] = block ?? was;
|
|
236
|
+
else if (event.type.endsWith("_start"))
|
|
237
|
+
partial.content[at] = { ...around, [kind]: "" };
|
|
238
|
+
else if (event.type.endsWith("_delta"))
|
|
239
|
+
partial.content[at] = { ...was, [kind]: String(was[kind] ?? "") + String(rest.delta ?? "") };
|
|
240
|
+
else
|
|
241
|
+
partial.content[at] = { ...was, ...around, [kind]: rest.content };
|
|
242
|
+
return { ...rest, partial };
|
|
243
|
+
}
|
|
244
|
+
// --- The one that asks ---
|
|
245
|
+
/** 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
|
+
async function letGoOf(sessions) {
|
|
247
|
+
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);
|
|
250
|
+
for (const session of sessions)
|
|
251
|
+
cleanupSessionResources?.(session);
|
|
252
|
+
}
|
|
253
|
+
catch { /* what cannot be let go of is left: it is bounded where it is kept */ }
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* A relay that asks with this process's own pi: the models it finds, and the
|
|
257
|
+
* keys it has for their providers. Its events are sent ones (see `leaner`).
|
|
258
|
+
* `close` when whoever it asks for is done: what is still being asked is
|
|
259
|
+
* asked no further, and what was kept for it is let go of.
|
|
260
|
+
*/
|
|
261
|
+
export function createModelRelay() {
|
|
262
|
+
let models;
|
|
263
|
+
const asking = new Set();
|
|
264
|
+
const sessions = new Set();
|
|
265
|
+
return {
|
|
266
|
+
async ask(request, signal) {
|
|
267
|
+
let reply;
|
|
268
|
+
const stop = new AbortController();
|
|
269
|
+
try {
|
|
270
|
+
const found = await (models ??= loadPi().then(pi => pi.ModelRuntime.create()));
|
|
271
|
+
const { provider, id } = request.model;
|
|
272
|
+
const by = request.by ?? "streamSimple";
|
|
273
|
+
// (A way that is none of these is not one to ask by, whatever pi's models have by that name.)
|
|
274
|
+
const way = WAYS.get(by);
|
|
275
|
+
if (!way)
|
|
276
|
+
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
|
+
// (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
|
+
const options = dataOf(request.options);
|
|
283
|
+
if (!options)
|
|
284
|
+
return undefined;
|
|
285
|
+
if (typeof options.sessionId === "string")
|
|
286
|
+
sessions.add(options.sessionId);
|
|
287
|
+
// (pi's models, asked by the name of the way: each takes the model, what it is to be sent, and the options.)
|
|
288
|
+
const ask = found[by].bind(found);
|
|
289
|
+
const asked = ask(own, request.context, { ...options, signal: stop.signal });
|
|
290
|
+
reply = way.events ? asked : (async function* () { yield { type: "done", message: await asked }; })();
|
|
291
|
+
}
|
|
292
|
+
catch {
|
|
293
|
+
// (A pi that cannot be had here is not one to ask by: whoever asked asks itself.)
|
|
294
|
+
models = undefined;
|
|
295
|
+
return undefined;
|
|
296
|
+
}
|
|
297
|
+
const off = onAbort(signal, () => stop.abort());
|
|
298
|
+
asking.add(stop);
|
|
299
|
+
const lean = leaner();
|
|
300
|
+
return (async function* () {
|
|
301
|
+
try {
|
|
302
|
+
for await (const event of reply)
|
|
303
|
+
yield lean(event);
|
|
304
|
+
}
|
|
305
|
+
catch (err) {
|
|
306
|
+
yield notAsked(request.model, `The model could not be asked: ${messageOf(err)}`, "error");
|
|
307
|
+
}
|
|
308
|
+
finally {
|
|
309
|
+
off();
|
|
310
|
+
asking.delete(stop);
|
|
311
|
+
}
|
|
312
|
+
})();
|
|
313
|
+
},
|
|
314
|
+
async close() {
|
|
315
|
+
for (const stop of asking)
|
|
316
|
+
stop.abort();
|
|
317
|
+
await letGoOf(sessions);
|
|
318
|
+
sessions.clear();
|
|
319
|
+
},
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* The asking end: a relay that is reached by messages. `heard` is to be told
|
|
324
|
+
* what the other end answers; `close` when the other end is gone — whatever
|
|
325
|
+
* is still waited for then ends as a request that failed, saying so (nobody
|
|
326
|
+
* cancelled it), and nothing more is asked by it.
|
|
327
|
+
*/
|
|
328
|
+
export function relayClient(send) {
|
|
329
|
+
const waiting = new Map();
|
|
330
|
+
let ids = 0, closed = false;
|
|
331
|
+
return {
|
|
332
|
+
relay: {
|
|
333
|
+
ask: (request, signal) => new Promise((resolve) => {
|
|
334
|
+
if (closed)
|
|
335
|
+
return resolve(undefined);
|
|
336
|
+
// (Cancelled before it was asked: nothing is sent.)
|
|
337
|
+
if (signal?.aborted)
|
|
338
|
+
return resolve((async function* () { yield notAsked(request.model, "Aborted"); })());
|
|
339
|
+
const id = ++ids;
|
|
340
|
+
const events = [];
|
|
341
|
+
let wake = () => { }, begun = false;
|
|
342
|
+
const off = onAbort(signal, () => send({ relayAbort: id }));
|
|
343
|
+
const reply = async function* () {
|
|
344
|
+
try {
|
|
345
|
+
for (;;) {
|
|
346
|
+
const event = events.shift();
|
|
347
|
+
if (!event)
|
|
348
|
+
await new Promise((next) => { wake = next; });
|
|
349
|
+
else {
|
|
350
|
+
yield event;
|
|
351
|
+
if (event.type === "done" || event.type === "error")
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
finally {
|
|
357
|
+
off();
|
|
358
|
+
waiting.delete(id);
|
|
359
|
+
}
|
|
360
|
+
};
|
|
361
|
+
const add = (event) => {
|
|
362
|
+
events.push(event);
|
|
363
|
+
wake();
|
|
364
|
+
if (!begun)
|
|
365
|
+
resolve(reply());
|
|
366
|
+
begun = true;
|
|
367
|
+
};
|
|
368
|
+
waiting.set(id, {
|
|
369
|
+
heard(answer) {
|
|
370
|
+
if ("event" in answer)
|
|
371
|
+
return add(answer.event);
|
|
372
|
+
// (Not one the other end can serve: nothing was asked.)
|
|
373
|
+
off();
|
|
374
|
+
waiting.delete(id);
|
|
375
|
+
if (!begun)
|
|
376
|
+
resolve(undefined);
|
|
377
|
+
},
|
|
378
|
+
end: () => add(notAsked(request.model, "The process that was asking the model ended before the reply had come.", "error")),
|
|
379
|
+
});
|
|
380
|
+
try {
|
|
381
|
+
// (Where its options have nothing under a name, that is said: the channel would not say it.)
|
|
382
|
+
const { data: options, mark } = marked(request.options);
|
|
383
|
+
send({ relay: { id, request: { ...request, options }, mark } });
|
|
384
|
+
}
|
|
385
|
+
catch {
|
|
386
|
+
// (A request that cannot be put on the channel — something in it is not data — is one nobody served.)
|
|
387
|
+
off();
|
|
388
|
+
waiting.delete(id);
|
|
389
|
+
resolve(undefined);
|
|
390
|
+
}
|
|
391
|
+
}),
|
|
392
|
+
},
|
|
393
|
+
heard(answer) {
|
|
394
|
+
waiting.get(answer.id)?.heard(answer);
|
|
395
|
+
},
|
|
396
|
+
close() {
|
|
397
|
+
closed = true;
|
|
398
|
+
for (const request of [...waiting.values()])
|
|
399
|
+
request.end();
|
|
400
|
+
},
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* The answering end: serves, by `relay`, the requests that `heard` is told
|
|
405
|
+
* of. `refuse`: whether a request is not to be made at all (it then ends as
|
|
406
|
+
* one that was cancelled) — asked before each, and waited for; `replied`:
|
|
407
|
+
* told what each reply used, as its last event passes. `close`: what is
|
|
408
|
+
* still being asked is asked no further.
|
|
409
|
+
*/
|
|
410
|
+
export function relayServer(relay, send, on = {}) {
|
|
411
|
+
const asking = new Map();
|
|
412
|
+
// What cannot be said — the channel will not carry it, or is gone — is not said: whoever asks for others
|
|
413
|
+
// is not failed by one of them.
|
|
414
|
+
const say = (answer) => {
|
|
415
|
+
try {
|
|
416
|
+
send(answer);
|
|
417
|
+
}
|
|
418
|
+
catch { /* (Nobody is there to hear it.) */ }
|
|
419
|
+
};
|
|
420
|
+
const serve = async (id, request, stop) => {
|
|
421
|
+
// Of a request that is not asked, what is said back of its model is its names: whatever else came as
|
|
422
|
+
// the model may be nothing the channel will carry.
|
|
423
|
+
let model = { provider: "", id: "" };
|
|
424
|
+
try {
|
|
425
|
+
const { provider, id: name, api } = request.model;
|
|
426
|
+
model = { provider: String(provider), id: String(name), ...(typeof api === "string" && { api }) };
|
|
427
|
+
if (await on.refuse?.(request))
|
|
428
|
+
return send({ relayed: { id, event: notAsked(model, "The call is to ask no more.") } });
|
|
429
|
+
const events = await relay.ask(request, stop.signal);
|
|
430
|
+
if (!events)
|
|
431
|
+
return send({ relayed: { id, not: true } });
|
|
432
|
+
for await (const event of events) {
|
|
433
|
+
const usage = usageAtEnd(event);
|
|
434
|
+
if (usage)
|
|
435
|
+
on.replied?.(usage);
|
|
436
|
+
send({ relayed: { id, event } });
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
catch (err) {
|
|
440
|
+
// (Whatever was thrown, and whether or not it can be said what.)
|
|
441
|
+
let why = "it cannot be said why";
|
|
442
|
+
try {
|
|
443
|
+
why = messageOf(err);
|
|
444
|
+
}
|
|
445
|
+
catch { /* (As it is.) */ }
|
|
446
|
+
say({ relayed: { id, event: notAsked(model, `The model could not be asked: ${why}`, "error") } });
|
|
447
|
+
}
|
|
448
|
+
finally {
|
|
449
|
+
asking.delete(id);
|
|
450
|
+
}
|
|
451
|
+
};
|
|
452
|
+
return {
|
|
453
|
+
heard(message) {
|
|
454
|
+
if ("relayAbort" in message)
|
|
455
|
+
return asking.get(message.relayAbort)?.abort();
|
|
456
|
+
const { id, request, mark } = message.relay;
|
|
457
|
+
// (A request by a number another is being asked by is nobody's: what would stop it would stop the other.)
|
|
458
|
+
if (asking.has(id))
|
|
459
|
+
return;
|
|
460
|
+
let asked;
|
|
461
|
+
try {
|
|
462
|
+
asked = { ...request, options: unmarked(request.options, mark) };
|
|
463
|
+
}
|
|
464
|
+
catch {
|
|
465
|
+
// (What cannot be gone through — it goes deeper than anything a request goes with — is not one to serve.)
|
|
466
|
+
return say({ relayed: { id, not: true } });
|
|
467
|
+
}
|
|
468
|
+
const stop = new AbortController();
|
|
469
|
+
asking.set(id, stop);
|
|
470
|
+
void serve(id, asked, stop);
|
|
471
|
+
},
|
|
472
|
+
close() {
|
|
473
|
+
for (const stop of asking.values())
|
|
474
|
+
stop.abort();
|
|
475
|
+
},
|
|
476
|
+
};
|
|
477
|
+
}
|
|
478
|
+
/** A relay whose events are sent ones, as one whose events are pi's own: each with the reply so far. */
|
|
479
|
+
export function withRepliesWhole(relay) {
|
|
480
|
+
return {
|
|
481
|
+
async ask(request, signal) {
|
|
482
|
+
const events = await relay.ask(request, signal);
|
|
483
|
+
if (!events)
|
|
484
|
+
return undefined;
|
|
485
|
+
return (async function* () {
|
|
486
|
+
const state = {};
|
|
487
|
+
for await (const event of events)
|
|
488
|
+
yield whole(event, state);
|
|
489
|
+
})();
|
|
490
|
+
},
|
|
491
|
+
};
|
|
492
|
+
}
|
package/dist/pi-adapter.d.ts
CHANGED
|
@@ -1,25 +1,50 @@
|
|
|
1
|
-
import type
|
|
1
|
+
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
|
-
/**
|
|
5
|
+
/**
|
|
6
|
+
* The pi coding agent: a fresh in-memory session for every call — in this
|
|
7
|
+
* process, or in a process of its own (see agent-host.ts). A call that has
|
|
8
|
+
* extensions is served in one: an extension is somebody's code, and where it
|
|
9
|
+
* runs it can hold up, or bring down, everything else that runs there. And
|
|
10
|
+
* so is every call of an adapter that was given variables (`env`: a run's):
|
|
11
|
+
* what an agent finds of pi, which key it has for a provider, and what the
|
|
12
|
+
* commands it runs are given, are a process's — and this process is the
|
|
13
|
+
* runner's, whose own are not a run's to change.
|
|
14
|
+
*/
|
|
6
15
|
export declare class PiAdapter implements AgentBackend {
|
|
7
16
|
private config;
|
|
8
|
-
|
|
17
|
+
/** Whether every call is served in a process of its own: where those processes are given variables this one has not. */
|
|
18
|
+
private apart;
|
|
19
|
+
/** The processes that serve this adapter's calls. */
|
|
20
|
+
private hosts;
|
|
21
|
+
constructor(config: ModelConfig, env?: Record<string, string>);
|
|
22
|
+
/** Have a call served: here, or by a host. */
|
|
23
|
+
ask(prompt: string, call: AgentCall): Promise<string>;
|
|
24
|
+
/** End the processes that served calls: what this adapter was for is over. (It can be asked again: it starts them anew.) */
|
|
25
|
+
close(): Promise<void>;
|
|
9
26
|
private createSession;
|
|
27
|
+
/** What is kept of each session that has extensions. */
|
|
28
|
+
private extended;
|
|
29
|
+
/** Where trama stands when each session's model is asked. */
|
|
30
|
+
private asking;
|
|
31
|
+
/** Be done with a session: its extensions, where it has any, told first that it is over. */
|
|
32
|
+
private letGoOf;
|
|
10
33
|
/**
|
|
11
34
|
* The configured provider/model is not in pi's catalog, so pi picked a model
|
|
12
35
|
* on its own. Say so once — otherwise a typo silently runs a different model.
|
|
13
36
|
*/
|
|
14
37
|
private warnUnknownModel;
|
|
15
|
-
private extractText;
|
|
16
38
|
/**
|
|
17
|
-
*
|
|
39
|
+
* Serve a call in this process: run one prompt in a fresh session and
|
|
40
|
+
* return the assistant's text reply. (What a host does; and what `ask`
|
|
41
|
+
* does itself for a call without extensions.)
|
|
18
42
|
*
|
|
19
43
|
* Cancellation during `createSession` is handled step-by-step inside it; once
|
|
20
|
-
* `session.prompt()` is running,
|
|
21
|
-
*
|
|
22
|
-
* `signal.aborted` is checked again when `prompt()` returns)
|
|
44
|
+
* `session.prompt()` is running, a cancelled call has pi abort the run — which
|
|
45
|
+
* settles the prompt (pi 1.x resolves it rather than rejecting, so
|
|
46
|
+
* `signal.aborted` is checked again when `prompt()` returns) and leaves on
|
|
47
|
+
* the session's record what the request that was cut off had taken by then.
|
|
23
48
|
*/
|
|
24
|
-
|
|
49
|
+
serve(prompt: string, call: AgentCall): Promise<string>;
|
|
25
50
|
}
|