@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.
- package/dist/agent-backend.d.ts +100 -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.d.ts +8 -0
- package/dist/agent-hosts.js +123 -56
- package/dist/agent.d.ts +18 -5
- package/dist/agent.js +23 -64
- package/dist/bridge-client.d.ts +6 -2
- package/dist/bridge-client.js +7 -1
- package/dist/budget.d.ts +6 -0
- package/dist/budget.js +1 -0
- package/dist/client.d.ts +3 -2
- package/dist/client.js +146 -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 +2 -0
- package/dist/index.js +73 -41
- package/dist/ipc-server.d.ts +2 -3
- package/dist/ipc-server.js +99 -38
- package/dist/journal-view.d.ts +8 -0
- package/dist/journal-view.js +63 -11
- package/dist/journal.d.ts +10 -4
- package/dist/journal.js +73 -7
- 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.d.ts +19 -0
- package/dist/model-relay.js +91 -9
- package/dist/model-request.d.ts +9 -0
- package/dist/model-request.js +185 -0
- 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 +32 -9
- package/dist/pi-adapter.js +198 -51
- package/dist/project.d.ts +39 -0
- package/dist/project.js +270 -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 +149 -0
- package/dist/runner-types.d.ts +26 -0
- package/dist/runner.d.ts +10 -125
- package/dist/runner.js +148 -461
- package/dist/schema.d.ts +45 -0
- package/dist/schema.js +113 -0
- package/dist/stopping.js +2 -3
- package/dist/tools.d.ts +8 -1
- package/dist/tools.js +36 -10
- package/dist/tree.d.ts +33 -149
- package/dist/tree.js +43 -1077
- package/dist/types.d.ts +182 -2
- package/dist/workspace.d.ts +28 -1
- package/dist/workspace.js +88 -13
- 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, projectNamed, 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
|
|
@@ -141,307 +43,10 @@ export const RUNTIME_TYPES = [
|
|
|
141
43
|
"export declare const agent: Agent;",
|
|
142
44
|
"export declare const tools: Tools;",
|
|
143
45
|
"export declare const workspace: Workspace;",
|
|
46
|
+
"/** What a model called a tool with, held to the parameters the tool declared (see AgentTool): the declared fields and no others — or it throws what is wrong, in words the model can be handed. */",
|
|
47
|
+
"export declare function heldTo(parameters: Schema | undefined, given: unknown): Record<string, unknown>;",
|
|
144
48
|
].join("\n"),
|
|
145
49
|
].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
50
|
// --- Staging: run against a copy, merge back what worked (see tree.ts) ---
|
|
446
51
|
/** Run fn in a temp directory, clean up afterwards regardless of outcome — including this process being stopped. */
|
|
447
52
|
export async function withTempDir(prefix, fn) {
|
|
@@ -591,7 +196,7 @@ function strandedBeside(copy, beside) {
|
|
|
591
196
|
* whyNotReplaceable). A project with a directory where its program should be
|
|
592
197
|
* has no place for one, and is not copied to try one in.
|
|
593
198
|
*/
|
|
594
|
-
|
|
199
|
+
function copyProjectWith(projectDir, privateDir, program, among = projectDir) {
|
|
595
200
|
const root = projectAt(projectDir);
|
|
596
201
|
const itsOwn = realRootOf(privateDir);
|
|
597
202
|
const copyDir = join(itsOwn, basename(root) || "project");
|
|
@@ -615,6 +220,12 @@ export function copyProjectWith(projectDir, privateDir, program, among = project
|
|
|
615
220
|
function tail(text, max = 20_000) {
|
|
616
221
|
return text.length <= max ? text : `[… ${text.length - max} earlier characters omitted]\n${text.slice(-max)}`;
|
|
617
222
|
}
|
|
223
|
+
/**
|
|
224
|
+
* How a run that failed is said to whoever asked for it: as a program's
|
|
225
|
+
* failure — which the reasons that begin so say for themselves, and is not
|
|
226
|
+
* said of them twice.
|
|
227
|
+
*/
|
|
228
|
+
export const failureOf = (reason) => (reason?.startsWith("Program failed") ? reason : `Program failed: ${reason}`);
|
|
618
229
|
/** A line as it is shown for a run: under the run's name, if it has one. */
|
|
619
230
|
export const tagged = (label, line) => label ? `[${label}] ${line}` : line;
|
|
620
231
|
/** The longest stretch of output held back while waiting for its line to end. */
|
|
@@ -699,7 +310,7 @@ function settle(projectDir, child, ended) {
|
|
|
699
310
|
// the next run look resumed.
|
|
700
311
|
if (state.__trama_yield != null) {
|
|
701
312
|
delete state.__trama_yield;
|
|
702
|
-
|
|
313
|
+
saveState(projectDir, state);
|
|
703
314
|
}
|
|
704
315
|
return { status: "done" };
|
|
705
316
|
}
|
|
@@ -748,11 +359,32 @@ async function runProgramOnce(options) {
|
|
|
748
359
|
let handedOff = false;
|
|
749
360
|
// Runs the program has asked for and that are still going. They belong to this run.
|
|
750
361
|
const nestedRuns = new Set();
|
|
362
|
+
/** What the program asked for is waited for as the run ends: the run is not over before it is. */
|
|
363
|
+
const notOverBefore = (asked) => {
|
|
364
|
+
const going = asked.finally(() => { nestedRuns.delete(going); });
|
|
365
|
+
nestedRuns.add(going);
|
|
366
|
+
return going;
|
|
367
|
+
};
|
|
368
|
+
/**
|
|
369
|
+
* What a program asks its runner for — a run, a project made — is this
|
|
370
|
+
* run's own: stopped when this run ends, or when the program no longer
|
|
371
|
+
* wants it (`stop`); counted in this run's budget; and on record both
|
|
372
|
+
* ways — this run's journal says what the call `seq` started, and what
|
|
373
|
+
* was started says which call started it.
|
|
374
|
+
*/
|
|
375
|
+
const itsOwn = (seq, stop, purpose) => ({
|
|
376
|
+
signal: AbortSignal.any([runEnded.signal, stop]),
|
|
377
|
+
above: options.meter,
|
|
378
|
+
parent: { run: journal.run, journal: journal.path, seq },
|
|
379
|
+
started: (run, path) => { if (run)
|
|
380
|
+
journal.note("child", { seq, run, journal: path, ...(purpose && { purpose }) }); },
|
|
381
|
+
});
|
|
751
382
|
const workspaces = new Map();
|
|
752
383
|
const workspaceAt = (dir) => {
|
|
753
384
|
let workspace = workspaces.get(dir);
|
|
385
|
+
// (Its shell is this run's: what a command there starts is stopped with the run, and has the run's variables.)
|
|
754
386
|
if (!workspace)
|
|
755
|
-
workspaces.set(dir, workspace = createWorkspace(dir, runEnded.signal));
|
|
387
|
+
workspaces.set(dir, workspace = createWorkspace(dir, runEnded.signal, (root, command, given) => tools.shellIn(root, command, given)));
|
|
756
388
|
return workspace;
|
|
757
389
|
};
|
|
758
390
|
// The workspace of the session this run is part of, if it is part of one.
|
|
@@ -788,18 +420,8 @@ async function runProgramOnce(options) {
|
|
|
788
420
|
// The run's own, as a run it asks for is: under its budget, with its variables, stopped when it
|
|
789
421
|
// ends or when the program no longer wants it, and not over before this is. (But the program's
|
|
790
422
|
// 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;
|
|
423
|
+
// (What it starts is a validation: of the program the project is made with.)
|
|
424
|
+
return notOverBefore(options.making(request, { ...itsOwn(seq, stop, "validate"), label, env: options.env }));
|
|
803
425
|
},
|
|
804
426
|
run: (request, stop, seq) => {
|
|
805
427
|
if (validating)
|
|
@@ -810,20 +432,8 @@ async function runProgramOnce(options) {
|
|
|
810
432
|
const release = allowance.hold();
|
|
811
433
|
// What this run was started with, the run it asks for has too — and what it is given besides.
|
|
812
434
|
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;
|
|
435
|
+
const { signal, ...asked } = itsOwn(seq, stop);
|
|
436
|
+
return notOverBefore(runProgram({ ...request, env, signal }, { depth: options.depth + 1, ...asked }, options.making).finally(release));
|
|
827
437
|
},
|
|
828
438
|
});
|
|
829
439
|
// A participant's output is shown under its name. It is not its parent's
|
|
@@ -943,6 +553,16 @@ async function runProgramOnce(options) {
|
|
|
943
553
|
await closeServer(server);
|
|
944
554
|
}
|
|
945
555
|
}
|
|
556
|
+
/** How whoever is asked for a fix begins an answer that says there is none (see `NoFix`). */
|
|
557
|
+
const NO_FIX = "NO FIX:";
|
|
558
|
+
/**
|
|
559
|
+
* There is no fix, by whoever was asked for one: the program cannot be made
|
|
560
|
+
* to run and still be the program it was. Not a fix that failed to come —
|
|
561
|
+
* an answer, and the last: nobody is asked again for what was said not to
|
|
562
|
+
* be had.
|
|
563
|
+
*/
|
|
564
|
+
class NoFix extends Error {
|
|
565
|
+
}
|
|
946
566
|
/** The instructions a request for a fix is made under. (Exported so the tests' stand-in LLM can tell one from any other call.) */
|
|
947
567
|
export const REPAIR_SYSTEM_PROMPT = "You are a TypeScript repair tool.";
|
|
948
568
|
const repairPrompt = (input) => `Fix this program so it runs.\n\n` +
|
|
@@ -952,6 +572,7 @@ const repairPrompt = (input) => `Fix this program so it runs.\n\n` +
|
|
|
952
572
|
`what you change in this directory is kept, with the program you answer with, if that program then runs. If it does not, none of it is.\n`
|
|
953
573
|
: `Nothing you change in this directory is kept: the program you answer with is all that is taken from you.\n`) +
|
|
954
574
|
(input.journal ? `The record of the run that failed — each call the program made, and what came back — is at ${input.journal}, a line of JSON for each.\n` : "") +
|
|
575
|
+
`If the program cannot be made to run without having it say what is not so, or leave out what it is there to do — a check taken out, a failure handed back as if it were a result — then there is no fix, and you are not to hand over such a program: answer instead with one line that begins "${NO_FIX}" and says why.\n` +
|
|
955
576
|
`\nRuntime types:\n${RUNTIME_TYPES}\n\n` +
|
|
956
577
|
`Broken program:\n${input.programSource}\n\n` +
|
|
957
578
|
`Error:\n${input.error}\n\n` +
|
|
@@ -963,7 +584,7 @@ const repairPrompt = (input) => `Fix this program so it runs.\n\n` +
|
|
|
963
584
|
* the copy, not in what a link leads to, nor in a directory made anew.
|
|
964
585
|
*/
|
|
965
586
|
const sameCopyAs = (copy, was) => () => {
|
|
966
|
-
const there = entryAt(copy), itself = was.get(
|
|
587
|
+
const there = entryAt(copy), itself = was.get(ITSELF);
|
|
967
588
|
if (!(there?.kind === "dir" && itself?.kind === "dir" && there.id === itself.id)) {
|
|
968
589
|
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
590
|
}
|
|
@@ -1016,6 +637,14 @@ export const shownPaths = (paths) => paths.slice(0, MAX_PATHS_SHOWN).join(", ")
|
|
|
1016
637
|
*/
|
|
1017
638
|
async function requestRepair(options, input, privateDir) {
|
|
1018
639
|
options.journal.note("fix-request", { error: input.error });
|
|
640
|
+
// What a project that is asked for the fix uses is on its own record, as any run's is — and is said here too,
|
|
641
|
+
// with the fix: what a fix took is then read where the fix was asked for, whoever made it. (What pi's agent
|
|
642
|
+
// uses for one is on this record anyway, as `usage`.) Counted as the run's count grew while it was asked.
|
|
643
|
+
const before = options.repairWith !== undefined ? options.meter?.counted() : undefined;
|
|
644
|
+
const usedByAProject = () => {
|
|
645
|
+
const now = before && options.meter?.counted();
|
|
646
|
+
return before && now ? { by: options.repairWith, used: { calls: now.calls - before.calls, tokens: now.tokens - before.tokens, cost: now.cost - before.cost } } : {};
|
|
647
|
+
};
|
|
1019
648
|
const timedOut = new AbortController();
|
|
1020
649
|
const limit = createAllowance(options.timeout);
|
|
1021
650
|
const signal = options.signal ? AbortSignal.any([timedOut.signal, options.signal]) : timedOut.signal;
|
|
@@ -1023,16 +652,27 @@ async function requestRepair(options, input, privateDir) {
|
|
|
1023
652
|
const kept = options.agentChanges !== "discard" && !options.validating;
|
|
1024
653
|
const staged = stageProject(options.projectDir, privateDir, input.programSource);
|
|
1025
654
|
limit.start(() => timedOut.abort());
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
655
|
+
// Who is asked: a project, where one is named — or pi's agent, at work in the copy with its own tools.
|
|
656
|
+
let fixed;
|
|
657
|
+
if (options.repairWith !== undefined) {
|
|
658
|
+
fixed = await fixedBy(options.repairWith, options, { ...input, kept, copy: staged.copy }, signal);
|
|
659
|
+
}
|
|
660
|
+
else {
|
|
661
|
+
const answer = await options.backend.ask(repairPrompt({ ...input, journal: options.journal.path, kept }), {
|
|
662
|
+
cwd: staged.copy, system: REPAIR_SYSTEM_PROMPT, signal,
|
|
663
|
+
used: (usage) => options.journal.used("fix", usage),
|
|
664
|
+
});
|
|
665
|
+
// (An answer that says there is no fix is that, and no program: it is not installed and tried as one.)
|
|
666
|
+
if (answer.trimStart().startsWith(NO_FIX))
|
|
667
|
+
throw new NoFix(answer.trimStart().slice(NO_FIX.length).trim() || "no reason was given");
|
|
668
|
+
fixed = stripCodeFences(answer);
|
|
669
|
+
}
|
|
1030
670
|
if (fixed.trim() === "")
|
|
1031
671
|
throw new Error("The repair returned an empty program.");
|
|
1032
672
|
if (!kept) {
|
|
1033
673
|
if (fixed === input.programSource)
|
|
1034
674
|
throw new Error("The repair returned the program unchanged.");
|
|
1035
|
-
options.journal.note("fix", { ok: true, source: fixed });
|
|
675
|
+
options.journal.note("fix", { ok: true, ...usedByAProject(), source: fixed });
|
|
1036
676
|
return { fixed };
|
|
1037
677
|
}
|
|
1038
678
|
let changed = [], unusable;
|
|
@@ -1051,6 +691,7 @@ async function requestRepair(options, input, privateDir) {
|
|
|
1051
691
|
}
|
|
1052
692
|
options.journal.note("fix", {
|
|
1053
693
|
ok: true,
|
|
694
|
+
...usedByAProject(),
|
|
1054
695
|
...(changed.length > 0 ? { changed: changed.slice(0, MAX_PATHS_NOTED) } : {}),
|
|
1055
696
|
...(changed.length > MAX_PATHS_NOTED ? { changedInAll: changed.length } : {}),
|
|
1056
697
|
alone: unusable,
|
|
@@ -1059,14 +700,54 @@ async function requestRepair(options, input, privateDir) {
|
|
|
1059
700
|
return unusable === undefined ? { fixed, staged } : { fixed, unusable };
|
|
1060
701
|
}
|
|
1061
702
|
catch (err) {
|
|
1062
|
-
const error = messageOf(err);
|
|
1063
|
-
options.journal.note("fix", { ok: false, error });
|
|
703
|
+
const error = err instanceof NoFix ? `It was said that there is none to be had: ${err.message}` : messageOf(err);
|
|
704
|
+
options.journal.note("fix", { ok: false, ...(err instanceof NoFix && { none: true }), ...usedByAProject(), error });
|
|
1064
705
|
return { error };
|
|
1065
706
|
}
|
|
1066
707
|
finally {
|
|
1067
708
|
limit.cancel();
|
|
1068
709
|
}
|
|
1069
710
|
}
|
|
711
|
+
/**
|
|
712
|
+
* Ask a project for a fix (see RunOptions.repairWith): its program is run
|
|
713
|
+
* with the copy as its workspace, and what it ends with is the answer. It is
|
|
714
|
+
* a run of the failing run's own — under its count, stopped with it, started
|
|
715
|
+
* with its variables, on its record — and a run like any otherwise, with a
|
|
716
|
+
* journal of its own in its own project. Not one that is fixed where it
|
|
717
|
+
* fails: what fixes would then be asked to fix what fixes.
|
|
718
|
+
*/
|
|
719
|
+
async function fixedBy(project, options, asked, signal) {
|
|
720
|
+
if (realRootOf(project) === realRootOf(options.projectDir)) {
|
|
721
|
+
throw new Error("A project is not asked to fix itself: repairWith names the project that failed.");
|
|
722
|
+
}
|
|
723
|
+
const { journal } = options;
|
|
724
|
+
const result = await runProgram({
|
|
725
|
+
projectDir: project,
|
|
726
|
+
workspaceDir: asked.copy,
|
|
727
|
+
maxRepairAttempts: 0,
|
|
728
|
+
timeout: options.timeout,
|
|
729
|
+
label: options.label ? `${options.label}: fix` : "fix",
|
|
730
|
+
env: options.env,
|
|
731
|
+
signal,
|
|
732
|
+
args: { program: asked.programSource, error: asked.error, journal: journal.path, kept: asked.kept, types: RUNTIME_TYPES },
|
|
733
|
+
}, {
|
|
734
|
+
depth: options.depth + 1,
|
|
735
|
+
parent: { run: journal.run, journal: journal.path },
|
|
736
|
+
started: (run, path) => { if (run)
|
|
737
|
+
journal.note("child", { run, journal: path, purpose: "fix" }); },
|
|
738
|
+
above: options.meter,
|
|
739
|
+
});
|
|
740
|
+
if (result.status !== "done") {
|
|
741
|
+
throw new Error(`The project asked for the fix ${result.status === "failed" ? "failed" : "did not end its work"}: ${result.reason ?? result.status}`);
|
|
742
|
+
}
|
|
743
|
+
const { program, unfixable } = (result.result ?? {});
|
|
744
|
+
if (typeof unfixable === "string" && program === undefined)
|
|
745
|
+
throw new NoFix(unfixable.trim() || "no reason was given");
|
|
746
|
+
if (typeof program !== "string") {
|
|
747
|
+
throw new Error("The project asked for the fix answered with no program: its result is to be { program }, the whole of the fixed program — or { unfixable }, why there is no fix.");
|
|
748
|
+
}
|
|
749
|
+
return program;
|
|
750
|
+
}
|
|
1070
751
|
/**
|
|
1071
752
|
* Try a proposed fix, in a copy of the project that has it for its program.
|
|
1072
753
|
*
|
|
@@ -1141,7 +822,7 @@ async function tryFix(options, staged, fixed, attempt) {
|
|
|
1141
822
|
// project is the directory that was copied, which the copy knows by what
|
|
1142
823
|
// it is.
|
|
1143
824
|
const projectRoot = realRootOf(projectDir);
|
|
1144
|
-
const copied = held.get(
|
|
825
|
+
const copied = held.get(ITSELF), there = entryAt(projectRoot);
|
|
1145
826
|
if (there && copied?.kind === "dir" && !(there.kind === "dir" && there.id === copied.id)) {
|
|
1146
827
|
throw new Error(`The program cannot be replaced: what is at ${projectRoot} is not the project the fix was tried on.`);
|
|
1147
828
|
}
|
|
@@ -1216,7 +897,7 @@ async function executeProgram(options) {
|
|
|
1216
897
|
for (let attempt = 1; attempt <= maxRepairAttempts; attempt++) {
|
|
1217
898
|
stillTheProject();
|
|
1218
899
|
// 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
|
|
900
|
+
const spent = options.backend.spent();
|
|
1220
901
|
if (spent !== undefined) {
|
|
1221
902
|
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
903
|
}
|
|
@@ -1275,15 +956,15 @@ async function journalled(journal, backend, run) {
|
|
|
1275
956
|
throw err;
|
|
1276
957
|
}
|
|
1277
958
|
finally {
|
|
1278
|
-
if (journal.run || backend.counts
|
|
959
|
+
if (journal.run || backend.counts())
|
|
1279
960
|
await backend.letGo();
|
|
1280
|
-
const spent = backend.spent
|
|
961
|
+
const spent = backend.spent() ?? backend.refused();
|
|
1281
962
|
if (spent !== undefined)
|
|
1282
963
|
journal.note("budget", { spent });
|
|
1283
964
|
journal.note("end", end);
|
|
1284
965
|
journal.close();
|
|
1285
966
|
// Nothing a run started outlives it: nor what served its agent calls.
|
|
1286
|
-
await backend.close
|
|
967
|
+
await backend.close();
|
|
1287
968
|
}
|
|
1288
969
|
}
|
|
1289
970
|
// --- Validating a candidate program (used by create and update) ---
|
|
@@ -1372,7 +1053,7 @@ export async function validateProgram(projectDir, backend, candidate, options) {
|
|
|
1372
1053
|
});
|
|
1373
1054
|
const { result, repair, left } = await journalled(journal, backend, async () => (await validatedIn(as)) ?? (await validatedIn(projectDir)));
|
|
1374
1055
|
if (result.status === "failed")
|
|
1375
|
-
throw new Error(
|
|
1056
|
+
throw new Error(failureOf(result.reason));
|
|
1376
1057
|
return { source: left, repairedError: repair?.error, ...(alone === undefined ? {} : { alone }) };
|
|
1377
1058
|
}
|
|
1378
1059
|
export function prepareProject(projectDir, privateDir) {
|
|
@@ -1504,7 +1185,7 @@ function stageProgram(projectDir, source) {
|
|
|
1504
1185
|
const refusal = whyNotReplaceable(projectDir);
|
|
1505
1186
|
if (refusal)
|
|
1506
1187
|
throw Object.assign(new Error(refusal), { code: "EACCES" });
|
|
1507
|
-
return
|
|
1188
|
+
return stageFileInProject(projectDir, "program.ts", source);
|
|
1508
1189
|
}
|
|
1509
1190
|
/**
|
|
1510
1191
|
* Make a validated program the project's program.ts and record it as a new
|
|
@@ -1567,18 +1248,24 @@ async function runProject(options, depth, askedFor, making) {
|
|
|
1567
1248
|
`Run \`trama list\` to see available projects.`);
|
|
1568
1249
|
}
|
|
1569
1250
|
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
|
-
}
|
|
1251
|
+
const timeout = checkedTimeout(options.timeout ?? config.defaultTimeout);
|
|
1252
|
+
const maxRepairAttempts = checkedRepairAttempts(options.maxRepairAttempts ?? config.maxRepairAttempts);
|
|
1578
1253
|
const env = options.env == null ? undefined : checkedEnv(options.env);
|
|
1254
|
+
// Who is asked for a fix, where it is a project: found now, and not when the program has failed — a run that
|
|
1255
|
+
// could not have been fixed as it was to be is not begun. (Where no fix is to be asked for, nobody is looked for.)
|
|
1256
|
+
const namedToFix = options.repairWith ?? config.repairWith;
|
|
1257
|
+
const repairWith = namedToFix !== undefined && maxRepairAttempts > 0 ? projectNamed(namedToFix) : undefined;
|
|
1258
|
+
if (repairWith !== undefined && !existsSync(join(repairWith, "meta.json"))) {
|
|
1259
|
+
throw new Error(`repairWith names no project: there is none at ${repairWith}`);
|
|
1260
|
+
}
|
|
1579
1261
|
// 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
1262
|
const budget = options.budget != null ? checkedBudget(options.budget) : askedFor ? undefined : config.budget;
|
|
1581
1263
|
const meter = createMeter(budget, askedFor?.above);
|
|
1264
|
+
const outOfBudget = (why) => console.warn(tagged(options.label, `[trama] ${why}`));
|
|
1265
|
+
// (Before the journal is opened: once it is, nothing stands between that and the run that ends it — a
|
|
1266
|
+
// journal with a beginning and no end is a run that died, and is not to be one that never began.)
|
|
1267
|
+
const stillTheProject = sameProjectAs(projectDir);
|
|
1268
|
+
const backend = createBackend(config, meter, saysOnce(meter, outOfBudget), env);
|
|
1582
1269
|
const journal = openJournal(projectDir, config.journalRuns, {
|
|
1583
1270
|
purpose: "run",
|
|
1584
1271
|
label: options.label,
|
|
@@ -1587,15 +1274,14 @@ async function runProject(options, depth, askedFor, making) {
|
|
|
1587
1274
|
workspace: options.workspaceDir,
|
|
1588
1275
|
timeout,
|
|
1589
1276
|
maxRepairAttempts,
|
|
1277
|
+
repairWith,
|
|
1590
1278
|
budget,
|
|
1591
1279
|
// (The names: what the variables hold is not for a journal.)
|
|
1592
1280
|
env: env && Object.keys(env),
|
|
1593
1281
|
args: options.args, // last: it is the one field of unknown size
|
|
1594
1282
|
});
|
|
1595
1283
|
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({
|
|
1284
|
+
const { result, repair } = await journalled(journal, backend, (backend) => executeProgram({
|
|
1599
1285
|
projectDir,
|
|
1600
1286
|
backend,
|
|
1601
1287
|
meter,
|
|
@@ -1609,6 +1295,7 @@ async function runProject(options, depth, askedFor, making) {
|
|
|
1609
1295
|
label: options.label,
|
|
1610
1296
|
env,
|
|
1611
1297
|
agentChanges: config.agentChanges,
|
|
1298
|
+
repairWith,
|
|
1612
1299
|
signal: options.signal,
|
|
1613
1300
|
journal,
|
|
1614
1301
|
}));
|