@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.
@@ -1,4 +1,10 @@
1
1
  import { onAbort, rejectOnAbort, throwIfAborted } from "./abort.js";
2
+ import { messageOf } from "./errors.js";
3
+ import { createAgentHosts } from "./agent-hosts.js";
4
+ import { CutOff, addReply, atLeast, nothingYet } from "./agent-backend.js";
5
+ import * as http from "http";
6
+ import * as https from "https";
7
+ import { dataOf, isData, notAsked, usageAtEnd, wholeOf } from "./model-relay.js";
2
8
  /**
3
9
  * pi is loaded when it is first needed, not when this file is: it is most of
4
10
  * what the runtime weighs, and listing projects, reading logs, or running a
@@ -7,32 +13,777 @@ import { onAbort, rejectOnAbort, throwIfAborted } from "./abort.js";
7
13
  const loadPi = () => import("@earendil-works/pi-coding-agent");
8
14
  /** The pi version this runtime is built against (recorded in each project's meta.json). */
9
15
  export const piVersion = async () => (await loadPi()).VERSION;
16
+ /**
17
+ * pi's own extensions — its MCP support among them. The `pi` command hands
18
+ * them to its loader, and the package does not export them: they are read
19
+ * from where pi keeps them, beside what it does export. A pi that keeps them
20
+ * elsewhere is one a call with extensions cannot be served by as it asked —
21
+ * its MCP servers would be missing with no word of it — and the call fails.
22
+ */
23
+ async function builtInExtensions() {
24
+ const kept = new URL("./extensions/index.js", import.meta.resolve("@earendil-works/pi-coding-agent"));
25
+ try {
26
+ const found = (await import(kept.href)).builtInExtensions;
27
+ if (!Array.isArray(found))
28
+ throw new Error("the file exports none");
29
+ return found;
30
+ }
31
+ catch (err) {
32
+ throw new Error(`pi's built-in extensions (its MCP support among them) cannot be had: trama reads them from pi's own files, at ${kept.pathname} (${messageOf(err)}).`);
33
+ }
34
+ }
10
35
  /** provider/model pairs already warned about, so a loop of agent calls warns once per process. */
11
36
  const warnedUnknownModels = new Set();
