@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/runner.js
CHANGED
|
@@ -1,29 +1,26 @@
|
|
|
1
1
|
import { spawn } from "child_process";
|
|
2
|
-
import { readFileSync, writeFileSync,
|
|
2
|
+
import { readFileSync, writeFileSync, readdirSync, mkdirSync, existsSync, statSync, symlinkSync, rmSync, readlinkSync, mkdtempSync, openSync, closeSync, chmodSync, accessSync, constants, } from "fs";
|
|
3
3
|
import { basename, join, dirname, relative } from "path";
|
|
4
|
-
import {
|
|
5
|
-
import { fileURLToPath } from "url";
|
|
4
|
+
import { tmpdir } from "os";
|
|
6
5
|
import { createHash, randomBytes } from "crypto";
|
|
7
6
|
import { onAbort, rejectOnAbort } from "./abort.js";
|
|
8
7
|
import { checkedBudget, createMeter } from "./budget.js";
|
|
9
|
-
import { PiAdapter } from "./pi-adapter.js";
|
|
10
8
|
import { LATEST_LOG_PATH, appendLogEntry, createContext } from "./context.js";
|
|
11
9
|
import { createAgent, stripCodeFences } from "./agent.js";
|
|
12
10
|
import { createTools } from "./tools.js";
|
|
13
11
|
import { createWorkspace } from "./workspace.js";
|
|
14
12
|
import { guardPath, identityOf, projectAt, realRootOf, sameProjectAs, wayTo } from "./path-guard.js";
|
|
15
|
-
import { copyTree, differences, entryAt,
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import { describeJson, isJsonObject } from "./serializable.js";
|
|
13
|
+
import { ITSELF, copyTree, differences, entryAt, pathAsListed, readTree } from "./tree.js";
|
|
14
|
+
import { mergeTree } from "./merge.js";
|
|
15
|
+
import { stageFile, stageFileInProject } from "./replace-file.js";
|
|
19
16
|
import { checkedEnv, createAllowance, superviseChild } from "./child-process.js";
|
|
20
|
-
import {
|
|
17
|
+
import { removeTempDir, removeWithThisProcess, requireWatchdog, stopGroups, stopWithThisProcess } from "./stopping.js";
|
|
21
18
|
import { createIPCServer, listen, closeServer } from "./ipc-server.js";
|
|
22
19
|
import { journalEntriesOf, openJournal } from "./journal.js";
|
|
23
20
|
import { messageOf } from "./errors.js";
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
21
|
+
import { checkedRepairAttempts, checkedTimeout, ensureProjectScaffold, loadProjectConfig, loadState, saveState } from "./project.js";
|
|
22
|
+
import { createBackend, saysOnce } from "./runner-backend.js";
|
|
23
|
+
import { copyToHistory, recordVersion } from "./history.js";
|
|
27
24
|
/**
|
|
28
25
|
* tsx lets node run program.ts. Resolved through the module system, so any
|
|
29
26
|
* install layout works. It is loaded into the program's own node process
|
|
@@ -32,101 +29,6 @@ const RUNTIME_PACKAGE_DIR = dirname(dirname(fileURLToPath(import.meta.url)));
|
|
|
32
29
|
* it has not acted on, and reports its death by signal as an exit code.
|
|
33
30
|
*/
|
|
34
31
|
const TSX_LOADER = import.meta.resolve("tsx");
|
|
35
|
-
/**
|
|
36
|
-
* The @trama-dev packages a program.ts can import, and where they are installed.
|
|
37
|
-
* The runtime always; the session layer when it is installed alongside (as it
|
|
38
|
-
* is with the CLI). The runtime never imports the session layer itself — it
|
|
39
|
-
* only makes it reachable from projects.
|
|
40
|
-
*/
|
|
41
|
-
const IMPORTABLE_PACKAGES = { runtime: RUNTIME_PACKAGE_DIR };
|
|
42
|
-
try {
|
|
43
|
-
// Resolves to <package>/dist/index.js
|
|
44
|
-
IMPORTABLE_PACKAGES.session = dirname(dirname(fileURLToPath(import.meta.resolve("@trama-dev/session"))));
|
|
45
|
-
}
|
|
46
|
-
catch { /* not installed — programs simply cannot import it */ }
|
|
47
|
-
// --- Project scaffolding ---
|
|
48
|
-
/**
|
|
49
|
-
* Point the project's node_modules/@trama-dev/<name> at an installed package,
|
|
50
|
-
* so program.ts can import it. Replaces any existing symlink whose target
|
|
51
|
-
* differs (including user-managed ones). Only refuses to touch a real
|
|
52
|
-
* directory/file to avoid destroying user content.
|
|
53
|
-
*
|
|
54
|
-
* The link points outside the project, and is meant to. Where it is put is
|
|
55
|
-
* inside it, like everything else the runtime writes: a project whose
|
|
56
|
-
* node_modules leads somewhere else is refused, not followed there.
|
|
57
|
-
*/
|
|
58
|
-
function linkPackage(projectDir, name, target) {
|
|
59
|
-
const linkDir = guardPath(projectDir, join("node_modules", "@trama-dev"));
|
|
60
|
-
// Not through the guard: it is the link itself that is looked at and replaced, not what it points at.
|
|
61
|
-
const linkPath = join(linkDir, name);
|
|
62
|
-
try {
|
|
63
|
-
if (!lstatSync(linkPath).isSymbolicLink()) {
|
|
64
|
-
throw new Error(`${linkPath} exists and is not a symlink. ` +
|
|
65
|
-
`trama needs this path for module resolution. ` +
|
|
66
|
-
`Remove it manually or rename it to proceed.`);
|
|
67
|
-
}
|
|
68
|
-
if (readlinkSync(linkPath) === target)
|
|
69
|
-
return;
|
|
70
|
-
rmSync(linkPath);
|
|
71
|
-
}
|
|
72
|
-
catch (err) {
|
|
73
|
-
if (err.code !== "ENOENT")
|
|
74
|
-
throw err;
|
|
75
|
-
}
|
|
76
|
-
mkdirSync(linkDir, { recursive: true });
|
|
77
|
-
symlinkSync(target, linkPath, "dir");
|
|
78
|
-
}
|
|
79
|
-
/** Make sure package.json exists and declares an ES module (program.ts uses top-level await). */
|
|
80
|
-
function ensureModulePackageJson(projectDir) {
|
|
81
|
-
const pkgPath = guardPath(projectDir, "package.json");
|
|
82
|
-
if (!existsSync(pkgPath)) {
|
|
83
|
-
writeFileSync(pkgPath, JSON.stringify({ type: "module" }, null, 2));
|
|
84
|
-
return;
|
|
85
|
-
}
|
|
86
|
-
const advice = "trama will not overwrite it automatically; fix or remove it and try again.";
|
|
87
|
-
let pkg;
|
|
88
|
-
try {
|
|
89
|
-
pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
|
|
90
|
-
}
|
|
91
|
-
catch (err) {
|
|
92
|
-
throw new Error(`Malformed package.json at ${pkgPath}. ${advice}\n` +
|
|
93
|
-
`Parse error: ${messageOf(err)}`);
|
|
94
|
-
}
|
|
95
|
-
if (!isJsonObject(pkg)) {
|
|
96
|
-
throw new Error(`Malformed package.json at ${pkgPath} — expected a JSON object but got ${describeJson(pkg)}. ${advice}`);
|
|
97
|
-
}
|
|
98
|
-
if (pkg.type !== "module") {
|
|
99
|
-
pkg.type = "module";
|
|
100
|
-
writeFileSync(pkgPath, JSON.stringify(pkg, null, 2));
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
/** Make sure .gitignore excludes what trama generates, without disturbing existing entries. */
|
|
104
|
-
function ensureGitignore(projectDir) {
|
|
105
|
-
const giPath = guardPath(projectDir, ".gitignore");
|
|
106
|
-
const required = ["node_modules/", "state.json", "logs/", "history/"];
|
|
107
|
-
const existing = existsSync(giPath) ? readFileSync(giPath, "utf-8") : "";
|
|
108
|
-
const present = new Set(existing.split("\n").map(line => line.trim()));
|
|
109
|
-
const missing = required.filter(entry => !present.has(entry));
|
|
110
|
-
if (missing.length === 0)
|
|
111
|
-
return;
|
|
112
|
-
const separator = existing === "" || existing.endsWith("\n") ? "" : "\n";
|
|
113
|
-
writeFileSync(giPath, existing + separator + missing.join("\n") + "\n");
|
|
114
|
-
}
|
|
115
|
-
/**
|
|
116
|
-
* Everything a project directory needs around program.ts before it can run:
|
|
117
|
-
* history/ and logs/, an ESM package.json, .gitignore entries, and links to the
|
|
118
|
-
* @trama-dev packages it can import.
|
|
119
|
-
* Idempotent — called before every run, so a freshly cloned project just works.
|
|
120
|
-
*/
|
|
121
|
-
export function ensureProjectScaffold(projectDir) {
|
|
122
|
-
projectAt(projectDir);
|
|
123
|
-
mkdirSync(guardPath(projectDir, "history"), { recursive: true });
|
|
124
|
-
mkdirSync(guardPath(projectDir, "logs"), { recursive: true });
|
|
125
|
-
ensureModulePackageJson(projectDir);
|
|
126
|
-
ensureGitignore(projectDir);
|
|
127
|
-
for (const [name, target] of Object.entries(IMPORTABLE_PACKAGES))
|
|
128
|
-
linkPackage(projectDir, name, target);
|
|
129
|
-
}
|
|
130
32
|
// --- The API reference shown to the LLM ---
|
|
131
33
|
/**
|
|
132
34
|
* The program-facing API, as shown to the LLM when it writes or repairs a
|
|
@@ -143,305 +45,6 @@ export const RUNTIME_TYPES = [
|
|
|
143
45
|
"export declare const workspace: Workspace;",
|
|
144
46
|
].join("\n"),
|
|
145
47
|
].join("\n\n");
|
|
146
|
-
// --- Config & state loaders ---
|
|
147
|
-
export function loadConfig() {
|
|
148
|
-
const configPath = join(homedir(), ".trama", "config.json");
|
|
149
|
-
const defaults = {
|
|
150
|
-
provider: "anthropic",
|
|
151
|
-
model: "claude-opus-5-5",
|
|
152
|
-
maxRepairAttempts: 3,
|
|
153
|
-
defaultTimeout: 300_000,
|
|
154
|
-
defaultMaxIterations: 100,
|
|
155
|
-
journalRuns: 20,
|
|
156
|
-
agentChanges: "keep",
|
|
157
|
-
};
|
|
158
|
-
let raw;
|
|
159
|
-
try {
|
|
160
|
-
raw = readFileSync(configPath, "utf-8");
|
|
161
|
-
}
|
|
162
|
-
catch (err) {
|
|
163
|
-
if (err.code === "ENOENT")
|
|
164
|
-
return defaults;
|
|
165
|
-
throw err;
|
|
166
|
-
}
|
|
167
|
-
let parsed;
|
|
168
|
-
try {
|
|
169
|
-
parsed = JSON.parse(raw);
|
|
170
|
-
}
|
|
171
|
-
catch (err) {
|
|
172
|
-
throw new Error(`Malformed config at ${configPath} — fix or delete it.\n` +
|
|
173
|
-
`Parse error: ${messageOf(err)}`);
|
|
174
|
-
}
|
|
175
|
-
if (!isJsonObject(parsed)) {
|
|
176
|
-
throw new Error(`Malformed config at ${configPath} — expected a JSON object but got ${describeJson(parsed)}. Fix or delete it to proceed.`);
|
|
177
|
-
}
|
|
178
|
-
// null is how JSON says a field is not there.
|
|
179
|
-
const given = Object.fromEntries(Object.entries(parsed).filter(([, value]) => value !== null));
|
|
180
|
-
return checkedConfig({ ...defaults, ...given }, "config");
|
|
181
|
-
}
|
|
182
|
-
/** A config that holds what the runtime can work with — or an error naming what does not, and where it came from. */
|
|
183
|
-
function checkedConfig(merged, source) {
|
|
184
|
-
const s = (v) => typeof v === "string" && v.length > 0;
|
|
185
|
-
const pint = (v) => Number.isInteger(v) && v > 0;
|
|
186
|
-
const checks = [
|
|
187
|
-
[s(merged.provider), `"provider" must be a non-empty string (got ${JSON.stringify(merged.provider)})`],
|
|
188
|
-
[s(merged.model), `"model" must be a non-empty string (got ${JSON.stringify(merged.model)})`],
|
|
189
|
-
[Number.isInteger(merged.maxRepairAttempts) && merged.maxRepairAttempts >= 0, `"maxRepairAttempts" must be a non-negative integer (got ${merged.maxRepairAttempts})`],
|
|
190
|
-
[Number.isFinite(merged.defaultTimeout) && merged.defaultTimeout > 0, `"defaultTimeout" must be a positive number (got ${merged.defaultTimeout})`],
|
|
191
|
-
[pint(merged.defaultMaxIterations), `"defaultMaxIterations" must be a positive integer (got ${merged.defaultMaxIterations})`],
|
|
192
|
-
[Number.isInteger(merged.journalRuns) && merged.journalRuns >= 0, `"journalRuns" must be a non-negative integer (got ${merged.journalRuns})`],
|
|
193
|
-
[merged.agentChanges === "keep" || merged.agentChanges === "discard", `"agentChanges" must be "keep" or "discard" (got ${JSON.stringify(merged.agentChanges)})`],
|
|
194
|
-
];
|
|
195
|
-
for (const [ok, msg] of checks) {
|
|
196
|
-
if (!ok)
|
|
197
|
-
throw new Error(`Invalid ${source}: ${msg}`);
|
|
198
|
-
}
|
|
199
|
-
if (merged.budget === undefined)
|
|
200
|
-
return merged;
|
|
201
|
-
try {
|
|
202
|
-
return { ...merged, budget: checkedBudget(merged.budget, `"budget"`) };
|
|
203
|
-
}
|
|
204
|
-
catch (err) {
|
|
205
|
-
throw new Error(`Invalid ${source}: ${messageOf(err)}`);
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
/** The global config, with the model/provider a project was created with taking precedence. */
|
|
209
|
-
export function loadProjectConfig(projectDir, meta = readProjectMeta(projectDir)) {
|
|
210
|
-
const config = loadConfig();
|
|
211
|
-
// null is how JSON says a field is not there. Anything else a project says
|
|
212
|
-
// is taken, and held to what the global config is held to — an empty or
|
|
213
|
-
// mistyped name is an error here, not a quiet return to another model.
|
|
214
|
-
if (meta.model != null)
|
|
215
|
-
config.model = meta.model;
|
|
216
|
-
if (meta.provider != null)
|
|
217
|
-
config.provider = meta.provider;
|
|
218
|
-
return checkedConfig(config, `meta.json in ${projectDir}`);
|
|
219
|
-
}
|
|
220
|
-
/**
|
|
221
|
-
* What does the LLM work for a project. The only place that picks a backend:
|
|
222
|
-
* everything else is handed one and does not know which it is.
|
|
223
|
-
*
|
|
224
|
-
* It is also where what is asked of a model is counted, and held to a
|
|
225
|
-
* budget (`meter`): every call passes here, whoever makes it. A call that
|
|
226
|
-
* comes when the budget is spent is refused; one under way is stopped where
|
|
227
|
-
* its agent would ask the model again — what the model was asked before
|
|
228
|
-
* that is used, and what it was answering is let finish. `spent` is told
|
|
229
|
-
* why, the first time either happens.
|
|
230
|
-
*/
|
|
231
|
-
export function createBackend(config, meter = createMeter(), spent = () => { }, env) {
|
|
232
|
-
// (`env`: the variables of the run whose calls these are — its agents' too, as they are its program's and its commands'.)
|
|
233
|
-
const backend = new PiAdapter(config, env);
|
|
234
|
-
// The calls that were cancelled.
|
|
235
|
-
const cutOff = new Set();
|
|
236
|
-
// Why a call was first refused, or stopped, for the budget.
|
|
237
|
-
let refused;
|
|
238
|
-
const overBudget = (why) => {
|
|
239
|
-
if (refused === undefined)
|
|
240
|
-
spent(why);
|
|
241
|
-
refused ??= why;
|
|
242
|
-
return new Error(why);
|
|
243
|
-
};
|
|
244
|
-
return {
|
|
245
|
-
spent: () => meter.spent(),
|
|
246
|
-
refused: () => refused,
|
|
247
|
-
counts: () => meter.capped(),
|
|
248
|
-
// The interface promises that a cancelled call rejects, and a run's end
|
|
249
|
-
// waits on that. Every backend is held to it here, rather than trusted with it.
|
|
250
|
-
async ask(prompt, call) {
|
|
251
|
-
let account;
|
|
252
|
-
try {
|
|
253
|
-
account = meter.admit();
|
|
254
|
-
}
|
|
255
|
-
catch (err) {
|
|
256
|
-
throw overBudget(messageOf(err));
|
|
257
|
-
}
|
|
258
|
-
// Stops the call where the budget is reached while it is under way.
|
|
259
|
-
const over = new AbortController();
|
|
260
|
-
let why;
|
|
261
|
-
const signal = call.signal ? AbortSignal.any([call.signal, over.signal]) : over.signal;
|
|
262
|
-
const work = backend.ask(prompt, {
|
|
263
|
-
...call,
|
|
264
|
-
signal,
|
|
265
|
-
sofar(usage, answered) {
|
|
266
|
-
const reached = account.sofar(usage);
|
|
267
|
-
call.sofar?.(usage, answered);
|
|
268
|
-
// A call that is over keeps what it ended with — its answer, or its own failure: what would be
|
|
269
|
-
// asked beside it is not asked, and that is all. (It is a request refused for the budget all the
|
|
270
|
-
// same, and said as one.)
|
|
271
|
-
if (answered) {
|
|
272
|
-
const spent = why ?? reached;
|
|
273
|
-
if (spent === undefined)
|
|
274
|
-
return true;
|
|
275
|
-
overBudget(spent);
|
|
276
|
-
return false;
|
|
277
|
-
}
|
|
278
|
-
// (Once it is to stop, it is to stop — whatever is said of it after.)
|
|
279
|
-
why ??= reached;
|
|
280
|
-
if (why === undefined)
|
|
281
|
-
return true;
|
|
282
|
-
over.abort();
|
|
283
|
-
return false;
|
|
284
|
-
},
|
|
285
|
-
// (What the call has used is counted from when it is known: nothing is stopped for it here — a reply that
|
|
286
|
-
// has come is not taken back — but whatever is asked next, by this call or another, is asked against it.)
|
|
287
|
-
had(usage) {
|
|
288
|
-
account.sofar(usage);
|
|
289
|
-
call.had?.(usage);
|
|
290
|
-
},
|
|
291
|
-
used(usage) {
|
|
292
|
-
account.sofar(usage);
|
|
293
|
-
call.used?.(usage);
|
|
294
|
-
},
|
|
295
|
-
});
|
|
296
|
-
const off = onAbort(signal, () => { cutOff.add(work); });
|
|
297
|
-
// What the call used is counted as its own until the backend has let go of it — which
|
|
298
|
-
// is when it has said the last of it — however long ago whoever asked was answered.
|
|
299
|
-
const settled = () => {
|
|
300
|
-
off();
|
|
301
|
-
account.close();
|
|
302
|
-
};
|
|
303
|
-
work.then(settled, settled);
|
|
304
|
-
try {
|
|
305
|
-
return await rejectOnAbort(work, signal);
|
|
306
|
-
}
|
|
307
|
-
catch (err) {
|
|
308
|
-
// (Stopped by whoever asked, it was stopped by them, whatever the budget had come to.)
|
|
309
|
-
throw why !== undefined && !call.signal?.aborted ? overBudget(why) : err;
|
|
310
|
-
}
|
|
311
|
-
},
|
|
312
|
-
close: () => backend.close(),
|
|
313
|
-
async letGo() {
|
|
314
|
-
let giveUp;
|
|
315
|
-
await Promise.race([
|
|
316
|
-
Promise.allSettled(cutOff),
|
|
317
|
-
new Promise(resolve => { giveUp = setTimeout(resolve, KILL_GRACE_MS); }),
|
|
318
|
-
]);
|
|
319
|
-
clearTimeout(giveUp);
|
|
320
|
-
},
|
|
321
|
-
};
|
|
322
|
-
}
|
|
323
|
-
/** The budgets of which it has been said that they are spent. */
|
|
324
|
-
const saidSpent = new WeakSet();
|
|
325
|
-
/**
|
|
326
|
-
* Say that a budget is spent, once for the budget — whoever comes up against
|
|
327
|
-
* it first: the run's own backend, or the backend of a project being made
|
|
328
|
-
* for the run's program, of which there may be many.
|
|
329
|
-
*/
|
|
330
|
-
export const saysOnce = (meter, say) => (why) => {
|
|
331
|
-
if (saidSpent.has(meter))
|
|
332
|
-
return;
|
|
333
|
-
saidSpent.add(meter);
|
|
334
|
-
say(why);
|
|
335
|
-
};
|
|
336
|
-
export function loadState(projectDir) {
|
|
337
|
-
const statePath = guardPath(projectDir, "state.json");
|
|
338
|
-
let raw;
|
|
339
|
-
try {
|
|
340
|
-
raw = readFileSync(statePath, "utf-8");
|
|
341
|
-
}
|
|
342
|
-
catch (err) {
|
|
343
|
-
if (err.code === "ENOENT")
|
|
344
|
-
return {};
|
|
345
|
-
throw err;
|
|
346
|
-
}
|
|
347
|
-
function fail(reason) {
|
|
348
|
-
throw new Error(`Corrupt state.json in ${projectDir} — cannot safely continue.\n${reason}\n` +
|
|
349
|
-
`Back up or delete state.json to reset state.`);
|
|
350
|
-
}
|
|
351
|
-
let parsed;
|
|
352
|
-
try {
|
|
353
|
-
parsed = JSON.parse(raw);
|
|
354
|
-
}
|
|
355
|
-
catch (err) {
|
|
356
|
-
fail(`Parse error: ${messageOf(err)}`);
|
|
357
|
-
}
|
|
358
|
-
if (!isJsonObject(parsed)) {
|
|
359
|
-
fail(`Expected a JSON object but got ${describeJson(parsed)}.`);
|
|
360
|
-
}
|
|
361
|
-
return parsed;
|
|
362
|
-
}
|
|
363
|
-
// --- History management ---
|
|
364
|
-
/** The index.jsonl field that carries the detail for each kind of versioned change. */
|
|
365
|
-
const HISTORY_DETAIL_FIELD = { create: "prompt", update: "prompt", repair: "error" };
|
|
366
|
-
/**
|
|
367
|
-
* Add a version to a project's history: its text as history/NNNN.ts, and a
|
|
368
|
-
* line in index.jsonl saying why (after `notes`, lines that belong with it).
|
|
369
|
-
* Either all of it is written or none of it. Returns how to take it back, for
|
|
370
|
-
* a caller whose own next step may still fail.
|
|
371
|
-
*/
|
|
372
|
-
function recordVersion(projectDir, source, reason, detail, notes = []) {
|
|
373
|
-
const historyDir = guardPath(projectDir, "history");
|
|
374
|
-
const indexPath = guardPath(projectDir, join("history", "index.jsonl"));
|
|
375
|
-
const versions = readdirSync(historyDir)
|
|
376
|
-
.filter(f => /^\d+\.ts$/.test(f))
|
|
377
|
-
.map(f => parseInt(f, 10))
|
|
378
|
-
.filter(n => Number.isSafeInteger(n) && n < Number.MAX_SAFE_INTEGER);
|
|
379
|
-
const version = versions.reduce((a, b) => Math.max(a, b), 0) + 1;
|
|
380
|
-
const snapshot = guardPath(projectDir, join("history", `${String(version).padStart(4, "0")}.ts`));
|
|
381
|
-
const entry = { version, reason, timestamp: new Date().toISOString() };
|
|
382
|
-
const detailField = HISTORY_DETAIL_FIELD[reason];
|
|
383
|
-
if (detailField && detail)
|
|
384
|
-
entry[detailField] = detail;
|
|
385
|
-
const lines = Buffer.from([...notes, entry].map(line => JSON.stringify(line) + "\n").join(""));
|
|
386
|
-
const sizeBefore = statSync(indexPath, { throwIfNoEntry: false })?.size;
|
|
387
|
-
let wroteSnapshot = false;
|
|
388
|
-
let appended = false;
|
|
389
|
-
// Takes back what was written here and nothing else. Another run of the
|
|
390
|
-
// project may be recording a version of its own at the same moment: if the
|
|
391
|
-
// index no longer ends with these lines alone, they are left in it, and the
|
|
392
|
-
// version file with them — a version on record that was never installed,
|
|
393
|
-
// rather than someone else's record cut out of the history.
|
|
394
|
-
const undo = () => {
|
|
395
|
-
try {
|
|
396
|
-
const index = readFileSync(indexPath);
|
|
397
|
-
const start = sizeBefore ?? 0;
|
|
398
|
-
const sinceThen = index.subarray(Math.min(start, index.length));
|
|
399
|
-
// What was appended is the end of the index — whole, or as far as a failed write got.
|
|
400
|
-
const cutTo = index.subarray(-lines.length).equals(lines) ? index.length - lines.length
|
|
401
|
-
: lines.subarray(0, sinceThen.length).equals(sinceThen) ? start
|
|
402
|
-
: null;
|
|
403
|
-
if (cutTo === null)
|
|
404
|
-
return;
|
|
405
|
-
if (cutTo === 0 && sizeBefore === undefined)
|
|
406
|
-
rmSync(indexPath, { force: true });
|
|
407
|
-
else if (cutTo < index.length)
|
|
408
|
-
truncateSync(indexPath, cutTo);
|
|
409
|
-
}
|
|
410
|
-
catch (err) {
|
|
411
|
-
// The index cannot be looked at. If the lines went into it, they stay,
|
|
412
|
-
// and the version file with them; if they never did, there is only the file.
|
|
413
|
-
if (appended && err.code !== "ENOENT")
|
|
414
|
-
return;
|
|
415
|
-
}
|
|
416
|
-
if (wroteSnapshot)
|
|
417
|
-
try {
|
|
418
|
-
rmSync(snapshot, { force: true });
|
|
419
|
-
}
|
|
420
|
-
catch { /* best-effort */ }
|
|
421
|
-
};
|
|
422
|
-
try {
|
|
423
|
-
// Never over a version file that is already there: that one is someone else's.
|
|
424
|
-
const fd = openSync(snapshot, "wx");
|
|
425
|
-
wroteSnapshot = true;
|
|
426
|
-
try {
|
|
427
|
-
writeFileSync(fd, source);
|
|
428
|
-
}
|
|
429
|
-
finally {
|
|
430
|
-
closeSync(fd);
|
|
431
|
-
}
|
|
432
|
-
appendFileSync(indexPath, lines);
|
|
433
|
-
appended = true;
|
|
434
|
-
}
|
|
435
|
-
catch (err) {
|
|
436
|
-
undo();
|
|
437
|
-
throw err;
|
|
438
|
-
}
|
|
439
|
-
return undo;
|
|
440
|
-
}
|
|
441
|
-
/** Save the current program.ts as the next version of the project, and record why. */
|
|
442
|
-
export function copyToHistory(projectDir, reason, detail) {
|
|
443
|
-
recordVersion(projectDir, readFileSync(guardPath(projectDir, "program.ts")), reason, detail);
|
|
444
|
-
}
|
|
445
48
|
// --- Staging: run against a copy, merge back what worked (see tree.ts) ---
|
|
446
49
|
/** Run fn in a temp directory, clean up afterwards regardless of outcome — including this process being stopped. */
|
|
447
50
|
export async function withTempDir(prefix, fn) {
|
|
@@ -591,7 +194,7 @@ function strandedBeside(copy, beside) {
|
|
|
591
194
|
* whyNotReplaceable). A project with a directory where its program should be
|
|
592
195
|
* has no place for one, and is not copied to try one in.
|
|
593
196
|
*/
|
|
594
|
-
|
|
197
|
+
function copyProjectWith(projectDir, privateDir, program, among = projectDir) {
|
|
595
198
|
const root = projectAt(projectDir);
|
|
596
199
|
const itsOwn = realRootOf(privateDir);
|
|
597
200
|
const copyDir = join(itsOwn, basename(root) || "project");
|
|
@@ -615,6 +218,12 @@ export function copyProjectWith(projectDir, privateDir, program, among = project
|
|
|
615
218
|
function tail(text, max = 20_000) {
|
|
616
219
|
return text.length <= max ? text : `[… ${text.length - max} earlier characters omitted]\n${text.slice(-max)}`;
|
|
617
220
|
}
|
|
221
|
+
/**
|
|
222
|
+
* How a run that failed is said to whoever asked for it: as a program's
|
|
223
|
+
* failure — which the reasons that begin so say for themselves, and is not
|
|
224
|
+
* said of them twice.
|
|
225
|
+
*/
|
|
226
|
+
export const failureOf = (reason) => (reason?.startsWith("Program failed") ? reason : `Program failed: ${reason}`);
|
|
618
227
|
/** A line as it is shown for a run: under the run's name, if it has one. */
|
|
619
228
|
export const tagged = (label, line) => label ? `[${label}] ${line}` : line;
|
|
620
229
|
/** The longest stretch of output held back while waiting for its line to end. */
|
|
@@ -699,7 +308,7 @@ function settle(projectDir, child, ended) {
|
|
|
699
308
|
// the next run look resumed.
|
|
700
309
|
if (state.__trama_yield != null) {
|
|
701
310
|
delete state.__trama_yield;
|
|
702
|
-
|
|
311
|
+
saveState(projectDir, state);
|
|
703
312
|
}
|
|
704
313
|
return { status: "done" };
|
|
705
314
|
}
|
|
@@ -748,6 +357,26 @@ async function runProgramOnce(options) {
|
|
|
748
357
|
let handedOff = false;
|
|
749
358
|
// Runs the program has asked for and that are still going. They belong to this run.
|
|
750
359
|
const nestedRuns = new Set();
|
|
360
|
+
/** What the program asked for is waited for as the run ends: the run is not over before it is. */
|
|
361
|
+
const notOverBefore = (asked) => {
|
|
362
|
+
const going = asked.finally(() => { nestedRuns.delete(going); });
|
|
363
|
+
nestedRuns.add(going);
|
|
364
|
+
return going;
|
|
365
|
+
};
|
|
366
|
+
/**
|
|
367
|
+
* What a program asks its runner for — a run, a project made — is this
|
|
368
|
+
* run's own: stopped when this run ends, or when the program no longer
|
|
369
|
+
* wants it (`stop`); counted in this run's budget; and on record both
|
|
370
|
+
* ways — this run's journal says what the call `seq` started, and what
|
|
371
|
+
* was started says which call started it.
|
|
372
|
+
*/
|
|
373
|
+
const itsOwn = (seq, stop, purpose) => ({
|
|
374
|
+
signal: AbortSignal.any([runEnded.signal, stop]),
|
|
375
|
+
above: options.meter,
|
|
376
|
+
parent: { run: journal.run, journal: journal.path, seq },
|
|
377
|
+
started: (run, path) => { if (run)
|
|
378
|
+
journal.note("child", { seq, run, journal: path, ...(purpose && { purpose }) }); },
|
|
379
|
+
});
|
|
751
380
|
const workspaces = new Map();
|
|
752
381
|
const workspaceAt = (dir) => {
|
|
753
382
|
let workspace = workspaces.get(dir);
|
|
@@ -788,18 +417,8 @@ async function runProgramOnce(options) {
|
|
|
788
417
|
// The run's own, as a run it asks for is: under its budget, with its variables, stopped when it
|
|
789
418
|
// ends or when the program no longer wants it, and not over before this is. (But the program's
|
|
790
419
|
// clock goes on: what it has made is its own work, with no timeout but the program's.)
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
above: options.meter,
|
|
794
|
-
label,
|
|
795
|
-
env: options.env,
|
|
796
|
-
parent: { run: journal.run, journal: journal.path, seq },
|
|
797
|
-
// (What it starts is a validation: of the program the project is made with.)
|
|
798
|
-
started: (run, path) => { if (run)
|
|
799
|
-
journal.note("child", { seq, run, journal: path, purpose: "validate" }); },
|
|
800
|
-
}).finally(() => { nestedRuns.delete(made); });
|
|
801
|
-
nestedRuns.add(made);
|
|
802
|
-
return made;
|
|
420
|
+
// (What it starts is a validation: of the program the project is made with.)
|
|
421
|
+
return notOverBefore(options.making(request, { ...itsOwn(seq, stop, "validate"), label, env: options.env }));
|
|
803
422
|
},
|
|
804
423
|
run: (request, stop, seq) => {
|
|
805
424
|
if (validating)
|
|
@@ -810,20 +429,8 @@ async function runProgramOnce(options) {
|
|
|
810
429
|
const release = allowance.hold();
|
|
811
430
|
// What this run was started with, the run it asks for has too — and what it is given besides.
|
|
812
431
|
const env = options.env || request.env ? { ...options.env, ...request.env } : undefined;
|
|
813
|
-
const
|
|
814
|
-
|
|
815
|
-
// The two journals point at each other: this one says which run the call started…
|
|
816
|
-
started: (run, path) => { if (run)
|
|
817
|
-
journal.note("child", { seq, run, journal: path }); },
|
|
818
|
-
// …and that run's journal says which call started it.
|
|
819
|
-
parent: { run: journal.run, journal: journal.path, seq },
|
|
820
|
-
above: options.meter,
|
|
821
|
-
}, options.making).finally(() => {
|
|
822
|
-
release();
|
|
823
|
-
nestedRuns.delete(nested);
|
|
824
|
-
});
|
|
825
|
-
nestedRuns.add(nested);
|
|
826
|
-
return nested;
|
|
432
|
+
const { signal, ...asked } = itsOwn(seq, stop);
|
|
433
|
+
return notOverBefore(runProgram({ ...request, env, signal }, { depth: options.depth + 1, ...asked }, options.making).finally(release));
|
|
827
434
|
},
|
|
828
435
|
});
|
|
829
436
|
// A participant's output is shown under its name. It is not its parent's
|
|
@@ -963,7 +570,7 @@ const repairPrompt = (input) => `Fix this program so it runs.\n\n` +
|
|
|
963
570
|
* the copy, not in what a link leads to, nor in a directory made anew.
|
|
964
571
|
*/
|
|
965
572
|
const sameCopyAs = (copy, was) => () => {
|
|
966
|
-
const there = entryAt(copy), itself = was.get(
|
|
573
|
+
const there = entryAt(copy), itself = was.get(ITSELF);
|
|
967
574
|
if (!(there?.kind === "dir" && itself?.kind === "dir" && there.id === itself.id)) {
|
|
968
575
|
throw new Error("the copy that was worked in is no longer where it was made: it was moved away, or something else put in its place");
|
|
969
576
|
}
|
|
@@ -1141,7 +748,7 @@ async function tryFix(options, staged, fixed, attempt) {
|
|
|
1141
748
|
// project is the directory that was copied, which the copy knows by what
|
|
1142
749
|
// it is.
|
|
1143
750
|
const projectRoot = realRootOf(projectDir);
|
|
1144
|
-
const copied = held.get(
|
|
751
|
+
const copied = held.get(ITSELF), there = entryAt(projectRoot);
|
|
1145
752
|
if (there && copied?.kind === "dir" && !(there.kind === "dir" && there.id === copied.id)) {
|
|
1146
753
|
throw new Error(`The program cannot be replaced: what is at ${projectRoot} is not the project the fix was tried on.`);
|
|
1147
754
|
}
|
|
@@ -1216,7 +823,7 @@ async function executeProgram(options) {
|
|
|
1216
823
|
for (let attempt = 1; attempt <= maxRepairAttempts; attempt++) {
|
|
1217
824
|
stillTheProject();
|
|
1218
825
|
// A fix is asked of a model: where no more may be, none is asked for, and nothing is got ready for one.
|
|
1219
|
-
const spent = options.backend.spent
|
|
826
|
+
const spent = options.backend.spent();
|
|
1220
827
|
if (spent !== undefined) {
|
|
1221
828
|
return failed(`${attempt === 1 ? "Program failed, and no repair was tried" : `Failed after ${attempt - 1} repair attempt(s), and no further repair was tried`}. ${spent}\n${lastError}`);
|
|
1222
829
|
}
|
|
@@ -1275,15 +882,15 @@ async function journalled(journal, backend, run) {
|
|
|
1275
882
|
throw err;
|
|
1276
883
|
}
|
|
1277
884
|
finally {
|
|
1278
|
-
if (journal.run || backend.counts
|
|
885
|
+
if (journal.run || backend.counts())
|
|
1279
886
|
await backend.letGo();
|
|
1280
|
-
const spent = backend.spent
|
|
887
|
+
const spent = backend.spent() ?? backend.refused();
|
|
1281
888
|
if (spent !== undefined)
|
|
1282
889
|
journal.note("budget", { spent });
|
|
1283
890
|
journal.note("end", end);
|
|
1284
891
|
journal.close();
|
|
1285
892
|
// Nothing a run started outlives it: nor what served its agent calls.
|
|
1286
|
-
await backend.close
|
|
893
|
+
await backend.close();
|
|
1287
894
|
}
|
|
1288
895
|
}
|
|
1289
896
|
// --- Validating a candidate program (used by create and update) ---
|
|
@@ -1372,7 +979,7 @@ export async function validateProgram(projectDir, backend, candidate, options) {
|
|
|
1372
979
|
});
|
|
1373
980
|
const { result, repair, left } = await journalled(journal, backend, async () => (await validatedIn(as)) ?? (await validatedIn(projectDir)));
|
|
1374
981
|
if (result.status === "failed")
|
|
1375
|
-
throw new Error(
|
|
982
|
+
throw new Error(failureOf(result.reason));
|
|
1376
983
|
return { source: left, repairedError: repair?.error, ...(alone === undefined ? {} : { alone }) };
|
|
1377
984
|
}
|
|
1378
985
|
export function prepareProject(projectDir, privateDir) {
|
|
@@ -1504,7 +1111,7 @@ function stageProgram(projectDir, source) {
|
|
|
1504
1111
|
const refusal = whyNotReplaceable(projectDir);
|
|
1505
1112
|
if (refusal)
|
|
1506
1113
|
throw Object.assign(new Error(refusal), { code: "EACCES" });
|
|
1507
|
-
return
|
|
1114
|
+
return stageFileInProject(projectDir, "program.ts", source);
|
|
1508
1115
|
}
|
|
1509
1116
|
/**
|
|
1510
1117
|
* Make a validated program the project's program.ts and record it as a new
|
|
@@ -1567,18 +1174,17 @@ async function runProject(options, depth, askedFor, making) {
|
|
|
1567
1174
|
`Run \`trama list\` to see available projects.`);
|
|
1568
1175
|
}
|
|
1569
1176
|
const config = loadProjectConfig(projectDir);
|
|
1570
|
-
const
|
|
1571
|
-
const
|
|
1572
|
-
if (!Number.isFinite(timeout) || timeout <= 0) {
|
|
1573
|
-
throw new Error(`Invalid timeout: ${timeout}. Must be a positive number.`);
|
|
1574
|
-
}
|
|
1575
|
-
if (!Number.isInteger(maxRepairAttempts) || maxRepairAttempts < 0) {
|
|
1576
|
-
throw new Error(`Invalid maxRepairAttempts: ${maxRepairAttempts}. Must be a non-negative integer.`);
|
|
1577
|
-
}
|
|
1177
|
+
const timeout = checkedTimeout(options.timeout ?? config.defaultTimeout);
|
|
1178
|
+
const maxRepairAttempts = checkedRepairAttempts(options.maxRepairAttempts ?? config.maxRepairAttempts);
|
|
1578
1179
|
const env = options.env == null ? undefined : checkedEnv(options.env);
|
|
1579
1180
|
// Its own budget — the config's, for a run nobody's program asked for and that was given none — under the budgets above it.
|
|
1580
1181
|
const budget = options.budget != null ? checkedBudget(options.budget) : askedFor ? undefined : config.budget;
|
|
1581
1182
|
const meter = createMeter(budget, askedFor?.above);
|
|
1183
|
+
const outOfBudget = (why) => console.warn(tagged(options.label, `[trama] ${why}`));
|
|
1184
|
+
// (Before the journal is opened: once it is, nothing stands between that and the run that ends it — a
|
|
1185
|
+
// journal with a beginning and no end is a run that died, and is not to be one that never began.)
|
|
1186
|
+
const stillTheProject = sameProjectAs(projectDir);
|
|
1187
|
+
const backend = createBackend(config, meter, saysOnce(meter, outOfBudget), env);
|
|
1582
1188
|
const journal = openJournal(projectDir, config.journalRuns, {
|
|
1583
1189
|
purpose: "run",
|
|
1584
1190
|
label: options.label,
|
|
@@ -1593,9 +1199,7 @@ async function runProject(options, depth, askedFor, making) {
|
|
|
1593
1199
|
args: options.args, // last: it is the one field of unknown size
|
|
1594
1200
|
});
|
|
1595
1201
|
askedFor?.started(journal.run, journal.path);
|
|
1596
|
-
const
|
|
1597
|
-
const outOfBudget = (why) => console.warn(tagged(options.label, `[trama] ${why}`));
|
|
1598
|
-
const { result, repair } = await journalled(journal, createBackend(config, meter, saysOnce(meter, outOfBudget), env), (backend) => executeProgram({
|
|
1202
|
+
const { result, repair } = await journalled(journal, backend, (backend) => executeProgram({
|
|
1599
1203
|
projectDir,
|
|
1600
1204
|
backend,
|
|
1601
1205
|
meter,
|