@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.
@@ -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, notAsked, usageAtEnd } 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,656 @@ 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 a request to a provider goes by, that is a process's own: its
187
+ * variables — a provider's key may be one — and its ways to the network. An
188
+ * extension may make them other than they were: read a file of variables,
189
+ * put something of its own before every request the process makes. A request
190
+ * asked from another process would then not be the request this one makes,
191
+ * and nothing in the request says so. So what they are is kept from before
192
+ * the first extension is loaded in this process (`asLoaded`), and a session
193
+ * hands its requests over only while they are that still (`asItWas`). It is
194
+ * what can be told, and not all an extension can do: one that reaches under
195
+ * these is not seen.
196
+ */
197
+ const shapeOf = () => ({
198
+ variables: JSON.stringify(process.env),
199
+ ways: [globalThis.fetch, globalThis[Symbol.for("undici.globalDispatcher.1")], http.globalAgent, https.globalAgent],
200
+ });
201
+ let asLoaded;
202
+ function asItWas() {
203
+ if (!asLoaded)
204
+ return false;
205
+ const now = shapeOf();
206
+ return now.variables === asLoaded.variables && now.ways.every((way, at) => way === asLoaded.ways[at]);
207
+ }
208
+ /**
209
+ * Stand where a session's models are asked. pi asks a model in more places
210
+ * than one — its agent for a turn, for a summary of a long conversation or of
211
+ * a branch, to keep a provider's cache warm while a session waits; and an
212
+ * extension may ask by the session's models for itself — and every one of
213
+ * them comes by one step: the request is made ready, and handed to the
214
+ * model's provider. So that step is where a call is asked whether its model
215
+ * may be asked again, and the provider's reply is where what it used is seen.
216
+ * (pi does not export the step: it is a method of what trama made, and is
217
+ * made to stand aside for this.)
218
+ */
219
+ function watch(models, asking) {
220
+ const standing = models;
221
+ const prepare = standing.prepareRequest.bind(models);
222
+ const refused = async function* (model) {
223
+ yield notAsked(model, "The call is to ask no more.");
224
+ };
225
+ // A provider that is an extension's own code may ask another model by these same models, and hand back what
226
+ // that model answered — there and then, from a queue of its own, or a reply it had asked for before: a reply
227
+ // that passes here twice, and used what it used once. So what a reply used is counted by the reply: once for
228
+ // each account of usage that passes, wherever and however often it passes. (pi hands a reply on as it is; a
229
+ // provider that makes a copy of one, account and all, has made another reply of it as far as can be told.)
230
+ const counted = new WeakSet();
231
+ // What is being asked at this moment is kept count of, for whoever waits on it (see leaveExtensions): the
232
+ // replies that are being gone through, and the requests that are being made ready. (A request that is made
233
+ // ready and then not asked — its asker was stopped before it came to that — never was one a model worked on.)
234
+ const count = (of, by) => {
235
+ asking[of] += by;
236
+ asking.changed?.();
237
+ };
238
+ const heard = async function* (reply, ...released) {
239
+ count("answering", 1);
240
+ try {
241
+ for await (const event of reply) {
242
+ const used = usageAtEnd(event);
243
+ if (used && !counted.has(used)) {
244
+ counted.add(used);
245
+ addReply(asking.seen, used);
246
+ asking.replied?.();
247
+ }
248
+ yield event;
249
+ }
250
+ }
251
+ finally {
252
+ count("answering", -1);
253
+ for (const release of released)
254
+ release();
255
+ }
256
+ };
257
+ // And every request goes with the word that stops it (Asking.cut), beside whatever its asker gave it to be
258
+ // stopped by: asked here or elsewhere, by pi or by an extension for itself.
259
+ const stoppable = (options) => {
260
+ const { signal, release } = either(options?.signal, asking.cut.signal);
261
+ return { options: { ...options, signal }, release };
262
+ };
263
+ standing.prepareRequest = async (model, options) => {
264
+ count("readying", 1);
265
+ try {
266
+ await asking.before?.();
267
+ // (Asked no more: the request ends as one that was cancelled before it was sent.)
268
+ if (asking.stopped?.())
269
+ return { provider: { stream: () => refused(model), streamSimple: () => refused(model) }, model, options: options ?? {} };
270
+ const prepared = await prepare(model, options);
271
+ const provider = prepared.provider;
272
+ return {
273
+ ...prepared,
274
+ provider: new Proxy(provider, {
275
+ get(target, key) {
276
+ if (key === "stream") {
277
+ return (...sent) => {
278
+ const here = stoppable(sent[2]);
279
+ return heard(target.stream(sent[0], sent[1], here.options), here.release);
280
+ };
281
+ }
282
+ if (key === "streamSimple") {
283
+ return (...sent) => {
284
+ const there = stoppable(options), here = stoppable(sent[2]);
285
+ return heard((async function* () {
286
+ yield* await asking.elsewhere?.(model, sent[1], there.options) ?? target.streamSimple(sent[0], sent[1], here.options);
287
+ })(), there.release, here.release);
288
+ };
289
+ }
290
+ const value = Reflect.get(target, key, target);
291
+ return typeof value === "function" ? value.bind(target) : value;
292
+ },
293
+ }),
294
+ };
295
+ }
296
+ finally {
297
+ // (Made ready, or not: counted until whoever had it made ready has had their turn to ask for the reply,
298
+ // which is counted from there — so that no moment between the two is one in which nothing is being asked.)
299
+ setImmediate(() => count("readying", -1));
300
+ }
301
+ };
302
+ }
303
+ /**
304
+ * Have what is asked on a session's account be its call's, from before the
305
+ * session is there: an extension may ask a model as it is told that the
306
+ * session begins, and that is the call's as much as what its agent asks —
307
+ * also where the call then fails before its agent was ever set going.
308
+ *
309
+ * Each time a model is about to be asked, what the call has used so far is
310
+ * said, and whoever hears it waited for: they may cancel the call there, and
311
+ * the model is then not asked. (One at a time: whoever hears it is told of
312
+ * one request, and answers for that one.) And a call that was cancelled, or
313
+ * whose session is gone, asks no more, whoever would have it ask — its agent,
314
+ * pi keeping a cache warm, an extension for itself. Gives back what says to
315
+ * stop the call while it is at its work.
316
+ */
317
+ function account(asking, call, signal, session) {
318
+ const { sofar, had, relay } = call;
319
+ const stopped = signal ? AbortSignal.any([signal, asking.refusal.signal]) : asking.refusal.signal;
320
+ asking.stop = stopped;
321
+ const counted = () => {
322
+ const its = session();
323
+ return its ? usageOf(its, asking.seen) : atLeast(undefined, asking.seen);
324
+ };
325
+ let heard = Promise.resolve();
326
+ // (A call that has its answer is not cancelled for what it has used: whoever hears says instead that
327
+ // nothing more may be asked beside it — and nothing is, from then.)
328
+ let noMore = false;
329
+ // (What stops a call in its work — it was cancelled, or cannot have the tools it named — stops what is asked
330
+ // on its account. Once it is over, a call that could not have its tools is one that failed, like any: what
331
+ // an extension asks beside it, as it is told the session ends, is asked. And nothing is, once what was being
332
+ // asked has been stopped — the session is being let go of: there is nobody left to say what the call has
333
+ // used to, and to wait for.)
334
+ const halted = () => asking.cut.signal.aborted || (asking.over ? signal?.aborted === true : stopped.aborted);
335
+ asking.stopped = () => asking.gone || noMore || halted();
336
+ // (Whoever hears what the call has used is not waited for once it is to ask no more, whatever they would
337
+ // say: the call was cancelled or cannot have what it named, while it is at its work — and, whenever the
338
+ // wait began, once what was being asked has been stopped.)
339
+ const atWork = AbortSignal.any([stopped, asking.cut.signal]);
340
+ asking.before = () => heard = heard.then(async () => {
341
+ const usage = sofar && !asking.gone && !noMore && !halted() && counted();
342
+ if (usage && await rejectOnAbort(Promise.resolve(sofar(usage, asking.over)), asking.over ? asking.cut.signal : atWork).catch(() => { }) === false && asking.over)
343
+ noMore = true;
344
+ });
345
+ // (As soon as a reply has come, what the call has used is said to whoever would not otherwise know
346
+ // it, were this process to be ended: before the reply is anybody else's to hear of.)
347
+ asking.replied = () => {
348
+ const usage = had && !asking.gone && counted();
349
+ if (usage)
350
+ had(usage);
351
+ };
352
+ // Where the call has extensions and somebody to ask its model by, its model is asked by them: what
353
+ // a reply used is then read where no extension is. Not where an extension has made the model's
354
+ // provider its own, has a hand in what a provider is sent and answers, or has made
355
+ // this process other than it was in what a request goes by — the model is then asked here, as the
356
+ // extension means it to be — nor where the request is not one that can be handed over (see dataOf).
357
+ if (relay && call.extensions) {
358
+ asking.elsewhere = async (model, context, options) => {
359
+ const data = dataOf(options), its = session();
360
+ if (!data || !its || !asItWas() || asking.models.getRegisteredProviderIds().includes(model.provider))
361
+ return undefined;
362
+ if (HANDS_IN.some(event => its.extensionRunner.hasHandlers(event)))
363
+ return undefined;
364
+ return relay.ask({ model, context, options: data, ...(asking.over && { answered: true }) }, options?.signal);
365
+ };
366
+ }
367
+ return stopped;
368
+ }
369
+ /**
370
+ * Tell a session's extensions that it is over, and wait for them — a while:
371
+ * an extension may hold what is to be let go of (a server it started), and
372
+ * one that does not answer is not waited for. What one of them put to the
373
+ * model and is still on its way there is seen off too, before the session is
374
+ * gone: it is stopped as it begins to ask (see `ask`), where a session that
375
+ * is disposed of under it would let it through.
376
+ *
377
+ * An extension that is asking a model is not one that does not answer: it
378
+ * may be summing up what was done, and a model takes the time it takes — a
379
+ * quarter of a minute for a page, a minute where it thinks first. So there
380
+ * are two clocks, and one of them runs at a time. The while extensions are
381
+ * given is their own, all told: it runs while no model is at work on what
382
+ * was asked on the session's account, and stands while one is. And the time
383
+ * a model may be at work for them, all told, is what pi gives one request of
384
+ * its own (`most`; none, where pi has no limit): it runs while a reply is
385
+ * being gone through. What they have all been told, and is still being asked
386
+ * beside what they answered, is waited for the same way. (A request that is
387
+ * only ever made ready — a session set going again and stopped as it begins,
388
+ * over and over — is no model at work: it is on their own time.) When either
389
+ * has run out, whoever let go of the session stops what is still asked (see
390
+ * Asking.cut): nothing is left being asked for a reply on the account of a
391
+ * session that is gone, to be nobody's.
392
+ */
393
+ async function leaveExtensions(session, puts, asking, most) {
394
+ const left = (async () => {
395
+ await session.extensionRunner.emit({ type: "session_shutdown", reason: "quit" });
396
+ while (puts.size > 0)
397
+ await Promise.allSettled([...puts]);
398
+ })().catch(() => { });
399
+ await new Promise((resolve) => {
400
+ // Whether they have all answered, and whether the wait is over; what is left of their own time, and of a
401
+ // model's for them; and the clock that runs one of those down — which, and since when.
402
+ let told = false, ended = false, theirs = EXTENSION_LEAVE_MS, models = most > 0 ? most : Infinity;
403
+ let clock, atWork = false, since = performance.now();
404
+ const done = () => {
405
+ if (ended)
406
+ return;
407
+ ended = true;
408
+ clearTimeout(clock);
409
+ if (asking)
410
+ asking.changed = undefined;
411
+ asking?.cut.signal.removeEventListener("abort", look);
412
+ resolve();
413
+ };
414
+ const look = () => {
415
+ if (ended)
416
+ return;
417
+ const now = performance.now();
418
+ if (atWork)
419
+ models -= now - since;
420
+ else
421
+ theirs -= now - since;
422
+ clearTimeout(clock);
423
+ // (What was stopped — the call was cancelled — is no model at work, however long it takes to end: it is
424
+ // given a moment for that when the wait is over, like anything that is stopped. See allEnded.)
425
+ const asked = asking && !asking.cut.signal.aborted ? asking : undefined;
426
+ atWork = asked !== undefined && asked.answering > 0;
427
+ since = now;
428
+ if (!atWork && told && !asked?.readying)
429
+ return done();
430
+ const has = atWork ? models : theirs;
431
+ // (A timer takes no more than this.)
432
+ clock = has === Infinity ? undefined : setTimeout(done, Math.min(Math.max(0, has), 2 ** 31 - 1));
433
+ };
434
+ if (asking)
435
+ asking.changed = look;
436
+ asking?.cut.signal.addEventListener("abort", look, { once: true });
437
+ void left.then(() => {
438
+ told = true;
439
+ look();
440
+ });
441
+ look();
442
+ });
443
+ }
444
+ /** 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. */
445
+ function allEnded(asking) {
446
+ return new Promise((resolve) => {
447
+ if (asking.answering <= 0)
448
+ return resolve();
449
+ const over = () => {
450
+ clearTimeout(late);
451
+ asking.changed = undefined;
452
+ resolve();
453
+ };
454
+ const late = setTimeout(over, STOPPED_MS);
455
+ asking.changed = () => { if (asking.answering <= 0)
456
+ over(); };
457
+ });
458
+ }
459
+ /**
460
+ * The most a model is waited for, at work for a session's extensions as it
461
+ * ends: what pi gives a request of its own, as the session's settings have
462
+ * it — the time for a request to a provider, or else the time a connection
463
+ * may be silent, which is none at all where the settings say so. What the
464
+ * settings have that pi itself would not take is not taken here either:
465
+ * then it is what pi gives where they say nothing.
466
+ */
467
+ function longestAsked(session) {
468
+ try {
469
+ const settings = session.settingsManager;
470
+ const own = settings?.getProviderRetrySettings?.().timeoutMs;
471
+ if (typeof own === "number" && Number.isFinite(own) && own > 0)
472
+ return own;
473
+ const silent = settings?.getHttpIdleTimeoutMs?.();
474
+ return typeof silent === "number" && silent >= 0 ? silent : REQUEST_MS;
475
+ }
476
+ catch {
477
+ return REQUEST_MS;
478
+ }
479
+ }
480
+ /**
481
+ * What a session has used: pi's own count, over everything the session asked
482
+ * of its model — a summary it made of a long conversation included — and
483
+ * what trama saw come (`seen`: see `watch`), where that is more: a reply that
484
+ * has come and is not on pi's record yet, and what an extension asked for
485
+ * itself, which never is. Nothing, where no tokens were counted: the model
486
+ * was never reached, or does not say.
487
+ */
488
+ function usageOf(session, seen) {
489
+ const { tokens, cost } = session.getSessionStats();
490
+ const { input, output, cacheRead, cacheWrite } = tokens;
491
+ return atLeast({ ...(session.model && { model: nameOf(session.model) }), input, output, cacheRead, cacheWrite, cost }, seen);
492
+ }
493
+ /**
494
+ * The model's answer: the text of the last reply the session has on record.
495
+ *
496
+ * The record, not the conversation as the model would next be shown it: pi
497
+ * takes a reply that failed out of that — one the provider refused as too
498
+ * long, one cut off — and what is left there to be last is an earlier turn.
499
+ * And an answer only if the model ended it itself: a reply that is the
500
+ * provider's error, or was cut off at the output limit, is the call's failure
501
+ * (the second with what there was of it: see CutOff). A reply cut off in the
502
+ * middle of a tool call is never the last: pi has the model make the call again.
503
+ */
504
+ function answerOf(session, taken = false) {
505
+ const replies = session.sessionManager.getEntries()
506
+ .flatMap(entry => (entry.type === "message" && entry.message.role === "assistant" ? [entry.message] : []));
507
+ const reply = replies.at(-1);
508
+ const text = reply?.content.map(block => (block.type === "text" ? block.text : "")).join("") ?? "";
509
+ if (reply?.stopReason === "error")
510
+ throw new Error(`The model did not answer: ${reply.errorMessage ?? "no reason given"}`);
511
+ if (reply?.stopReason === "length")
512
+ throw new CutOff(text);
513
+ if (!text) {
514
+ throw new Error(taken
515
+ ? "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."
516
+ : "Empty response from LLM");
517
+ }
518
+ return text;
519
+ }
520
+ /**
521
+ * The pi coding agent: a fresh in-memory session for every call — in this
522
+ * process, or in a process of its own (see agent-host.ts). A call that has
523
+ * extensions is served in one: an extension is somebody's code, and where it
524
+ * runs it can hold up, or bring down, everything else that runs there. And
525
+ * so is every call of an adapter that was given variables (`env`: a run's):
526
+ * what an agent finds of pi, which key it has for a provider, and what the
527
+ * commands it runs are given, are a process's — and this process is the
528
+ * runner's, whose own are not a run's to change.
529
+ */
13
530
  export class PiAdapter {
14
531
  config;
15
- constructor(config) {
532
+ /** Whether every call is served in a process of its own: where those processes are given variables this one has not. */
533
+ apart;
534
+ /** The processes that serve this adapter's calls. */
535
+ hosts;
536
+ constructor(config, env) {
16
537
  this.config = config;
538
+ // (Variables that are none are none given: such a run's calls are served as any run's.)
539
+ this.apart = env !== undefined && Object.keys(env).length > 0;
540
+ this.hosts = createAgentHosts(this.apart ? env : undefined);
541
+ }
542
+ /** Have a call served: here, or by a host. */
543
+ async ask(prompt, call) {
544
+ return call.extensions || this.apart ? this.hosts.ask(this.config, prompt, call) : this.serve(prompt, call);
545
+ }
546
+ /** End the processes that served calls: what this adapter was for is over. (It can be asked again: it starts them anew.) */
547
+ async close() {
548
+ await this.hosts.close();
17
549
  }
18
- async createSession(cwd, systemPrompt, signal) {
550
+ async createSession(cwd, systemPrompt, signal, asked = {}) {
19
551
  // Each step below is given up on the moment the call is cancelled.
20
552
  const raceAbort = (step) => rejectOnAbort(step, signal);
21
- const { createAgentSession, SessionManager, DefaultResourceLoader, ModelRuntime, getAgentDir } = await raceAbort(loadPi());
553
+ const { createAgentSession, SessionManager, SettingsManager, DefaultResourceLoader, ModelRuntime, getAgentDir, formatSkillsForPrompt } = await raceAbort(loadPi());
22
554
  const agentDir = getAgentDir();
23
- const resourceLoader = new DefaultResourceLoader({
555
+ // Skills and prompt templates are pi's for the user and for where the agent works — the
556
+ // project's own, in its .pi directory, among them: and a call has those it chose, and no others.
557
+ const found = { skills: [], templates: [] };
558
+ const only = (choice, items) => {
559
+ const names = named(choice);
560
+ return names ? items.filter(item => names.includes(item.name)) : items;
561
+ };
562
+ const resources = new DefaultResourceLoader({
24
563
  cwd,
25
564
  agentDir,
26
565
  noExtensions: true,
27
- noSkills: true,
566
+ noSkills: !chosen(asked.skills),
567
+ noPromptTemplates: !chosen(asked.templates),
568
+ skillsOverride: (base) => {
569
+ found.skills = base.skills.map(skill => skill.name);
570
+ return { ...base, skills: only(asked.skills, base.skills) };
571
+ },
572
+ promptsOverride: (base) => {
573
+ found.templates = base.prompts.map(template => template.name);
574
+ return { ...base, prompts: only(asked.templates, base.prompts) };
575
+ },
28
576
  ...(systemPrompt && { appendSystemPrompt: [systemPrompt] }),
29
577
  });
30
- await raceAbort(resourceLoader.reload());
578
+ await raceAbort(resources.reload());
579
+ // Extensions are the user's own, unless the call says the project's are its too: an extension
580
+ // is code, and what a project holds its program can write. So they are loaded apart, by a
581
+ // loader that takes of the project's what the call said it may, and the session has the rest
582
+ // from the other. And so, where the project's are not the call's, an extension that asks is
583
+ // told the project is not one to be trusted — pi has extensions ask that before they take
584
+ // anything of a project's for their own. The session's settings are otherwise what any call's
585
+ // are, the project's among them: a call does not come to other tools, or another shell, for
586
+ // having asked for extensions.
587
+ if (asked.extensions !== undefined && typeof asked.extensions !== "boolean" && asked.extensions !== "project") {
588
+ throw new Error(`extensions is true, false or "project", not ${JSON.stringify(asked.extensions)}`);
589
+ }
590
+ // Whose extensions: the user's — or the project's with them, where the call says so. Then the project
591
+ // is one to be trusted, as it is when pi is run in it and told to: its extensions are loaded, the
592
+ // MCP servers it names are started, and an extension that asks is told so.
593
+ const withProjects = asked.extensions === "project";
594
+ let resourceLoader = resources;
595
+ const wary = asked.extensions && !withProjects
596
+ ? Object.assign(Object.create(SettingsManager.create(cwd, agentDir)), { isProjectTrusted: () => false })
597
+ : undefined;
598
+ const extended = asked.extensions ? { puts: new Set(), over: false } : undefined;
599
+ if (extended) {
600
+ // A session that is to ask no more — its call cancelled, or over — is stopped each time it begins to
601
+ // (see `ask`); and an extension may set it going again each time it stops, by more ways than one. All
602
+ // of that is done without the runner coming to anything else: not to the clock that is to give the
603
+ // call up, nor to any other run. So each beginning of such a session waits a turn of the runner's —
604
+ // by a handler of trama's own among the extensions, which is what pi waits for when a run begins.
605
+ // And where the agent's model is about to be asked for the first time — for a turn, or to sum a
606
+ // conversation up — what the agent has by then is looked at from there too (see whyNotTheTools).
607
+ const breathes = (pi) => {
608
+ pi.on("agent_start", async () => {
609
+ if (extended.over || signal?.aborted)
610
+ await new Promise(resolve => setImmediate(resolve));
611
+ });
612
+ const looks = () => {
613
+ extended.look?.();
614
+ extended.look = undefined;
615
+ };
616
+ pi.on("turn_start", looks);
617
+ pi.on("session_before_compact", looks);
618
+ };
619
+ const builtIn = await raceAbort(builtInExtensions());
620
+ // (What this process is, before anything of an extension's is loaded in it: see shapeOf.)
621
+ asLoaded ??= shapeOf();
622
+ const own = new DefaultResourceLoader({
623
+ cwd,
624
+ agentDir,
625
+ extensionFactories: [...builtIn, breathes],
626
+ settingsManager: SettingsManager.create(cwd, agentDir, { projectTrusted: withProjects }),
627
+ // (Nothing but its extensions is asked of it, and so it need find nothing else.)
628
+ noSkills: true,
629
+ noPromptTemplates: true,
630
+ noThemes: true,
631
+ noContextFiles: true,
632
+ });
633
+ await raceAbort(own.reload());
634
+ resourceLoader = {
635
+ getExtensions: () => own.getExtensions(),
636
+ getSkills: () => resources.getSkills(),
637
+ getPrompts: () => resources.getPrompts(),
638
+ getThemes: () => resources.getThemes(),
639
+ getAgentsFiles: () => resources.getAgentsFiles(),
640
+ getSystemPrompt: () => resources.getSystemPrompt(),
641
+ getSystemPromptSource: () => resources.getSystemPromptSource(),
642
+ getAppendSystemPrompt: () => resources.getAppendSystemPrompt(),
643
+ getAppendSystemPromptSources: () => resources.getAppendSystemPromptSources(),
644
+ extendResources: (paths) => resources.extendResources(paths),
645
+ reload: async (options) => {
646
+ await resources.reload(options);
647
+ await own.reload();
648
+ },
649
+ };
650
+ }
31
651
  // 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.
652
+ // user's models.json). The project's own, if it is unknown there, resolves
653
+ // to undefined, in which case pi falls back to its own default selection;
654
+ // a model a call names is that model or the call fails.
34
655
  const modelRuntime = await raceAbort(ModelRuntime.create({ signal }));
35
- const model = modelRuntime.getModel(this.config.provider, this.config.model);
656
+ const asking = { models: modelRuntime, seen: nothingYet(), answering: 0, readying: 0, cut: new AbortController(), over: false, gone: false, refusal: new AbortController() };
657
+ watch(modelRuntime, asking);
658
+ // (A call names it "provider/model": the provider's name ends at a stroke, and either name may have more of them.)
659
+ const strokes = [...(asked.model ?? "").matchAll(/\//g)].map(stroke => stroke.index);
660
+ const model = asked.model === undefined
661
+ ? modelRuntime.getModel(this.config.provider, this.config.model)
662
+ : strokes.map(at => modelRuntime.getModel(asked.model.slice(0, at), asked.model.slice(at + 1))).find(Boolean);
663
+ if (asked.model !== undefined && !model) {
664
+ throw new Error(`Unknown model "${asked.model}". A model is named "provider/model", as pi's model catalog has it.`);
665
+ }
36
666
  // Keep a reference to the raw promise so we can clean up a late-arriving session
37
667
  const sessionPromise = createAgentSession({
38
668
  cwd,
@@ -41,25 +671,147 @@ export class PiAdapter {
41
671
  model,
42
672
  sessionManager: SessionManager.inMemory(cwd),
43
673
  resourceLoader,
674
+ ...(wary && { settingsManager: wary }),
675
+ ...(asked.thinking !== undefined && { thinkingLevel: asked.thinking }),
676
+ ...(asked.tools && { tools: asked.tools }),
44
677
  });
678
+ let session;
679
+ // The telling of extensions that a session begins, while it lasts.
680
+ let beginning;
681
+ const stopped = account(asking, asked, signal, () => session);
682
+ // (A call that is cancelled asks no more — and what is being asked for it then is asked no further, whoever
683
+ // asked: from here, while its session is being made — and let go of, should that fail. Once the session
684
+ // is there, it is whoever has it who listens: see `serve`.)
685
+ const offCut = onAbort(signal, () => asking.cut.abort());
45
686
  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);
687
+ ({ session } = await raceAbort(sessionPromise));
688
+ this.asking.set(session, asking);
689
+ // A session that is set going again once its call is over, or stopped, is stopped as it begins to: a
690
+ // command of an extension that asks the model once more, or what an extension starts while it is being
691
+ // told that the call is over.
692
+ if (asked.sofar || asked.extensions) {
693
+ const here = session;
694
+ here.subscribe((event) => {
695
+ if (event.type !== "turn_start" && event.type !== "compaction_start")
696
+ return;
697
+ if (asking.over || stopped.aborted)
698
+ void here.abort().catch(() => { });
699
+ });
54
700
  }
701
+ // An extension is told that its session has begun, as pi tells it where pi runs by itself:
702
+ // that is when it sets itself up. What goes wrong in one later is said, and is not the call's failure.
703
+ // A command of one can wait for the model it asked, as it can there; the session is one call's, and
704
+ // is not to be left for another.
705
+ if (extended) {
706
+ const here = session;
707
+ const stays = async () => ({ cancelled: true });
708
+ // What an extension puts to the model — a command of it, asking — is the call's to wait for (see
709
+ // `ask`), and the command's own, where it waits: pi calls a session idle while a question is still
710
+ // on its way to being asked, so what was put is kept account of here, as it is put.
711
+ const { puts } = extended;
712
+ this.extended.set(session, extended);
713
+ const prompting = session.prompt.bind(session);
714
+ session.prompt = (text, options) => {
715
+ const put = prompting(text, options);
716
+ if (options?.source !== "extension")
717
+ return put;
718
+ const over = () => { puts.delete(put); };
719
+ puts.add(put);
720
+ put.then(over, over);
721
+ return put;
722
+ };
723
+ // A command that waits is told, when it has waited, that its call was cancelled — where it was: one
724
+ // that asks until it is satisfied then stops asking, and need not be stopped each time it begins to.
725
+ const idle = async () => {
726
+ while (puts.size > 0)
727
+ await Promise.allSettled([...puts]);
728
+ await here.waitForIdle();
729
+ throwIfAborted(signal);
730
+ };
731
+ beginning = session.bindExtensions({
732
+ mode: "print",
733
+ commandContextActions: {
734
+ waitForIdle: idle,
735
+ newSession: stays,
736
+ fork: stays,
737
+ switchSession: stays,
738
+ navigateTree: async (target, options) => ({ cancelled: (await here.navigateTree(target, options)).cancelled }),
739
+ reload: () => here.reload(),
740
+ },
741
+ // (A command that was not let wait, its call being cancelled, did not fail: nothing is said of it.)
742
+ onError: (failure) => {
743
+ if (signal?.aborted && failure.error === "Aborted")
744
+ return;
745
+ console.warn(`[trama] an extension failed (${failure.extensionPath}): ${failure.error}`);
746
+ },
747
+ });
748
+ await raceAbort(beginning);
749
+ }
750
+ // With no model it can use, pi reports a placeholder that is not in its
751
+ // catalog — a model is named only when it is a real one.
752
+ const picked = session.model;
753
+ const serving = picked && modelRuntime.getModel(picked.provider, picked.id) ? nameOf(picked) : null;
754
+ const refusal = whyNotAsAsked(session, asked, serving, found, formatSkillsForPrompt);
755
+ if (refusal)
756
+ throw new Error(refusal);
757
+ if (!model)
758
+ this.warnUnknownModel(serving);
759
+ offCut();
55
760
  return session;
56
761
  }
57
762
  catch (err) {
58
- // If abort won the race, the real promise may still resolve later — dispose it
59
- sessionPromise.then(({ session }) => session.dispose()).catch(() => { });
763
+ // A session that is here is let go of, once, before the call fails — its extensions, if they were
764
+ // still being told that it begins, having heard that out first (or been given the while they are
765
+ // given to hear of its end). Where the call was cancelled before the session came, it may still
766
+ // come: it is disposed of when it does, and no extension was told of it.
767
+ // The call is over, failed; and what its extensions asked a model, as they were told that the session
768
+ // begins and that it is over, is what it used — said when the session is gone, as of any call.
769
+ asking.over = true;
770
+ if (extended)
771
+ extended.over = true;
772
+ try {
773
+ if (session) {
774
+ if (beginning)
775
+ await within(beginning, EXTENSION_LEAVE_MS);
776
+ await this.letGoOf(session, asked);
777
+ }
778
+ else {
779
+ sessionPromise.then(({ session: late }) => late.dispose()).catch(() => { });
780
+ }
781
+ }
782
+ finally {
783
+ asking.gone = true;
784
+ offCut();
785
+ const usage = session && asked.used && usageOf(session, asking.seen);
786
+ if (usage)
787
+ asked.used(usage);
788
+ }
60
789
  throw err;
61
790
  }
62
791
  }
792
+ /** What is kept of each session that has extensions. */
793
+ extended = new WeakMap();
794
+ /** Where trama stands when each session's model is asked. */
795
+ asking = new WeakMap();
796
+ /** Be done with a session: its extensions, where it has any, told first that it is over. */
797
+ async letGoOf(session, asked) {
798
+ const asking = this.asking.get(session);
799
+ try {
800
+ if (asked.extensions)
801
+ await leaveExtensions(session, this.extended.get(session)?.puts ?? new Set(), asking, longestAsked(session));
802
+ }
803
+ catch (err) {
804
+ console.warn(`[trama] an extension could not be told its session is over: ${messageOf(err)}`);
805
+ }
806
+ finally {
807
+ // What is still being asked on its account — it was waited for as long as anything is — is asked no
808
+ // further; and has a moment to end, and say what it had used: that is the call's too.
809
+ asking?.cut.abort();
810
+ if (asking && asked.extensions)
811
+ await allEnded(asking);
812
+ session.dispose();
813
+ }
814
+ }
63
815
  /**
64
816
  * The configured provider/model is not in pi's catalog, so pi picked a model
65
817
  * on its own. Say so once — otherwise a typo silently runs a different model.
@@ -75,47 +827,105 @@ export class PiAdapter {
75
827
  : `pi has no fallback model available, so LLM calls will fail. `) +
76
828
  `Check "provider" and "model" in ~/.trama/config.json or the project's meta.json.`);
77
829
  }
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
830
  /**
92
- * Run one prompt in a fresh session and return the assistant's text reply.
831
+ * Serve a call in this process: run one prompt in a fresh session and
832
+ * return the assistant's text reply. (What a host does; and what `ask`
833
+ * does itself for a call without extensions.)
93
834
  *
94
835
  * 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).
836
+ * `session.prompt()` is running, a cancelled call has pi abort the run — which
837
+ * settles the prompt (pi 1.x resolves it rather than rejecting, so
838
+ * `signal.aborted` is checked again when `prompt()` returns) and leaves on
839
+ * the session's record what the request that was cut off had taken by then.
98
840
  */
99
- async ask(prompt, call) {
100
- const { cwd, system, signal } = call;
841
+ async serve(prompt, call) {
842
+ const { cwd, system, signal, used, sofar } = call;
101
843
  throwIfAborted(signal);
102
- const session = await this.createSession(cwd, system, signal);
844
+ const session = await this.createSession(cwd, system, signal, call);
845
+ // (A call that is cancelled asks no more — and what is being asked for it then is asked no further, whoever
846
+ // asked: while it is at its work, and while its extensions are told that it is over.)
847
+ const offCut = onAbort(signal, () => this.asking.get(session)?.cut.abort());
103
848
  let offAbort = () => { };
849
+ // What is kept of the call where its model is asked (see `account`): whether it has come to its end, and
850
+ // whether its session is gone. (A session that was not made here has nothing asked on its account that
851
+ // is seen: what is kept of its call is then kept here alone.)
852
+ const asking = this.asking.get(session);
853
+ const its = asking ?? { over: false, gone: false, refusal: new AbortController() };
854
+ // What is kept of the session beside it, where it has extensions.
855
+ const extended = this.extended.get(session);
856
+ // Why the call cannot have the tools it named, where that was found as its run began. It is
857
+ // then stopped as a cancelled call is — it asks nothing, and what would hold it is not waited
858
+ // for long — and fails with that.
859
+ let refused;
860
+ const stopped = asking?.stop ?? (signal ? AbortSignal.any([signal, its.refusal.signal]) : its.refusal.signal);
104
861
  try {
105
862
  throwIfAborted(signal);
106
- offAbort = onAbort(signal, () => session.dispose());
107
- await session.prompt(prompt);
863
+ offAbort = onAbort(signal, () => { session.abort().catch(() => { }); });
864
+ // Where the agent has not the tools the call named, that is found as its run begins (see
865
+ // createSession), and the call is stopped as one that was cancelled is.
866
+ if (extended && call.extensions) {
867
+ extended.look = () => {
868
+ refused = whyNotTheTools(session, call.tools);
869
+ if (refused === undefined)
870
+ return;
871
+ // (The session is stopped where it hears next that a turn begins — just after this: see createSession.)
872
+ extended.over = true;
873
+ its.refusal.abort();
874
+ };
875
+ }
876
+ if (!asking && (sofar || call.extensions)) {
877
+ session.subscribe((event) => {
878
+ if (event.type !== "turn_start" && event.type !== "compaction_start")
879
+ return;
880
+ if (its.over || stopped.aborted)
881
+ void session.abort().catch(() => { });
882
+ });
883
+ }
884
+ // The prompt is a program's text, whatever it begins with — but where the call has the user's skills,
885
+ // templates or extensions, and does not say its prompt is text all the same: each of those has a line of
886
+ // its own to be called up by ("/skill:name", "/name", a command), and pi reads a prompt for all of them
887
+ // or for none.
888
+ let taken = false;
889
+ const answered = async () => {
890
+ await session.prompt(prompt, {
891
+ expandPromptTemplates: !call.asText && (chosen(call.skills) || chosen(call.templates) || Boolean(call.extensions)),
892
+ preflightResult: (how) => { taken = how === "handled"; },
893
+ });
894
+ // A command that asked the model has the model's answer be the call's: what it put to the model is
895
+ // waited for — also where the command itself did not wait, or pi had not yet set the run going.
896
+ const puts = this.extended.get(session)?.puts;
897
+ while (puts && puts.size > 0)
898
+ await Promise.allSettled([...puts]);
899
+ if (taken)
900
+ await session.waitForIdle();
901
+ };
902
+ await notHeld(answered(), stopped, HELD_MS).catch((err) => { if (refused === undefined)
903
+ throw err; });
904
+ // (What the call cannot have as it asked is its failure, found before the model was asked anything.)
905
+ if (refused !== undefined)
906
+ throw new Error(refused);
108
907
  // An aborted prompt resolves with no usable answer — report it as an abort,
109
908
  // not as an empty LLM response.
110
909
  throwIfAborted(signal);
111
- const text = this.extractText(session);
112
- if (!text)
113
- throw new Error("Empty response from LLM");
114
- return text;
910
+ return answerOf(session, taken);
115
911
  }
116
912
  finally {
117
913
  offAbort();
118
- session.dispose();
914
+ its.over = true;
915
+ if (extended)
916
+ extended.over = true;
917
+ try {
918
+ await this.letGoOf(session, call);
919
+ }
920
+ finally {
921
+ // What the call used is said when all is over that could use anything on its account, however it
922
+ // ended. (Whoever counts has not waited for this: they were told as each reply came.)
923
+ its.gone = true;
924
+ offCut();
925
+ const usage = used && usageOf(session, this.asking.get(session)?.seen);
926
+ if (usage)
927
+ used(usage);
928
+ }
119
929
  }
120
930
  }
121
931
  }