@trama-dev/runtime 0.6.1 → 0.8.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 (64) hide show
  1. package/dist/agent-backend.d.ts +100 -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.d.ts +8 -0
  6. package/dist/agent-hosts.js +123 -56
  7. package/dist/agent.d.ts +18 -5
  8. package/dist/agent.js +23 -64
  9. package/dist/bridge-client.d.ts +6 -2
  10. package/dist/bridge-client.js +7 -1
  11. package/dist/budget.d.ts +6 -0
  12. package/dist/budget.js +1 -0
  13. package/dist/client.d.ts +3 -2
  14. package/dist/client.js +146 -2
  15. package/dist/context.js +3 -2
  16. package/dist/history.d.ts +9 -0
  17. package/dist/history.js +98 -0
  18. package/dist/index.d.ts +2 -0
  19. package/dist/index.js +73 -41
  20. package/dist/ipc-server.d.ts +2 -3
  21. package/dist/ipc-server.js +99 -38
  22. package/dist/journal-view.d.ts +8 -0
  23. package/dist/journal-view.js +63 -11
  24. package/dist/journal.d.ts +10 -4
  25. package/dist/journal.js +73 -7
  26. package/dist/merge-deeds.d.ts +22 -0
  27. package/dist/merge-deeds.js +201 -0
  28. package/dist/merge-doing.d.ts +9 -0
  29. package/dist/merge-doing.js +410 -0
  30. package/dist/merge-settle.d.ts +14 -0
  31. package/dist/merge-settle.js +166 -0
  32. package/dist/merge-shared.d.ts +64 -0
  33. package/dist/merge-shared.js +159 -0
  34. package/dist/merge.d.ts +150 -0
  35. package/dist/merge.js +209 -0
  36. package/dist/model-relay.d.ts +19 -0
  37. package/dist/model-relay.js +91 -9
  38. package/dist/model-request.d.ts +9 -0
  39. package/dist/model-request.js +185 -0
  40. package/dist/own-tools.d.ts +60 -0
  41. package/dist/own-tools.js +209 -0
  42. package/dist/path-guard.js +8 -6
  43. package/dist/pi-adapter.d.ts +32 -9
  44. package/dist/pi-adapter.js +198 -51
  45. package/dist/project.d.ts +39 -0
  46. package/dist/project.js +270 -0
  47. package/dist/replace-file.d.ts +13 -2
  48. package/dist/replace-file.js +23 -6
  49. package/dist/runner-backend.d.ts +43 -0
  50. package/dist/runner-backend.js +149 -0
  51. package/dist/runner-types.d.ts +26 -0
  52. package/dist/runner.d.ts +10 -125
  53. package/dist/runner.js +148 -461
  54. package/dist/schema.d.ts +45 -0
  55. package/dist/schema.js +113 -0
  56. package/dist/stopping.js +2 -3
  57. package/dist/tools.d.ts +8 -1
  58. package/dist/tools.js +36 -10
  59. package/dist/tree.d.ts +33 -149
  60. package/dist/tree.js +43 -1077
  61. package/dist/types.d.ts +182 -2
  62. package/dist/workspace.d.ts +28 -1
  63. package/dist/workspace.js +88 -13
  64. 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, isData, notAsked, usageAtEnd, wholeOf } from "./model-relay.js";
