@trama-dev/runtime 0.6.1 → 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.
- package/dist/agent-backend.d.ts +51 -0
- package/dist/agent-backend.js +4 -0
- package/dist/agent-host.d.ts +46 -7
- package/dist/agent-host.js +59 -19
- package/dist/agent-hosts.js +122 -56
- package/dist/agent.d.ts +16 -5
- package/dist/agent.js +22 -64
- package/dist/bridge-client.d.ts +6 -2
- package/dist/bridge-client.js +6 -1
- package/dist/client.d.ts +2 -2
- package/dist/client.js +126 -2
- package/dist/context.js +3 -2
- package/dist/history.d.ts +9 -0
- package/dist/history.js +98 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +70 -41
- package/dist/ipc-server.d.ts +2 -3
- package/dist/ipc-server.js +93 -37
- package/dist/journal-view.js +19 -9
- package/dist/journal.d.ts +10 -4
- package/dist/journal.js +28 -6
- package/dist/merge-deeds.d.ts +22 -0
- package/dist/merge-deeds.js +201 -0
- package/dist/merge-doing.d.ts +9 -0
- package/dist/merge-doing.js +410 -0
- package/dist/merge-settle.d.ts +14 -0
- package/dist/merge-settle.js +166 -0
- package/dist/merge-shared.d.ts +64 -0
- package/dist/merge-shared.js +159 -0
- package/dist/merge.d.ts +150 -0
- package/dist/merge.js +209 -0
- package/dist/model-relay.js +35 -5
- package/dist/own-tools.d.ts +60 -0
- package/dist/own-tools.js +209 -0
- package/dist/path-guard.js +8 -6
- package/dist/pi-adapter.d.ts +22 -0
- package/dist/pi-adapter.js +147 -46
- package/dist/project.d.ts +31 -0
- package/dist/project.js +253 -0
- package/dist/replace-file.d.ts +13 -2
- package/dist/replace-file.js +23 -6
- package/dist/runner-backend.d.ts +43 -0
- package/dist/runner-backend.js +125 -0
- package/dist/runner-types.d.ts +8 -0
- package/dist/runner.d.ts +8 -123
- package/dist/runner.js +57 -453
- package/dist/schema.d.ts +38 -0
- package/dist/schema.js +104 -0
- package/dist/stopping.js +2 -3
- package/dist/tools.js +31 -7
- package/dist/tree.d.ts +33 -149
- package/dist/tree.js +43 -1077
- package/dist/types.d.ts +54 -2
- package/dist/workspace.d.ts +20 -0
- package/dist/workspace.js +76 -12
- package/package.json +2 -2
package/dist/pi-adapter.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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
7
|
import { dataOf, isData, notAsked, usageAtEnd, wholeOf } from "./model-relay.js";
|
|
@@ -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
|
|
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
|
-
|
|
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
|
|
136
|
-
: `The agent cannot be given the tools ${JSON.stringify(
|
|
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
|
-
|
|
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
|
-
|
|
436
|
-
|
|
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
|
|
627
|
-
|
|
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")
|
|
@@ -784,6 +885,21 @@ export class PiAdapter {
|
|
|
784
885
|
if (asked.model !== undefined && !model) {
|
|
785
886
|
throw new Error(`Unknown model "${asked.model}". A model is named "provider/model", as pi's model catalog has it.`);
|
|
786
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
|
+
}
|
|
787
903
|
// Keep a reference to the raw promise so we can clean up a late-arriving session
|
|
788
904
|
const sessionPromise = createAgentSession({
|
|
789
905
|
cwd,
|
|
@@ -794,7 +910,8 @@ export class PiAdapter {
|
|
|
794
910
|
resourceLoader,
|
|
795
911
|
...(wary && { settingsManager: wary }),
|
|
796
912
|
...(asked.thinking !== undefined && { thinkingLevel: asked.thinking }),
|
|
797
|
-
...(asked.tools && { tools: asked.tools }),
|
|
913
|
+
...(asked.tools && { tools: [...asked.tools, ...ownTools.map(tool => tool.name)] }),
|
|
914
|
+
...(ownTools.length > 0 && { customTools: ownTools.map(asPisTool) }),
|
|
798
915
|
});
|
|
799
916
|
let session;
|
|
800
917
|
// The telling of extensions that a session begins, while it lasts.
|
|
@@ -807,18 +924,8 @@ export class PiAdapter {
|
|
|
807
924
|
try {
|
|
808
925
|
({ session } = await raceAbort(sessionPromise));
|
|
809
926
|
this.asking.set(session, asking);
|
|
810
|
-
|
|
811
|
-
|
|
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
|
-
}
|
|
927
|
+
if (asked.sofar || asked.extensions)
|
|
928
|
+
stoppedAsItBegins(session, () => asking.over || stopped.aborted);
|
|
822
929
|
// An extension is told that its session has begun, as pi tells it where pi runs by itself:
|
|
823
930
|
// that is when it sets itself up. What goes wrong in one later is said, and is not the call's failure.
|
|
824
931
|
// A command of one can wait for the model it asked, as it can there; the session is one call's, and
|
|
@@ -905,7 +1012,7 @@ export class PiAdapter {
|
|
|
905
1012
|
offCut();
|
|
906
1013
|
const usage = session && asked.used && usageOf(session, asking.seen);
|
|
907
1014
|
if (usage)
|
|
908
|
-
asked.used(usage);
|
|
1015
|
+
asked.used?.(usage);
|
|
909
1016
|
}
|
|
910
1017
|
throw err;
|
|
911
1018
|
}
|
|
@@ -963,10 +1070,6 @@ export class PiAdapter {
|
|
|
963
1070
|
const { cwd, system, signal, used, sofar } = call;
|
|
964
1071
|
throwIfAborted(signal);
|
|
965
1072
|
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
1073
|
// What is kept of the call where its model is asked (see `account`): whether it has come to its end, and
|
|
971
1074
|
// whether its session is gone. (A session that was not made here has nothing asked on its account that
|
|
972
1075
|
// is seen: what is kept of its call is then kept here alone.)
|
|
@@ -974,6 +1077,10 @@ export class PiAdapter {
|
|
|
974
1077
|
const its = asking ?? { over: false, gone: false, refusal: new AbortController() };
|
|
975
1078
|
// What is kept of the session beside it, where it has extensions.
|
|
976
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 = () => { };
|
|
977
1084
|
// Why the call cannot have the tools it named, where that was found as its run began. It is
|
|
978
1085
|
// then stopped as a cancelled call is — it asks nothing, and what would hold it is not waited
|
|
979
1086
|
// for long — and fails with that.
|
|
@@ -986,7 +1093,7 @@ export class PiAdapter {
|
|
|
986
1093
|
// createSession), and the call is stopped as one that was cancelled is.
|
|
987
1094
|
if (extended && call.extensions) {
|
|
988
1095
|
extended.look = () => {
|
|
989
|
-
refused = whyNotTheTools(session, call
|
|
1096
|
+
refused = whyNotTheTools(session, call);
|
|
990
1097
|
if (refused === undefined)
|
|
991
1098
|
return;
|
|
992
1099
|
// (The session is stopped where it hears next that a turn begins — just after this: see createSession.)
|
|
@@ -994,14 +1101,8 @@ export class PiAdapter {
|
|
|
994
1101
|
its.refusal.abort();
|
|
995
1102
|
};
|
|
996
1103
|
}
|
|
997
|
-
if (!asking && (sofar || call.extensions))
|
|
998
|
-
session
|
|
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
|
-
}
|
|
1104
|
+
if (!asking && (sofar || call.extensions))
|
|
1105
|
+
stoppedAsItBegins(session, () => its.over || stopped.aborted);
|
|
1005
1106
|
// The prompt is a program's text, whatever it begins with — but where the call has the user's skills,
|
|
1006
1107
|
// templates or extensions, and does not say its prompt is text all the same: each of those has a line of
|
|
1007
1108
|
// its own to be called up by ("/skill:name", "/name", a command), and pi reads a prompt for all of them
|
|
@@ -1014,7 +1115,7 @@ export class PiAdapter {
|
|
|
1014
1115
|
});
|
|
1015
1116
|
// A command that asked the model has the model's answer be the call's: what it put to the model is
|
|
1016
1117
|
// waited for — also where the command itself did not wait, or pi had not yet set the run going.
|
|
1017
|
-
const puts =
|
|
1118
|
+
const puts = extended?.puts;
|
|
1018
1119
|
while (puts && puts.size > 0)
|
|
1019
1120
|
await Promise.allSettled([...puts]);
|
|
1020
1121
|
if (taken)
|
|
@@ -1028,7 +1129,7 @@ export class PiAdapter {
|
|
|
1028
1129
|
// An aborted prompt resolves with no usable answer — report it as an abort,
|
|
1029
1130
|
// not as an empty LLM response.
|
|
1030
1131
|
throwIfAborted(signal);
|
|
1031
|
-
return answerOf(session, taken);
|
|
1132
|
+
return endedWith(session, call.ownTools) ?? answerOf(session, taken);
|
|
1032
1133
|
}
|
|
1033
1134
|
finally {
|
|
1034
1135
|
offAbort();
|
|
@@ -1043,7 +1144,7 @@ export class PiAdapter {
|
|
|
1043
1144
|
// ended. (Whoever counts has not waited for this: they were told as each reply came.)
|
|
1044
1145
|
its.gone = true;
|
|
1045
1146
|
offCut();
|
|
1046
|
-
const usage = used && usageOf(session,
|
|
1147
|
+
const usage = used && usageOf(session, asking?.seen);
|
|
1047
1148
|
if (usage)
|
|
1048
1149
|
used(usage);
|
|
1049
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;
|
package/dist/project.js
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
// What a project is on disk before anything of it is run: the files trama
|
|
2
|
+
// keeps around a program.ts, the config a run of it goes by, and the state
|
|
3
|
+
// its last run left.
|
|
4
|
+
import { readFileSync, writeFileSync, mkdirSync, existsSync, symlinkSync, rmSync, lstatSync, readlinkSync, accessSync, constants, } from "fs";
|
|
5
|
+
import { join, dirname } from "path";
|
|
6
|
+
import { homedir } from "os";
|
|
7
|
+
import { fileURLToPath } from "url";
|
|
8
|
+
import { checkedBudget } from "./budget.js";
|
|
9
|
+
import { guardPath, projectAt } from "./path-guard.js";
|
|
10
|
+
import { stageFileInProject } from "./replace-file.js";
|
|
11
|
+
import { readProjectMeta } from "./meta.js";
|
|
12
|
+
import { describeJson, isJsonObject } from "./serializable.js";
|
|
13
|
+
import { messageOf } from "./errors.js";
|
|
14
|
+
// --- Locating the runtime itself ---
|
|
15
|
+
/** The installed @trama-dev/runtime package — this file lives in its dist/. */
|
|
16
|
+
const RUNTIME_PACKAGE_DIR = dirname(dirname(fileURLToPath(import.meta.url)));
|
|
17
|
+
/**
|
|
18
|
+
* The @trama-dev packages a program.ts can import, and where they are installed.
|
|
19
|
+
* The runtime always; the session layer when it is installed alongside (as it
|
|
20
|
+
* is with the CLI). The runtime never imports the session layer itself — it
|
|
21
|
+
* only makes it reachable from projects.
|
|
22
|
+
*/
|
|
23
|
+
const IMPORTABLE_PACKAGES = { runtime: RUNTIME_PACKAGE_DIR };
|
|
24
|
+
try {
|
|
25
|
+
// Resolves to <package>/dist/index.js
|
|
26
|
+
IMPORTABLE_PACKAGES.session = dirname(dirname(fileURLToPath(import.meta.resolve("@trama-dev/session"))));
|
|
27
|
+
}
|
|
28
|
+
catch { /* not installed — programs simply cannot import it */ }
|
|
29
|
+
// --- Project scaffolding ---
|
|
30
|
+
/**
|
|
31
|
+
* Point the project's node_modules/@trama-dev/<name> at an installed package,
|
|
32
|
+
* so program.ts can import it. Replaces any existing symlink whose target
|
|
33
|
+
* differs (including user-managed ones). Only refuses to touch a real
|
|
34
|
+
* directory/file to avoid destroying user content.
|
|
35
|
+
*
|
|
36
|
+
* The link points outside the project, and is meant to. Where it is put is
|
|
37
|
+
* inside it, like everything else the runtime writes: a project whose
|
|
38
|
+
* node_modules leads somewhere else is refused, not followed there.
|
|
39
|
+
*/
|
|
40
|
+
function linkPackage(projectDir, name, target) {
|
|
41
|
+
const linkDir = guardPath(projectDir, join("node_modules", "@trama-dev"));
|
|
42
|
+
// Not through the guard: it is the link itself that is looked at and replaced, not what it points at.
|
|
43
|
+
const linkPath = join(linkDir, name);
|
|
44
|
+
try {
|
|
45
|
+
if (!lstatSync(linkPath).isSymbolicLink()) {
|
|
46
|
+
throw new Error(`${linkPath} exists and is not a symlink. ` +
|
|
47
|
+
`trama needs this path for module resolution. ` +
|
|
48
|
+
`Remove it manually or rename it to proceed.`);
|
|
49
|
+
}
|
|
50
|
+
if (readlinkSync(linkPath) === target)
|
|
51
|
+
return;
|
|
52
|
+
rmSync(linkPath);
|
|
53
|
+
}
|
|
54
|
+
catch (err) {
|
|
55
|
+
if (err.code !== "ENOENT")
|
|
56
|
+
throw err;
|
|
57
|
+
}
|
|
58
|
+
mkdirSync(linkDir, { recursive: true });
|
|
59
|
+
symlinkSync(target, linkPath, "dir");
|
|
60
|
+
}
|
|
61
|
+
/** Make sure package.json exists and declares an ES module (program.ts uses top-level await). */
|
|
62
|
+
function ensureModulePackageJson(projectDir) {
|
|
63
|
+
const pkgPath = guardPath(projectDir, "package.json");
|
|
64
|
+
if (!existsSync(pkgPath)) {
|
|
65
|
+
writeFileSync(pkgPath, JSON.stringify({ type: "module" }, null, 2));
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
const advice = "trama will not overwrite it automatically; fix or remove it and try again.";
|
|
69
|
+
let pkg;
|
|
70
|
+
try {
|
|
71
|
+
pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
|
|
72
|
+
}
|
|
73
|
+
catch (err) {
|
|
74
|
+
throw new Error(`Malformed package.json at ${pkgPath}. ${advice}\n` +
|
|
75
|
+
`Parse error: ${messageOf(err)}`);
|
|
76
|
+
}
|
|
77
|
+
if (!isJsonObject(pkg)) {
|
|
78
|
+
throw new Error(`Malformed package.json at ${pkgPath} — expected a JSON object but got ${describeJson(pkg)}. ${advice}`);
|
|
79
|
+
}
|
|
80
|
+
if (pkg.type !== "module") {
|
|
81
|
+
pkg.type = "module";
|
|
82
|
+
writeFileSync(pkgPath, JSON.stringify(pkg, null, 2));
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/** Make sure .gitignore excludes what trama generates, without disturbing existing entries. */
|
|
86
|
+
function ensureGitignore(projectDir) {
|
|
87
|
+
const giPath = guardPath(projectDir, ".gitignore");
|
|
88
|
+
const required = ["node_modules/", "state.json", "logs/", "history/"];
|
|
89
|
+
const existing = existsSync(giPath) ? readFileSync(giPath, "utf-8") : "";
|
|
90
|
+
const present = new Set(existing.split("\n").map(line => line.trim()));
|
|
91
|
+
const missing = required.filter(entry => !present.has(entry));
|
|
92
|
+
if (missing.length === 0)
|
|
93
|
+
return;
|
|
94
|
+
const separator = existing === "" || existing.endsWith("\n") ? "" : "\n";
|
|
95
|
+
writeFileSync(giPath, existing + separator + missing.join("\n") + "\n");
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Everything a project directory needs around program.ts before it can run:
|
|
99
|
+
* history/ and logs/, an ESM package.json, .gitignore entries, and links to the
|
|
100
|
+
* @trama-dev packages it can import.
|
|
101
|
+
* Idempotent — called before every run, so a freshly cloned project just works.
|
|
102
|
+
*/
|
|
103
|
+
export function ensureProjectScaffold(projectDir) {
|
|
104
|
+
projectAt(projectDir);
|
|
105
|
+
mkdirSync(guardPath(projectDir, "history"), { recursive: true });
|
|
106
|
+
mkdirSync(guardPath(projectDir, "logs"), { recursive: true });
|
|
107
|
+
ensureModulePackageJson(projectDir);
|
|
108
|
+
ensureGitignore(projectDir);
|
|
109
|
+
for (const [name, target] of Object.entries(IMPORTABLE_PACKAGES))
|
|
110
|
+
linkPackage(projectDir, name, target);
|
|
111
|
+
}
|
|
112
|
+
// --- Config & state loaders ---
|
|
113
|
+
export function loadConfig() {
|
|
114
|
+
const configPath = join(homedir(), ".trama", "config.json");
|
|
115
|
+
const defaults = {
|
|
116
|
+
provider: "anthropic",
|
|
117
|
+
model: "claude-opus-5-5",
|
|
118
|
+
maxRepairAttempts: 3,
|
|
119
|
+
defaultTimeout: 300_000,
|
|
120
|
+
defaultMaxIterations: 100,
|
|
121
|
+
journalRuns: 20,
|
|
122
|
+
agentChanges: "keep",
|
|
123
|
+
};
|
|
124
|
+
let raw;
|
|
125
|
+
try {
|
|
126
|
+
raw = readFileSync(configPath, "utf-8");
|
|
127
|
+
}
|
|
128
|
+
catch (err) {
|
|
129
|
+
if (err.code === "ENOENT")
|
|
130
|
+
return defaults;
|
|
131
|
+
throw err;
|
|
132
|
+
}
|
|
133
|
+
let parsed;
|
|
134
|
+
try {
|
|
135
|
+
parsed = JSON.parse(raw);
|
|
136
|
+
}
|
|
137
|
+
catch (err) {
|
|
138
|
+
throw new Error(`Malformed config at ${configPath} — fix or delete it.\n` +
|
|
139
|
+
`Parse error: ${messageOf(err)}`);
|
|
140
|
+
}
|
|
141
|
+
if (!isJsonObject(parsed)) {
|
|
142
|
+
throw new Error(`Malformed config at ${configPath} — expected a JSON object but got ${describeJson(parsed)}. Fix or delete it to proceed.`);
|
|
143
|
+
}
|
|
144
|
+
// null is how JSON says a field is not there.
|
|
145
|
+
const given = Object.fromEntries(Object.entries(parsed).filter(([, value]) => value !== null));
|
|
146
|
+
return checkedConfig({ ...defaults, ...given }, "config");
|
|
147
|
+
}
|
|
148
|
+
/** A config that holds what the runtime can work with — or an error naming what does not, and where it came from. */
|
|
149
|
+
function checkedConfig(merged, source) {
|
|
150
|
+
const s = (v) => typeof v === "string" && v.length > 0;
|
|
151
|
+
const pint = (v) => Number.isInteger(v) && v > 0;
|
|
152
|
+
const checks = [
|
|
153
|
+
[s(merged.provider), `"provider" must be a non-empty string (got ${JSON.stringify(merged.provider)})`],
|
|
154
|
+
[s(merged.model), `"model" must be a non-empty string (got ${JSON.stringify(merged.model)})`],
|
|
155
|
+
[Number.isInteger(merged.maxRepairAttempts) && merged.maxRepairAttempts >= 0, `"maxRepairAttempts" must be a non-negative integer (got ${merged.maxRepairAttempts})`],
|
|
156
|
+
[Number.isFinite(merged.defaultTimeout) && merged.defaultTimeout > 0, `"defaultTimeout" must be a positive number (got ${merged.defaultTimeout})`],
|
|
157
|
+
[pint(merged.defaultMaxIterations), `"defaultMaxIterations" must be a positive integer (got ${merged.defaultMaxIterations})`],
|
|
158
|
+
[Number.isInteger(merged.journalRuns) && merged.journalRuns >= 0, `"journalRuns" must be a non-negative integer (got ${merged.journalRuns})`],
|
|
159
|
+
[merged.agentChanges === "keep" || merged.agentChanges === "discard", `"agentChanges" must be "keep" or "discard" (got ${JSON.stringify(merged.agentChanges)})`],
|
|
160
|
+
];
|
|
161
|
+
for (const [ok, msg] of checks) {
|
|
162
|
+
if (!ok)
|
|
163
|
+
throw new Error(`Invalid ${source}: ${msg}`);
|
|
164
|
+
}
|
|
165
|
+
if (merged.budget === undefined)
|
|
166
|
+
return merged;
|
|
167
|
+
try {
|
|
168
|
+
return { ...merged, budget: checkedBudget(merged.budget, `"budget"`) };
|
|
169
|
+
}
|
|
170
|
+
catch (err) {
|
|
171
|
+
throw new Error(`Invalid ${source}: ${messageOf(err)}`);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
/** The time a run is given, held to what a time is. */
|
|
175
|
+
export function checkedTimeout(timeout) {
|
|
176
|
+
if (!Number.isFinite(timeout) || timeout <= 0)
|
|
177
|
+
throw new Error(`Invalid timeout: ${timeout}. Must be a positive number.`);
|
|
178
|
+
return timeout;
|
|
179
|
+
}
|
|
180
|
+
/** How many fixes a run may be tried with, held to what a count is. */
|
|
181
|
+
export function checkedRepairAttempts(attempts) {
|
|
182
|
+
if (!Number.isInteger(attempts) || attempts < 0)
|
|
183
|
+
throw new Error(`Invalid maxRepairAttempts: ${attempts}. Must be a non-negative integer.`);
|
|
184
|
+
return attempts;
|
|
185
|
+
}
|
|
186
|
+
/** The global config, with the model/provider a project was created with taking precedence. */
|
|
187
|
+
export function loadProjectConfig(projectDir, meta = readProjectMeta(projectDir)) {
|
|
188
|
+
const config = loadConfig();
|
|
189
|
+
// null is how JSON says a field is not there. Anything else a project says
|
|
190
|
+
// is taken, and held to what the global config is held to — an empty or
|
|
191
|
+
// mistyped name is an error here, not a quiet return to another model.
|
|
192
|
+
if (meta.model != null)
|
|
193
|
+
config.model = meta.model;
|
|
194
|
+
if (meta.provider != null)
|
|
195
|
+
config.provider = meta.provider;
|
|
196
|
+
return checkedConfig(config, `meta.json in ${projectDir}`);
|
|
197
|
+
}
|
|
198
|
+
export function loadState(projectDir) {
|
|
199
|
+
const statePath = guardPath(projectDir, "state.json");
|
|
200
|
+
let raw;
|
|
201
|
+
try {
|
|
202
|
+
raw = readFileSync(statePath, "utf-8");
|
|
203
|
+
}
|
|
204
|
+
catch (err) {
|
|
205
|
+
if (err.code === "ENOENT")
|
|
206
|
+
return {};
|
|
207
|
+
throw err;
|
|
208
|
+
}
|
|
209
|
+
function fail(reason) {
|
|
210
|
+
throw new Error(`Corrupt state.json in ${projectDir} — cannot safely continue.\n${reason}\n` +
|
|
211
|
+
`Back up or delete state.json to reset state.`);
|
|
212
|
+
}
|
|
213
|
+
let parsed;
|
|
214
|
+
try {
|
|
215
|
+
parsed = JSON.parse(raw);
|
|
216
|
+
}
|
|
217
|
+
catch (err) {
|
|
218
|
+
fail(`Parse error: ${messageOf(err)}`);
|
|
219
|
+
}
|
|
220
|
+
if (!isJsonObject(parsed)) {
|
|
221
|
+
fail(`Expected a JSON object but got ${describeJson(parsed)}.`);
|
|
222
|
+
}
|
|
223
|
+
return parsed;
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Put a project's state on file: all of it, in the place of what was there.
|
|
227
|
+
* It is written beside the file and moved into its place, and not written
|
|
228
|
+
* into it — a program that is stopped in the middle of a checkpoint leaves
|
|
229
|
+
* the state before, and not half of a state, which no run after would start
|
|
230
|
+
* from. (Taking a file's place does not ask the file's leave, as writing
|
|
231
|
+
* into it did: so it is asked here. A state file its owner made read-only
|
|
232
|
+
* stays as it is.)
|
|
233
|
+
*
|
|
234
|
+
* Where no file can be made beside it — a project whose own directory is
|
|
235
|
+
* closed to that, and whose files are not — the state is written into its
|
|
236
|
+
* file, as it always was: there is no other way to it there, and a project
|
|
237
|
+
* kept so is still one that can be run.
|
|
238
|
+
*/
|
|
239
|
+
export function saveState(projectDir, state) {
|
|
240
|
+
const path = guardPath(projectDir, "state.json");
|
|
241
|
+
const text = JSON.stringify(state, null, 2);
|
|
242
|
+
if (existsSync(path))
|
|
243
|
+
accessSync(path, constants.W_OK);
|
|
244
|
+
try {
|
|
245
|
+
stageFileInProject(projectDir, "state.json", text).commit();
|
|
246
|
+
}
|
|
247
|
+
catch (err) {
|
|
248
|
+
const code = err.code;
|
|
249
|
+
if (code !== "EACCES" && code !== "EPERM" && code !== "EROFS")
|
|
250
|
+
throw err;
|
|
251
|
+
writeFileSync(path, text);
|
|
252
|
+
}
|
|
253
|
+
}
|
package/dist/replace-file.d.ts
CHANGED
|
@@ -26,6 +26,17 @@ export interface StagedFile {
|
|
|
26
26
|
* is being replaced hands on its permissions, as it would if it were written
|
|
27
27
|
* into — unless `mode` says what the new file's are. It is a new file all the
|
|
28
28
|
* same, so a second hard link to the old one, or its owner, are not carried
|
|
29
|
-
* over.
|
|
29
|
+
* over. And while it is being written it is its writer's alone, where it is
|
|
30
|
+
* to have permissions that are handed to it: what takes the place of a file
|
|
31
|
+
* others may not read is not readable by them for the time the writing takes.
|
|
32
|
+
*
|
|
33
|
+
* `makeDirs` makes the directories on the way — with the root itself, unless
|
|
34
|
+
* it is given as what does not (see stageFileInProject).
|
|
35
|
+
*/
|
|
36
|
+
export declare function stageFile(rootDir: string, relativePath: string, content: string | Buffer, mode?: number, makeDirs?: (dir: string) => void): StagedFile;
|
|
37
|
+
/**
|
|
38
|
+
* stageFile, under a root that is something in itself — a project, which
|
|
39
|
+
* somebody may have moved away since it was named: it must be there, and is
|
|
40
|
+
* not made anew for the sake of what goes into it (see makeDirsIn).
|
|
30
41
|
*/
|
|
31
|
-
export declare function
|
|
42
|
+
export declare function stageFileInProject(projectDir: string, relativePath: string, content: string | Buffer, mode?: number): StagedFile;
|