@trama-dev/runtime 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/agent-backend.d.ts +51 -0
  2. package/dist/agent-backend.js +4 -0
  3. package/dist/agent-host.d.ts +46 -7
  4. package/dist/agent-host.js +59 -19
  5. package/dist/agent-hosts.js +122 -56
  6. package/dist/agent.d.ts +16 -5
  7. package/dist/agent.js +22 -64
  8. package/dist/bridge-client.d.ts +6 -2
  9. package/dist/bridge-client.js +6 -1
  10. package/dist/client.d.ts +2 -2
  11. package/dist/client.js +126 -2
  12. package/dist/context.js +3 -2
  13. package/dist/history.d.ts +9 -0
  14. package/dist/history.js +98 -0
  15. package/dist/index.d.ts +1 -0
  16. package/dist/index.js +70 -41
  17. package/dist/ipc-server.d.ts +2 -3
  18. package/dist/ipc-server.js +93 -37
  19. package/dist/journal-view.js +19 -9
  20. package/dist/journal.d.ts +10 -4
  21. package/dist/journal.js +28 -6
  22. package/dist/merge-deeds.d.ts +22 -0
  23. package/dist/merge-deeds.js +201 -0
  24. package/dist/merge-doing.d.ts +9 -0
  25. package/dist/merge-doing.js +410 -0
  26. package/dist/merge-settle.d.ts +14 -0
  27. package/dist/merge-settle.js +166 -0
  28. package/dist/merge-shared.d.ts +64 -0
  29. package/dist/merge-shared.js +159 -0
  30. package/dist/merge.d.ts +150 -0
  31. package/dist/merge.js +209 -0
  32. package/dist/model-relay.d.ts +63 -5
  33. package/dist/model-relay.js +206 -23
  34. package/dist/own-tools.d.ts +60 -0
  35. package/dist/own-tools.js +209 -0
  36. package/dist/path-guard.js +8 -6
  37. package/dist/pi-adapter.d.ts +22 -0
  38. package/dist/pi-adapter.js +294 -72
  39. package/dist/project.d.ts +31 -0
  40. package/dist/project.js +253 -0
  41. package/dist/replace-file.d.ts +13 -2
  42. package/dist/replace-file.js +23 -6
  43. package/dist/runner-backend.d.ts +43 -0
  44. package/dist/runner-backend.js +125 -0
  45. package/dist/runner-types.d.ts +8 -0
  46. package/dist/runner.d.ts +8 -123
  47. package/dist/runner.js +57 -453
  48. package/dist/schema.d.ts +38 -0
  49. package/dist/schema.js +104 -0
  50. package/dist/stopping.js +2 -3
  51. package/dist/tools.js +31 -7
  52. package/dist/tree.d.ts +33 -149
  53. package/dist/tree.js +43 -1077
  54. package/dist/types.d.ts +54 -2
  55. package/dist/workspace.d.ts +20 -0
  56. package/dist/workspace.js +76 -12
  57. package/package.json +2 -2
@@ -1,10 +1,10 @@
1
1
  import { onAbort, rejectOnAbort, throwIfAborted } from "./abort.js";
2
2
  import { messageOf } from "./errors.js";
3
3
  import { createAgentHosts } from "./agent-hosts.js";
4
- import { CutOff, addReply, atLeast, nothingYet } from "./agent-backend.js";
4
+ import { CutOff, NOT_WAITED_FOR, addReply, atLeast, nothingYet } from "./agent-backend.js";
5
5
  import * as http from "http";
6
6
  import * as https from "https";