7
+ import { createModelRelay, dataOf, isData, modelNamed, 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,7 @@ 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"];
185
281
  /**
186
282
  * What pi's agent has every request of its own go with, to be told of what
187
283
  * a provider is sent and answers: pi's own, which do nothing where no
@@ -189,7 +285,7 @@ const HANDS_IN = ["before_provider_request", "before_provider_headers", "after_p
189
285
  * by the way the agent asks, is one the agent makes for itself — or one made
190
286
  * with all the agent's was made with, which is the same to a provider.
191
287
  */
192
- const HOOKS = ["onPayload", "onResponse", "onProviderStreamEvent"];
288
+ export const HOOKS = ["onPayload", "onResponse", "onProviderStreamEvent"];
193
289
  /**
194
290
  * What else goes with a request the agent makes for itself, and is nothing
195
291
  * a provider is handed: what the agent's loop calls as a turn goes, which pi
@@ -201,7 +297,7 @@ const HOOKS = ["onPayload", "onResponse", "onProviderStreamEvent"];
201
297
  * is set up by a function more has its agent's requests asked where the call
202
298
  * is served, until it is named here.
203
299
  */
204
- const LOOPS = ["beforeToolCall", "afterToolCall", "finishTurn", "prepareRequest", "prepareNextTurn", "convertToLlm", "transformContext", "getSteeringMessages", "getFollowUpMessages"];
300
+ export const LOOPS = ["beforeToolCall", "afterToolCall", "finishTurn", "prepareRequest", "prepareNextTurn", "convertToLlm", "transformContext", "getSteeringMessages", "getFollowUpMessages"];
205
301
  /**
206
302
  * What a provider is asked by, of what it has: whether what comes of it comes
207
303
  * as the events of a reply, and the way a relay asks by in its place (none,
@@ -425,15 +521,22 @@ function account(asking, call, signal, session) {
425
521
  const atWork = AbortSignal.any([stopped, asking.cut.signal]);
426
522
  asking.before = () => heard = heard.then(async () => {
427
523
  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)
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)
429
527
  noMore = true;
430
528
  });
431
529
  // (As soon as a reply has come, what the call has used is said to whoever would not otherwise know
432
530
  // it, were this process to be ended: before the reply is anybody else's to hear of.)
433
531
  asking.replied = () => {
434
532
  const usage = had && !asking.gone && counted();
435
- if (usage)
436
- had(usage);
533
+ try {
534
+ if (usage)
535
+ had(usage);
536
+ }
537
+ catch {
538
+ // (As above: a hearer that throws has said nothing.)
539
+ }
437
540
  };
438
541
  // Where the call has extensions and somebody to ask its model by, its model is asked by them: what
439
542
  // a reply used is then read where no extension is. Not where an extension has made the model's
@@ -623,10 +726,8 @@ function usageOf(session, seen) {
623
726
  * middle of a tool call is never the last: pi has the model make the call again.
624
727
  */
625
728
  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("") ?? "";
729
+ const reply = messagesOf(session).flatMap(message => (message.role === "assistant" ? [message] : [])).at(-1);
730
+ const text = reply ? wordsOf(reply.content) : "";
630
731
  if (reply?.stopReason === "error")
631
732
  throw new Error(`The model did not answer: ${reply.errorMessage ?? "no reason given"}`);
632
733
  if (reply?.stopReason === "length")
@@ -648,12 +749,16 @@ function answerOf(session, taken = false) {
648
749
  * commands it runs are given, are a process's — and this process is the
649
750
  * runner's, whose own are not a run's to change.
650
751
  */
752
+ /** How long a provider is waited for, for one request to a model that does not say: as pi's agent waits for one. */
753
+ const MODEL_TIMEOUT_MS = 300_000;
651
754
  export class PiAdapter {
652
755
  config;
653
756
  /** Whether every call is served in a process of its own: where those processes are given variables this one has not. */
654
757
  apart;
655
758
  /** The processes that serve this adapter's calls. */
656
759
  hosts;
760
+ /** Who asks a model for a request that is no call of an agent's, where that is this process: made when one first comes. */
761
+ asks;
657
762
  constructor(config, env) {
658
763
  this.config = config;
659
764
  // (Variables that are none are none given: such a run's calls are served as any run's.)
@@ -664,9 +769,53 @@ export class PiAdapter {
664
769
  async ask(prompt, call) {
665
770
  return call.extensions || this.apart ? this.hosts.ask(this.config, prompt, call) : this.serve(prompt, call);
666
771
  }
772
+ /**
773
+ * Ask a model once (see AgentBackend.complete): by pi's own models, as pi
774
+ * hands a request to a provider — no session of pi's, and so none of what
775
+ * a session does: no tool is run, nothing is asked again, nothing summed
776
+ * up. Asked where this adapter's calls have their models asked for them:
777
+ * here — or, for an adapter that was given variables, by the process
778
+ * that was started with them, where a key that is among them is the key.
779
+ */
780
+ async complete(request, call) {
781
+ throwIfAborted(call.signal);
782
+ const { context, model, thinking, timeout, ...sampled } = request;
783
+ // (Without a name of its own, the project's model — by name too: which of pi's that is, is for whoever asks it to say.)
784
+ const named = model ?? `${this.config.provider}/${this.config.model}`;
785
+ const stroke = named.indexOf("/");
786
+ const relay = this.apart ? this.hosts.asks : this.asks ??= createModelRelay();
787
+ const events = await relay.ask({
788
+ named, model: { provider: named.slice(0, stroke), id: named.slice(stroke + 1) }, context,
789
+ // (As pi's agent has a provider waited for, where the request does not say.)
790
+ options: { ...sampled, ...(thinking !== undefined && { reasoning: thinking }), timeoutMs: timeout ?? MODEL_TIMEOUT_MS },
791
+ }, call.signal);
792
+ if (!events)
793
+ throw new Error("The model could not be asked: pi was not to be had to ask it by.");
794
+ let last;
795
+ for await (const event of events)
796
+ last = event;
797
+ const reply = last?.type === "done" ? last.message : last?.type === "error" ? last.error : undefined;
798
+ if (!last || !isData(reply) || typeof reply !== "object" || reply === null || Array.isArray(reply))
799
+ throw new Error("The model could not be asked: nothing came of asking it.");
800
+ const said = reply;
801
+ // What it used, however it ended — where it used anything: a reply that failed half-way was paid for as far as it came.
802
+ const usage = usageAtEnd(last);
803
+ if (usage && usage.input + usage.output + usage.cacheRead + usage.cacheWrite > 0) {
804
+ call.used?.({ model: `${String(said.provider)}/${String(said.model)}`, input: usage.input, output: usage.output, cacheRead: usage.cacheRead, cacheWrite: usage.cacheWrite, cost: usage.cost.total });
805
+ }
806
+ throwIfAborted(call.signal);
807
+ const kind = last.unasked;
808
+ if (kind !== undefined) {
809
+ throw new Error(kind === "model" && model === undefined
810
+ ? `The project's model, ${named}, is not one pi has. A request to a model is answered by the model it names, or by the project's: there is no agent here whose own choice it could fall back on.`
811
+ : String(said.errorMessage));
812
+ }
813
+ return said;
814
+ }
667
815
  /** End the processes that served calls: what this adapter was for is over. (It can be asked again: it starts them anew.) */
668
816
  async close() {
669
- await this.hosts.close();
817
+ await Promise.all([this.hosts.close(), this.asks?.close()]);
818
+ this.asks = undefined;
670
819
  }
671
820
  async createSession(cwd, systemPrompt, signal, asked = {}) {
672
821
  // Each step below is given up on the moment the call is cancelled.
@@ -776,14 +925,27 @@ export class PiAdapter {
776
925
  const modelRuntime = await raceAbort(ModelRuntime.create({ signal }));
777
926
  const asking = { models: modelRuntime, seen: nothingYet(), answering: 0, readying: 0, cut: new AbortController(), over: false, gone: false, refusal: new AbortController() };
778
927
  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
928
  const model = asked.model === undefined
782
929
  ? 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);
930
+ : modelNamed(modelRuntime, asked.model);
784
931
  if (asked.model !== undefined && !model) {
785
932
  throw new Error(`Unknown model "${asked.model}". A model is named "provider/model", as pi's model catalog has it.`);
786
933
  }
934
+ // The caller's own tools are handed to pi as tools of pi's embedder — and named to it with the tools the
935
+ // call named, where it named any: with a list of names, pi has a tool it is handed only where it is on the
936
+ // list. A name pi would take for something else is refused first: pi's own tool by that name would be gone.
937
+ const ownTools = asked.ownTools ?? [];
938
+ if (ownTools.length > 0) {
939
+ const pis = await raceAbort(pisOwnTools());
940
+ for (const [at, { name }] of ownTools.entries()) {
941
+ if (pis.has(name))
942
+ throw new Error(`The tool "${name}" cannot be the call's own: pi has a tool of that name.`);
943
+ if (name.startsWith("mcp__"))
944
+ 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.`);
945
+ if (ownTools.findIndex(other => other.name === name) !== at)
946
+ throw new Error(`Two of the call's own tools are named "${name}".`);
947
+ }
948
+ }
787
949
  // Keep a reference to the raw promise so we can clean up a late-arriving session
788
950
  const sessionPromise = createAgentSession({
789
951
  cwd,
@@ -794,7 +956,8 @@ export class PiAdapter {
794
956
  resourceLoader,
795
957
  ...(wary && { settingsManager: wary }),
796
958
  ...(asked.thinking !== undefined && { thinkingLevel: asked.thinking }),
797
- ...(asked.tools && { tools: asked.tools }),
959
+ ...(asked.tools && { tools: [...asked.tools, ...ownTools.map(tool => tool.name)] }),
960
+ ...(ownTools.length > 0 && { customTools: ownTools.map(asPisTool) }),
798
961
  });
799
962
  let session;
800
963
  // The telling of extensions that a session begins, while it lasts.
@@ -807,18 +970,8 @@ export class PiAdapter {
807
970
  try {
808
971
  ({ session } = await raceAbort(sessionPromise));
809
972
  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
- }
973
+ if (asked.sofar || asked.extensions)
974
+ stoppedAsItBegins(session, () => asking.over || stopped.aborted);
822
975
  // An extension is told that its session has begun, as pi tells it where pi runs by itself:
823
976
  // that is when it sets itself up. What goes wrong in one later is said, and is not the call's failure.
824
977
  // A command of one can wait for the model it asked, as it can there; the session is one call's, and
@@ -905,7 +1058,7 @@ export class PiAdapter {
905
1058
  offCut();
906
1059
  const usage = session && asked.used && usageOf(session, asking.seen);
907
1060
  if (usage)
908
- asked.used(usage);
1061
+ asked.used?.(usage);
909
1062
  }
910
1063
  throw err;
911
1064
  }
@@ -963,10 +1116,6 @@ export class PiAdapter {
963
1116
  const { cwd, system, signal, used, sofar } = call;
964
1117
  throwIfAborted(signal);
965
1118
  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());
969
- let offAbort = () => { };
970
1119
  // What is kept of the call where its model is asked (see `account`): whether it has come to its end, and
971
1120
  // whether its session is gone. (A session that was not made here has nothing asked on its account that
972
1121
  // is seen: what is kept of its call is then kept here alone.)
@@ -974,6 +1123,10 @@ export class PiAdapter {
974
1123
  const its = asking ?? { over: false, gone: false, refusal: new AbortController() };
975
1124
  // What is kept of the session beside it, where it has extensions.
976
1125
  const extended = this.extended.get(session);
1126
+ // (A call that is cancelled asks no more — and what is being asked for it then is asked no further, whoever
1127
+ // asked: while it is at its work, and while its extensions are told that it is over.)
1128
+ const offCut = onAbort(signal, () => asking?.cut.abort());
1129
+ let offAbort = () => { };
977
1130
  // Why the call cannot have the tools it named, where that was found as its run began. It is
978
1131
  // then stopped as a cancelled call is — it asks nothing, and what would hold it is not waited
979
1132
  // for long — and fails with that.
@@ -986,7 +1139,7 @@ export class PiAdapter {
986
1139
  // createSession), and the call is stopped as one that was cancelled is.
987
1140
  if (extended && call.extensions) {
988
1141
  extended.look = () => {
989
- refused = whyNotTheTools(session, call.tools);
1142
+ refused = whyNotTheTools(session, call);
990
1143
  if (refused === undefined)
991
1144
  return;
992
1145
  // (The session is stopped where it hears next that a turn begins — just after this: see createSession.)
@@ -994,14 +1147,8 @@ export class PiAdapter {
994
1147
  its.refusal.abort();
995
1148
  };
996
1149
  }
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
- }
1150
+ if (!asking && (sofar || call.extensions))
1151
+ stoppedAsItBegins(session, () => its.over || stopped.aborted);
1005
1152
  // The prompt is a program's text, whatever it begins with — but where the call has the user's skills,
1006
1153
  // templates or extensions, and does not say its prompt is text all the same: each of those has a line of
1007
1154
  // its own to be called up by ("/skill:name", "/name", a command), and pi reads a prompt for all of them
@@ -1014,7 +1161,7 @@ export class PiAdapter {
1014
1161
  });
1015
1162
  // A command that asked the model has the model's answer be the call's: what it put to the model is
1016
1163
  // 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;
1164
+ const puts = extended?.puts;
1018
1165
  while (puts && puts.size > 0)
1019
1166
  await Promise.allSettled([...puts]);
1020
1167
  if (taken)
@@ -1028,7 +1175,7 @@ export class PiAdapter {
1028
1175
  // An aborted prompt resolves with no usable answer — report it as an abort,
1029
1176
  // not as an empty LLM response.
1030
1177
  throwIfAborted(signal);
1031
- return answerOf(session, taken);
1178
+ return endedWith(session, call.ownTools) ?? answerOf(session, taken);
1032
1179
  }
1033
1180
  finally {
1034
1181
  offAbort();
@@ -1043,7 +1190,7 @@ export class PiAdapter {
1043
1190
  // ended. (Whoever counts has not waited for this: they were told as each reply came.)
1044
1191
  its.gone = true;
1045
1192
  offCut();
1046
- const usage = used && usageOf(session, this.asking.get(session)?.seen);
1193
+ const usage = used && usageOf(session, asking?.seen);
1047
1194
  if (usage)
1048
1195
  used(usage);
1049
1196
  }
@@ -0,0 +1,39 @@
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
+ /**
11
+ * Where a project is, that is named as `repairWith` names one: by a path —
12
+ * what has a stroke in it, or begins with a dot or with "~" for the user's
13
+ * home — or else by its name among the user's projects.
14
+ */
15
+ export declare function projectNamed(given: string): string;
16
+ /** Whether what names a project names it by a path, and not by its name among the user's projects. */
17
+ export declare const namesAPath: (given: string) => boolean;
18
+ /** The time a run is given, held to what a time is. */
19
+ export declare function checkedTimeout(timeout: number): number;
20
+ /** How many fixes a run may be tried with, held to what a count is. */
21
+ export declare function checkedRepairAttempts(attempts: number): number;
22
+ /** The global config, with the model/provider a project was created with taking precedence. */
23
+ export declare function loadProjectConfig(projectDir: string, meta?: import("./meta.js").ProjectMeta): TramaConfig;
24
+ export declare function loadState(projectDir: string): Record<string, unknown>;
25
+ /**
26
+ * Put a project's state on file: all of it, in the place of what was there.
27
+ * It is written beside the file and moved into its place, and not written
28
+ * into it — a program that is stopped in the middle of a checkpoint leaves
29
+ * the state before, and not half of a state, which no run after would start
30
+ * from. (Taking a file's place does not ask the file's leave, as writing
31
+ * into it did: so it is asked here. A state file its owner made read-only
32
+ * stays as it is.)
33
+ *
34
+ * Where no file can be made beside it — a project whose own directory is
35
+ * closed to that, and whose files are not — the state is written into its
36
+ * file, as it always was: there is no other way to it there, and a project
37
+ * kept so is still one that can be run.
38
+ */
39
+ export declare function saveState(projectDir: string, state: Record<string, unknown>): void;