@trama-dev/runtime 0.5.0 → 0.6.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.
@@ -0,0 +1,339 @@
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
+ // Three things are here: the one that asks (createModelRelay), and the two
18
+ // ends of a channel between it and a session (relayClient, relayServer).
19
+ import { createRequire } from "module";
20
+ import { pathToFileURL } from "url";
21
+ import { onAbort } from "./abort.js";
22
+ import { messageOf } from "./errors.js";
23
+ 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
+ ];
30
+ /**
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.
35
+ */
36
+ export function dataOf(options = {}) {
37
+ if (["apiKey", "fetch", "telemetry", "deferred"].some(key => options[key] !== undefined))
38
+ return undefined;
39
+ return Object.fromEntries(DATA_OPTIONS.filter(key => options[key] !== undefined).map(key => [key, options[key]]));
40
+ }
41
+ /** What the reply an event is the last of used — undefined of any other event. */
42
+ export function usageAtEnd(event) {
43
+ const reply = event.type === "done" ? event.message : event.type === "error" ? event.error : undefined;
44
+ return reply?.usage;
45
+ }
46
+ /**
47
+ * The event that ends a reply the model was not asked for: as pi makes the
48
+ * reply of a request that was cancelled before it was sent. (Said as one that
49
+ * was cancelled, whyever it was: pi reads the words of a reply that failed —
50
+ * for a number that looks like a server's, to try again; for a limit, to sum
51
+ * the conversation up — and a request that is not to be made is neither.)
52
+ */
53
+ export function notAsked(model, why, as = "aborted") {
54
+ return {
55
+ type: "error",
56
+ reason: as,
57
+ error: {
58
+ role: "assistant", content: [], api: model.api, provider: model.provider, model: model.id,
59
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
60
+ stopReason: as, errorMessage: why, timestamp: Date.now(),
61
+ },
62
+ };
63
+ }
64
+ // --- An event without the reply so far, and with it again ---
65
+ // Every event of a reply but the last carries `partial`: the whole reply so
66
+ // far. Sent as they are, a reply's events grow with the square of its length.
67
+ // And `partial` is one object that pi goes on changing: read a moment late,
68
+ // it holds what later events bring. So an event is sent with what it adds —
69
+ // text and thinking as their delta, anything else as the one block it is of
70
+ // (see `leaner`) — and the reply so far is put together again where it is
71
+ // wanted.
72
+ const wordsOf = (type) => type.startsWith("text_") ? "text" : type.startsWith("thinking_") ? "thinking" : undefined;
73
+ /** 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. */
74
+ const SMALL = 8 * 1024;
75
+ /**
76
+ * Makes of a reply's events the events as they are sent: without the reply
77
+ * so far. (One for each reply: it keeps how much of each tool call has been
78
+ * sent.) What an event adds is sent with it — but a tool call's arguments,
79
+ * which pi puts together from their pieces in its own way for each kind of
80
+ * provider, can only be sent whole: so they are, with every piece while they
81
+ * are short, and after that each time they have grown by half — and whole at
82
+ * their end. Whoever is shown a long tool call as it comes is shown its
83
+ * arguments as they were a little while before.
84
+ */
85
+ export function leaner() {
86
+ const grown = new Map(), sent = new Map();
87
+ return (event) => {
88
+ if (event.type === "done" || event.type === "error")
89
+ return event;
90
+ const { partial, ...rest } = event;
91
+ const { content, ...top } = partial;
92
+ if (event.type === "start")
93
+ return { ...rest, top };
94
+ const at = rest.contentIndex, kind = wordsOf(event.type);
95
+ if (!kind) {
96
+ const now = (grown.get(at) ?? 0) + (typeof rest.delta === "string" ? rest.delta.length : 0);
97
+ grown.set(at, now);
98
+ const whole = !event.type.endsWith("_delta") || now <= SMALL || now >= (sent.get(at) ?? 0) * 1.5;
99
+ if (!whole)
100
+ return { ...rest, top };
101
+ sent.set(at, now);
102
+ return { ...rest, top, block: content[at] };
103
+ }
104
+ if (event.type.endsWith("_delta"))
105
+ return { ...rest, top };
106
+ // (Its beginning and its end: the block without its words, which are had from the deltas, or from `content`.)
107
+ const { [kind]: _words, ...around } = content[at] ?? {};
108
+ return { ...rest, top, around };
109
+ };
110
+ }
111
+ /** An event that was sent without the reply so far (see `leaner`), with it. */
112
+ export function whole(event, state) {
113
+ if (event.type === "done" || event.type === "error")
114
+ return event;
115
+ const { top, block, around, ...rest } = event;
116
+ const partial = state.partial = { ...state.partial, ...top, content: [...(state.partial?.content ?? [])] };
117
+ if (event.type === "start")
118
+ return { ...rest, partial };
119
+ const at = rest.contentIndex, was = partial.content[at] ?? {};
120
+ const kind = wordsOf(event.type);
121
+ if (!kind)
122
+ partial.content[at] = block ?? was;
123
+ else if (event.type.endsWith("_start"))
124
+ partial.content[at] = { ...around, [kind]: "" };
125
+ else if (event.type.endsWith("_delta"))
126
+ partial.content[at] = { ...was, [kind]: String(was[kind] ?? "") + String(rest.delta ?? "") };
127
+ else
128
+ partial.content[at] = { ...was, ...around, [kind]: rest.content };
129
+ return { ...rest, partial };
130
+ }
131
+ // --- The one that asks ---
132
+ /** 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
+ async function letGoOf(sessions) {
134
+ 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);
137
+ for (const session of sessions)
138
+ cleanupSessionResources?.(session);
139
+ }
140
+ catch { /* what cannot be let go of is left: it is bounded where it is kept */ }
141
+ }
142
+ /**
143
+ * A relay that asks with this process's own pi: the models it finds, and the
144
+ * keys it has for their providers. Its events are sent ones (see `leaner`).
145
+ * `close` when whoever it asks for is done: what is still being asked is
146
+ * asked no further, and what was kept for it is let go of.
147
+ */
148
+ export function createModelRelay() {
149
+ let models;
150
+ const asking = new Set();
151
+ const sessions = new Set();
152
+ return {
153
+ async ask(request, signal) {
154
+ let reply;
155
+ const stop = new AbortController();
156
+ try {
157
+ const found = await (models ??= loadPi().then(pi => pi.ModelRuntime.create()));
158
+ const { provider, id } = request.model;
159
+ const own = found.getModel(provider, id);
160
+ // The same model, to the letter, with a key to ask it by — and a provider nobody has had a hand in.
161
+ if (!own || JSON.stringify(own) !== JSON.stringify(request.model) || !found.hasConfiguredAuth(provider))
162
+ return undefined;
163
+ // (What goes with a request is held to here as where it was sent from: whoever sent it may not be who should have.)
164
+ const options = dataOf(request.options);
165
+ if (!options)
166
+ return undefined;
167
+ if (typeof options.sessionId === "string")
168
+ sessions.add(options.sessionId);
169
+ reply = found.streamSimple(own, request.context, { ...options, signal: stop.signal });
170
+ }
171
+ catch {
172
+ // (A pi that cannot be had here is not one to ask by: whoever asked asks itself.)
173
+ models = undefined;
174
+ return undefined;
175
+ }
176
+ const off = onAbort(signal, () => stop.abort());
177
+ asking.add(stop);
178
+ const lean = leaner();
179
+ return (async function* () {
180
+ try {
181
+ for await (const event of reply)
182
+ yield lean(event);
183
+ }
184
+ catch (err) {
185
+ yield notAsked(request.model, `The model could not be asked: ${messageOf(err)}`, "error");
186
+ }
187
+ finally {
188
+ off();
189
+ asking.delete(stop);
190
+ }
191
+ })();
192
+ },
193
+ async close() {
194
+ for (const stop of asking)
195
+ stop.abort();
196
+ await letGoOf(sessions);
197
+ sessions.clear();
198
+ },
199
+ };
200
+ }
201
+ /**
202
+ * The asking end: a relay that is reached by messages. `heard` is to be told
203
+ * what the other end answers; `close` when the other end is gone — whatever
204
+ * is still waited for then ends as a request that failed, saying so (nobody
205
+ * cancelled it), and nothing more is asked by it.
206
+ */
207
+ export function relayClient(send) {
208
+ const waiting = new Map();
209
+ let ids = 0, closed = false;
210
+ return {
211
+ relay: {
212
+ ask: (request, signal) => new Promise((resolve) => {
213
+ if (closed)
214
+ return resolve(undefined);
215
+ // (Cancelled before it was asked: nothing is sent.)
216
+ if (signal?.aborted)
217
+ return resolve((async function* () { yield notAsked(request.model, "Aborted"); })());
218
+ const id = ++ids;
219
+ const events = [];
220
+ let wake = () => { }, begun = false;
221
+ const off = onAbort(signal, () => send({ relayAbort: id }));
222
+ const reply = async function* () {
223
+ try {
224
+ for (;;) {
225
+ const event = events.shift();
226
+ if (!event)
227
+ await new Promise((next) => { wake = next; });
228
+ else {
229
+ yield event;
230
+ if (event.type === "done" || event.type === "error")
231
+ return;
232
+ }
233
+ }
234
+ }
235
+ finally {
236
+ off();
237
+ waiting.delete(id);
238
+ }
239
+ };
240
+ const add = (event) => {
241
+ events.push(event);
242
+ wake();
243
+ if (!begun)
244
+ resolve(reply());
245
+ begun = true;
246
+ };
247
+ waiting.set(id, {
248
+ heard(answer) {
249
+ if ("event" in answer)
250
+ return add(answer.event);
251
+ // (Not one the other end can serve: nothing was asked.)
252
+ off();
253
+ waiting.delete(id);
254
+ if (!begun)
255
+ resolve(undefined);
256
+ },
257
+ end: () => add(notAsked(request.model, "The process that was asking the model ended before the reply had come.", "error")),
258
+ });
259
+ try {
260
+ send({ relay: { id, request } });
261
+ }
262
+ catch {
263
+ // (A request that cannot be put on the channel — something in it is not data — is one nobody served.)
264
+ off();
265
+ waiting.delete(id);
266
+ resolve(undefined);
267
+ }
268
+ }),
269
+ },
270
+ heard(answer) {
271
+ waiting.get(answer.id)?.heard(answer);
272
+ },
273
+ close() {
274
+ closed = true;
275
+ for (const request of [...waiting.values()])
276
+ request.end();
277
+ },
278
+ };
279
+ }
280
+ /**
281
+ * The answering end: serves, by `relay`, the requests that `heard` is told
282
+ * of. `refuse`: whether a request is not to be made at all (it then ends as
283
+ * one that was cancelled) — asked before each, and waited for; `replied`:
284
+ * told what each reply used, as its last event passes. `close`: what is
285
+ * still being asked is asked no further.
286
+ */
287
+ export function relayServer(relay, send, on = {}) {
288
+ const asking = new Map();
289
+ const serve = async (id, request, stop) => {
290
+ try {
291
+ if (await on.refuse?.(request))
292
+ return send({ relayed: { id, event: notAsked(request.model, "The call is to ask no more.") } });
293
+ const events = await relay.ask(request, stop.signal);
294
+ if (!events)
295
+ return send({ relayed: { id, not: true } });
296
+ for await (const event of events) {
297
+ const usage = usageAtEnd(event);
298
+ if (usage)
299
+ on.replied?.(usage);
300
+ send({ relayed: { id, event } });
301
+ }
302
+ }
303
+ catch (err) {
304
+ send({ relayed: { id, event: notAsked(request.model, `The model could not be asked: ${messageOf(err)}`, "error") } });
305
+ }
306
+ finally {
307
+ asking.delete(id);
308
+ }
309
+ };
310
+ return {
311
+ heard(message) {
312
+ if ("relayAbort" in message)
313
+ return asking.get(message.relayAbort)?.abort();
314
+ const { id, request } = message.relay;
315
+ const stop = new AbortController();
316
+ asking.set(id, stop);
317
+ void serve(id, request, stop);
318
+ },
319
+ close() {
320
+ for (const stop of asking.values())
321
+ stop.abort();
322
+ },
323
+ };
324
+ }
325
+ /** A relay whose events are sent ones, as one whose events are pi's own: each with the reply so far. */
326
+ export function withRepliesWhole(relay) {
327
+ return {
328
+ async ask(request, signal) {
329
+ const events = await relay.ask(request, signal);
330
+ if (!events)
331
+ return undefined;
332
+ return (async function* () {
333
+ const state = {};
334
+ for await (const event of events)
335
+ yield whole(event, state);
336
+ })();
337
+ },
338
+ };
339
+ }
@@ -1,25 +1,50 @@
1
- import type { AgentBackend, AgentCall } from "./agent-backend.js";
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
- /** The pi coding agent, run in-process: a fresh in-memory session for every call. */
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
- constructor(config: ModelConfig);
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
- * Run one prompt in a fresh session and return the assistant's text reply.
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, abort disposes the session so pi settles the
21
- * in-flight prompt (pi 1.x resolves rather than rejects on dispose, so
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
- ask(prompt: string, call: AgentCall): Promise<string>;
49
+ serve(prompt: string, call: AgentCall): Promise<string>;
25
50
  }