7
- import { dataOf, notAsked, usageAtEnd } from "./model-relay.js";
7
+ import { dataOf, isData, notAsked, usageAtEnd, wholeOf } from "./model-relay.js";
8
8
  /**
9
9
  * pi is loaded when it is first needed, not when this file is: it is most of
10
10
  * what the runtime weighs, and listing projects, reading logs, or running a
@@ -32,6 +32,79 @@ async function builtInExtensions() {
32
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
33
  }
34
34
  }
35
+ /**
36
+ * The names of pi's own tools — those it gives an agent unasked, and those it
37
+ * has besides. pi takes a tool it is handed by the name of one of them for
38
+ * that tool, with no word of it; so a caller's own tool is held against them
39
+ * here. Read from where pi keeps them, as its extensions are: the package
40
+ * does not export the list, and a pi that keeps it elsewhere is one a call
41
+ * with tools of its own cannot be served by as it asked — the call fails.
42
+ */
43
+ async function pisOwnTools() {
44
+ const kept = new URL("./core/tools/index.js", import.meta.resolve("@earendil-works/pi-coding-agent"));
45
+ try {
46
+ const found = (await import(kept.href)).allToolNames;
47
+ if (!(found instanceof Set))
48
+ throw new Error("the file exports none");
49
+ return found;
50
+ }
51
+ catch (err) {
52
+ throw new Error(`The names of pi's own tools cannot be had: trama reads them from pi's own files, at ${kept.pathname} (${messageOf(err)}).`);
53
+ }
54
+ }
55
+ /** What a session has on record of what was said in it, in order: pi's messages, whoever's each is. */
56
+ const messagesOf = (session) => session.sessionManager.getEntries().flatMap(entry => (entry.type === "message" ? [entry.message] : []));
57
+ /** The words of what a message holds. */
58
+ const wordsOf = (content) => content.map(block => (block.type === "text" ? block.text ?? "" : "")).join("");
59
+ /**
60
+ * What a call's own tool said that ended the agent's work — the answer of
61
+ * such a call. A run that a tool ended has that tool's result as the last
62
+ * thing on its record: the model was not asked again. (Where the model was —
63
+ * it had called, in the same reply, a tool that ends nothing — the last
64
+ * thing is its reply, and that is the answer, as of any call.)
65
+ */
66
+ function endedWith(session, ownTools) {
67
+ const ending = new Set((ownTools ?? []).filter(tool => tool.ends).map(tool => tool.name));
68
+ if (ending.size === 0)
69
+ return undefined;
70
+ const last = messagesOf(session).at(-1);
71
+ // (Of the call's own that end it: a run may be ended by another's tool — an extension's — which is no answer of this call's.
72
+ // And not one that failed: such a tool has ended nothing — see asPisTool — and the model was asked again.)
73
+ if (last?.role !== "toolResult" || !ending.has(last.toolName))
74
+ return undefined;
75
+ return wordsOf(last.content);
76
+ }
77
+ /**
78
+ * A caller's own tool, as pi has a tool. Run one at a time unless it says
79
+ * it may be run beside another (pi's own way is to run together all that a
80
+ * model calls in one reply). And over as soon as its signal says the call
81
+ * is cancelled, whatever becomes of the asking: pi waits for a tool for as
82
+ * long as the tool takes, and a cancelled call would be held by it.
83
+ */
84
+ function asPisTool(own) {
85
+ return {
86
+ name: own.name,
87
+ label: own.name,
88
+ description: own.description,
89
+ parameters: own.parameters,
90
+ executionMode: own.parallel ? "parallel" : "sequential",
91
+ async execute(id, args, signal) {
92
+ let off = () => { };
93
+ const cancelled = new Promise((resolve) => { off = onAbort(signal, () => resolve(NOT_WAITED_FOR)); });
94
+ const asked = own.run(args, id, signal).catch((err) => ({ text: messageOf(err), failed: true }));
95
+ const { text, images = [], failed } = await Promise.race([asked, cancelled]).finally(off);
96
+ return {
97
+ // (Where a tool has images and no words, there is no text at all: pi then says for itself that there is
98
+ // something to see — and a text of no words, beside an image, is one some providers refuse.)
99
+ content: [...(text !== "" || images.length === 0 ? [{ type: "text", text }] : []), ...images.map(image => ({ type: "image", ...image }))],
100
+ details: undefined,
101
+ ...(failed && { isError: true }),
102
+ // (pi ends an agent's run on a result that says so, failed or not: a tool that failed has ended nothing.)
103
+ ...(own.ends && !failed && { terminate: true }),
104
+ };
105
+ },
106
+ };
107
+ }
35
108
  /** provider/model pairs already warned about, so a loop of agent calls warns once per process. */
