@trama-dev/runtime 0.2.0 → 0.2.2
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/README.md +1 -1
- package/dist/client.js +36 -11
- package/dist/index.js +28 -27
- package/dist/lifetime.d.ts +8 -0
- package/dist/lifetime.js +70 -0
- package/dist/runner.d.ts +36 -36
- package/dist/runner.js +237 -226
- package/dist/tools.d.ts +0 -2
- package/dist/tools.js +28 -15
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -32,7 +32,7 @@ The runtime is what makes agent programs **self-contained and shareable**:
|
|
|
32
32
|
- **Execution** — child process spawning, streaming output, timeout management, background process cleanup.
|
|
33
33
|
- **IPC bridge** — a local HTTP server that every `ctx`, `agent`, `tools` and `workspace` call goes through: one point where the runtime validates each request and can cancel work in flight when a run ends.
|
|
34
34
|
- **State persistence** — `ctx.state` survives across runs. Programs can be long-running, interruptible, and resumable.
|
|
35
|
-
- **Auto-repair** — on crash, the runtime gets an LLM fix and
|
|
35
|
+
- **Auto-repair** — on crash, the runtime gets an LLM fix and tries it on a private copy of the project, installing it only if it works. Up to 3 attempts.
|
|
36
36
|
- **Version history** — every create, update, and repair saves a snapshot to `history/`.
|
|
37
37
|
- **Scaffolding** — package.json, module symlinks, gitignore, logs. `git clone && trama run` just works.
|
|
38
38
|
|
package/dist/client.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// A thin wrapper that forwards every call to the runner's IPC server
|
|
3
3
|
// (ipc-server.ts), which does the real work.
|
|
4
4
|
import { readFileSync } from "fs";
|
|
5
|
+
import { request } from "http";
|
|
5
6
|
import { assertSerializable } from "./serializable.js";
|
|
6
7
|
const PORT = process.env.TRAMA_PORT;
|
|
7
8
|
if (!PORT) {
|
|
@@ -13,18 +14,42 @@ if (!INIT_PATH) {
|
|
|
13
14
|
throw new Error("@trama-dev/runtime: TRAMA_INIT env var missing. " +
|
|
14
15
|
"This program must be launched by the trama runner.");
|
|
15
16
|
}
|
|
16
|
-
const BASE = `http://127.0.0.1:${PORT}`;
|
|
17
17
|
const initData = JSON.parse(readFileSync(INIT_PATH, "utf-8"));
|
|
18
|
-
/**
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
18
|
+
/**
|
|
19
|
+
* POST one call to the runner and return its result.
|
|
20
|
+
*
|
|
21
|
+
* A call lasts as long as the work behind it — an agent run, or a wait for
|
|
22
|
+
* another program — so this uses node:http, which sets no deadline for the
|
|
23
|
+
* response. (fetch gives up after five minutes without response headers.)
|
|
24
|
+
*/
|
|
25
|
+
function call(endpoint, body) {
|
|
26
|
+
return new Promise((resolve, reject) => {
|
|
27
|
+
const payload = JSON.stringify(body);
|
|
28
|
+
const req = request({
|
|
29
|
+
host: "127.0.0.1",
|
|
30
|
+
port: PORT,
|
|
31
|
+
path: endpoint,
|
|
32
|
+
method: "POST",
|
|
33
|
+
headers: {
|
|
34
|
+
"Content-Type": "application/json",
|
|
35
|
+
"Content-Length": Buffer.byteLength(payload),
|
|
36
|
+
"Authorization": `Bearer ${initData.token}`,
|
|
37
|
+
},
|
|
38
|
+
}, (res) => {
|
|
39
|
+
const chunks = [];
|
|
40
|
+
res.on("data", (chunk) => chunks.push(chunk));
|
|
41
|
+
res.on("error", reject);
|
|
42
|
+
res.on("end", () => {
|
|
43
|
+
const text = Buffer.concat(chunks).toString("utf-8");
|
|
44
|
+
if (res.statusCode !== 200)
|
|
45
|
+
reject(new Error(`trama runtime error: ${text}`));
|
|
46
|
+
else
|
|
47
|
+
resolve(JSON.parse(text).result);
|
|
48
|
+
});
|
|
49
|
+
});
|
|
50
|
+
req.on("error", reject);
|
|
51
|
+
req.end(payload);
|
|
24
52
|
});
|
|
25
|
-
if (!res.ok)
|
|
26
|
-
throw new Error(`trama runtime error: ${await res.text()}`);
|
|
27
|
-
return (await res.json()).result;
|
|
28
53
|
}
|
|
29
54
|
/** Log payloads are best-effort: anything that can't be sent as JSON is replaced by its string form. */
|
|
30
55
|
function sendable(data) {
|
|
@@ -81,7 +106,7 @@ export const tools = {
|
|
|
81
106
|
};
|
|
82
107
|
/** workspace.* exists only inside a session — everywhere else it fails clearly, without a round trip. */
|
|
83
108
|
async function workspaceCall(endpoint, body) {
|
|
84
|
-
if (!initData.
|
|
109
|
+
if (!initData.inSession) {
|
|
85
110
|
throw new Error("workspace is only available when running in a session");
|
|
86
111
|
}
|
|
87
112
|
return call(endpoint, body);
|
package/dist/index.js
CHANGED
|
@@ -3,7 +3,7 @@ import { readFileSync, writeFileSync, mkdirSync, readdirSync, existsSync, statSy
|
|
|
3
3
|
import { join } from "path";
|
|
4
4
|
import { homedir } from "os";
|
|
5
5
|
import { PiAdapter, PI_VERSION, stripCodeFences } from "./pi-adapter.js";
|
|
6
|
-
import { loadConfig, loadProjectConfig, loadState,
|
|
6
|
+
import { loadConfig, loadProjectConfig, loadState, validateProgram, installValidatedProgram, withTempDir, ensureProjectScaffold, RUNTIME_TYPES, } from "./runner.js";
|
|
7
7
|
import { guardPath } from "./path-guard.js";
|
|
8
8
|
export { runProgram } from "./runner.js";
|
|
9
9
|
export { createWorkspace } from "./workspace.js";
|
|
@@ -117,6 +117,11 @@ export function resolveProject(name) {
|
|
|
117
117
|
async function isolatedAsk(adapter, prompt, options) {
|
|
118
118
|
return withTempDir("trama-gen-", (dir) => adapter.withCwd(dir).ask(prompt, options));
|
|
119
119
|
}
|
|
120
|
+
const validationOptions = (config) => ({
|
|
121
|
+
timeout: config.defaultTimeout,
|
|
122
|
+
maxRepairAttempts: config.maxRepairAttempts,
|
|
123
|
+
maxIterations: config.defaultMaxIterations,
|
|
124
|
+
});
|
|
120
125
|
// --- Public API ---
|
|
121
126
|
export async function createProject(name, prompt, options) {
|
|
122
127
|
validateProjectName(name);
|
|
@@ -141,16 +146,14 @@ export async function createProject(name, prompt, options) {
|
|
|
141
146
|
writeFileSync(join(projectDir, "meta.json"), JSON.stringify(meta, null, 2));
|
|
142
147
|
const adapter = new PiAdapter(config, projectDir);
|
|
143
148
|
console.log(`Generating program for "${name}"...`);
|
|
144
|
-
const
|
|
145
|
-
|
|
149
|
+
const candidate = stripCodeFences(await isolatedAsk(adapter, `${prompt}\n\nOutput ONLY the TypeScript program. No markdown fences. No explanation.`, { system: getSystemPrompt() }));
|
|
150
|
+
// From here on the project is kept even if validation fails, so the
|
|
151
|
+
// generated program can be inspected and fixed by hand.
|
|
152
|
+
writeFileSync(join(projectDir, "program.ts"), candidate);
|
|
146
153
|
keepProjectOnFailure = true;
|
|
147
154
|
console.log("Validating program...");
|
|
148
|
-
await
|
|
149
|
-
|
|
150
|
-
maxRepairAttempts: config.maxRepairAttempts,
|
|
151
|
-
maxIterations: config.defaultMaxIterations,
|
|
152
|
-
});
|
|
153
|
-
copyToHistory(projectDir, "create", prompt);
|
|
155
|
+
const validated = await validateProgram(projectDir, adapter, candidate, validationOptions(config));
|
|
156
|
+
installValidatedProgram(projectDir, validated, "create", prompt);
|
|
154
157
|
console.log(`Created ${name}. Run with: trama run ${name}`);
|
|
155
158
|
}
|
|
156
159
|
catch (err) {
|
|
@@ -174,25 +177,24 @@ export async function updateProject(name, prompt) {
|
|
|
174
177
|
`\n\nOriginal prompt: ${meta.input.prompt}` +
|
|
175
178
|
`\n\nCurrent program.ts:\n${originalSource}` +
|
|
176
179
|
(Object.keys(state).length > 0 ? `\n\nCurrent state:\n${JSON.stringify(state, null, 2)}` : "");
|
|
177
|
-
//
|
|
178
|
-
//
|
|
180
|
+
// The new program is generated and validated off to the side. The project is
|
|
181
|
+
// only written to once there is a program that works, so a failed update has
|
|
182
|
+
// nothing to undo.
|
|
179
183
|
try {
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
return { keep: true, value: undefined };
|
|
192
|
-
});
|
|
184
|
+
console.log(`Updating "${name}"...`);
|
|
185
|
+
const candidate = stripCodeFences(await isolatedAsk(adapter, `${prompt}\n\nOutput the complete updated program.ts. No partial patches. No markdown fences. No explanation.`, { system: systemPrompt }));
|
|
186
|
+
console.log("Validating updated program...");
|
|
187
|
+
const validated = await validateProgram(projectDir, adapter, candidate, validationOptions(config));
|
|
188
|
+
try {
|
|
189
|
+
installValidatedProgram(projectDir, validated, "update", prompt);
|
|
190
|
+
}
|
|
191
|
+
catch (err) {
|
|
192
|
+
writeFileSync(programPath, originalSource); // recording the version failed: don't leave an unrecorded program behind
|
|
193
|
+
throw err;
|
|
194
|
+
}
|
|
193
195
|
}
|
|
194
196
|
catch (err) {
|
|
195
|
-
throw new Error(`Update failed — project
|
|
197
|
+
throw new Error(`Update failed — the project is unchanged.\n` +
|
|
196
198
|
`${err instanceof Error ? err.message : err}`);
|
|
197
199
|
}
|
|
198
200
|
console.log(`Updated ${name}. Run with: trama run ${name}`);
|
|
@@ -203,9 +205,8 @@ export async function listProjects() {
|
|
|
203
205
|
console.log("No projects found.");
|
|
204
206
|
return;
|
|
205
207
|
}
|
|
206
|
-
// Dot-directories are not projects (a rollback snapshot is kept beside its project while a run is in flight).
|
|
207
208
|
const entries = readdirSync(dir, { withFileTypes: true })
|
|
208
|
-
.filter(e => e.isDirectory()
|
|
209
|
+
.filter(e => e.isDirectory());
|
|
209
210
|
if (entries.length === 0) {
|
|
210
211
|
console.log("No projects found.");
|
|
211
212
|
return;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Register something to undo if this process ends before `settle` is called.
|
|
3
|
+
* `undo` must be synchronous. Returns `settle`: call it once the thing has been
|
|
4
|
+
* dealt with in the normal course of the run.
|
|
5
|
+
*/
|
|
6
|
+
export declare function untilSettled(undo: () => void): () => void;
|
|
7
|
+
/** Remove a temp directory. Best-effort: failing to clean up must never change a run's outcome. */
|
|
8
|
+
export declare function removeTempDir(dir: string): void;
|
package/dist/lifetime.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// What this process must undo if it ends while a run is still in flight:
|
|
2
|
+
// stop the processes it started, and delete what it left in the temp directory.
|
|
3
|
+
//
|
|
4
|
+
// A program, and every shell command it runs, leads its own process group — so
|
|
5
|
+
// that a timeout can take down everything it started. The cost is that none of
|
|
6
|
+
// them die with the runner: without this, Ctrl-C on `trama run` would leave the
|
|
7
|
+
// program running, and a program that coordinates others (a session) would
|
|
8
|
+
// leave them running when it ended.
|
|
9
|
+
import { rmSync } from "fs";
|
|
10
|
+
const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
11
|
+
const pending = new Set();
|
|
12
|
+
let installed = false;
|
|
13
|
+
function runPending() {
|
|
14
|
+
for (const undo of [...pending]) {
|
|
15
|
+
try {
|
|
16
|
+
undo();
|
|
17
|
+
}
|
|
18
|
+
catch { /* best-effort: we are on the way out */ }
|
|
19
|
+
}
|
|
20
|
+
pending.clear();
|
|
21
|
+
}
|
|
22
|
+
function onSignal(signal) {
|
|
23
|
+
runPending();
|
|
24
|
+
// Having a handler at all cancelled the signal's default action. Step aside
|
|
25
|
+
// and send it again, so that what happens next is what would have happened
|
|
26
|
+
// had this handler never been installed: the process dies of it, or whoever
|
|
27
|
+
// else handles the signal decides. (Common libraries only act on a signal
|
|
28
|
+
// when they are its sole listener, so simply staying out of the way is not
|
|
29
|
+
// enough — the signal has to arrive once more without us.)
|
|
30
|
+
uninstall();
|
|
31
|
+
process.kill(process.pid, signal);
|
|
32
|
+
}
|
|
33
|
+
function install() {
|
|
34
|
+
if (installed)
|
|
35
|
+
return;
|
|
36
|
+
installed = true;
|
|
37
|
+
process.on("exit", runPending);
|
|
38
|
+
for (const signal of SIGNALS)
|
|
39
|
+
process.on(signal, onSignal);
|
|
40
|
+
}
|
|
41
|
+
/** Leave the host process's signal handling untouched whenever nothing is in flight. */
|
|
42
|
+
function uninstall() {
|
|
43
|
+
if (!installed)
|
|
44
|
+
return;
|
|
45
|
+
installed = false;
|
|
46
|
+
process.removeListener("exit", runPending);
|
|
47
|
+
for (const signal of SIGNALS)
|
|
48
|
+
process.removeListener(signal, onSignal);
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Register something to undo if this process ends before `settle` is called.
|
|
52
|
+
* `undo` must be synchronous. Returns `settle`: call it once the thing has been
|
|
53
|
+
* dealt with in the normal course of the run.
|
|
54
|
+
*/
|
|
55
|
+
export function untilSettled(undo) {
|
|
56
|
+
pending.add(undo);
|
|
57
|
+
install();
|
|
58
|
+
return () => {
|
|
59
|
+
pending.delete(undo);
|
|
60
|
+
if (pending.size === 0)
|
|
61
|
+
uninstall();
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
/** Remove a temp directory. Best-effort: failing to clean up must never change a run's outcome. */
|
|
65
|
+
export function removeTempDir(dir) {
|
|
66
|
+
try {
|
|
67
|
+
rmSync(dir, { recursive: true, force: true });
|
|
68
|
+
}
|
|
69
|
+
catch { /* left for the OS to reap */ }
|
|
70
|
+
}
|
package/dist/runner.d.ts
CHANGED
|
@@ -21,9 +21,7 @@ export declare function loadState(projectDir: string): Record<string, unknown>;
|
|
|
21
21
|
* Save the current program.ts as the next version: copy it to history/NNNN.ts
|
|
22
22
|
* and record why in index.jsonl.
|
|
23
23
|
*
|
|
24
|
-
*
|
|
25
|
-
* own — they are noted in index.jsonl only (reason "create-repair" /
|
|
26
|
-
* "update-repair"), and the validated program becomes the create/update version.
|
|
24
|
+
* (See installValidatedProgram for how a create or update is recorded.)
|
|
27
25
|
*/
|
|
28
26
|
export declare function copyToHistory(projectDir: string, reason: string, detail?: string): void;
|
|
29
27
|
type DirSnapshot = Map<string, {
|
|
@@ -33,47 +31,49 @@ type DirSnapshot = Map<string, {
|
|
|
33
31
|
/** Record all files in a directory with their size and mtime for change detection. */
|
|
34
32
|
export declare function snapshotDir(dir: string, prefix?: string): DirSnapshot;
|
|
35
33
|
/**
|
|
36
|
-
*
|
|
37
|
-
*
|
|
34
|
+
* Merge what a run did to a staged copy back into the real directory, with a
|
|
35
|
+
* three-way check so that nothing changed in the real directory meanwhile —
|
|
36
|
+
* by another session participant, or by the user — is overwritten.
|
|
38
37
|
*
|
|
39
|
-
* @param
|
|
40
|
-
* @param realDir - real
|
|
41
|
-
* @param
|
|
42
|
-
* @param realSeed - real
|
|
38
|
+
* @param stagedDir - the copy after the run (source of changes)
|
|
39
|
+
* @param realDir - the real directory (destination)
|
|
40
|
+
* @param stagedBefore - snapshot of the copy before the run (detects what the run changed)
|
|
41
|
+
* @param realSeed - snapshot of the real directory when the copy was taken (detects concurrent changes)
|
|
43
42
|
*
|
|
44
|
-
* For each file the run
|
|
45
|
-
* -
|
|
46
|
-
* - Modified
|
|
47
|
-
*
|
|
48
|
-
* Best-effort: anything that cannot be
|
|
43
|
+
* For each file the run touched in the copy:
|
|
44
|
+
* - Created: copied, unless that path has meanwhile appeared in the real directory.
|
|
45
|
+
* - Modified: copied only if the real file still matches realSeed.
|
|
46
|
+
* - Deleted: deleted only if the real file still matches realSeed.
|
|
47
|
+
* Best-effort: anything that cannot be merged safely is skipped, never thrown.
|
|
49
48
|
*/
|
|
50
|
-
export declare function
|
|
51
|
-
/**
|
|
52
|
-
* Run fn against a directory that can be put back exactly as it was: if fn
|
|
53
|
-
* returns keep:false or throws, the directory is rolled back. Returns fn's value.
|
|
54
|
-
*
|
|
55
|
-
* The snapshot is a hidden copy next to the directory, on the same file
|
|
56
|
-
* system, so rolling back is two renames — move the directory aside, move the
|
|
57
|
-
* snapshot into its place — and at no point does the content exist nowhere.
|
|
58
|
-
* (If the process is killed outright, the snapshot is left behind beside the
|
|
59
|
-
* directory: it is the pre-change state.)
|
|
60
|
-
*/
|
|
61
|
-
export declare function withSnapshot<T>(dir: string, fn: () => Promise<{
|
|
62
|
-
keep: boolean;
|
|
63
|
-
value: T;
|
|
64
|
-
}>): Promise<T>;
|
|
65
|
-
/** Run fn in a temp directory, clean up afterwards regardless of outcome. */
|
|
49
|
+
export declare function commitStagedChanges(stagedDir: string, realDir: string, stagedBefore: DirSnapshot, realSeed: DirSnapshot): void;
|
|
50
|
+
/** Run fn in a temp directory, clean up afterwards regardless of outcome — including this process being stopped. */
|
|
66
51
|
export declare function withTempDir<T>(prefix: string, fn: (dir: string) => Promise<T>): Promise<T>;
|
|
67
52
|
/**
|
|
68
|
-
* Validate a
|
|
69
|
-
*
|
|
70
|
-
*
|
|
71
|
-
*
|
|
53
|
+
* Validate a candidate program.ts for a project without touching the project:
|
|
54
|
+
* run it (with repair) in a throwaway copy. Returns the program that worked —
|
|
55
|
+
* the candidate itself, or a repaired version of it, with the failure that was
|
|
56
|
+
* repaired. Throws if it cannot be made to run.
|
|
57
|
+
*
|
|
58
|
+
* Only the project's own files are shielded. What the program does beyond
|
|
59
|
+
* them — network calls, shell commands, other projects it runs — is real.
|
|
72
60
|
*/
|
|
73
|
-
export declare function
|
|
61
|
+
export declare function validateProgram(projectDir: string, adapter: PiAdapter, candidate: string, options: {
|
|
74
62
|
timeout: number;
|
|
75
63
|
maxRepairAttempts: number;
|
|
76
64
|
maxIterations: number;
|
|
77
|
-
}): Promise<
|
|
65
|
+
}): Promise<{
|
|
66
|
+
source: string;
|
|
67
|
+
repairedError?: string;
|
|
68
|
+
}>;
|
|
69
|
+
/**
|
|
70
|
+
* Make a validated program the project's program.ts and record it as a new
|
|
71
|
+
* version. A repair made while validating is not a version of its own — it is
|
|
72
|
+
* noted in the history index only.
|
|
73
|
+
*/
|
|
74
|
+
export declare function installValidatedProgram(projectDir: string, validated: {
|
|
75
|
+
source: string;
|
|
76
|
+
repairedError?: string;
|
|
77
|
+
}, reason: "create" | "update", prompt: string): void;
|
|
78
78
|
export declare function runProgram(options: RunOptions): Promise<ProgramResult>;
|
|
79
79
|
export {};
|
package/dist/runner.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { spawn } from "child_process";
|
|
2
|
-
import { readFileSync, writeFileSync, appendFileSync, readdirSync, copyFileSync, mkdirSync, existsSync, statSync, symlinkSync, rmSync, lstatSync, readlinkSync, cpSync, mkdtempSync, openSync, closeSync,
|
|
3
|
-
import { join, dirname
|
|
2
|
+
import { readFileSync, writeFileSync, appendFileSync, readdirSync, copyFileSync, mkdirSync, existsSync, statSync, symlinkSync, rmSync, lstatSync, readlinkSync, cpSync, mkdtempSync, openSync, closeSync, realpathSync, } from "fs";
|
|
3
|
+
import { join, dirname } from "path";
|
|
4
4
|
import { homedir, tmpdir } from "os";
|
|
5
5
|
import { fileURLToPath } from "url";
|
|
6
6
|
import { randomBytes } from "crypto";
|
|
@@ -10,7 +10,8 @@ import { createAgent } from "./agent.js";
|
|
|
10
10
|
import { createTools } from "./tools.js";
|
|
11
11
|
import { createWorkspace } from "./workspace.js";
|
|
12
12
|
import { guardPath } from "./path-guard.js";
|
|
13
|
-
import { superviseChild } from "./child-process.js";
|
|
13
|
+
import { signalGroup, superviseChild } from "./child-process.js";
|
|
14
|
+
import { removeTempDir, untilSettled } from "./lifetime.js";
|
|
14
15
|
import { createIPCServer, listen, closeServer } from "./ipc-server.js";
|
|
15
16
|
// --- Locating the runtime itself ---
|
|
16
17
|
/** The installed @trama-dev/runtime package — this file lives in its dist/. */
|
|
@@ -212,9 +213,7 @@ const HISTORY_DETAIL_FIELD = { create: "prompt", update: "prompt", repair: "erro
|
|
|
212
213
|
* Save the current program.ts as the next version: copy it to history/NNNN.ts
|
|
213
214
|
* and record why in index.jsonl.
|
|
214
215
|
*
|
|
215
|
-
*
|
|
216
|
-
* own — they are noted in index.jsonl only (reason "create-repair" /
|
|
217
|
-
* "update-repair"), and the validated program becomes the create/update version.
|
|
216
|
+
* (See installValidatedProgram for how a create or update is recorded.)
|
|
218
217
|
*/
|
|
219
218
|
export function copyToHistory(projectDir, reason, detail) {
|
|
220
219
|
const historyDir = guardPath(projectDir, "history");
|
|
@@ -259,130 +258,104 @@ export function snapshotDir(dir, prefix = "") {
|
|
|
259
258
|
}
|
|
260
259
|
const sameStat = (a, b) => a.size === b.size && a.mtimeMs === b.mtimeMs;
|
|
261
260
|
/**
|
|
262
|
-
*
|
|
263
|
-
*
|
|
261
|
+
* Merge what a run did to a staged copy back into the real directory, with a
|
|
262
|
+
* three-way check so that nothing changed in the real directory meanwhile —
|
|
263
|
+
* by another session participant, or by the user — is overwritten.
|
|
264
264
|
*
|
|
265
|
-
* @param
|
|
266
|
-
* @param realDir - real
|
|
267
|
-
* @param
|
|
268
|
-
* @param realSeed - real
|
|
265
|
+
* @param stagedDir - the copy after the run (source of changes)
|
|
266
|
+
* @param realDir - the real directory (destination)
|
|
267
|
+
* @param stagedBefore - snapshot of the copy before the run (detects what the run changed)
|
|
268
|
+
* @param realSeed - snapshot of the real directory when the copy was taken (detects concurrent changes)
|
|
269
269
|
*
|
|
270
|
-
* For each file the run
|
|
271
|
-
* -
|
|
272
|
-
* - Modified
|
|
273
|
-
*
|
|
274
|
-
* Best-effort: anything that cannot be
|
|
270
|
+
* For each file the run touched in the copy:
|
|
271
|
+
* - Created: copied, unless that path has meanwhile appeared in the real directory.
|
|
272
|
+
* - Modified: copied only if the real file still matches realSeed.
|
|
273
|
+
* - Deleted: deleted only if the real file still matches realSeed.
|
|
274
|
+
* Best-effort: anything that cannot be merged safely is skipped, never thrown.
|
|
275
275
|
*/
|
|
276
|
-
export function
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
276
|
+
export function commitStagedChanges(stagedDir, realDir, stagedBefore, realSeed) {
|
|
277
|
+
const stagedAfter = snapshotDir(stagedDir);
|
|
278
|
+
/** The real file as it is now — but only if nobody has touched it since the copy was taken. */
|
|
279
|
+
const untouchedSinceSeed = (relPath, dstPath) => {
|
|
280
|
+
const seedStat = realSeed.get(relPath);
|
|
281
|
+
const realNow = statSync(dstPath, { throwIfNoEntry: false });
|
|
282
|
+
return seedStat === undefined || (realNow !== undefined && sameStat(realNow, seedStat));
|
|
283
|
+
};
|
|
284
|
+
for (const relPath of new Set([...stagedBefore.keys(), ...stagedAfter.keys()])) {
|
|
285
|
+
const beforeStat = stagedBefore.get(relPath);
|
|
286
|
+
const afterStat = stagedAfter.get(relPath);
|
|
287
|
+
if (beforeStat && afterStat && sameStat(beforeStat, afterStat))
|
|
280
288
|
continue; // the run didn't touch it
|
|
281
289
|
try {
|
|
282
|
-
// A
|
|
283
|
-
//
|
|
290
|
+
// A symlink placed at this path, or in a parent directory, could point
|
|
291
|
+
// outside the real directory — guardPath throws.
|
|
284
292
|
const dstPath = guardPath(realDir, relPath);
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
293
|
+
if (!afterStat) {
|
|
294
|
+
if (untouchedSinceSeed(relPath, dstPath))
|
|
295
|
+
rmSync(dstPath, { force: true });
|
|
296
|
+
}
|
|
297
|
+
else if (beforeStat) {
|
|
298
|
+
if (!untouchedSinceSeed(relPath, dstPath))
|
|
289
299
|
continue; // changed or removed concurrently
|
|
300
|
+
copyFileSync(join(stagedDir, relPath), dstPath);
|
|
290
301
|
}
|
|
291
|
-
else
|
|
292
|
-
|
|
302
|
+
else {
|
|
303
|
+
if (statSync(dstPath, { throwIfNoEntry: false }))
|
|
304
|
+
continue; // someone else created it first — keep theirs
|
|
305
|
+
mkdirSync(dirname(dstPath), { recursive: true });
|
|
306
|
+
copyFileSync(join(stagedDir, relPath), dstPath);
|
|
293
307
|
}
|
|
294
|
-
mkdirSync(dirname(dstPath), { recursive: true });
|
|
295
|
-
copyFileSync(join(tempDir, relPath), dstPath);
|
|
296
308
|
}
|
|
297
309
|
catch {
|
|
298
|
-
// Escapes the
|
|
310
|
+
// Escapes the directory, path-shape conflict, permissions — skip
|
|
299
311
|
}
|
|
300
312
|
}
|
|
301
313
|
}
|
|
302
|
-
/**
|
|
303
|
-
* Run fn against a directory that can be put back exactly as it was: if fn
|
|
304
|
-
* returns keep:false or throws, the directory is rolled back. Returns fn's value.
|
|
305
|
-
*
|
|
306
|
-
* The snapshot is a hidden copy next to the directory, on the same file
|
|
307
|
-
* system, so rolling back is two renames — move the directory aside, move the
|
|
308
|
-
* snapshot into its place — and at no point does the content exist nowhere.
|
|
309
|
-
* (If the process is killed outright, the snapshot is left behind beside the
|
|
310
|
-
* directory: it is the pre-change state.)
|
|
311
|
-
*/
|
|
312
|
-
export async function withSnapshot(dir, fn) {
|
|
313
|
-
const target = resolve(dir);
|
|
314
|
-
const snap = mkdtempSync(join(dirname(target), `.${basename(target)}.trama-snapshot-`));
|
|
315
|
-
let rolledBack = false;
|
|
316
|
-
const rollBack = () => {
|
|
317
|
-
const discarded = `${snap}.discarded`;
|
|
318
|
-
renameSync(target, discarded);
|
|
319
|
-
renameSync(snap, target);
|
|
320
|
-
rolledBack = true;
|
|
321
|
-
removeTempDir(discarded);
|
|
322
|
-
};
|
|
323
|
-
try {
|
|
324
|
-
cpSync(target, snap, { recursive: true });
|
|
325
|
-
let result;
|
|
326
|
-
try {
|
|
327
|
-
result = await fn();
|
|
328
|
-
}
|
|
329
|
-
catch (err) {
|
|
330
|
-
rollBack();
|
|
331
|
-
throw err;
|
|
332
|
-
}
|
|
333
|
-
if (!result.keep)
|
|
334
|
-
rollBack();
|
|
335
|
-
return result.value;
|
|
336
|
-
}
|
|
337
|
-
finally {
|
|
338
|
-
if (!rolledBack)
|
|
339
|
-
removeTempDir(snap);
|
|
340
|
-
}
|
|
341
|
-
}
|
|
342
|
-
/** Remove a temp directory. Best-effort: failing to clean up must never change a run's outcome. */
|
|
343
|
-
function removeTempDir(dir) {
|
|
344
|
-
try {
|
|
345
|
-
rmSync(dir, { recursive: true, force: true });
|
|
346
|
-
}
|
|
347
|
-
catch { /* left for the OS to reap */ }
|
|
348
|
-
}
|
|
349
|
-
/** Run fn in a temp directory, clean up afterwards regardless of outcome. */
|
|
314
|
+
/** Run fn in a temp directory, clean up afterwards regardless of outcome — including this process being stopped. */
|
|
350
315
|
export async function withTempDir(prefix, fn) {
|
|
351
316
|
const dir = mkdtempSync(join(tmpdir(), prefix));
|
|
317
|
+
const settled = untilSettled(() => removeTempDir(dir));
|
|
352
318
|
try {
|
|
353
319
|
return await fn(dir);
|
|
354
320
|
}
|
|
355
321
|
finally {
|
|
356
322
|
removeTempDir(dir);
|
|
323
|
+
settled();
|
|
357
324
|
}
|
|
358
325
|
}
|
|
326
|
+
/** Copy a directory's contents into an existing one, keeping symlinks as they are written. */
|
|
327
|
+
function copyDirInto(srcDir, dstDir) {
|
|
328
|
+
// realpath: a project directory may itself be a symlink.
|
|
329
|
+
cpSync(realpathSync(srcDir), dstDir, { recursive: true, verbatimSymlinks: true });
|
|
330
|
+
}
|
|
359
331
|
/**
|
|
360
|
-
* Run fn against a private copy of
|
|
361
|
-
* invisible to
|
|
362
|
-
*
|
|
363
|
-
*
|
|
332
|
+
* Run fn against a private copy of a directory. What fn does there stays
|
|
333
|
+
* invisible to the real directory unless fn asks to commit it — then it is
|
|
334
|
+
* merged back (see commitStagedChanges). If fn fails, or this process is
|
|
335
|
+
* stopped half-way, the real directory was never touched.
|
|
364
336
|
*/
|
|
365
|
-
async function
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
return withTempDir("trama-repair-ws-", async (stagedDir) => {
|
|
370
|
-
cpSync(workspaceDir, stagedDir, { recursive: true });
|
|
337
|
+
async function withStagedCopy(realDir, fn) {
|
|
338
|
+
const realSeed = snapshotDir(realDir);
|
|
339
|
+
return withTempDir("trama-staged-", async (stagedDir) => {
|
|
340
|
+
copyDirInto(realDir, stagedDir);
|
|
371
341
|
const stagedBefore = snapshotDir(stagedDir);
|
|
372
342
|
const { commit, value } = await fn(stagedDir);
|
|
373
343
|
if (commit)
|
|
374
|
-
|
|
344
|
+
commitStagedChanges(stagedDir, realDir, stagedBefore, realSeed);
|
|
375
345
|
return value;
|
|
376
346
|
});
|
|
377
347
|
}
|
|
378
|
-
|
|
348
|
+
/** The end of a long output — where the error is — with a note of how much was dropped. */
|
|
349
|
+
function tail(text, max = 20_000) {
|
|
350
|
+
return text.length <= max ? text : `[… ${text.length - max} earlier characters omitted]\n${text.slice(-max)}`;
|
|
351
|
+
}
|
|
352
|
+
const describeFailure = (r) => `program.ts exited with code ${r.exitCode}\nstdout: ${tail(r.stdout)}\nstderr: ${tail(r.stderr)}`;
|
|
379
353
|
/**
|
|
380
354
|
* Hand the program its starting state through a private temp file rather than
|
|
381
355
|
* env vars — no OS size limit, and mode 0600 in an unpredictable directory
|
|
382
|
-
* keeps it
|
|
356
|
+
* keeps it (and the bridge secret in it) from other local users.
|
|
383
357
|
*/
|
|
384
|
-
function writeInitFile(payload) {
|
|
385
|
-
const dir = mkdtempSync(join(tmpdir(), "trama-init-"));
|
|
358
|
+
function writeInitFile(dir, payload) {
|
|
386
359
|
const file = join(dir, "init.json");
|
|
387
360
|
const fd = openSync(file, "w", 0o600);
|
|
388
361
|
try {
|
|
@@ -391,7 +364,7 @@ function writeInitFile(payload) {
|
|
|
391
364
|
finally {
|
|
392
365
|
closeSync(fd);
|
|
393
366
|
}
|
|
394
|
-
return
|
|
367
|
+
return file;
|
|
395
368
|
}
|
|
396
369
|
function toChildResult(exit) {
|
|
397
370
|
const { stdout, stderr } = exit;
|
|
@@ -402,14 +375,37 @@ function toChildResult(exit) {
|
|
|
402
375
|
return { exitCode: 0, stdout, stderr };
|
|
403
376
|
return { exitCode: exit.code ?? 1, stdout, stderr };
|
|
404
377
|
}
|
|
378
|
+
/**
|
|
379
|
+
* Decide how a finished run ended. A terminal signal the program completed
|
|
380
|
+
* takes precedence over its exit code: a program that called ctx.done() and
|
|
381
|
+
* then crashed is done. Returns null for a failure (non-zero exit, no signal).
|
|
382
|
+
*/
|
|
383
|
+
function settle(projectDir, child, terminalSignal) {
|
|
384
|
+
// Read state first: if the program left state.json corrupt, say so now
|
|
385
|
+
// rather than report an outcome (or start a repair) on top of it.
|
|
386
|
+
const state = loadState(projectDir);
|
|
387
|
+
if (terminalSignal)
|
|
388
|
+
return terminalSignal;
|
|
389
|
+
if (child.exitCode !== 0)
|
|
390
|
+
return null;
|
|
391
|
+
// Natural success without done() or yield(): if this run was the resumption
|
|
392
|
+
// of an earlier yield, that yield is now over — don't let its marker make
|
|
393
|
+
// the next run look resumed.
|
|
394
|
+
if (state.__trama_yield != null) {
|
|
395
|
+
delete state.__trama_yield;
|
|
396
|
+
writeFileSync(guardPath(projectDir, "state.json"), JSON.stringify(state, null, 2));
|
|
397
|
+
}
|
|
398
|
+
return { status: "done" };
|
|
399
|
+
}
|
|
405
400
|
/**
|
|
406
401
|
* Run program.ts once in the given directory: scaffold, start the IPC server,
|
|
407
|
-
* spawn the program, wait for it,
|
|
408
|
-
*
|
|
409
|
-
* when the run could not happen at all
|
|
402
|
+
* spawn the program, wait for it, tear everything down, and say how it ended.
|
|
403
|
+
* The program's output is echoed as it runs. A program that fails is a result,
|
|
404
|
+
* not an exception — this throws only when the run could not happen at all
|
|
405
|
+
* (bad project, server or spawn failure) or left state.json unreadable.
|
|
410
406
|
*/
|
|
411
407
|
async function runProgramOnce(options) {
|
|
412
|
-
const { projectDir, adapter, timeout, maxIterations, argsOverride,
|
|
408
|
+
const { projectDir, adapter, timeout, maxIterations, argsOverride, stopOnReady, workspaceDir } = options;
|
|
413
409
|
ensureProjectScaffold(projectDir);
|
|
414
410
|
// Cancels in-flight LLM calls, fetches and observes once the run is over.
|
|
415
411
|
const runEnded = new AbortController();
|
|
@@ -439,84 +435,73 @@ async function runProgramOnce(options) {
|
|
|
439
435
|
// The first terminal signal wins; ctx itself rejects a conflicting second one.
|
|
440
436
|
onTerminalSignal: result => { terminalSignal ??= result; },
|
|
441
437
|
});
|
|
442
|
-
|
|
438
|
+
// If this process is stopped while the program is running, take the program down with it.
|
|
439
|
+
let programStopped = () => { };
|
|
443
440
|
try {
|
|
444
|
-
const
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
441
|
+
const child = await withTempDir("trama-init-", async (initDir) => {
|
|
442
|
+
const port = await listen(server);
|
|
443
|
+
const initFile = writeInitFile(initDir, {
|
|
444
|
+
token,
|
|
445
|
+
input: ctx.input,
|
|
446
|
+
state: ctx.state,
|
|
447
|
+
iteration: ctx.iteration,
|
|
448
|
+
maxIterations: ctx.maxIterations,
|
|
449
|
+
inSession: workspaceDir !== undefined,
|
|
450
|
+
resumed: ctx.resumed,
|
|
451
|
+
yieldReason: ctx.yieldReason,
|
|
452
|
+
});
|
|
453
|
+
const program = spawn(process.execPath, [TSX_CLI, guardPath(projectDir, "program.ts")], {
|
|
454
|
+
cwd: projectDir,
|
|
455
|
+
env: { ...process.env, TRAMA_PORT: String(port), TRAMA_INIT: initFile },
|
|
456
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
457
|
+
detached: true,
|
|
458
|
+
});
|
|
459
|
+
const pgid = program.pid;
|
|
460
|
+
if (pgid)
|
|
461
|
+
programStopped = untilSettled(() => signalGroup(pgid, "SIGKILL"));
|
|
462
|
+
return toChildResult(await superviseChild(program, {
|
|
463
|
+
timeout,
|
|
464
|
+
stopSignal: stopOnReady ? readyStop.signal : undefined,
|
|
465
|
+
sinks: {
|
|
466
|
+
stdout: chunk => { process.stdout.write(chunk); },
|
|
467
|
+
stderr: chunk => { process.stderr.write(chunk); },
|
|
468
|
+
},
|
|
469
|
+
}));
|
|
461
470
|
});
|
|
462
|
-
|
|
463
|
-
timeout,
|
|
464
|
-
stopSignal: stopOnReady ? readyStop.signal : undefined,
|
|
465
|
-
sinks: streamOutput ? {
|
|
466
|
-
stdout: chunk => { process.stdout.write(chunk); },
|
|
467
|
-
stderr: chunk => { process.stderr.write(chunk); },
|
|
468
|
-
} : undefined,
|
|
469
|
-
});
|
|
470
|
-
return { child: toChildResult(exit), terminalSignal };
|
|
471
|
+
return { outcome: settle(projectDir, child, terminalSignal), failure: describeFailure(child) };
|
|
471
472
|
}
|
|
472
473
|
finally {
|
|
473
474
|
// The program is gone (or never started): cancel what it left in flight,
|
|
474
475
|
// kill shells it left running in the background, and drop its connections.
|
|
476
|
+
programStopped();
|
|
475
477
|
if (readyTimer)
|
|
476
478
|
clearTimeout(readyTimer);
|
|
477
479
|
runEnded.abort();
|
|
478
480
|
tools.killActiveShells();
|
|
479
481
|
server.closeAllConnections();
|
|
480
482
|
await closeServer(server).catch(() => { });
|
|
481
|
-
if (initDir)
|
|
482
|
-
removeTempDir(initDir);
|
|
483
|
-
}
|
|
484
|
-
}
|
|
485
|
-
/**
|
|
486
|
-
* Decide how a finished run ended. A terminal signal the program persisted
|
|
487
|
-
* takes precedence over its exit code: a program that called ctx.done() and
|
|
488
|
-
* then crashed is done. Returns null for a failure (non-zero exit, no signal).
|
|
489
|
-
*/
|
|
490
|
-
function settle(projectDir, run) {
|
|
491
|
-
// Read state first: if the program left state.json corrupt, say so now
|
|
492
|
-
// rather than report an outcome (or start a repair) on top of it.
|
|
493
|
-
const state = loadState(projectDir);
|
|
494
|
-
if (run.terminalSignal)
|
|
495
|
-
return run.terminalSignal;
|
|
496
|
-
if (run.child.exitCode !== 0)
|
|
497
|
-
return null;
|
|
498
|
-
// Natural success without done() or yield(): if this run was the resumption
|
|
499
|
-
// of an earlier yield, that yield is now over — don't let its marker make
|
|
500
|
-
// the next run look resumed.
|
|
501
|
-
if (state.__trama_yield != null) {
|
|
502
|
-
delete state.__trama_yield;
|
|
503
|
-
writeFileSync(guardPath(projectDir, "state.json"), JSON.stringify(state, null, 2));
|
|
504
483
|
}
|
|
505
|
-
return { status: "done" };
|
|
506
484
|
}
|
|
507
485
|
/**
|
|
508
486
|
* Ask the LLM for a fix. The repair agent has tools, so it works in a
|
|
509
|
-
* throwaway copy of the project
|
|
510
|
-
*
|
|
511
|
-
*
|
|
487
|
+
* throwaway copy of the project that holds the program it is asked to fix —
|
|
488
|
+
* whatever it reads is real, whatever it writes is discarded; only the program
|
|
489
|
+
* text it returns is used. Bounded by its own timeout.
|
|
490
|
+
* Returns null (and records why) if no usable fix came back.
|
|
512
491
|
*/
|
|
513
492
|
async function requestRepair(options, input, repairErrors) {
|
|
514
493
|
return withTempDir("trama-repair-", async (tempDir) => {
|
|
515
|
-
|
|
494
|
+
copyDirInto(options.projectDir, tempDir);
|
|
495
|
+
writeFileSync(guardPath(tempDir, "program.ts"), input.programSource);
|
|
516
496
|
const controller = new AbortController();
|
|
517
497
|
const timer = setTimeout(() => controller.abort(), options.timeout);
|
|
518
498
|
try {
|
|
519
|
-
|
|
499
|
+
const fixed = await options.adapter.withCwd(tempDir).repair({ ...input, runtimeTypes: RUNTIME_TYPES }, controller.signal);
|
|
500
|
+
if (fixed.trim() === "")
|
|
501
|
+
throw new Error("The repair returned an empty program.");
|
|
502
|
+
if (fixed === input.programSource)
|
|
503
|
+
throw new Error("The repair returned the program unchanged.");
|
|
504
|
+
return fixed;
|
|
520
505
|
}
|
|
521
506
|
catch (err) {
|
|
522
507
|
repairErrors.push(err instanceof Error ? err.message : String(err));
|
|
@@ -528,92 +513,112 @@ async function requestRepair(options, input, repairErrors) {
|
|
|
528
513
|
});
|
|
529
514
|
}
|
|
530
515
|
/**
|
|
531
|
-
*
|
|
532
|
-
*
|
|
533
|
-
*
|
|
516
|
+
* Try a proposed fix: run it on a private copy of the project (and of the
|
|
517
|
+
* shared workspace). Only if it works does anything reach the real ones — the
|
|
518
|
+
* fix becomes program.ts, and what the run wrote is merged back. A fix that
|
|
519
|
+
* fails, or a runner that is stopped half-way, leaves the project exactly as
|
|
520
|
+
* it was, because it was never touched.
|
|
534
521
|
*/
|
|
535
|
-
async function
|
|
536
|
-
const { projectDir } = options;
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
522
|
+
async function tryFix(options, fixed) {
|
|
523
|
+
const { projectDir, workspaceDir } = options;
|
|
524
|
+
const inStagedProject = (stagedWorkspace) => withStagedCopy(projectDir, async (stagedProject) => {
|
|
525
|
+
writeFileSync(guardPath(stagedProject, "program.ts"), fixed);
|
|
526
|
+
let run;
|
|
527
|
+
try {
|
|
528
|
+
run = await runProgramOnce({
|
|
529
|
+
...options, projectDir: stagedProject, adapter: options.adapter.withCwd(stagedProject), workspaceDir: stagedWorkspace,
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
catch (err) {
|
|
533
|
+
// The copy could not be run at all, or was left unusable. Either way this fix did not work.
|
|
534
|
+
run = { outcome: null, failure: `The repaired program could not be run: ${err instanceof Error ? err.message : err}` };
|
|
535
|
+
}
|
|
536
|
+
return { commit: run.outcome !== null, value: run };
|
|
545
537
|
});
|
|
538
|
+
const run = workspaceDir
|
|
539
|
+
? await withStagedCopy(workspaceDir, async (stagedWorkspace) => {
|
|
540
|
+
const value = await inStagedProject(stagedWorkspace);
|
|
541
|
+
return { commit: value.outcome !== null, value };
|
|
542
|
+
})
|
|
543
|
+
: await inStagedProject(undefined);
|
|
544
|
+
// The merge above carries over what the run changed; the fix itself was
|
|
545
|
+
// written before the run started, so it is installed explicitly.
|
|
546
|
+
if (run.outcome)
|
|
547
|
+
writeFileSync(guardPath(projectDir, "program.ts"), fixed);
|
|
548
|
+
return run;
|
|
546
549
|
}
|
|
547
550
|
/**
|
|
548
|
-
* Run a program to an outcome. If it crashes, ask the LLM to repair it and
|
|
549
|
-
* the fix — up to maxRepairAttempts times.
|
|
550
|
-
* trace: the project and the shared workspace are as they were before it ran.
|
|
551
|
+
* Run a program to an outcome. If it crashes, ask the LLM to repair it and try
|
|
552
|
+
* the fix — up to maxRepairAttempts times.
|
|
551
553
|
*/
|
|
552
554
|
async function executeProgram(options) {
|
|
553
555
|
const { projectDir, maxRepairAttempts } = options;
|
|
554
|
-
const
|
|
555
|
-
const
|
|
556
|
-
if (outcome)
|
|
557
|
-
return outcome;
|
|
558
|
-
let lastError =
|
|
559
|
-
if (maxRepairAttempts === 0)
|
|
560
|
-
return
|
|
561
|
-
|
|
562
|
-
// Each attempt builds on the previous one's source, even though a failed
|
|
563
|
-
// attempt is rolled back out of the real project.
|
|
556
|
+
const failed = (reason) => ({ result: { status: "failed", reason } });
|
|
557
|
+
const firstRun = await runProgramOnce(options);
|
|
558
|
+
if (firstRun.outcome)
|
|
559
|
+
return { result: firstRun.outcome };
|
|
560
|
+
let lastError = firstRun.failure;
|
|
561
|
+
if (maxRepairAttempts === 0)
|
|
562
|
+
return failed(`Program failed (repair disabled): ${lastError}`);
|
|
563
|
+
// Each attempt builds on the previous one's source, though a fix that failed never reached the project.
|
|
564
564
|
let currentSource = readFileSync(guardPath(projectDir, "program.ts"), "utf-8");
|
|
565
565
|
const repairErrors = [];
|
|
566
566
|
const repairDetails = () => repairErrors.length > 0
|
|
567
567
|
? `\nRepair errors:\n${repairErrors.map((e, i) => ` [${i + 1}] ${e}`).join("\n")}` : "";
|
|
568
568
|
for (let attempt = 0; attempt < maxRepairAttempts; attempt++) {
|
|
569
569
|
const fixed = await requestRepair(options, { programSource: currentSource, error: lastError }, repairErrors);
|
|
570
|
-
if (!fixed)
|
|
571
|
-
return
|
|
572
|
-
}
|
|
570
|
+
if (!fixed)
|
|
571
|
+
return failed(`Failed after ${attempt + 1} repair attempt(s): ${lastError}${repairDetails()}`);
|
|
573
572
|
currentSource = fixed;
|
|
574
|
-
const
|
|
575
|
-
if (
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
options.onRepair?.(attempt, maxRepairAttempts, lastError);
|
|
579
|
-
}
|
|
580
|
-
catch (bookkeepingErr) {
|
|
581
|
-
console.warn(`[trama] repair bookkeeping failed: ${bookkeepingErr instanceof Error ? bookkeepingErr.message : bookkeepingErr}`);
|
|
582
|
-
}
|
|
583
|
-
return applied.outcome;
|
|
584
|
-
}
|
|
585
|
-
lastError = applied.error;
|
|
573
|
+
const run = await tryFix(options, fixed);
|
|
574
|
+
if (run.outcome)
|
|
575
|
+
return { result: run.outcome, repair: { attempt, error: lastError } };
|
|
576
|
+
lastError = run.failure;
|
|
586
577
|
}
|
|
587
|
-
return
|
|
578
|
+
return failed(`Failed after ${maxRepairAttempts} repair attempts: ${lastError}${repairDetails()}`);
|
|
588
579
|
}
|
|
589
|
-
// ---
|
|
590
|
-
const
|
|
580
|
+
// --- Validating a candidate program (used by create and update) ---
|
|
581
|
+
const VALIDATION_READY_GRACE_MS = 2_000;
|
|
591
582
|
/**
|
|
592
|
-
* Validate a
|
|
593
|
-
*
|
|
594
|
-
*
|
|
595
|
-
*
|
|
583
|
+
* Validate a candidate program.ts for a project without touching the project:
|
|
584
|
+
* run it (with repair) in a throwaway copy. Returns the program that worked —
|
|
585
|
+
* the candidate itself, or a repaired version of it, with the failure that was
|
|
586
|
+
* repaired. Throws if it cannot be made to run.
|
|
587
|
+
*
|
|
588
|
+
* Only the project's own files are shielded. What the program does beyond
|
|
589
|
+
* them — network calls, shell commands, other projects it runs — is real.
|
|
596
590
|
*/
|
|
597
|
-
export async function
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
const
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
stopOnReady: { graceMs:
|
|
607
|
-
onRepair(_attempt, _max, error) {
|
|
608
|
-
appendHistoryIndex(projectDir, { reason: `${reason}-repair`, timestamp: new Date().toISOString(), error });
|
|
609
|
-
},
|
|
591
|
+
export async function validateProgram(projectDir, adapter, candidate, options) {
|
|
592
|
+
return withTempDir("trama-validate-", async (trialDir) => {
|
|
593
|
+
copyDirInto(projectDir, trialDir);
|
|
594
|
+
const programPath = guardPath(trialDir, "program.ts");
|
|
595
|
+
writeFileSync(programPath, candidate);
|
|
596
|
+
const { result, repair } = await executeProgram({
|
|
597
|
+
...options,
|
|
598
|
+
projectDir: trialDir,
|
|
599
|
+
adapter: adapter.withCwd(trialDir),
|
|
600
|
+
stopOnReady: { graceMs: VALIDATION_READY_GRACE_MS },
|
|
610
601
|
});
|
|
611
602
|
if (result.status === "failed") {
|
|
612
603
|
throw new Error(`Program failed: ${result.reason}`);
|
|
613
604
|
}
|
|
614
|
-
|
|
605
|
+
return { source: readFileSync(programPath, "utf-8"), repairedError: repair?.error };
|
|
615
606
|
});
|
|
616
607
|
}
|
|
608
|
+
/**
|
|
609
|
+
* Make a validated program the project's program.ts and record it as a new
|
|
610
|
+
* version. A repair made while validating is not a version of its own — it is
|
|
611
|
+
* noted in the history index only.
|
|
612
|
+
*/
|
|
613
|
+
export function installValidatedProgram(projectDir, validated, reason, prompt) {
|
|
614
|
+
writeFileSync(guardPath(projectDir, "program.ts"), validated.source);
|
|
615
|
+
if (validated.repairedError) {
|
|
616
|
+
appendHistoryIndex(projectDir, {
|
|
617
|
+
reason: `${reason}-repair`, timestamp: new Date().toISOString(), error: validated.repairedError,
|
|
618
|
+
});
|
|
619
|
+
}
|
|
620
|
+
copyToHistory(projectDir, reason, prompt);
|
|
621
|
+
}
|
|
617
622
|
// --- Core execution ---
|
|
618
623
|
export async function runProgram(options) {
|
|
619
624
|
const { projectDir } = options;
|
|
@@ -630,7 +635,7 @@ export async function runProgram(options) {
|
|
|
630
635
|
if (!Number.isInteger(maxRepairAttempts) || maxRepairAttempts < 0) {
|
|
631
636
|
throw new Error(`Invalid maxRepairAttempts: ${maxRepairAttempts}. Must be a non-negative integer.`);
|
|
632
637
|
}
|
|
633
|
-
|
|
638
|
+
const { result, repair } = await executeProgram({
|
|
634
639
|
projectDir,
|
|
635
640
|
adapter: new PiAdapter(config, projectDir),
|
|
636
641
|
maxRepairAttempts,
|
|
@@ -638,12 +643,18 @@ export async function runProgram(options) {
|
|
|
638
643
|
maxIterations: config.defaultMaxIterations,
|
|
639
644
|
argsOverride: options.args,
|
|
640
645
|
workspaceDir: options.workspaceDir,
|
|
641
|
-
onRepair(attempt, max, error) {
|
|
642
|
-
// Runs after the repaired program's own run, so this lands at the end of its log.
|
|
643
|
-
const entry = { ts: Date.now(), message: `Repair attempt ${attempt + 1}/${max}`, data: { error } };
|
|
644
|
-
appendFileSync(guardPath(projectDir, join("logs", "latest.jsonl")), JSON.stringify(entry) + "\n");
|
|
645
|
-
console.log(`[trama] Repair attempt ${attempt + 1}/${max}`);
|
|
646
|
-
copyToHistory(projectDir, "repair", error);
|
|
647
|
-
},
|
|
648
646
|
});
|
|
647
|
+
if (repair) {
|
|
648
|
+
// The program is fixed and has run; failing to write this down must not turn that into an error.
|
|
649
|
+
try {
|
|
650
|
+
const entry = { ts: Date.now(), message: `Repair attempt ${repair.attempt + 1}/${maxRepairAttempts}`, data: { error: repair.error } };
|
|
651
|
+
appendFileSync(guardPath(projectDir, join("logs", "latest.jsonl")), JSON.stringify(entry) + "\n");
|
|
652
|
+
console.log(`[trama] Repair attempt ${repair.attempt + 1}/${maxRepairAttempts}`);
|
|
653
|
+
copyToHistory(projectDir, "repair", repair.error);
|
|
654
|
+
}
|
|
655
|
+
catch (err) {
|
|
656
|
+
console.warn(`[trama] repair bookkeeping failed: ${err instanceof Error ? err.message : err}`);
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
return result;
|
|
649
660
|
}
|
package/dist/tools.d.ts
CHANGED
|
@@ -1,6 +1,4 @@
|
|
|
1
1
|
import type { Tools } from "./types.js";
|
|
2
|
-
import { cappedBuffer } from "./child-process.js";
|
|
3
|
-
export { cappedBuffer };
|
|
4
2
|
export interface ToolsWithCleanup extends Tools {
|
|
5
3
|
/** Kill every shell command still running, and anything they left in the background. */
|
|
6
4
|
killActiveShells(): void;
|
package/dist/tools.js
CHANGED
|
@@ -2,8 +2,8 @@ import { spawn } from "child_process";
|
|
|
2
2
|
import { readFileSync, writeFileSync, mkdirSync } from "fs";
|
|
3
3
|
import { resolve, dirname } from "path";
|
|
4
4
|
import { guardPath } from "./path-guard.js";
|
|
5
|
-
import {
|
|
6
|
-
|
|
5
|
+
import { signalGroup, superviseChild } from "./child-process.js";
|
|
6
|
+
import { untilSettled } from "./lifetime.js";
|
|
7
7
|
const MAX_FETCH_BODY = 10 * 1024 * 1024; // 10 MB
|
|
8
8
|
const DEFAULT_SHELL_TIMEOUT = 30_000;
|
|
9
9
|
const GROUP_SWEEP_MS = 250;
|
|
@@ -11,11 +11,20 @@ export function createTools(projectDir, signal) {
|
|
|
11
11
|
const normalizedProjectDir = resolve(projectDir);
|
|
12
12
|
// Each shell command leads its own process group, so background processes it
|
|
13
13
|
// starts stay killable after the shell itself exits. A group is tracked from
|
|
14
|
-
// spawn until it has no members left
|
|
15
|
-
// exited — only those are probed, since a group that is still starting
|
|
16
|
-
// may not be visible yet.
|
|
14
|
+
// spawn until it has no members left. `shellExited` marks groups whose shell
|
|
15
|
+
// has exited — only those are probed, since a group that is still starting
|
|
16
|
+
// up may not be visible yet. `forget` tells the process-lifetime guard the
|
|
17
|
+
// group no longer needs killing if this process dies.
|
|
17
18
|
const groups = new Map();
|
|
18
19
|
let sweeper = null;
|
|
20
|
+
const untrack = (pgid) => {
|
|
21
|
+
groups.get(pgid)?.forget();
|
|
22
|
+
groups.delete(pgid);
|
|
23
|
+
};
|
|
24
|
+
// Shell commands must not see the bridge's address or the init file (which
|
|
25
|
+
// holds its secret). A top-level runner has neither in its environment, but
|
|
26
|
+
// a runner inside a program — a session's creator — inherits both.
|
|
27
|
+
const { TRAMA_PORT: _port, TRAMA_INIT: _init, ...shellEnv } = process.env;
|
|
19
28
|
const stopSweeping = () => {
|
|
20
29
|
if (sweeper)
|
|
21
30
|
clearInterval(sweeper);
|
|
@@ -24,21 +33,22 @@ export function createTools(projectDir, signal) {
|
|
|
24
33
|
/** Forget groups that have fully exited, so a recycled pid is never signalled. */
|
|
25
34
|
const sweep = () => {
|
|
26
35
|
let pending = false;
|
|
27
|
-
for (const [pgid,
|
|
28
|
-
if (!shellExited)
|
|
36
|
+
for (const [pgid, group] of groups) {
|
|
37
|
+
if (!group.shellExited)
|
|
29
38
|
continue;
|
|
30
39
|
if (signalGroup(pgid, 0))
|
|
31
40
|
pending = true;
|
|
32
41
|
else
|
|
33
|
-
|
|
42
|
+
untrack(pgid);
|
|
34
43
|
}
|
|
35
44
|
if (!pending)
|
|
36
45
|
stopSweeping();
|
|
37
46
|
};
|
|
38
47
|
const markShellExited = (pgid) => {
|
|
39
|
-
|
|
48
|
+
const group = groups.get(pgid);
|
|
49
|
+
if (!group)
|
|
40
50
|
return; // already killed by killActiveShells
|
|
41
|
-
|
|
51
|
+
group.shellExited = true;
|
|
42
52
|
if (!sweeper) {
|
|
43
53
|
sweeper = setInterval(sweep, GROUP_SWEEP_MS);
|
|
44
54
|
sweeper.unref();
|
|
@@ -46,9 +56,10 @@ export function createTools(projectDir, signal) {
|
|
|
46
56
|
};
|
|
47
57
|
return {
|
|
48
58
|
killActiveShells() {
|
|
49
|
-
for (const pgid of groups.keys())
|
|
59
|
+
for (const pgid of [...groups.keys()]) {
|
|
50
60
|
signalGroup(pgid, "SIGKILL");
|
|
51
|
-
|
|
61
|
+
untrack(pgid);
|
|
62
|
+
}
|
|
52
63
|
stopSweeping();
|
|
53
64
|
},
|
|
54
65
|
async read(path) {
|
|
@@ -71,12 +82,14 @@ export function createTools(projectDir, signal) {
|
|
|
71
82
|
const cwd = options.cwd ? guardPath(normalizedProjectDir, options.cwd) : normalizedProjectDir;
|
|
72
83
|
const child = spawn("sh", ["-c", command], {
|
|
73
84
|
cwd,
|
|
85
|
+
env: shellEnv,
|
|
74
86
|
stdio: ["pipe", "pipe", "pipe"],
|
|
75
87
|
detached: true,
|
|
76
88
|
});
|
|
77
89
|
const pgid = child.pid;
|
|
78
|
-
if (pgid)
|
|
79
|
-
groups.set(pgid, false);
|
|
90
|
+
if (pgid) {
|
|
91
|
+
groups.set(pgid, { shellExited: false, forget: untilSettled(() => signalGroup(pgid, "SIGKILL")) });
|
|
92
|
+
}
|
|
80
93
|
try {
|
|
81
94
|
const exit = await superviseChild(child, { timeout: options.timeout ?? DEFAULT_SHELL_TIMEOUT });
|
|
82
95
|
if (pgid)
|
|
@@ -90,7 +103,7 @@ export function createTools(projectDir, signal) {
|
|
|
90
103
|
catch (spawnError) {
|
|
91
104
|
// Failed to start (e.g. cwd does not exist) — a result, not an exception.
|
|
92
105
|
if (pgid)
|
|
93
|
-
|
|
106
|
+
untrack(pgid);
|
|
94
107
|
return { exitCode: 1, stdout: "", stderr: spawnError.message };
|
|
95
108
|
}
|
|
96
109
|
},
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trama-dev/runtime",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"exports": {
|
|
6
6
|
".": {
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
"license": "MIT",
|
|
23
23
|
"repository": {
|
|
24
24
|
"type": "git",
|
|
25
|
-
"url": "https://github.com/NaNhkNaN/trama.git",
|
|
25
|
+
"url": "git+https://github.com/NaNhkNaN/trama.git",
|
|
26
26
|
"directory": "packages/runtime"
|
|
27
27
|
},
|
|
28
28
|
"homepage": "https://github.com/NaNhkNaN/trama",
|
|
@@ -38,6 +38,6 @@
|
|
|
38
38
|
},
|
|
39
39
|
"dependencies": {
|
|
40
40
|
"@earendil-works/pi-coding-agent": "1.5.2",
|
|
41
|
-
"tsx": "
|
|
41
|
+
"tsx": "4.23.15"
|
|
42
42
|
}
|
|
43
43
|
}
|