12
- /** The pi coding agent, run in-process: a fresh in-memory session for every call. */
37
+ const nameOf = (model) => `${model.provider}/${model.id}`;
38
+ const chosen = (choice) => choice === true || Array.isArray(choice);
39
+ const named = (choice) => (Array.isArray(choice) ? choice : undefined);
40
+ const WAYS_TO_READ = ["read", "bash", "indirect"];
41
+ /**
42
+ * How long an extension is given to hear that its session is over, while it is not asking a model — and, where a
43
+ * call is cancelled while it is still being told that one begins, to have heard that first. (While it is asking a
44
+ * model, it is waited for: see leaveExtensions.)
45
+ */
46
+ const EXTENSION_LEAVE_MS = 5_000;
47
+ /** How long pi gives a request to a provider, where its settings do not say: the most a model is waited for, at work for extensions as their session ends. */
48
+ const REQUEST_MS = 300_000;
49
+ /** How long what was stopped is given to end, and say what it had used, before the count is closed. */
50
+ const STOPPED_MS = 1_000;
51
+ /**
52
+ * How long a cancelled call is waited for where something holds it. Less
53
+ * than a runner gives the process that serves the call to let go of it
54
+ * (KILL_GRACE_MS): what the call used is said when it is given up here, and
55
+ * that is to be heard there before the process is ended.
56
+ */
57
+ const HELD_MS = 3_000;
58
+ /**
59
+ * `work` — but once `signal` has said to stop, waited for no longer than a
60
+ * while: a call that was cancelled is not held for good by what does not
61
+ * return (an extension's handler, where the call has extensions).
62
+ */
63
+ function notHeld(work, signal, ms) {
64
+ if (!signal)
65
+ return work;
66
+ return new Promise((resolve, reject) => {
67
+ let late;
68
+ const off = onAbort(signal, () => { late = setTimeout(() => reject(new Error("Aborted")), ms); });
69
+ const over = () => {
70
+ off();
71
+ clearTimeout(late);
72
+ };
73
+ work.then(value => { over(); resolve(value); }, err => { over(); reject(err); });
74
+ });
75
+ }
76
+ /** Wait for `work`, but no longer than a while. (What becomes of it is not asked.) */
77
+ async function within(work, ms) {
78
+ let giveUp;
79
+ await Promise.race([work.catch(() => { }), new Promise(resolve => { giveUp = setTimeout(resolve, ms); })]);
80
+ clearTimeout(giveUp);
81
+ }
82
+ /**
83
+ * Why a session is not the one a call asked for. pi takes a level it does not
84
+ * have for the model, or a tool it has not got, and gives what it can without
85
+ * a word; a call is to have what it asked for or fail. (`serving` is the model
86
+ * by name, if pi has a real one.)
87
+ */
88
+ function whyNotAsAsked(session, asked, serving, found, asTold) {
89
+ const { thinking } = asked;
90
+ // (An extension pi has something against — it did not load, or a tool of it bears the name of another's — is
91
+ // not one the call has as it was written: and it may be where a tool the call names was to come from.)
92
+ const failed = asked.extensions ? session.resourceLoader.getExtensions().errors[0] : undefined;
93
+ if (failed)
94
+ return `The extension ${failed.path} is not as pi would have it: ${failed.error}`;
95
+ if (thinking !== undefined && session.thinkingLevel !== thinking) {
96
+ return `The model${serving ? ` ${serving}` : ""} does not think at level "${thinking}". ` +
97
+ `Its levels: ${session.getAvailableThinkingLevels().join(", ")}.`;
98
+ }
99
+ // (With extensions, an agent's tools are not all there yet: see whyNotTheTools.)
100
+ const tools = asked.extensions ? undefined : whyNotTheTools(session, asked.tools);
101
+ if (tools)
102
+ return tools;
103
+ const lacking = (kind, choice, had) => {
104
+ const missing = named(choice)?.find(name => !had.includes(name));
105
+ return missing === undefined ? undefined : `pi has no ${kind} "${missing}". Its ${kind}s: ${had.join(", ") || "none"}.`;
106
+ };
107
+ const missing = lacking("skill", asked.skills, found.skills) ?? lacking("prompt template", asked.templates, found.templates);
108
+ if (missing)
109
+ return missing;
110
+ // pi tells a model of its skills only where the model has something to read them with: a skill
111
+ // that is for the model to take up (and not only to be called by name, in the prompt) has to be told of.
112
+ // Looked for is what pi would write of them, word for word — nothing, where none is for the model to take up.
113
+ if (chosen(asked.skills)) {
114
+ const skills = session.resourceLoader.getSkills().skills;
115
+ if (!WAYS_TO_READ.some(way => session.systemPrompt.includes(asTold(skills, way).trim()))) {
116
+ const untold = skills.filter(skill => !skill.disableModelInvocation).map(skill => skill.name);
117
+ return `The agent cannot take up its skills (${untold.join(", ")}) with the tools ${JSON.stringify(session.getActiveToolNames())}: ` +
118
+ `pi tells a model of its skills only where it has "read" or "bash" to read them with.`;
119
+ }
120
+ }
121
+ return undefined;
122
+ }
123
+ /**
124
+ * Why an agent has not the tools a call named — to be asked when it has all
125
+ * it is to have. Without extensions that is when its session is made. With
126
+ * them it is when the model is about to be asked for the first time: an
127
+ * extension may add tools as the run begins (pi's own connects the user's MCP
128
+ * servers then, and their tools are the agent's from there on).
129
+ */
130
+ function whyNotTheTools(session, tools) {
131
+ if (tools === undefined)
132
+ return undefined;
133
+ const given = session.getActiveToolNames();
134
+ // (pi gives no tool that was not named. What it does not know by the name it was given, it leaves out.)
135
+ return tools.every(name => given.includes(name)) ? undefined
136
+ : `The agent cannot be given the tools ${JSON.stringify(tools)}: pi would give it ${JSON.stringify(given)}.`;
137
+ }
138
+ /**
139
+ * A signal that says to stop when either does. One of them is whatever an
140
+ * asker gave its request to be stopped by — which need not be a signal of
141
+ * the system's own making (a library's, an older runtime's): such a one is
142
+ * listened to as far as it can be, and the request is asked all the same.
143
+ */
144
+ function either(own, cut) {
145
+ const nothing = () => { };
146
+ if (own === undefined || own === null)
147
+ return { signal: cut, release: nothing };
148
+ if (own instanceof AbortSignal)
149
+ return { signal: AbortSignal.any([own, cut]), release: nothing };
150
+ const both = new AbortController();
151
+ const theirs = own;
152
+ const byThem = () => both.abort(theirs.reason);
153
+ const byCut = () => both.abort(cut.reason);
154
+ if (theirs.aborted === true)
155
+ byThem();
156
+ else if (cut.aborted)
157
+ byCut();
158
+ else {
159
+ cut.addEventListener("abort", byCut, { once: true });
160
+ try {
161
+ if (typeof theirs.addEventListener === "function")
162
+ theirs.addEventListener("abort", byThem, { once: true });
163
+ }
164
+ catch {
165
+ // (Not one that can be listened to: the request is stopped by what stops the call, and by nothing else.)
166
+ }
167
+ }
168
+ return {
169
+ signal: both.signal,
170
+ // (When the request is over: nothing of it is left listening to either.)
171
+ release: () => {
172
+ cut.removeEventListener("abort", byCut);
173
+ try {
174
+ if (typeof theirs.removeEventListener === "function")
175
+ theirs.removeEventListener("abort", byThem);
176
+ }
177
+ catch {
178
+ // (As it could not be listened to.)
179
+ }
180
+ },
181
+ };
182
+ }
183
+ /** What an extension may have a hand in, of a request to a provider: a session where one does asks its model itself. */
184
+ const HANDS_IN = ["before_provider_request", "before_provider_headers", "after_provider_response", "provider_stream_event"];
185
+ /**
186
+ * What pi's agent has every request of its own go with, to be told of what
187
+ * a provider is sent and answers: pi's own, which do nothing where no
188
+ * extension has a hand in (HANDS_IN). A request that goes with all of them,
189
+ * by the way the agent asks, is one the agent makes for itself — or one made
190
+ * with all the agent's was made with, which is the same to a provider.
191
+ */
192
+ const HOOKS = ["onPayload", "onResponse", "onProviderStreamEvent"];
193
+ /**
194
+ * What else goes with a request the agent makes for itself, and is nothing
195
+ * a provider is handed: what the agent's loop calls as a turn goes, which pi
196
+ * passes along with what a provider is to have. (The functions of
197
+ * pi-agent-core's `createLoopConfig` that pi sets, less the hooks above. The
198
+ * rest of what a loop is set up by is data, and goes as any data.) Named,
199
+ * because it cannot be told otherwise: a function of the loop's is a
200
+ * function like one an asker might mean a provider to have. A pi whose loop
201
+ * is set up by a function more has its agent's requests asked where the call
202
+ * is served, until it is named here.
203
+ */
204
+ const LOOPS = ["beforeToolCall", "afterToolCall", "finishTurn", "prepareRequest", "prepareNextTurn", "convertToLlm", "transformContext", "getSteeringMessages", "getFollowUpMessages"];
205
+ /**
206
+ * What a provider is asked by, of what it has: whether what comes of it comes
207
+ * as the events of a reply, and the way a relay asks by in its place (none,
208
+ * of a reply that was to be fetched later: it is fetched where it was asked
209
+ * for). Whatever else a provider has is not asking a model.
210
+ */
211
+ const ASKED_BY = new Map([
212
+ ["stream", { events: true, way: "stream" }],
213
+ ["streamSimple", { events: true, way: "streamSimple" }],
214
+ ["fetchDeferred", { events: true }],
215
+ ["generateImages", { events: false, way: "generateImages" }],
216
+ ["classify", { events: false, way: "classify" }],
217
+ ]);
218
+ /** What is said of a request that is not made: its call is to ask no more. */
219
+ const NO_MORE = "The call is to ask no more.";
220
+ /**
221
+ * What a request to a provider goes by, that is a process's own: its
222
+ * variables — a provider's key may be one — and its ways to the network. An
223
+ * extension may make them other than they were: read a file of variables,
224
+ * put something of its own before every request the process makes. A request
225
+ * asked from another process would then not be the request this one makes,
226
+ * and nothing in the request says so. So what they are is kept from before
227
+ * the first extension is loaded in this process (`asLoaded`), and a session
228
+ * hands its requests over only while they are that still (`asItWas`). It is
229
+ * what can be told, and not all an extension can do: one that reaches under
230
+ * these is not seen.
231
+ */
232
+ const shapeOf = () => ({
233
+ variables: JSON.stringify(process.env),
234
+ ways: [globalThis.fetch, globalThis[Symbol.for("undici.globalDispatcher.1")], http.globalAgent, https.globalAgent],
235
+ });
236
+ let asLoaded;
237
+ function asItWas() {
238
+ if (!asLoaded)
239
+ return false;
240
+ const now = shapeOf();
241
+ return now.variables === asLoaded.variables && now.ways.every((way, at) => way === asLoaded.ways[at]);
242
+ }
243
+ /**
244
+ * Stand where a session's models are asked. pi asks a model in more places
245
+ * than one — its agent for a turn, for a summary of a long conversation or of
246
+ * a branch, to keep a provider's cache warm while a session waits; and an
247
+ * extension may ask by the session's models for itself — and every one of
248
+ * them comes by one step: the request is made ready, and handed to the
249
+ * model's provider. So that step is where a call is asked whether its model
250
+ * may be asked again, and the provider's reply is where what it used is seen.
251
+ * (pi does not export the step: it is a method of what trama made, and is
252
+ * made to stand aside for this.)
253
+ */
254
+ function watch(models, asking) {
255
+ const standing = models;
256
+ const prepare = standing.prepareRequest.bind(models);
257
+ // A provider for a call that is to ask no more: whatever it is asked by, the request ends as one that was
258
+ // cancelled before it was sent — or, where what comes of it comes all at once, fails saying so. But to have
259
+ // a provider give up a reply it was keeping for later is to ask no model: that is done, whoever is stopped.
260
+ const refusing = (model, options) => {
261
+ const refused = async function* () {
262
+ yield notAsked(model, NO_MORE);
263
+ };
264
+ const failed = async () => { throw new Error(NO_MORE); };
265
+ return {
266
+ stream: refused, streamSimple: refused, fetchDeferred: refused, generateImages: failed, classify: failed,
267
+ cancelDeferred: async (_model, handle) => {
268
+ const real = await prepare(model, options);
269
+ const cancel = real.provider.cancelDeferred;
270
+ if (typeof cancel !== "function")
271
+ throw new Error(`Provider ${model.provider} does not support deferred responses`);
272
+ await cancel.call(real.provider, real.model, handle, real.options);
273
+ },
274
+ };
275
+ };
276
+ // A provider that is an extension's own code may ask another model by these same models, and hand back what
277
+ // that model answered — there and then, from a queue of its own, or a reply it had asked for before: a reply
278
+ // that passes here twice, and used what it used once. So what a reply used is counted by the reply: once for
279
+ // each account of usage that passes, wherever and however often it passes. (pi hands a reply on as it is; a
280
+ // provider that makes a copy of one, account and all, has made another reply of it as far as can be told.)
281
+ const counted = new WeakSet();
282
+ // What is being asked at this moment is kept count of, for whoever waits on it (see leaveExtensions): the
283
+ // replies that are being gone through, and the requests that are being made ready. (A request that is made
284
+ // ready and then not asked — its asker was stopped before it came to that — never was one a model worked on.)
285
+ const count = (of, by) => {
286
+ asking[of] += by;
287
+ asking.changed?.();
288
+ };
289
+ const heard = async function* (reply, ...released) {
290
+ count("answering", 1);
291
+ try {
292
+ for await (const event of reply) {
293
+ const used = usageAtEnd(event);
294
+ if (used && !counted.has(used)) {
295
+ counted.add(used);
296
+ addReply(asking.seen, used);
297
+ asking.replied?.();
298
+ }
299
+ yield event;
300
+ }
301
+ }
302
+ finally {
303
+ count("answering", -1);
304
+ for (const release of released)
305
+ release();
306
+ }
307
+ };
308
+ // And every request goes with the word that stops it (Asking.cut), beside whatever its asker gave it to be
309
+ // stopped by: asked here or elsewhere, by pi or by an extension for itself.
310
+ const stoppable = (options) => {
311
+ const { signal, release } = either(options?.signal, asking.cut.signal);
312
+ return { options: { ...options, signal }, release };
313
+ };
314
+ // What a request's asker would make of its headers (pi's agent has a function go with every request of its
315
+ // own, for extensions that would: it makes nothing of them where none does) is seen as it is made: whether
316
+ // the headers came out of it other than they went in — name by name, in their order, and a name with nothing
317
+ // under it a name all the same: pi lays headers one over another by all of that.
318
+ // (What cannot be told at all is not what it was, for all that can be said of it.)
319
+ const told = (headers) => {
320
+ try {
321
+ return JSON.stringify(headers !== null && typeof headers === "object"
322
+ ? Object.entries(headers).map(([name, value]) => [name, value === undefined ? 0 : [value]]) : [headers]);
323
+ }
324
+ catch {
325
+ return undefined;
326
+ }
327
+ };
328
+ const seeing = (options, headers) => {
329
+ const theirs = options?.transformHeaders;
330
+ if (typeof theirs !== "function")
331
+ return options;
332
+ return {
333
+ ...options,
334
+ transformHeaders: async (had) => {
335
+ const were = told(had);
336
+ const made = await theirs(had);
337
+ if (were === undefined || told(made) !== were)
338
+ headers.changed = true;
339
+ return made;
340
+ },
341
+ };
342
+ };
343
+ standing.prepareRequest = async (model, options) => {
344
+ count("readying", 1);
345
+ try {
346
+ await asking.before?.();
347
+ // (Asked no more.)
348
+ if (asking.stopped?.())
349
+ return { provider: refusing(model, options), model, options: options ?? {} };
350
+ const headers = { changed: false };
351
+ const prepared = await prepare(model, seeing(options, headers));
352
+ return {
353
+ ...prepared,
354
+ provider: new Proxy(prepared.provider, {
355
+ get(target, key) {
356
+ const value = Reflect.get(target, key, target);
357
+ if (typeof value !== "function")
358
+ return value;
359
+ const by = ASKED_BY.get(key);
360
+ if (!by)
361
+ return value.bind(target);
362
+ // A model is asked: what a provider is handed is the model, what it is to be sent, and the options.
363
+ // Elsewhere, where that can be — or here, by the provider itself. What comes all at once is made a
364
+ // reply of one event, and counted and waited for as any reply; and whoever asked is given it whole.
365
+ return (...sent) => {
366
+ const there = stoppable(options), here = stoppable(sent[2]);
367
+ const reply = heard((async function* () {
368
+ const elsewhere = by.way && await asking.elsewhere?.(by.way, model, sent[1], there.options, headers);
369
+ if (elsewhere)
370
+ yield* elsewhere;
371
+ else if (by.events)
372
+ yield* value.call(target, sent[0], sent[1], here.options);
373
+ else
374
+ yield { type: "done", message: await value.call(target, sent[0], sent[1], here.options) };
375
+ })(), there.release, here.release);
376
+ return by.events ? reply : wholeOf(reply);
377
+ };
378
+ },
379
+ }),
380
+ };
381
+ }
382
+ finally {
383
+ // (Made ready, or not: counted until whoever had it made ready has had their turn to ask for the reply,
384
+ // which is counted from there — so that no moment between the two is one in which nothing is being asked.)
385
+ setImmediate(() => count("readying", -1));
386
+ }
387
+ };
388
+ }
389
+ /**
390
+ * Have what is asked on a session's account be its call's, from before the
391
+ * session is there: an extension may ask a model as it is told that the
392
+ * session begins, and that is the call's as much as what its agent asks —
393
+ * also where the call then fails before its agent was ever set going.
394
+ *
395
+ * Each time a model is about to be asked, what the call has used so far is
396
+ * said, and whoever hears it waited for: they may cancel the call there, and
397
+ * the model is then not asked. (One at a time: whoever hears it is told of
398
+ * one request, and answers for that one.) And a call that was cancelled, or
399
+ * whose session is gone, asks no more, whoever would have it ask — its agent,
400
+ * pi keeping a cache warm, an extension for itself. Gives back what says to
401
+ * stop the call while it is at its work.
402
+ */
403
+ function account(asking, call, signal, session) {
404
+ const { sofar, had, relay } = call;
405
+ const stopped = signal ? AbortSignal.any([signal, asking.refusal.signal]) : asking.refusal.signal;
406
+ asking.stop = stopped;
407
+ const counted = () => {
408
+ const its = session();
409
+ return its ? usageOf(its, asking.seen) : atLeast(undefined, asking.seen);
410
+ };
411
+ let heard = Promise.resolve();
412
+ // (A call that has its answer is not cancelled for what it has used: whoever hears says instead that
413
+ // nothing more may be asked beside it — and nothing is, from then.)
414
+ let noMore = false;
415
+ // (What stops a call in its work — it was cancelled, or cannot have the tools it named — stops what is asked
416
+ // on its account. Once it is over, a call that could not have its tools is one that failed, like any: what
417
+ // an extension asks beside it, as it is told the session ends, is asked. And nothing is, once what was being
418
+ // asked has been stopped — the session is being let go of: there is nobody left to say what the call has
419
+ // used to, and to wait for.)
420
+ const halted = () => asking.cut.signal.aborted || (asking.over ? signal?.aborted === true : stopped.aborted);
421
+ asking.stopped = () => asking.gone || noMore || halted();
422
+ // (Whoever hears what the call has used is not waited for once it is to ask no more, whatever they would
423
+ // say: the call was cancelled or cannot have what it named, while it is at its work — and, whenever the
424
+ // wait began, once what was being asked has been stopped.)
425
+ const atWork = AbortSignal.any([stopped, asking.cut.signal]);
426
+ asking.before = () => heard = heard.then(async () => {
427
+ const usage = sofar && !asking.gone && !noMore && !halted() && counted();
428
+ if (usage && await rejectOnAbort(Promise.resolve(sofar(usage, asking.over)), asking.over ? asking.cut.signal : atWork).catch(() => { }) === false && asking.over)
429
+ noMore = true;
430
+ });
431
+ // (As soon as a reply has come, what the call has used is said to whoever would not otherwise know
432
+ // it, were this process to be ended: before the reply is anybody else's to hear of.)
433
+ asking.replied = () => {
434
+ const usage = had && !asking.gone && counted();
435
+ if (usage)
436
+ had(usage);
437
+ };
438
+ // Where the call has extensions and somebody to ask its model by, its model is asked by them: what
439
+ // a reply used is then read where no extension is. Not where an extension has made the model's
440
+ // provider its own, has a hand in what a provider is sent and answers, or has made
441
+ // this process other than it was in what a request goes by — the model is then asked here, as the
442
+ // extension means it to be — nor where the request is not one that can be handed over: something
443
+ // goes with it that is not data, and whoever asked may mean something by it (see dataOf).
444
+ if (relay && call.extensions) {
445
+ asking.elsewhere = async (by, model, context, options = {}, headers) => {
446
+ const its = session();
447
+ if (!its || !asItWas() || asking.models.getRegisteredProviderIds().includes(model.provider))
448
+ return undefined;
449
+ if (HANDS_IN.some(event => its.extensionRunner.hasHandlers(event)))
450
+ return undefined;
451
+ // All that goes with a request is data, or the request is not handed over: whoever made it may mean
452
+ // something by it. But what is known to be nothing a provider is handed is left out first.
453
+ // What would make something of the request's headers, where that was seen to be nothing (see `watch`):
454
+ // the request is the same without it.
455
+ if (headers.changed)
456
+ return undefined;
457
+ const left = new Set(["transformHeaders"]);
458
+ // pi's own hooks, which do nothing here (see HANDS_IN) — and are pi's own where they are the very ones
459
+ // the session's agent has: any other is its asker's hand in the request.
460
+ const agent = its.agent;
461
+ for (const hook of HOOKS) {
462
+ if (options[hook] === undefined)
463
+ continue;
464
+ if (options[hook] !== agent[hook])
465
+ return undefined;
466
+ left.add(hook);
467
+ }
468
+ // And of a request the agent makes for itself, the rest of what its loop is set up by (see LOOPS); and
469
+ // in its conversation, which is of pi's making, what a tool kept beside its result — no provider is
470
+ // sent that, so it need not be what it was on the other side.
471
+ const agents = by === "streamSimple" && HOOKS.every(hook => options[hook] === agent[hook]);
472
+ if (agents)
473
+ for (const name of LOOPS)
474
+ left.add(name);
475
+ let data;
476
+ try {
477
+ data = dataOf(Object.fromEntries(Object.entries(options).filter(([name]) => !left.has(name))));
478
+ if (!data || (!agents && !isData(context)))
479
+ return undefined;
480
+ }
481
+ catch {
482
+ // (What cannot be gone through — it goes deeper than can be followed — is not known to be data.)
483
+ return undefined;
484
+ }
485
+ return relay.ask({ ...(by !== "streamSimple" && { by }), model, context, options: data, ...(asking.over && { answered: true }) }, options.signal);
486
+ };
487
+ }
488
+ return stopped;
489
+ }
490
+ /**
491
+ * Tell a session's extensions that it is over, and wait for them — a while:
492
+ * an extension may hold what is to be let go of (a server it started), and
493
+ * one that does not answer is not waited for. What one of them put to the
494
+ * model and is still on its way there is seen off too, before the session is
495
+ * gone: it is stopped as it begins to ask (see `ask`), where a session that
496
+ * is disposed of under it would let it through.
497
+ *
498
+ * An extension that is asking a model is not one that does not answer: it
499
+ * may be summing up what was done, and a model takes the time it takes — a
500
+ * quarter of a minute for a page, a minute where it thinks first. So there
501
+ * are two clocks, and one of them runs at a time. The while extensions are
502
+ * given is their own, all told: it runs while no model is at work on what
503
+ * was asked on the session's account, and stands while one is. And the time
504
+ * a model may be at work for them, all told, is what pi gives one request of
505
+ * its own (`most`; none, where pi has no limit): it runs while a reply is
506
+ * being gone through. What they have all been told, and is still being asked
507
+ * beside what they answered, is waited for the same way. (A request that is
508
+ * only ever made ready — a session set going again and stopped as it begins,
509
+ * over and over — is no model at work: it is on their own time.) When either
510
+ * has run out, whoever let go of the session stops what is still asked (see
511
+ * Asking.cut): nothing is left being asked for a reply on the account of a
512
+ * session that is gone, to be nobody's.
513
+ */
514
+ async function leaveExtensions(session, puts, asking, most) {
515
+ const left = (async () => {
516
+ await session.extensionRunner.emit({ type: "session_shutdown", reason: "quit" });
517
+ while (puts.size > 0)
518
+ await Promise.allSettled([...puts]);
519
+ })().catch(() => { });
520
+ await new Promise((resolve) => {
521
+ // Whether they have all answered, and whether the wait is over; what is left of their own time, and of a
522
+ // model's for them; and the clock that runs one of those down — which, and since when.
523
+ let told = false, ended = false, theirs = EXTENSION_LEAVE_MS, models = most > 0 ? most : Infinity;
524
+ let clock, atWork = false, since = performance.now();
525
+ const done = () => {
526
+ if (ended)
527
+ return;
528
+ ended = true;
529
+ clearTimeout(clock);
530
+ if (asking)
531
+ asking.changed = undefined;
532
+ asking?.cut.signal.removeEventListener("abort", look);
533
+ resolve();
534
+ };
535
+ const look = () => {
536
+ if (ended)
537
+ return;
538
+ const now = performance.now();
539
+ if (atWork)
540
+ models -= now - since;
541
+ else
542
+ theirs -= now - since;
543
+ clearTimeout(clock);
544
+ // (What was stopped — the call was cancelled — is no model at work, however long it takes to end: it is
545
+ // given a moment for that when the wait is over, like anything that is stopped. See allEnded.)
546
+ const asked = asking && !asking.cut.signal.aborted ? asking : undefined;
547
+ atWork = asked !== undefined && asked.answering > 0;
548
+ since = now;
549
+ if (!atWork && told && !asked?.readying)
550
+ return done();
551
+ const has = atWork ? models : theirs;
552
+ // (A timer takes no more than this.)
553
+ clock = has === Infinity ? undefined : setTimeout(done, Math.min(Math.max(0, has), 2 ** 31 - 1));
554
+ };
555
+ if (asking)
556
+ asking.changed = look;
557
+ asking?.cut.signal.addEventListener("abort", look, { once: true });
558
+ void left.then(() => {
559
+ told = true;
560
+ look();
561
+ });
562
+ look();
563
+ });
564
+ }
565
+ /** Wait until no reply is being gone through on a session's account — what was stopped ends, and says what it had used — or for a moment, whichever is less. */
566
+ function allEnded(asking) {
567
+ return new Promise((resolve) => {
568
+ if (asking.answering <= 0)
569
+ return resolve();
570
+ const over = () => {
571
+ clearTimeout(late);
572
+ asking.changed = undefined;
573
+ resolve();
574
+ };
575
+ const late = setTimeout(over, STOPPED_MS);
576
+ asking.changed = () => { if (asking.answering <= 0)
577
+ over(); };
578
+ });
579
+ }
580
+ /**
581
+ * The most a model is waited for, at work for a session's extensions as it
582
+ * ends: what pi gives a request of its own, as the session's settings have
583
+ * it — the time for a request to a provider, or else the time a connection
584
+ * may be silent, which is none at all where the settings say so. What the
585
+ * settings have that pi itself would not take is not taken here either:
586
+ * then it is what pi gives where they say nothing.
587
+ */
588
+ function longestAsked(session) {
589
+ try {
590
+ const settings = session.settingsManager;
591
+ const own = settings?.getProviderRetrySettings?.().timeoutMs;
592
+ if (typeof own === "number" && Number.isFinite(own) && own > 0)
593
+ return own;
594
+ const silent = settings?.getHttpIdleTimeoutMs?.();
595
+ return typeof silent === "number" && silent >= 0 ? silent : REQUEST_MS;
596
+ }
597
+ catch {
598
+ return REQUEST_MS;
599
+ }
600
+ }
601
+ /**
602
+ * What a session has used: pi's own count, over everything the session asked
603
+ * of its model — a summary it made of a long conversation included — and
604
+ * what trama saw come (`seen`: see `watch`), where that is more: a reply that
605
+ * has come and is not on pi's record yet, and what an extension asked for
606
+ * itself, which never is. Nothing, where no tokens were counted: the model
607
+ * was never reached, or does not say.
608
+ */
609
+ function usageOf(session, seen) {
610
+ const { tokens, cost } = session.getSessionStats();
611
+ const { input, output, cacheRead, cacheWrite } = tokens;
612
+ return atLeast({ ...(session.model && { model: nameOf(session.model) }), input, output, cacheRead, cacheWrite, cost }, seen);
613
+ }
614
+ /**
615
+ * The model's answer: the text of the last reply the session has on record.
616
+ *
617
+ * The record, not the conversation as the model would next be shown it: pi
618
+ * takes a reply that failed out of that — one the provider refused as too
619
+ * long, one cut off — and what is left there to be last is an earlier turn.
620
+ * And an answer only if the model ended it itself: a reply that is the
621
+ * provider's error, or was cut off at the output limit, is the call's failure
622
+ * (the second with what there was of it: see CutOff). A reply cut off in the
623
+ * middle of a tool call is never the last: pi has the model make the call again.
624
+ */
625
+ function answerOf(session, taken = false) {
626
+ const replies = session.sessionManager.getEntries()
627
+ .flatMap(entry => (entry.type === "message" && entry.message.role === "assistant" ? [entry.message] : []));
628
+ const reply = replies.at(-1);
629
+ const text = reply?.content.map(block => (block.type === "text" ? block.text : "")).join("") ?? "";
630
+ if (reply?.stopReason === "error")
631
+ throw new Error(`The model did not answer: ${reply.errorMessage ?? "no reason given"}`);
632
+ if (reply?.stopReason === "length")
633
+ throw new CutOff(text);
634
+ if (!text) {
635
+ throw new Error(taken
636
+ ? "The prompt was taken by an extension — a command of its own, or its reading of what is asked — and the model gave no answer."
637
+ : "Empty response from LLM");
638
+ }
639
+ return text;
640
+ }
641
+ /**
642
+ * The pi coding agent: a fresh in-memory session for every call — in this
643
+ * process, or in a process of its own (see agent-host.ts). A call that has
644
+ * extensions is served in one: an extension is somebody's code, and where it
645
+ * runs it can hold up, or bring down, everything else that runs there. And
646
+ * so is every call of an adapter that was given variables (`env`: a run's):
647
+ * what an agent finds of pi, which key it has for a provider, and what the
648
+ * commands it runs are given, are a process's — and this process is the
649
+ * runner's, whose own are not a run's to change.
650
+ */
13
651
  export class PiAdapter {
14
652
  config;
15
- constructor(config) {
653
+ /** Whether every call is served in a process of its own: where those processes are given variables this one has not. */
654
+ apart;
655
+ /** The processes that serve this adapter's calls. */
656
+ hosts;
657
+ constructor(config, env) {
16
658
  this.config = config;
659
+ // (Variables that are none are none given: such a run's calls are served as any run's.)
660
+ this.apart = env !== undefined && Object.keys(env).length > 0;
661
+ this.hosts = createAgentHosts(this.apart ? env : undefined);
17
662
  }
18
- async createSession(cwd, systemPrompt, signal) {
663
+ /** Have a call served: here, or by a host. */
664
+ async ask(prompt, call) {
665
+ return call.extensions || this.apart ? this.hosts.ask(this.config, prompt, call) : this.serve(prompt, call);
666
+ }
667
+ /** End the processes that served calls: what this adapter was for is over. (It can be asked again: it starts them anew.) */
668
+ async close() {
669
+ await this.hosts.close();
670
+ }
671
+ async createSession(cwd, systemPrompt, signal, asked = {}) {
19
672
  // Each step below is given up on the moment the call is cancelled.
20
673
  const raceAbort = (step) => rejectOnAbort(step, signal);
21
- const { createAgentSession, SessionManager, DefaultResourceLoader, ModelRuntime, getAgentDir } = await raceAbort(loadPi());
674
+ const { createAgentSession, SessionManager, SettingsManager, DefaultResourceLoader, ModelRuntime, getAgentDir, formatSkillsForPrompt } = await raceAbort(loadPi());
22
675
  const agentDir = getAgentDir();
23
- const resourceLoader = new DefaultResourceLoader({
676
+ // Skills and prompt templates are pi's for the user and for where the agent works — the
677
+ // project's own, in its .pi directory, among them: and a call has those it chose, and no others.
678
+ const found = { skills: [], templates: [] };
679
+ const only = (choice, items) => {
680
+ const names = named(choice);
681
+ return names ? items.filter(item => names.includes(item.name)) : items;
682
+ };
683
+ const resources = new DefaultResourceLoader({
24
684
  cwd,
25
685
  agentDir,
26
686
  noExtensions: true,
27
- noSkills: true,
687
+ noSkills: !chosen(asked.skills),
688
+ noPromptTemplates: !chosen(asked.templates),
689
+ skillsOverride: (base) => {
690
+ found.skills = base.skills.map(skill => skill.name);
691
+ return { ...base, skills: only(asked.skills, base.skills) };
692
+ },
693
+ promptsOverride: (base) => {
694
+ found.templates = base.prompts.map(template => template.name);
695
+ return { ...base, prompts: only(asked.templates, base.prompts) };
696
+ },
28
697
  ...(systemPrompt && { appendSystemPrompt: [systemPrompt] }),
29
698
  });
30
- await raceAbort(resourceLoader.reload());
699
+ await raceAbort(resources.reload());
700
+ // Extensions are the user's own, unless the call says the project's are its too: an extension
701
+ // is code, and what a project holds its program can write. So they are loaded apart, by a
702
+ // loader that takes of the project's what the call said it may, and the session has the rest
703
+ // from the other. And so, where the project's are not the call's, an extension that asks is
704
+ // told the project is not one to be trusted — pi has extensions ask that before they take
705
+ // anything of a project's for their own. The session's settings are otherwise what any call's
706
+ // are, the project's among them: a call does not come to other tools, or another shell, for
707
+ // having asked for extensions.
708
+ if (asked.extensions !== undefined && typeof asked.extensions !== "boolean" && asked.extensions !== "project") {
709
+ throw new Error(`extensions is true, false or "project", not ${JSON.stringify(asked.extensions)}`);
710
+ }
711
+ // Whose extensions: the user's — or the project's with them, where the call says so. Then the project
712
+ // is one to be trusted, as it is when pi is run in it and told to: its extensions are loaded, the
713
+ // MCP servers it names are started, and an extension that asks is told so.
714
+ const withProjects = asked.extensions === "project";
715
+ let resourceLoader = resources;
716
+ const wary = asked.extensions && !withProjects
717
+ ? Object.assign(Object.create(SettingsManager.create(cwd, agentDir)), { isProjectTrusted: () => false })
718
+ : undefined;
719
+ const extended = asked.extensions ? { puts: new Set(), over: false } : undefined;
720
+ if (extended) {
721
+ // A session that is to ask no more — its call cancelled, or over — is stopped each time it begins to
722
+ // (see `ask`); and an extension may set it going again each time it stops, by more ways than one. All
723
+ // of that is done without the runner coming to anything else: not to the clock that is to give the
724
+ // call up, nor to any other run. So each beginning of such a session waits a turn of the runner's —
725
+ // by a handler of trama's own among the extensions, which is what pi waits for when a run begins.
726
+ // And where the agent's model is about to be asked for the first time — for a turn, or to sum a
727
+ // conversation up — what the agent has by then is looked at from there too (see whyNotTheTools).
728
+ const breathes = (pi) => {
729
+ pi.on("agent_start", async () => {
730
+ if (extended.over || signal?.aborted)
731
+ await new Promise(resolve => setImmediate(resolve));
732
+ });
733
+ const looks = () => {
734
+ extended.look?.();
735
+ extended.look = undefined;
736
+ };
737
+ pi.on("turn_start", looks);
738
+ pi.on("session_before_compact", looks);
739
+ };
740
+ const builtIn = await raceAbort(builtInExtensions());
741
+ // (What this process is, before anything of an extension's is loaded in it: see shapeOf.)
742
+ asLoaded ??= shapeOf();
743
+ const own = new DefaultResourceLoader({
744
+ cwd,
745
+ agentDir,
746
+ extensionFactories: [...builtIn, breathes],
747
+ settingsManager: SettingsManager.create(cwd, agentDir, { projectTrusted: withProjects }),
748
+ // (Nothing but its extensions is asked of it, and so it need find nothing else.)
749
+ noSkills: true,
750
+ noPromptTemplates: true,
751
+ noThemes: true,
752
+ noContextFiles: true,
753
+ });
754
+ await raceAbort(own.reload());
755
+ resourceLoader = {
756
+ getExtensions: () => own.getExtensions(),
757
+ getSkills: () => resources.getSkills(),
758
+ getPrompts: () => resources.getPrompts(),
759
+ getThemes: () => resources.getThemes(),
760
+ getAgentsFiles: () => resources.getAgentsFiles(),
761
+ getSystemPrompt: () => resources.getSystemPrompt(),
762
+ getSystemPromptSource: () => resources.getSystemPromptSource(),
763
+ getAppendSystemPrompt: () => resources.getAppendSystemPrompt(),
764
+ getAppendSystemPromptSources: () => resources.getAppendSystemPromptSources(),
765
+ extendResources: (paths) => resources.extendResources(paths),
766
+ reload: async (options) => {
767
+ await resources.reload(options);
768
+ await own.reload();
769
+ },
770
+ };
771
+ }
31
772
  // Resolve the model through pi's model runtime (built-in catalog plus the
32
- // user's models.json). An unknown provider/model resolves to undefined, in
33
- // which case pi falls back to its own default selection.
773
+ // user's models.json). The project's own, if it is unknown there, resolves
774
+ // to undefined, in which case pi falls back to its own default selection;
775
+ // a model a call names is that model or the call fails.
34
776
  const modelRuntime = await raceAbort(ModelRuntime.create({ signal }));
35
- const model = modelRuntime.getModel(this.config.provider, this.config.model);
777
+ const asking = { models: modelRuntime, seen: nothingYet(), answering: 0, readying: 0, cut: new AbortController(), over: false, gone: false, refusal: new AbortController() };
778
+ watch(modelRuntime, asking);
779
+ // (A call names it "provider/model": the provider's name ends at a stroke, and either name may have more of them.)
780
+ const strokes = [...(asked.model ?? "").matchAll(/\//g)].map(stroke => stroke.index);
781
+ const model = asked.model === undefined
782
+ ? modelRuntime.getModel(this.config.provider, this.config.model)
783
+ : strokes.map(at => modelRuntime.getModel(asked.model.slice(0, at), asked.model.slice(at + 1))).find(Boolean);
784
+ if (asked.model !== undefined && !model) {
785
+ throw new Error(`Unknown model "${asked.model}". A model is named "provider/model", as pi's model catalog has it.`);
786
+ }
36
787
  // Keep a reference to the raw promise so we can clean up a late-arriving session
37
788
  const sessionPromise = createAgentSession({
38
789
  cwd,
@@ -41,25 +792,147 @@ export class PiAdapter {
41
792
  model,
42
793
  sessionManager: SessionManager.inMemory(cwd),
43
794
  resourceLoader,
795
+ ...(wary && { settingsManager: wary }),
796
+ ...(asked.thinking !== undefined && { thinkingLevel: asked.thinking }),
797
+ ...(asked.tools && { tools: asked.tools }),
44
798
  });
799
+ let session;
800
+ // The telling of extensions that a session begins, while it lasts.
801
+ let beginning;
802
+ const stopped = account(asking, asked, signal, () => session);
803
+ // (A call that is cancelled asks no more — and what is being asked for it then is asked no further, whoever
804
+ // asked: from here, while its session is being made — and let go of, should that fail. Once the session
805
+ // is there, it is whoever has it who listens: see `serve`.)
806
+ const offCut = onAbort(signal, () => asking.cut.abort());
45
807
  try {
46
- const { session } = await raceAbort(sessionPromise);
47
- if (!model) {
48
- // With nothing to fall back to, pi reports a placeholder model that is
49
- // not in its catalog — only name the fallback when it is a real one.
50
- const picked = session.model;
51
- const fallback = picked && modelRuntime.getModel(picked.provider, picked.id)
52
- ? `${picked.provider}/${picked.id}` : null;
53
- this.warnUnknownModel(fallback);
808
+ ({ session } = await raceAbort(sessionPromise));
809
+ this.asking.set(session, asking);
810
+ // A session that is set going again once its call is over, or stopped, is stopped as it begins to: a
811
+ // command of an extension that asks the model once more, or what an extension starts while it is being
812
+ // told that the call is over.
813
+ if (asked.sofar || asked.extensions) {
814
+ const here = session;
815
+ here.subscribe((event) => {
816
+ if (event.type !== "turn_start" && event.type !== "compaction_start")
817
+ return;
818
+ if (asking.over || stopped.aborted)
819
+ void here.abort().catch(() => { });
820
+ });
821
+ }
822
+ // An extension is told that its session has begun, as pi tells it where pi runs by itself:
823
+ // that is when it sets itself up. What goes wrong in one later is said, and is not the call's failure.
824
+ // A command of one can wait for the model it asked, as it can there; the session is one call's, and
825
+ // is not to be left for another.
826
+ if (extended) {
827
+ const here = session;
828
+ const stays = async () => ({ cancelled: true });
829
+ // What an extension puts to the model — a command of it, asking — is the call's to wait for (see
830
+ // `ask`), and the command's own, where it waits: pi calls a session idle while a question is still
831
+ // on its way to being asked, so what was put is kept account of here, as it is put.
832
+ const { puts } = extended;
833
+ this.extended.set(session, extended);
834
+ const prompting = session.prompt.bind(session);
835
+ session.prompt = (text, options) => {
836
+ const put = prompting(text, options);
837
+ if (options?.source !== "extension")
838
+ return put;
839
+ const over = () => { puts.delete(put); };
840
+ puts.add(put);
841
+ put.then(over, over);
842
+ return put;
843
+ };
844
+ // A command that waits is told, when it has waited, that its call was cancelled — where it was: one
845
+ // that asks until it is satisfied then stops asking, and need not be stopped each time it begins to.
846
+ const idle = async () => {
847
+ while (puts.size > 0)
848
+ await Promise.allSettled([...puts]);
849
+ await here.waitForIdle();
850
+ throwIfAborted(signal);
851
+ };
852
+ beginning = session.bindExtensions({
853
+ mode: "print",
854
+ commandContextActions: {
855
+ waitForIdle: idle,
856
+ newSession: stays,
857
+ fork: stays,
858
+ switchSession: stays,
859
+ navigateTree: async (target, options) => ({ cancelled: (await here.navigateTree(target, options)).cancelled }),
860
+ reload: () => here.reload(),
861
+ },
862
+ // (A command that was not let wait, its call being cancelled, did not fail: nothing is said of it.)
863
+ onError: (failure) => {
864
+ if (signal?.aborted && failure.error === "Aborted")
865
+ return;
866
+ console.warn(`[trama] an extension failed (${failure.extensionPath}): ${failure.error}`);
867
+ },
868
+ });
869
+ await raceAbort(beginning);
54
870
  }
871
+ // With no model it can use, pi reports a placeholder that is not in its
872
+ // catalog — a model is named only when it is a real one.
873
+ const picked = session.model;
874
+ const serving = picked && modelRuntime.getModel(picked.provider, picked.id) ? nameOf(picked) : null;
875
+ const refusal = whyNotAsAsked(session, asked, serving, found, formatSkillsForPrompt);
876
+ if (refusal)
877
+ throw new Error(refusal);
878
+ if (!model)
879
+ this.warnUnknownModel(serving);
880
+ offCut();
55
881
  return session;
56
882
  }
57
883
  catch (err) {
58
- // If abort won the race, the real promise may still resolve later — dispose it
59
- sessionPromise.then(({ session }) => session.dispose()).catch(() => { });
884
+ // A session that is here is let go of, once, before the call fails — its extensions, if they were
885
+ // still being told that it begins, having heard that out first (or been given the while they are
886
+ // given to hear of its end). Where the call was cancelled before the session came, it may still
887
+ // come: it is disposed of when it does, and no extension was told of it.
888
+ // The call is over, failed; and what its extensions asked a model, as they were told that the session
889
+ // begins and that it is over, is what it used — said when the session is gone, as of any call.
890
+ asking.over = true;
891
+ if (extended)
892
+ extended.over = true;
893
+ try {
894
+ if (session) {
895
+ if (beginning)
896
+ await within(beginning, EXTENSION_LEAVE_MS);
897
+ await this.letGoOf(session, asked);
898
+ }
899
+ else {
900
+ sessionPromise.then(({ session: late }) => late.dispose()).catch(() => { });
901
+ }
902
+ }
903
+ finally {
904
+ asking.gone = true;
905
+ offCut();
906
+ const usage = session && asked.used && usageOf(session, asking.seen);
907
+ if (usage)
908
+ asked.used(usage);
909
+ }
60
910
  throw err;
61
911
  }
62
912
  }
913
+ /** What is kept of each session that has extensions. */
914
+ extended = new WeakMap();
915
+ /** Where trama stands when each session's model is asked. */
916
+ asking = new WeakMap();
917
+ /** Be done with a session: its extensions, where it has any, told first that it is over. */
918
+ async letGoOf(session, asked) {
919
+ const asking = this.asking.get(session);
920
+ try {
921
+ if (asked.extensions)
922
+ await leaveExtensions(session, this.extended.get(session)?.puts ?? new Set(), asking, longestAsked(session));
923
+ }
924
+ catch (err) {
925
+ console.warn(`[trama] an extension could not be told its session is over: ${messageOf(err)}`);
926
+ }
927
+ finally {
928
+ // What is still being asked on its account — it was waited for as long as anything is — is asked no
929
+ // further; and has a moment to end, and say what it had used: that is the call's too.
930
+ asking?.cut.abort();
931
+ if (asking && asked.extensions)
932
+ await allEnded(asking);
933
+ session.dispose();
934
+ }
935
+ }
63
936
  /**
64
937
  * The configured provider/model is not in pi's catalog, so pi picked a model
65
938
  * on its own. Say so once — otherwise a typo silently runs a different model.
@@ -75,47 +948,105 @@ export class PiAdapter {
75
948
  : `pi has no fallback model available, so LLM calls will fail. `) +
76
949
  `Check "provider" and "model" in ~/.trama/config.json or the project's meta.json.`);
77
950
  }
78
- extractText(session) {
79
- const messages = session.state.messages;
80
- for (let i = messages.length - 1; i >= 0; i--) {
81
- const msg = messages[i];
82
- if ("role" in msg && msg.role === "assistant") {
83
- return msg.content
84
- .filter(b => b.type === "text" && b.text)
85
- .map(b => b.text)
86
- .join("");
87
- }
88
- }
89
- return "";
90
- }
91
951
  /**
92
- * Run one prompt in a fresh session and return the assistant's text reply.
952
+ * Serve a call in this process: run one prompt in a fresh session and
953
+ * return the assistant's text reply. (What a host does; and what `ask`
954
+ * does itself for a call without extensions.)
93
955
  *
94
956
  * Cancellation during `createSession` is handled step-by-step inside it; once
95
- * `session.prompt()` is running, abort disposes the session so pi settles the
96
- * in-flight prompt (pi 1.x resolves rather than rejects on dispose, so
97
- * `signal.aborted` is checked again when `prompt()` returns).
957
+ * `session.prompt()` is running, a cancelled call has pi abort the run — which
958
+ * settles the prompt (pi 1.x resolves it rather than rejecting, so
959
+ * `signal.aborted` is checked again when `prompt()` returns) and leaves on
960
+ * the session's record what the request that was cut off had taken by then.
98
961
  */
99
- async ask(prompt, call) {
100
- const { cwd, system, signal } = call;
962
+ async serve(prompt, call) {
963
+ const { cwd, system, signal, used, sofar } = call;
101
964
  throwIfAborted(signal);
102
- const session = await this.createSession(cwd, system, signal);
965
+ const session = await this.createSession(cwd, system, signal, call);
966
+ // (A call that is cancelled asks no more — and what is being asked for it then is asked no further, whoever
967
+ // asked: while it is at its work, and while its extensions are told that it is over.)
968
+ const offCut = onAbort(signal, () => this.asking.get(session)?.cut.abort());
103
969
  let offAbort = () => { };
970
+ // What is kept of the call where its model is asked (see `account`): whether it has come to its end, and
971
+ // whether its session is gone. (A session that was not made here has nothing asked on its account that
972
+ // is seen: what is kept of its call is then kept here alone.)
973
+ const asking = this.asking.get(session);
974
+ const its = asking ?? { over: false, gone: false, refusal: new AbortController() };
975
+ // What is kept of the session beside it, where it has extensions.
976
+ const extended = this.extended.get(session);
977
+ // Why the call cannot have the tools it named, where that was found as its run began. It is
978
+ // then stopped as a cancelled call is — it asks nothing, and what would hold it is not waited
979
+ // for long — and fails with that.
980
+ let refused;
981
+ const stopped = asking?.stop ?? (signal ? AbortSignal.any([signal, its.refusal.signal]) : its.refusal.signal);
104
982
  try {
105
983
  throwIfAborted(signal);
106
- offAbort = onAbort(signal, () => session.dispose());
107
- await session.prompt(prompt);
984
+ offAbort = onAbort(signal, () => { session.abort().catch(() => { }); });
985
+ // Where the agent has not the tools the call named, that is found as its run begins (see
986
+ // createSession), and the call is stopped as one that was cancelled is.
987
+ if (extended && call.extensions) {
988
+ extended.look = () => {
989
+ refused = whyNotTheTools(session, call.tools);
990
+ if (refused === undefined)
991
+ return;
992
+ // (The session is stopped where it hears next that a turn begins — just after this: see createSession.)
993
+ extended.over = true;
994
+ its.refusal.abort();
995
+ };
996
+ }
997
+ if (!asking && (sofar || call.extensions)) {
998
+ session.subscribe((event) => {
999
+ if (event.type !== "turn_start" && event.type !== "compaction_start")
1000
+ return;
1001
+ if (its.over || stopped.aborted)
1002
+ void session.abort().catch(() => { });
1003
+ });
1004
+ }
1005
+ // The prompt is a program's text, whatever it begins with — but where the call has the user's skills,
1006
+ // templates or extensions, and does not say its prompt is text all the same: each of those has a line of
1007
+ // its own to be called up by ("/skill:name", "/name", a command), and pi reads a prompt for all of them
1008
+ // or for none.
1009
+ let taken = false;
1010
+ const answered = async () => {
1011
+ await session.prompt(prompt, {
1012
+ expandPromptTemplates: !call.asText && (chosen(call.skills) || chosen(call.templates) || Boolean(call.extensions)),
1013
+ preflightResult: (how) => { taken = how === "handled"; },
1014
+ });
1015
+ // A command that asked the model has the model's answer be the call's: what it put to the model is
1016
+ // waited for — also where the command itself did not wait, or pi had not yet set the run going.
1017
+ const puts = this.extended.get(session)?.puts;
1018
+ while (puts && puts.size > 0)
1019
+ await Promise.allSettled([...puts]);
1020
+ if (taken)
1021
+ await session.waitForIdle();
1022
+ };
1023
+ await notHeld(answered(), stopped, HELD_MS).catch((err) => { if (refused === undefined)
1024
+ throw err; });
1025
+ // (What the call cannot have as it asked is its failure, found before the model was asked anything.)
1026
+ if (refused !== undefined)
1027
+ throw new Error(refused);
108
1028
  // An aborted prompt resolves with no usable answer — report it as an abort,
109
1029
  // not as an empty LLM response.
110
1030
  throwIfAborted(signal);
111
- const text = this.extractText(session);
112
- if (!text)
113
- throw new Error("Empty response from LLM");
114
- return text;
1031
+ return answerOf(session, taken);
115
1032
  }
116
1033
  finally {
117
1034
  offAbort();
118
- session.dispose();
1035
+ its.over = true;
1036
+ if (extended)
1037
+ extended.over = true;
1038
+ try {
1039
+ await this.letGoOf(session, call);
1040
+ }
1041
+ finally {
1042
+ // What the call used is said when all is over that could use anything on its account, however it
1043
+ // ended. (Whoever counts has not waited for this: they were told as each reply came.)
1044
+ its.gone = true;
1045
+ offCut();
1046
+ const usage = used && usageOf(session, this.asking.get(session)?.seen);
1047
+ if (usage)
1048
+ used(usage);
1049
+ }
119
1050
  }
120
1051
  }
121
1052
  }