36
109
  const warnedUnknownModels = new Set();
37
110
  const nameOf = (model) => `${model.provider}/${model.id}`;
@@ -97,7 +170,7 @@ function whyNotAsAsked(session, asked, serving, found, asTold) {
97
170
  `Its levels: ${session.getAvailableThinkingLevels().join(", ")}.`;
98
171
  }
99
172
  // (With extensions, an agent's tools are not all there yet: see whyNotTheTools.)
100
- const tools = asked.extensions ? undefined : whyNotTheTools(session, asked.tools);
173
+ const tools = asked.extensions ? undefined : whyNotTheTools(session, asked);
101
174
  if (tools)
102
175
  return tools;
103
176
  const lacking = (kind, choice, had) => {
@@ -127,13 +200,36 @@ function whyNotAsAsked(session, asked, serving, found, asTold) {
127
200
  * extension may add tools as the run begins (pi's own connects the user's MCP
128
201
  * servers then, and their tools are the agent's from there on).
129
202
  */
130
- function whyNotTheTools(session, tools) {
131
- if (tools === undefined)
203
+ function whyNotTheTools(session, { tools, ownTools }) {
204
+ const own = (ownTools ?? []).map(tool => tool.name);
205
+ // (A tool of the caller's own by the name of an extension's is the tool from then on, to pi, and nothing is said of it.)
206
+ for (const extension of session.resourceLoader.getExtensions().extensions) {
207
+ const taken = own.find(name => extension.tools.has(name));
208
+ if (taken !== undefined)
209
+ return `The tool "${taken}" cannot be the call's own: the extension ${extension.path} has a tool of that name.`;
210
+ }
211
+ // The caller's own are named to pi with pi's (see createSession), and are the agent's as those are.
212
+ const wanted = tools ? [...tools, ...own] : own.length > 0 ? own : undefined;
213
+ if (wanted === undefined)
132
214
  return undefined;
133
215
  const given = session.getActiveToolNames();
134
216
  // (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)}.`;
217
+ return wanted.every(name => given.includes(name)) ? undefined
218
+ : `The agent cannot be given the tools ${JSON.stringify(wanted)}: pi would give it ${JSON.stringify(given)}.`;
219
+ }
220
+ /**
221
+ * Have a session that is set going again once its call is over, or stopped
222
+ * (`done` says which it is by now), stopped as it begins to: a command of an
223
+ * extension that asks the model once more, or what an extension starts
224
+ * while it is being told that the call is over.
225
+ */
226
+ function stoppedAsItBegins(session, done) {
227
+ session.subscribe((event) => {
228
+ if (event.type !== "turn_start" && event.type !== "compaction_start")
229
+ return;
230
+ if (done())
231
+ void session.abort().catch(() => { });
232
+ });
137
233
  }
138
234
  /**
139
235
  * A signal that says to stop when either does. One of them is whatever an
@@ -181,7 +277,42 @@ function either(own, cut) {
181
277
  };
182
278
  }
183
279
  /** 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"];
280
+ export const HANDS_IN = ["before_provider_request", "before_provider_headers", "after_provider_response", "provider_stream_event"];
281
+ /**
282
+ * What pi's agent has every request of its own go with, to be told of what
283
+ * a provider is sent and answers: pi's own, which do nothing where no
284
+ * extension has a hand in (HANDS_IN). A request that goes with all of them,
285
+ * by the way the agent asks, is one the agent makes for itself — or one made
286
+ * with all the agent's was made with, which is the same to a provider.
287
+ */
288
+ export const HOOKS = ["onPayload", "onResponse", "onProviderStreamEvent"];
289
+ /**
290
+ * What else goes with a request the agent makes for itself, and is nothing
291
+ * a provider is handed: what the agent's loop calls as a turn goes, which pi
292
+ * passes along with what a provider is to have. (The functions of
293
+ * pi-agent-core's `createLoopConfig` that pi sets, less the hooks above. The
294
+ * rest of what a loop is set up by is data, and goes as any data.) Named,
295
+ * because it cannot be told otherwise: a function of the loop's is a
296
+ * function like one an asker might mean a provider to have. A pi whose loop
297
+ * is set up by a function more has its agent's requests asked where the call
298
+ * is served, until it is named here.
299
+ */
300
+ export const LOOPS = ["beforeToolCall", "afterToolCall", "finishTurn", "prepareRequest", "prepareNextTurn", "convertToLlm", "transformContext", "getSteeringMessages", "getFollowUpMessages"];
301
+ /**
302
+ * What a provider is asked by, of what it has: whether what comes of it comes
303
+ * as the events of a reply, and the way a relay asks by in its place (none,
304
+ * of a reply that was to be fetched later: it is fetched where it was asked
305
+ * for). Whatever else a provider has is not asking a model.
306
+ */
307
+ const ASKED_BY = new Map([
308
+ ["stream", { events: true, way: "stream" }],
309
+ ["streamSimple", { events: true, way: "streamSimple" }],
310
+ ["fetchDeferred", { events: true }],
311
+ ["generateImages", { events: false, way: "generateImages" }],
312
+ ["classify", { events: false, way: "classify" }],
313
+ ]);
314
+ /** What is said of a request that is not made: its call is to ask no more. */
315
+ const NO_MORE = "The call is to ask no more.";
185
316
  /**
186
317
  * What a request to a provider goes by, that is a process's own: its
187
318
  * variables — a provider's key may be one — and its ways to the network. An
@@ -219,8 +350,24 @@ function asItWas() {
219
350
  function watch(models, asking) {
220
351
  const standing = models;
221
352
  const prepare = standing.prepareRequest.bind(models);
222
- const refused = async function* (model) {
223
- yield notAsked(model, "The call is to ask no more.");
353
+ // A provider for a call that is to ask no more: whatever it is asked by, the request ends as one that was
354
+ // cancelled before it was sent — or, where what comes of it comes all at once, fails saying so. But to have
355
+ // a provider give up a reply it was keeping for later is to ask no model: that is done, whoever is stopped.
356
+ const refusing = (model, options) => {
357
+ const refused = async function* () {
358
+ yield notAsked(model, NO_MORE);
359
+ };
360
+ const failed = async () => { throw new Error(NO_MORE); };
361
+ return {
362
+ stream: refused, streamSimple: refused, fetchDeferred: refused, generateImages: failed, classify: failed,
363
+ cancelDeferred: async (_model, handle) => {
364
+ const real = await prepare(model, options);
365
+ const cancel = real.provider.cancelDeferred;
366
+ if (typeof cancel !== "function")
367
+ throw new Error(`Provider ${model.provider} does not support deferred responses`);
368
+ await cancel.call(real.provider, real.model, handle, real.options);
369
+ },
370
+ };
224
371
  };
225
372
  // A provider that is an extension's own code may ask another model by these same models, and hand back what
226
373
  // that model answered — there and then, from a queue of its own, or a reply it had asked for before: a reply
@@ -260,35 +407,70 @@ function watch(models, asking) {
260
407
  const { signal, release } = either(options?.signal, asking.cut.signal);
261
408
  return { options: { ...options, signal }, release };
262
409
  };
410
+ // What a request's asker would make of its headers (pi's agent has a function go with every request of its
411
+ // own, for extensions that would: it makes nothing of them where none does) is seen as it is made: whether
412
+ // the headers came out of it other than they went in — name by name, in their order, and a name with nothing
413
+ // under it a name all the same: pi lays headers one over another by all of that.
414
+ // (What cannot be told at all is not what it was, for all that can be said of it.)
415
+ const told = (headers) => {
416
+ try {
417
+ return JSON.stringify(headers !== null && typeof headers === "object"
418
+ ? Object.entries(headers).map(([name, value]) => [name, value === undefined ? 0 : [value]]) : [headers]);
419
+ }
420
+ catch {
421
+ return undefined;
422
+ }
423
+ };
424
+ const seeing = (options, headers) => {
425
+ const theirs = options?.transformHeaders;
426
+ if (typeof theirs !== "function")
427
+ return options;
428
+ return {
429
+ ...options,
430
+ transformHeaders: async (had) => {
431
+ const were = told(had);
432
+ const made = await theirs(had);
433
+ if (were === undefined || told(made) !== were)
434
+ headers.changed = true;
435
+ return made;
436
+ },
437
+ };
438
+ };
263
439
  standing.prepareRequest = async (model, options) => {
264
440
  count("readying", 1);
265
441
  try {
266
442
  await asking.before?.();
267
- // (Asked no more: the request ends as one that was cancelled before it was sent.)
443
+ // (Asked no more.)
268
444
  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;
445
+ return { provider: refusing(model, options), model, options: options ?? {} };
446
+ const headers = { changed: false };
447
+ const prepared = await prepare(model, seeing(options, headers));
272
448
  return {
273
449
  ...prepared,
274
- provider: new Proxy(provider, {
450
+ provider: new Proxy(prepared.provider, {
275
451
  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
452
  const value = Reflect.get(target, key, target);
291
- return typeof value === "function" ? value.bind(target) : value;
453
+ if (typeof value !== "function")
454
+ return value;
455
+ const by = ASKED_BY.get(key);
456
+ if (!by)
457
+ return value.bind(target);
458
+ // A model is asked: what a provider is handed is the model, what it is to be sent, and the options.
459
+ // Elsewhere, where that can be — or here, by the provider itself. What comes all at once is made a
460
+ // reply of one event, and counted and waited for as any reply; and whoever asked is given it whole.
461
+ return (...sent) => {
462
+ const there = stoppable(options), here = stoppable(sent[2]);
463
+ const reply = heard((async function* () {
464
+ const elsewhere = by.way && await asking.elsewhere?.(by.way, model, sent[1], there.options, headers);
465
+ if (elsewhere)
466
+ yield* elsewhere;
467
+ else if (by.events)
468
+ yield* value.call(target, sent[0], sent[1], here.options);
469
+ else
470
+ yield { type: "done", message: await value.call(target, sent[0], sent[1], here.options) };
471
+ })(), there.release, here.release);
472
+ return by.events ? reply : wholeOf(reply);
473
+ };
292
474
  },
293
475
  }),
294
476
  };
@@ -339,29 +521,71 @@ function account(asking, call, signal, session) {
339
521
  const atWork = AbortSignal.any([stopped, asking.cut.signal]);
340
522
  asking.before = () => heard = heard.then(async () => {
341
523
  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)
524
+ // (Whoever hears is not to throw. One that does has said nothing: it is not for a count to fail the call it is of.)
525
+ const said = usage ? new Promise((resolve) => resolve(sofar(usage, asking.over))) : undefined;
526
+ if (said && await rejectOnAbort(said, asking.over ? asking.cut.signal : atWork).catch(() => { }) === false && asking.over)
343
527
  noMore = true;
344
528
  });
345
529
  // (As soon as a reply has come, what the call has used is said to whoever would not otherwise know
346
530
  // it, were this process to be ended: before the reply is anybody else's to hear of.)
347
531
  asking.replied = () => {
348
532
  const usage = had && !asking.gone && counted();
349
- if (usage)
350
- had(usage);
533
+ try {
534
+ if (usage)
535
+ had(usage);
536
+ }
537
+ catch {
538
+ // (As above: a hearer that throws has said nothing.)
539
+ }
351
540
  };
352
541
  // Where the call has extensions and somebody to ask its model by, its model is asked by them: what
353
542
  // a reply used is then read where no extension is. Not where an extension has made the model's
354
543
  // provider its own, has a hand in what a provider is sent and answers, or has made
355
544
  // 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).
545
+ // extension means it to be — nor where the request is not one that can be handed over: something
546
+ // goes with it that is not data, and whoever asked may mean something by it (see dataOf).
357
547
  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))
548
+ asking.elsewhere = async (by, model, context, options = {}, headers) => {
549
+ const its = session();
550
+ if (!its || !asItWas() || asking.models.getRegisteredProviderIds().includes(model.provider))
361
551
  return undefined;
362
552
  if (HANDS_IN.some(event => its.extensionRunner.hasHandlers(event)))
363
553
  return undefined;
364
- return relay.ask({ model, context, options: data, ...(asking.over && { answered: true }) }, options?.signal);
554
+ // All that goes with a request is data, or the request is not handed over: whoever made it may mean
555
+ // something by it. But what is known to be nothing a provider is handed is left out first.
556
+ // What would make something of the request's headers, where that was seen to be nothing (see `watch`):
557
+ // the request is the same without it.
558
+ if (headers.changed)
559
+ return undefined;
560
+ const left = new Set(["transformHeaders"]);
561
+ // pi's own hooks, which do nothing here (see HANDS_IN) — and are pi's own where they are the very ones
562
+ // the session's agent has: any other is its asker's hand in the request.
563
+ const agent = its.agent;
564
+ for (const hook of HOOKS) {
565
+ if (options[hook] === undefined)
566
+ continue;
567
+ if (options[hook] !== agent[hook])
568
+ return undefined;
569
+ left.add(hook);
570
+ }
571
+ // And of a request the agent makes for itself, the rest of what its loop is set up by (see LOOPS); and
572
+ // in its conversation, which is of pi's making, what a tool kept beside its result — no provider is
573
+ // sent that, so it need not be what it was on the other side.
574
+ const agents = by === "streamSimple" && HOOKS.every(hook => options[hook] === agent[hook]);
575
+ if (agents)
576
+ for (const name of LOOPS)
577
+ left.add(name);
578
+ let data;
579
+ try {
580
+ data = dataOf(Object.fromEntries(Object.entries(options).filter(([name]) => !left.has(name))));
581
+ if (!data || (!agents && !isData(context)))
582
+ return undefined;
583
+ }
584
+ catch {
585
+ // (What cannot be gone through — it goes deeper than can be followed — is not known to be data.)
586
+ return undefined;
587
+ }
588
+ return relay.ask({ ...(by !== "streamSimple" && { by }), model, context, options: data, ...(asking.over && { answered: true }) }, options.signal);
365
589
  };
366
590
  }
367
591
  return stopped;
@@ -502,10 +726,8 @@ function usageOf(session, seen) {
502
726
  * middle of a tool call is never the last: pi has the model make the call again.
503
727
  */
504
728
  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("") ?? "";
729
+ const reply = messagesOf(session).flatMap(message => (message.role === "assistant" ? [message] : [])).at(-1);
730
+ const text = reply ? wordsOf(reply.content) : "";
509
731
  if (reply?.stopReason === "error")
510
732
  throw new Error(`The model did not answer: ${reply.errorMessage ?? "no reason given"}`);
511
733
  if (reply?.stopReason === "length")
@@ -663,6 +885,21 @@ export class PiAdapter {
663
885
  if (asked.model !== undefined && !model) {
664
886
  throw new Error(`Unknown model "${asked.model}". A model is named "provider/model", as pi's model catalog has it.`);
665
887
  }
888
+ // The caller's own tools are handed to pi as tools of pi's embedder — and named to it with the tools the
889
+ // call named, where it named any: with a list of names, pi has a tool it is handed only where it is on the
890
+ // list. A name pi would take for something else is refused first: pi's own tool by that name would be gone.
891
+ const ownTools = asked.ownTools ?? [];
892
+ if (ownTools.length > 0) {
893
+ const pis = await raceAbort(pisOwnTools());
894
+ for (const [at, { name }] of ownTools.entries()) {
895
+ if (pis.has(name))
896
+ throw new Error(`The tool "${name}" cannot be the call's own: pi has a tool of that name.`);
897
+ if (name.startsWith("mcp__"))
898
+ throw new Error(`The tool "${name}" cannot be the call's own: a name that begins "mcp__" is a tool of an MCP server's.`);
899
+ if (ownTools.findIndex(other => other.name === name) !== at)
900
+ throw new Error(`Two of the call's own tools are named "${name}".`);
901
+ }
902
+ }
666
903
  // Keep a reference to the raw promise so we can clean up a late-arriving session
667
904
  const sessionPromise = createAgentSession({
668
905
  cwd,
@@ -673,7 +910,8 @@ export class PiAdapter {
673
910
  resourceLoader,
674
911
  ...(wary && { settingsManager: wary }),
675
912
  ...(asked.thinking !== undefined && { thinkingLevel: asked.thinking }),
676
- ...(asked.tools && { tools: asked.tools }),
913
+ ...(asked.tools && { tools: [...asked.tools, ...ownTools.map(tool => tool.name)] }),
914
+ ...(ownTools.length > 0 && { customTools: ownTools.map(asPisTool) }),
677
915
  });
678
916
  let session;
679
917
  // The telling of extensions that a session begins, while it lasts.
@@ -686,18 +924,8 @@ export class PiAdapter {
686
924
  try {
687
925
  ({ session } = await raceAbort(sessionPromise));
688
926
  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
- });
700
- }
927
+ if (asked.sofar || asked.extensions)
928
+ stoppedAsItBegins(session, () => asking.over || stopped.aborted);
701
929
  // An extension is told that its session has begun, as pi tells it where pi runs by itself:
702
930
  // that is when it sets itself up. What goes wrong in one later is said, and is not the call's failure.
703
931
  // A command of one can wait for the model it asked, as it can there; the session is one call's, and
@@ -784,7 +1012,7 @@ export class PiAdapter {
784
1012
  offCut();
785
1013
  const usage = session && asked.used && usageOf(session, asking.seen);
786
1014
  if (usage)
787
- asked.used(usage);
1015
+ asked.used?.(usage);
788
1016
  }
789
1017
  throw err;
790
1018
  }
@@ -842,10 +1070,6 @@ export class PiAdapter {
842
1070
  const { cwd, system, signal, used, sofar } = call;
843
1071
  throwIfAborted(signal);
844
1072
  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());
848
- let offAbort = () => { };
849
1073
  // What is kept of the call where its model is asked (see `account`): whether it has come to its end, and
850
1074
  // whether its session is gone. (A session that was not made here has nothing asked on its account that
851
1075
  // is seen: what is kept of its call is then kept here alone.)
@@ -853,6 +1077,10 @@ export class PiAdapter {
853
1077
  const its = asking ?? { over: false, gone: false, refusal: new AbortController() };
854
1078
  // What is kept of the session beside it, where it has extensions.
855
1079
  const extended = this.extended.get(session);
1080
+ // (A call that is cancelled asks no more — and what is being asked for it then is asked no further, whoever
1081
+ // asked: while it is at its work, and while its extensions are told that it is over.)
1082
+ const offCut = onAbort(signal, () => asking?.cut.abort());
1083
+ let offAbort = () => { };
856
1084
  // Why the call cannot have the tools it named, where that was found as its run began. It is
857
1085
  // then stopped as a cancelled call is — it asks nothing, and what would hold it is not waited
858
1086
  // for long — and fails with that.
@@ -865,7 +1093,7 @@ export class PiAdapter {
865
1093
  // createSession), and the call is stopped as one that was cancelled is.
866
1094
  if (extended && call.extensions) {
867
1095
  extended.look = () => {
868
- refused = whyNotTheTools(session, call.tools);
1096
+ refused = whyNotTheTools(session, call);
869
1097
  if (refused === undefined)
870
1098
  return;
871
1099
  // (The session is stopped where it hears next that a turn begins — just after this: see createSession.)
@@ -873,14 +1101,8 @@ export class PiAdapter {
873
1101
  its.refusal.abort();
874
1102
  };
875
1103
  }
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
- }
1104
+ if (!asking && (sofar || call.extensions))
1105
+ stoppedAsItBegins(session, () => its.over || stopped.aborted);
884
1106
  // The prompt is a program's text, whatever it begins with — but where the call has the user's skills,
885
1107
  // templates or extensions, and does not say its prompt is text all the same: each of those has a line of
886
1108
  // its own to be called up by ("/skill:name", "/name", a command), and pi reads a prompt for all of them
@@ -893,7 +1115,7 @@ export class PiAdapter {
893
1115
  });
894
1116
  // A command that asked the model has the model's answer be the call's: what it put to the model is
895
1117
  // 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;
1118
+ const puts = extended?.puts;
897
1119
  while (puts && puts.size > 0)
898
1120
  await Promise.allSettled([...puts]);
899
1121
  if (taken)
@@ -907,7 +1129,7 @@ export class PiAdapter {
907
1129
  // An aborted prompt resolves with no usable answer — report it as an abort,
908
1130
  // not as an empty LLM response.
909
1131
  throwIfAborted(signal);
910
- return answerOf(session, taken);
1132
+ return endedWith(session, call.ownTools) ?? answerOf(session, taken);
911
1133
  }
912
1134
  finally {
913
1135
  offAbort();
@@ -922,7 +1144,7 @@ export class PiAdapter {
922
1144
  // ended. (Whoever counts has not waited for this: they were told as each reply came.)
923
1145
  its.gone = true;
924
1146
  offCut();
925
- const usage = used && usageOf(session, this.asking.get(session)?.seen);
1147
+ const usage = used && usageOf(session, asking?.seen);
926
1148
  if (usage)
927
1149
  used(usage);
928
1150
  }
@@ -0,0 +1,31 @@
1
+ import type { TramaConfig } from "./runner-types.js";
2
+ /**
3
+ * Everything a project directory needs around program.ts before it can run:
4
+ * history/ and logs/, an ESM package.json, .gitignore entries, and links to the
5
+ * @trama-dev packages it can import.
6
+ * Idempotent — called before every run, so a freshly cloned project just works.
7
+ */
8
+ export declare function ensureProjectScaffold(projectDir: string): void;
9
+ export declare function loadConfig(): TramaConfig;
10
+ /** The time a run is given, held to what a time is. */
11
+ export declare function checkedTimeout(timeout: number): number;
12
+ /** How many fixes a run may be tried with, held to what a count is. */
13
+ export declare function checkedRepairAttempts(attempts: number): number;
14
+ /** The global config, with the model/provider a project was created with taking precedence. */
15
+ export declare function loadProjectConfig(projectDir: string, meta?: import("./meta.js").ProjectMeta): TramaConfig;
16
+ export declare function loadState(projectDir: string): Record<string, unknown>;
17
+ /**
18
+ * Put a project's state on file: all of it, in the place of what was there.
19
+ * It is written beside the file and moved into its place, and not written
20
+ * into it — a program that is stopped in the middle of a checkpoint leaves
21
+ * the state before, and not half of a state, which no run after would start
22
+ * from. (Taking a file's place does not ask the file's leave, as writing
23
+ * into it did: so it is asked here. A state file its owner made read-only
24
+ * stays as it is.)
25
+ *
26
+ * Where no file can be made beside it — a project whose own directory is
27
+ * closed to that, and whose files are not — the state is written into its
28
+ * file, as it always was: there is no other way to it there, and a project
29
+ * kept so is still one that can be run.
30
+ */
31
+ export declare function saveState(projectDir: string, state: Record<string, unknown>): void;