@trama-dev/runtime 0.1.5 → 0.2.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/runner.js CHANGED
@@ -1,183 +1,135 @@
1
- import { createServer } from "http";
2
1
  import { spawn } from "child_process";
3
- import { readFileSync, writeFileSync, appendFileSync, readdirSync, copyFileSync, mkdirSync, existsSync, statSync, symlinkSync, rmSync, lstatSync, readlinkSync, cpSync, mkdtempSync, openSync, closeSync, } from "fs";
4
- import { join, dirname } from "path";
2
+ import { readFileSync, writeFileSync, appendFileSync, readdirSync, copyFileSync, mkdirSync, existsSync, statSync, symlinkSync, rmSync, lstatSync, readlinkSync, cpSync, mkdtempSync, openSync, closeSync, renameSync, } from "fs";
3
+ import { join, dirname, basename, resolve } from "path";
5
4
  import { homedir, tmpdir } from "os";
6
5
  import { fileURLToPath } from "url";
7
- import { StringDecoder } from "string_decoder";
6
+ import { randomBytes } from "crypto";
8
7
  import { PiAdapter } from "./pi-adapter.js";
9
8
  import { createContext } from "./context.js";
10
9
  import { createAgent } from "./agent.js";
11
- import { createTools, cappedBuffer } from "./tools.js";
12
- import { guardPath } from "./path-guard.js";
13
- import { assertSerializable } from "./serializable.js";
10
+ import { createTools } from "./tools.js";
14
11
  import { createWorkspace } from "./workspace.js";
15
- // --- Module resolution for child processes ---
12
+ import { guardPath } from "./path-guard.js";
13
+ import { superviseChild } from "./child-process.js";
14
+ import { createIPCServer, listen, closeServer } from "./ipc-server.js";
15
+ // --- Locating the runtime itself ---
16
+ /** The installed @trama-dev/runtime package — this file lives in its dist/. */
17
+ const RUNTIME_PACKAGE_DIR = dirname(dirname(fileURLToPath(import.meta.url)));
18
+ /** tsx executes program.ts. Resolved through the module system, so any install layout works. */
19
+ const TSX_CLI = fileURLToPath(import.meta.resolve("tsx/cli"));
16
20
  /**
17
- * Find the node_modules directory that contains @trama-dev/runtime.
18
- * Works for both global install and monorepo development.
21
+ * The @trama-dev packages a program.ts can import, and where they are installed.
22
+ * The runtime always; the session layer when it is installed alongside (as it
23
+ * is with the CLI). The runtime never imports the session layer itself — it
24
+ * only makes it reachable from projects.
19
25
  */
20
- function findRuntimeNodeModules() {
21
- let dir = dirname(fileURLToPath(import.meta.url));
22
- while (dir !== dirname(dir)) {
23
- const candidate = join(dir, "node_modules");
24
- if (existsSync(join(candidate, "@trama-dev", "runtime"))) {
25
- return candidate;
26
- }
27
- dir = dirname(dir);
28
- }
29
- throw new Error("Could not locate node_modules containing @trama-dev/runtime");
26
+ const IMPORTABLE_PACKAGES = { runtime: RUNTIME_PACKAGE_DIR };
27
+ try {
28
+ // Resolves to <package>/dist/index.js
29
+ IMPORTABLE_PACKAGES.session = dirname(dirname(fileURLToPath(import.meta.resolve("@trama-dev/session"))));
30
30
  }
31
- const TRAMA_NODE_MODULES = findRuntimeNodeModules();
32
- const TSX_CLI = join(TRAMA_NODE_MODULES, "tsx", "dist", "cli.mjs");
33
- export const PI_VERSION = JSON.parse(readFileSync(join(TRAMA_NODE_MODULES, "@mariozechner", "pi-coding-agent", "package.json"), "utf-8")).version;
31
+ catch { /* not installed — programs simply cannot import it */ }
32
+ // --- Project scaffolding ---
34
33
  /**
35
- * Ensure the project directory has a node_modules symlink to @trama-dev/runtime.
36
- * Replaces any existing symlink whose target differs (including user-managed ones).
37
- * Only refuses to touch a real directory/file to avoid destroying user content.
34
+ * Point the project's node_modules/@trama-dev/<name> at an installed package,
35
+ * so program.ts can import it. Replaces any existing symlink whose target
36
+ * differs (including user-managed ones). Only refuses to touch a real
37
+ * directory/file to avoid destroying user content.
38
38
  */
39
- function ensureRuntimeLink(projectDir) {
40
- // node_modules/@trama-dev/runtime is deliberately a symlink pointing OUTSIDE
41
- // the project (to the global trama install). Do not apply guardPath here.
39
+ function linkPackage(projectDir, name, target) {
40
+ // The link deliberately points OUTSIDE the project — do not apply guardPath here.
42
41
  const linkDir = join(projectDir, "node_modules", "@trama-dev");
43
- const linkPath = join(linkDir, "runtime");
44
- const target = join(TRAMA_NODE_MODULES, "@trama-dev", "runtime");
42
+ const linkPath = join(linkDir, name);
45
43
  try {
46
- const stat = lstatSync(linkPath);
47
- if (stat.isSymbolicLink()) {
48
- // Symlink exists — replace if target doesn't match
49
- if (readlinkSync(linkPath) === target)
50
- return;
51
- rmSync(linkPath);
52
- }
53
- else {
54
- // Real directory/file — not ours, refuse to destroy it
44
+ if (!lstatSync(linkPath).isSymbolicLink()) {
55
45
  throw new Error(`${linkPath} exists and is not a symlink. ` +
56
46
  `trama needs this path for module resolution. ` +
57
47
  `Remove it manually or rename it to proceed.`);
58
48
  }
49
+ if (readlinkSync(linkPath) === target)
50
+ return;
51
+ rmSync(linkPath);
59
52
  }
60
53
  catch (err) {
61
54
  if (err.code !== "ENOENT")
62
55
  throw err;
63
- // ENOENT — path doesn't exist, proceed to create
64
56
  }
65
57
  mkdirSync(linkDir, { recursive: true });
66
58
  symlinkSync(target, linkPath, "dir");
67
59
  }
68
- /**
69
- * Ensure project has ESM package.json and .gitignore.
70
- * If package.json exists but lacks "type": "module", patches it in.
71
- */
72
- export function ensureProjectScaffold(projectDir) {
60
+ /** Make sure package.json exists and declares an ES module (program.ts uses top-level await). */
61
+ function ensureModulePackageJson(projectDir) {
73
62
  const pkgPath = guardPath(projectDir, "package.json");
74
- if (existsSync(pkgPath)) {
75
- let pkg;
76
- try {
77
- pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
78
- }
79
- catch (err) {
80
- throw new Error(`Malformed package.json at ${pkgPath}. ` +
81
- `trama will not overwrite it automatically; fix or remove it and try again.\n` +
82
- `Parse error: ${err instanceof Error ? err.message : err}`);
83
- }
84
- if (typeof pkg !== "object" || pkg === null || Array.isArray(pkg)) {
85
- throw new Error(`Malformed package.json at ${pkgPath} — expected a JSON object but got ${Array.isArray(pkg) ? "an array" : typeof pkg}. trama will not overwrite it automatically; fix or remove it and try again.`);
86
- }
87
- const pkgObj = pkg;
88
- if (pkgObj.type !== "module") {
89
- pkgObj.type = "module";
90
- writeFileSync(pkgPath, JSON.stringify(pkgObj, null, 2));
91
- }
92
- }
93
- else {
63
+ if (!existsSync(pkgPath)) {
94
64
  writeFileSync(pkgPath, JSON.stringify({ type: "module" }, null, 2));
65
+ return;
95
66
  }
96
- const giPath = guardPath(projectDir, ".gitignore");
97
- const requiredEntries = ["node_modules/", "state.json", "logs/", "history/"];
98
- if (existsSync(giPath)) {
99
- const existing = readFileSync(giPath, "utf-8");
100
- const missing = requiredEntries.filter(e => !existing.split("\n").some(line => line.trim() === e));
101
- if (missing.length > 0) {
102
- const suffix = existing.endsWith("\n") ? "" : "\n";
103
- writeFileSync(giPath, existing + suffix + missing.join("\n") + "\n");
104
- }
67
+ const advice = "trama will not overwrite it automatically; fix or remove it and try again.";
68
+ let pkg;
69
+ try {
70
+ pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
71
+ }
72
+ catch (err) {
73
+ throw new Error(`Malformed package.json at ${pkgPath}. ${advice}\n` +
74
+ `Parse error: ${err instanceof Error ? err.message : err}`);
75
+ }
76
+ if (typeof pkg !== "object" || pkg === null || Array.isArray(pkg)) {
77
+ throw new Error(`Malformed package.json at ${pkgPath} — expected a JSON object but got ${Array.isArray(pkg) ? "an array" : typeof pkg}. ${advice}`);
105
78
  }
106
- else {
107
- writeFileSync(giPath, requiredEntries.join("\n") + "\n");
79
+ const pkgObj = pkg;
80
+ if (pkgObj.type !== "module") {
81
+ pkgObj.type = "module";
82
+ writeFileSync(pkgPath, JSON.stringify(pkgObj, null, 2));
108
83
  }
109
84
  }
110
- // --- Runtime type definitions (included in system prompts) ---
85
+ /** Make sure .gitignore excludes what trama generates, without disturbing existing entries. */
86
+ function ensureGitignore(projectDir) {
87
+ const giPath = guardPath(projectDir, ".gitignore");
88
+ const required = ["node_modules/", "state.json", "logs/", "history/"];
89
+ const existing = existsSync(giPath) ? readFileSync(giPath, "utf-8") : "";
90
+ const present = new Set(existing.split("\n").map(line => line.trim()));
91
+ const missing = required.filter(entry => !present.has(entry));
92
+ if (missing.length === 0)
93
+ return;
94
+ const separator = existing === "" || existing.endsWith("\n") ? "" : "\n";
95
+ writeFileSync(giPath, existing + separator + missing.join("\n") + "\n");
96
+ }
111
97
  /**
112
- * Simplified API reference for LLM system prompts.
113
- * NOT the canonical type definitions (those live in types.ts).
114
- * Kept as a readable string rather than auto-generated, because the LLM
115
- * needs a concise reference, not the full implementation types.
116
- * If types.ts changes, review whether this summary needs updating.
98
+ * Everything a project directory needs around program.ts before it can run:
99
+ * history/ and logs/, an ESM package.json, .gitignore entries, and links to the
100
+ * @trama-dev packages it can import.
101
+ * Idempotent — called before every run, so a freshly cloned project just works.
117
102
  */
118
- export const RUNTIME_TYPES = `// @trama-dev/runtime - Complete API
119
-
120
- export interface Ctx {
121
- input: { prompt: string; args: Record<string, unknown> };
122
- state: Record<string, unknown>;
123
- iteration: number;
124
- maxIterations: number;
125
- readonly resumed: boolean;
126
- readonly yieldReason: string | null;
127
- log(message: string, data?: Record<string, unknown>): Promise<void>;
128
- ready(data?: Record<string, unknown>): Promise<void>;
129
- checkpoint(): Promise<void>;
130
- done(result?: Record<string, unknown>): Promise<void>;
131
- yield(reason: string): Promise<never>;
132
- }
133
-
134
- export interface Agent {
135
- instruct(prompt: string, options?: { system?: string }): Promise<string>;
136
- /** @deprecated Use instruct() instead */
137
- ask(prompt: string, options?: { system?: string }): Promise<string>;
138
- generate<T>(input: {
139
- prompt: string;
140
- schema: Record<string, string>;
141
- system?: string;
142
- }): Promise<T>;
143
- }
144
-
145
- export interface ShellResult {
146
- exitCode: number;
147
- stdout: string;
148
- stderr: string;
149
- }
150
-
151
- export interface Tools {
152
- read(path: string): Promise<string>;
153
- write(path: string, content: string): Promise<void>;
154
- shell(command: string, options?: { cwd?: string; timeout?: number }): Promise<ShellResult>;
155
- fetch(url: string, options?: {
156
- method?: string;
157
- headers?: Record<string, string>;
158
- body?: string;
159
- }): Promise<{ status: number; body: string; headers: Record<string, string> }>;
160
- }
161
-
162
- export type ObserveResult = string | Array<{ path: string; content: string }>;
163
-
164
- export interface Workspace {
165
- read(path: string): Promise<string>;
166
- write(path: string, content: string): Promise<void>;
167
- list(pattern: string): Promise<string[]>;
168
- observe(pattern: string, options?: { expect?: number; timeout?: number }): Promise<ObserveResult>;
103
+ export function ensureProjectScaffold(projectDir) {
104
+ mkdirSync(guardPath(projectDir, "history"), { recursive: true });
105
+ mkdirSync(guardPath(projectDir, "logs"), { recursive: true });
106
+ ensureModulePackageJson(projectDir);
107
+ ensureGitignore(projectDir);
108
+ for (const [name, target] of Object.entries(IMPORTABLE_PACKAGES))
109
+ linkPackage(projectDir, name, target);
169
110
  }
170
-
171
- export declare const ctx: Ctx;
172
- export declare const agent: Agent;
173
- export declare const tools: Tools;
174
- export declare const workspace: Workspace;`;
111
+ // --- The API reference shown to the LLM ---
112
+ /**
113
+ * The program-facing API, as shown to the LLM when it writes or repairs a
114
+ * program. This is the declaration file generated from types.ts, so the prompt
115
+ * cannot drift from the real API — doc comments included.
116
+ */
117
+ export const RUNTIME_TYPES = [
118
+ "// @trama-dev/runtime - Complete API",
119
+ readFileSync(new URL("./types.d.ts", import.meta.url), "utf-8").trim(),
120
+ [
121
+ "export declare const ctx: Ctx;",
122
+ "export declare const agent: Agent;",
123
+ "export declare const tools: Tools;",
124
+ "export declare const workspace: Workspace;",
125
+ ].join("\n"),
126
+ ].join("\n\n");
175
127
  // --- Config & state loaders ---
176
128
  export function loadConfig() {
177
129
  const configPath = join(homedir(), ".trama", "config.json");
178
130
  const defaults = {
179
131
  provider: "anthropic",
180
- model: "claude-opus-4-6",
132
+ model: "claude-opus-5-5",
181
133
  maxRepairAttempts: 3,
182
134
  defaultTimeout: 300_000,
183
135
  defaultMaxIterations: 100,
@@ -218,6 +170,16 @@ export function loadConfig() {
218
170
  }
219
171
  return merged;
220
172
  }
173
+ /** The global config, with the model/provider a project was created with taking precedence. */
174
+ export function loadProjectConfig(projectDir) {
175
+ const config = loadConfig();
176
+ const meta = JSON.parse(readFileSync(guardPath(projectDir, "meta.json"), "utf-8"));
177
+ if (meta.model)
178
+ config.model = meta.model;
179
+ if (meta.provider)
180
+ config.provider = meta.provider;
181
+ return config;
182
+ }
221
183
  export function loadState(projectDir) {
222
184
  const statePath = guardPath(projectDir, "state.json");
223
185
  if (!existsSync(statePath))
@@ -239,363 +201,35 @@ export function loadState(projectDir) {
239
201
  }
240
202
  return parsed;
241
203
  }
242
- // --- IPC Server ---
243
- const MAX_IPC_BODY = 50 * 1024 * 1024; // 50 MB
244
- /** Validate required fields in IPC request body. Returns error message or null. */
245
- function validateIPC(data, fields) {
246
- for (const [name, type] of Object.entries(fields)) {
247
- const val = data[name];
248
- if (type === "object") {
249
- if (typeof val !== "object" || val === null || Array.isArray(val)) {
250
- return `Missing or invalid field: ${name} (expected object)`;
251
- }
252
- }
253
- else if (typeof val !== type) {
254
- return `Missing or invalid field: ${name} (expected ${type})`;
255
- }
256
- }
257
- return null;
258
- }
259
- function createIPCServer(ctx, agentImpl, toolsImpl, workspaceImpl, signalTracker) {
260
- return createServer((req, res) => {
261
- if (req.method !== "POST") {
262
- res.writeHead(405);
263
- res.end("Method not allowed");
264
- return;
265
- }
266
- const chunks = [];
267
- let byteCount = 0;
268
- let overflow = false;
269
- req.on("data", (chunk) => {
270
- if (overflow)
271
- return;
272
- chunks.push(chunk);
273
- byteCount += chunk.length;
274
- if (byteCount > MAX_IPC_BODY) {
275
- overflow = true;
276
- res.writeHead(413);
277
- res.end("IPC request body exceeds 50MB limit");
278
- req.destroy();
279
- }
280
- });
281
- req.on("end", async () => {
282
- if (overflow)
283
- return;
284
- try {
285
- const data = JSON.parse(Buffer.concat(chunks).toString("utf-8"));
286
- let result;
287
- // Per-endpoint field validation
288
- const validationRules = {
289
- "/agent/ask": { prompt: "string" },
290
- "/agent/generate": { prompt: "string", schema: "object" },
291
- "/tools/read": { path: "string" },
292
- "/tools/write": { path: "string", content: "string" },
293
- "/tools/shell": { command: "string" },
294
- "/tools/fetch": { url: "string" },
295
- "/ctx/checkpoint": { state: "object" },
296
- "/ctx/log": { message: "string" },
297
- "/ctx/done": { state: "object" },
298
- "/ctx/yield": { state: "object", reason: "string" },
299
- "/workspace/read": { path: "string" },
300
- "/workspace/write": { path: "string", content: "string" },
301
- "/workspace/list": { pattern: "string" },
302
- "/workspace/observe": { pattern: "string" },
303
- };
304
- const rules = req.url ? validationRules[req.url] : undefined;
305
- if (rules) {
306
- const validationError = validateIPC(data, rules);
307
- if (validationError) {
308
- res.writeHead(400);
309
- res.end(validationError);
310
- return;
311
- }
312
- }
313
- switch (req.url) {
314
- case "/agent/ask":
315
- result = await agentImpl.ask(data.prompt, { system: data.system });
316
- res.writeHead(200, { "Content-Type": "application/json" });
317
- res.end(JSON.stringify({ result }));
318
- break;
319
- case "/agent/generate":
320
- result = await agentImpl.generate(data);
321
- res.writeHead(200, { "Content-Type": "application/json" });
322
- res.end(JSON.stringify({ result }));
323
- break;
324
- case "/tools/read":
325
- result = await toolsImpl.read(data.path);
326
- res.writeHead(200, { "Content-Type": "application/json" });
327
- res.end(JSON.stringify({ result }));
328
- break;
329
- case "/tools/write":
330
- await toolsImpl.write(data.path, data.content);
331
- res.writeHead(200, { "Content-Type": "application/json" });
332
- res.end(JSON.stringify({ result: null }));
333
- break;
334
- case "/tools/shell":
335
- result = await toolsImpl.shell(data.command, { cwd: data.cwd, timeout: data.timeout });
336
- res.writeHead(200, { "Content-Type": "application/json" });
337
- res.end(JSON.stringify({ result }));
338
- break;
339
- case "/tools/fetch":
340
- result = await toolsImpl.fetch(data.url, {
341
- method: data.method, headers: data.headers, body: data.body,
342
- });
343
- res.writeHead(200, { "Content-Type": "application/json" });
344
- res.end(JSON.stringify({ result }));
345
- break;
346
- case "/ctx/checkpoint":
347
- assertSerializable(data.state, "ctx.state");
348
- ctx.state = data.state;
349
- await ctx.checkpoint();
350
- res.writeHead(200, { "Content-Type": "application/json" });
351
- res.end(JSON.stringify({ result: null }));
352
- break;
353
- case "/ctx/log":
354
- await ctx.log(data.message, data.data);
355
- res.writeHead(200, { "Content-Type": "application/json" });
356
- res.end(JSON.stringify({ result: null }));
357
- break;
358
- case "/ctx/ready":
359
- if (data.data !== undefined && (typeof data.data !== "object" || data.data === null || Array.isArray(data.data))) {
360
- res.writeHead(400);
361
- res.end("Invalid field: data (expected object or undefined)");
362
- break;
363
- }
364
- await ctx.ready(data.data);
365
- res.writeHead(200, { "Content-Type": "application/json" });
366
- res.end(JSON.stringify({ result: null }));
367
- break;
368
- case "/ctx/done":
369
- assertSerializable(data.state, "ctx.state");
370
- ctx.state = data.state;
371
- await ctx.done(data.result);
372
- if (signalTracker)
373
- signalTracker.doneCalled = true;
374
- res.writeHead(200, { "Content-Type": "application/json" });
375
- res.end(JSON.stringify({ result: null }));
376
- break;
377
- case "/ctx/yield":
378
- assertSerializable(data.state, "ctx.state");
379
- ctx.state = data.state;
380
- await ctx.yield(data.reason);
381
- if (signalTracker)
382
- signalTracker.yieldCalled = true;
383
- // yield() calls process.exit(0) on the server-side context,
384
- // but in IPC mode we just persist and respond — the client exits.
385
- res.writeHead(200, { "Content-Type": "application/json" });
386
- res.end(JSON.stringify({ result: null }));
387
- break;
388
- case "/workspace/read":
389
- if (!workspaceImpl) {
390
- res.writeHead(400);
391
- res.end("Workspace is only available when running in a session");
392
- break;
393
- }
394
- result = await workspaceImpl.read(data.path);
395
- res.writeHead(200, { "Content-Type": "application/json" });
396
- res.end(JSON.stringify({ result }));
397
- break;
398
- case "/workspace/write":
399
- if (!workspaceImpl) {
400
- res.writeHead(400);
401
- res.end("Workspace is only available when running in a session");
402
- break;
403
- }
404
- await workspaceImpl.write(data.path, data.content);
405
- res.writeHead(200, { "Content-Type": "application/json" });
406
- res.end(JSON.stringify({ result: null }));
407
- break;
408
- case "/workspace/list":
409
- if (!workspaceImpl) {
410
- res.writeHead(400);
411
- res.end("Workspace is only available when running in a session");
412
- break;
413
- }
414
- result = await workspaceImpl.list(data.pattern);
415
- res.writeHead(200, { "Content-Type": "application/json" });
416
- res.end(JSON.stringify({ result }));
417
- break;
418
- case "/workspace/observe":
419
- if (!workspaceImpl) {
420
- res.writeHead(400);
421
- res.end("Workspace is only available when running in a session");
422
- break;
423
- }
424
- result = await workspaceImpl.observe(data.pattern, {
425
- expect: data.expect, timeout: data.timeout,
426
- });
427
- res.writeHead(200, { "Content-Type": "application/json" });
428
- res.end(JSON.stringify({ result }));
429
- break;
430
- default:
431
- res.writeHead(404);
432
- res.end("Not found");
433
- }
434
- }
435
- catch (err) {
436
- if (!res.headersSent)
437
- res.writeHead(500);
438
- res.end(String(err));
439
- }
440
- });
441
- });
442
- }
443
- function startServer(server) {
444
- return new Promise((resolve, reject) => {
445
- server.listen(0, "127.0.0.1", () => {
446
- const addr = server.address();
447
- if (addr && typeof addr === "object") {
448
- resolve(addr.port);
449
- }
450
- else {
451
- reject(new Error("Failed to get server port"));
452
- }
453
- });
454
- server.on("error", reject);
455
- });
456
- }
457
- function closeServer(server) {
458
- return new Promise((resolve, reject) => {
459
- server.close(err => {
460
- if (!err || err.code === "ERR_SERVER_NOT_RUNNING") {
461
- resolve();
462
- }
463
- else {
464
- reject(err);
465
- }
466
- });
467
- });
468
- }
469
- /** Abort in-flight operations, kill orphan shells, drop HTTP connections, then close. */
470
- function forceCloseServer(server, toolsImpl, abortController) {
471
- abortController?.abort();
472
- toolsImpl.killActiveShells();
473
- server.closeAllConnections();
474
- return closeServer(server);
475
- }
476
- // --- Child process management ---
477
- /**
478
- * Collect stdout/stderr as strings and wait for exit.
479
- * Enforces wall-clock timeout via explicit setTimeout + kill.
480
- */
481
- function waitForChild(child, options) {
482
- const { timeout, sinks, stopSignal } = options;
483
- return new Promise((resolve, reject) => {
484
- const out = cappedBuffer();
485
- const err = cappedBuffer();
486
- const outDecoder = new StringDecoder("utf-8");
487
- const errDecoder = new StringDecoder("utf-8");
488
- let timedOut = false;
489
- let exited = false;
490
- let stopRequested = false;
491
- let killFallbackTimer = null;
492
- const killChild = (sig) => {
493
- if (child.pid) {
494
- try {
495
- process.kill(-child.pid, sig);
496
- }
497
- catch { /* already gone */ }
498
- }
499
- else {
500
- child.kill(sig);
501
- }
502
- };
503
- const scheduleKill = (reason) => {
504
- if (exited)
505
- return;
506
- if (reason === "timeout") {
507
- timedOut = true;
508
- }
509
- else if (stopRequested || timedOut) {
510
- return;
511
- }
512
- else {
513
- stopRequested = true;
514
- }
515
- killChild("SIGTERM");
516
- if (killFallbackTimer)
517
- clearTimeout(killFallbackTimer);
518
- killFallbackTimer = setTimeout(() => {
519
- if (!exited)
520
- killChild("SIGKILL");
521
- }, 5000);
522
- killFallbackTimer.unref?.();
523
- };
524
- const onStopRequest = () => scheduleKill("stop-request");
525
- stopSignal?.addEventListener("abort", onStopRequest, { once: true });
526
- child.stdout?.on("data", (chunk) => {
527
- const text = outDecoder.write(chunk);
528
- out.append(text);
529
- sinks?.stdout?.(text);
530
- });
531
- child.stderr?.on("data", (chunk) => {
532
- const text = errDecoder.write(chunk);
533
- err.append(text);
534
- sinks?.stderr?.(text);
535
- });
536
- const timer = setTimeout(() => {
537
- scheduleKill("timeout");
538
- }, timeout);
539
- child.on("error", (err) => {
540
- clearTimeout(timer);
541
- if (killFallbackTimer)
542
- clearTimeout(killFallbackTimer);
543
- stopSignal?.removeEventListener("abort", onStopRequest);
544
- reject(err);
545
- });
546
- child.on("close", (code, signal) => {
547
- exited = true;
548
- clearTimeout(timer);
549
- if (killFallbackTimer)
550
- clearTimeout(killFallbackTimer);
551
- stopSignal?.removeEventListener("abort", onStopRequest);
552
- const outFlush = outDecoder.end();
553
- const errFlush = errDecoder.end();
554
- if (outFlush) {
555
- out.append(outFlush);
556
- sinks?.stdout?.(outFlush);
557
- }
558
- if (errFlush) {
559
- err.append(errFlush);
560
- sinks?.stderr?.(errFlush);
561
- }
562
- if (timedOut) {
563
- resolve({ exitCode: 1, stdout: out.value, stderr: err.value + "\n[trama] program killed: timeout" });
564
- }
565
- else if (stopRequested && (code === 0 || signal === "SIGTERM")) {
566
- resolve({ exitCode: 0, stdout: out.value, stderr: err.value });
567
- }
568
- else {
569
- resolve({ exitCode: code ?? 1, stdout: out.value, stderr: err.value });
570
- }
571
- });
572
- });
573
- }
574
204
  // --- History management ---
205
+ /** Append one metadata line to history/index.jsonl. */
206
+ function appendHistoryIndex(projectDir, entry) {
207
+ appendFileSync(guardPath(projectDir, join("history", "index.jsonl")), JSON.stringify(entry) + "\n");
208
+ }
209
+ /** The index.jsonl field that carries the detail for each kind of versioned change. */
210
+ const HISTORY_DETAIL_FIELD = { create: "prompt", update: "prompt", repair: "error" };
575
211
  /**
576
- * Copy current program.ts to history/NNNN.ts and append to index.jsonl.
212
+ * Save the current program.ts as the next version: copy it to history/NNNN.ts
213
+ * and record why in index.jsonl.
577
214
  *
578
- * WARNING: Do NOT use this for create-time repair attempts.
579
- * Create-time repairs go to index.jsonl only (reason: "create-repair").
215
+ * Repairs made while validating a create or update are NOT versions of their
216
+ * own — they are noted in index.jsonl only (reason "create-repair" /
217
+ * "update-repair"), and the validated program becomes the create/update version.
580
218
  */
581
219
  export function copyToHistory(projectDir, reason, detail) {
582
220
  const historyDir = guardPath(projectDir, "history");
583
- const existing = readdirSync(historyDir).filter(f => /^\d+\.ts$/.test(f));
584
- const nums = existing.map(f => parseInt(f.replace(".ts", ""), 10));
585
- const nextNum = nums.length > 0 ? nums.reduce((a, b) => Math.max(a, b), 0) + 1 : 1;
586
- const next = String(nextNum).padStart(Math.max(4, String(nextNum).length), "0");
587
- const srcPath = guardPath(projectDir, "program.ts");
588
- const dstPath = guardPath(projectDir, join("history", `${next}.ts`));
589
- copyFileSync(srcPath, dstPath);
590
- const entry = { version: nextNum, reason, timestamp: new Date().toISOString() };
591
- if (reason === "repair" && detail)
592
- entry.error = detail;
593
- if (reason === "update" && detail)
594
- entry.prompt = detail;
595
- const indexPath = guardPath(projectDir, join("history", "index.jsonl"));
596
- appendFileSync(indexPath, JSON.stringify(entry) + "\n");
221
+ const versions = readdirSync(historyDir)
222
+ .filter(f => /^\d+\.ts$/.test(f))
223
+ .map(f => parseInt(f, 10));
224
+ const version = versions.reduce((a, b) => Math.max(a, b), 0) + 1;
225
+ const fileName = `${String(version).padStart(4, "0")}.ts`;
226
+ copyFileSync(guardPath(projectDir, "program.ts"), guardPath(projectDir, join("history", fileName)));
227
+ const entry = { version, reason, timestamp: new Date().toISOString() };
228
+ const detailField = HISTORY_DETAIL_FIELD[reason];
229
+ if (detailField && detail)
230
+ entry[detailField] = detail;
231
+ appendHistoryIndex(projectDir, entry);
597
232
  }
598
- // --- Helpers ---
599
233
  /** Record all files in a directory with their size and mtime for change detection. */
600
234
  export function snapshotDir(dir, prefix = "") {
601
235
  const result = new Map();
@@ -623,110 +257,95 @@ export function snapshotDir(dir, prefix = "") {
623
257
  }
624
258
  return result;
625
259
  }
260
+ const sameStat = (a, b) => a.size === b.size && a.mtimeMs === b.mtimeMs;
626
261
  /**
627
262
  * Commit workspace changes from a temp workspace back to the real workspace,
628
263
  * using a three-way check to avoid overwriting concurrent updates by other participants.
629
264
  *
630
- * @param tempDir - temp workspace after the rerun (source of changes)
265
+ * @param tempDir - temp workspace after the run (source of changes)
631
266
  * @param realDir - real shared workspace (destination)
632
- * @param tempBefore - temp workspace snapshot before the rerun (detects what the rerun changed)
267
+ * @param tempBefore - temp workspace snapshot before the run (detects what the run changed)
633
268
  * @param realSeed - real workspace snapshot at seed time (detects concurrent changes)
634
269
  *
635
- * For each file changed in the temp workspace during the rerun:
636
- * - New file (not in tempBefore): always copy to real workspace.
637
- * - Modified file: only copy if the real workspace's current state still matches
638
- * realSeed. If it doesn't, another participant changed it concurrently — skip.
270
+ * For each file the run created or modified in the temp workspace:
271
+ * - New file: copied unless that path has meanwhile appeared in the real workspace.
272
+ * - Modified file: copied only if the real workspace's copy still matches realSeed.
273
+ * If it doesn't, another participant changed or removed it concurrently — skip.
274
+ * Best-effort: anything that cannot be committed safely is skipped, never thrown.
639
275
  */
640
276
  export function commitWorkspaceChanges(tempDir, realDir, tempBefore, realSeed) {
641
- const tempAfter = snapshotDir(tempDir);
642
- for (const [relPath, afterStat] of tempAfter) {
277
+ for (const [relPath, afterStat] of snapshotDir(tempDir)) {
643
278
  const beforeStat = tempBefore.get(relPath);
644
- // Was this file created or modified by the rerun?
645
- if (beforeStat && beforeStat.size === afterStat.size && beforeStat.mtimeMs === afterStat.mtimeMs) {
646
- continue; // Unchanged in temp — nothing to commit
647
- }
648
- const dstPath = join(realDir, relPath);
649
- // Verify the path resolves inside the workspace root before any stat/write.
650
- // A concurrent participant could have placed a symlink at this path or in
651
- // a parent directory, pointing outside the workspace.
279
+ if (beforeStat && sameStat(beforeStat, afterStat))
280
+ continue; // the run didn't touch it
652
281
  try {
653
- guardPath(realDir, relPath);
654
- }
655
- catch {
656
- continue; // Path escapes workspace via symlink — skip
657
- }
658
- if (beforeStat) {
659
- // File existed before the rerun — three-way check against the real workspace.
660
- // If the real workspace's version no longer matches the seed, another
661
- // participant modified it concurrently — skip to preserve their update.
662
- const seedStat = realSeed.get(relPath);
663
- if (seedStat) {
664
- try {
665
- const realNow = statSync(dstPath);
666
- if (realNow.size !== seedStat.size || realNow.mtimeMs !== seedStat.mtimeMs) {
667
- continue; // Concurrent modification — preserve other participant's version
668
- }
669
- }
670
- catch {
671
- continue; // File removed concurrently — don't resurrect
672
- }
673
- }
674
- }
675
- else {
676
- // New file created by the rerun — check if another participant also
677
- // created the same path concurrently in the real workspace.
678
- try {
679
- statSync(dstPath);
680
- continue; // Path already exists in real workspace — preserve other participant's version
282
+ // A concurrent participant could have placed a symlink at this path or in
283
+ // a parent directory, pointing outside the workspace — guardPath throws.
284
+ const dstPath = guardPath(realDir, relPath);
285
+ const realNow = statSync(dstPath, { throwIfNoEntry: false });
286
+ if (beforeStat) {
287
+ const seedStat = realSeed.get(relPath);
288
+ if (seedStat && (!realNow || !sameStat(realNow, seedStat)))
289
+ continue; // changed or removed concurrently
681
290
  }
682
- catch {
683
- // ENOENT — path doesn't exist in real workspace, safe to create
291
+ else if (realNow) {
292
+ continue; // someone else created the same path first — keep theirs
684
293
  }
685
- }
686
- // Best-effort commit with path-guard enforcement.
687
- // Verify the destination resolves inside the workspace root before writing.
688
- // A concurrent participant could have placed a symlink pointing outside
689
- // the workspace — guardPath catches that. Any other filesystem conflict
690
- // (path-shape, permissions) is also caught and skipped.
691
- try {
692
- guardPath(realDir, relPath);
693
- const srcPath = join(tempDir, relPath);
694
294
  mkdirSync(dirname(dstPath), { recursive: true });
695
- copyFileSync(srcPath, dstPath);
295
+ copyFileSync(join(tempDir, relPath), dstPath);
696
296
  }
697
297
  catch {
698
- // Path escapes workspace via symlink, path-shape conflict, or other error — skip
298
+ // Escapes the workspace, path-shape conflict, permissions — skip
699
299
  }
700
300
  }
701
301
  }
702
302
  /**
703
- * Snapshot a directory, run fn, restore from snapshot if fn returns false
704
- * or if fn throws. Always cleans up the snapshot. Returns whatever fn returns.
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.)
705
311
  */
706
312
  export async function withSnapshot(dir, fn) {
707
- const snap = mkdtempSync(join(tmpdir(), "trama-snapshot-"));
708
- const restore = () => {
709
- rmSync(dir, { recursive: true, force: true });
710
- cpSync(snap, dir, { recursive: true });
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);
711
322
  };
712
323
  try {
713
- cpSync(dir, snap, { recursive: true });
324
+ cpSync(target, snap, { recursive: true });
714
325
  let result;
715
326
  try {
716
327
  result = await fn();
717
328
  }
718
329
  catch (err) {
719
- restore();
330
+ rollBack();
720
331
  throw err;
721
332
  }
722
333
  if (!result.keep)
723
- restore();
334
+ rollBack();
724
335
  return result.value;
725
336
  }
726
337
  finally {
727
- rmSync(snap, { recursive: true, force: true });
338
+ if (!rolledBack)
339
+ removeTempDir(snap);
728
340
  }
729
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
+ }
730
349
  /** Run fn in a temp directory, clean up afterwards regardless of outcome. */
731
350
  export async function withTempDir(prefix, fn) {
732
351
  const dir = mkdtempSync(join(tmpdir(), prefix));
@@ -734,83 +353,97 @@ export async function withTempDir(prefix, fn) {
734
353
  return await fn(dir);
735
354
  }
736
355
  finally {
737
- rmSync(dir, { recursive: true, force: true });
356
+ removeTempDir(dir);
738
357
  }
739
358
  }
740
359
  /**
741
- * Attempt a single repair call with its own timeout and cancellation.
742
- * Returns true if repair succeeded, false if it failed (error is appended to repairErrors).
360
+ * Run fn against a private copy of the shared workspace, so its writes stay
361
+ * invisible to other participants unless fn asks to commit them — in which
362
+ * case what it created or changed is merged back (see commitWorkspaceChanges).
363
+ * Outside a session there is no workspace and fn simply runs.
743
364
  */
744
- async function repairWithTimeout(adapter, input, timeout, repairErrors) {
745
- const controller = new AbortController();
746
- const timer = setTimeout(() => controller.abort(), timeout);
365
+ async function withStagedWorkspace(workspaceDir, fn) {
366
+ if (!workspaceDir)
367
+ return (await fn(undefined)).value;
368
+ const realSeed = snapshotDir(workspaceDir);
369
+ return withTempDir("trama-repair-ws-", async (stagedDir) => {
370
+ cpSync(workspaceDir, stagedDir, { recursive: true });
371
+ const stagedBefore = snapshotDir(stagedDir);
372
+ const { commit, value } = await fn(stagedDir);
373
+ if (commit)
374
+ commitWorkspaceChanges(stagedDir, workspaceDir, stagedBefore, realSeed);
375
+ return value;
376
+ });
377
+ }
378
+ const formatError = (r) => `program.ts exited with code ${r.exitCode}\nstdout: ${r.stdout}\nstderr: ${r.stderr}`;
379
+ /**
380
+ * Hand the program its starting state through a private temp file rather than
381
+ * env vars — no OS size limit, and mode 0600 in an unpredictable directory
382
+ * keeps it from other local users. Returns the directory to remove afterwards.
383
+ */
384
+ function writeInitFile(payload) {
385
+ const dir = mkdtempSync(join(tmpdir(), "trama-init-"));
386
+ const file = join(dir, "init.json");
387
+ const fd = openSync(file, "w", 0o600);
747
388
  try {
748
- return await adapter.repair(input, controller.signal);
749
- }
750
- catch (err) {
751
- repairErrors.push(err instanceof Error ? err.message : String(err));
752
- return null;
389
+ writeFileSync(fd, JSON.stringify(payload));
753
390
  }
754
391
  finally {
755
- clearTimeout(timer);
392
+ closeSync(fd);
756
393
  }
394
+ return { dir, file };
395
+ }
396
+ function toChildResult(exit) {
397
+ const { stdout, stderr } = exit;
398
+ if (exit.timedOut)
399
+ return { exitCode: 1, stdout, stderr: stderr + "\n[trama] program killed: timeout" };
400
+ // Stopped by us after ctx.ready() — going down on SIGTERM is the expected outcome.
401
+ if (exit.stopped && (exit.code === 0 || exit.signal === "SIGTERM"))
402
+ return { exitCode: 0, stdout, stderr };
403
+ return { exitCode: exit.code ?? 1, stdout, stderr };
757
404
  }
758
405
  /**
759
- * Run program.ts once in the given directory. Sets up scaffolding, IPC server,
760
- * writes init file, spawns child, waits for result, and cleans up.
761
- * Returns the child process result — does NOT throw on non-zero exit.
406
+ * Run program.ts once in the given directory: scaffold, start the IPC server,
407
+ * spawn the program, wait for it, and tear everything down.
408
+ * Reports how the program ended — does NOT throw on non-zero exit. Throws only
409
+ * when the run could not happen at all (bad project, server or spawn failure).
762
410
  */
763
411
  async function runProgramOnce(options) {
764
412
  const { projectDir, adapter, timeout, maxIterations, argsOverride, streamOutput, stopOnReady, workspaceDir } = options;
765
- const signalTracker = { doneCalled: false, yieldCalled: false };
766
413
  ensureProjectScaffold(projectDir);
767
- ensureRuntimeLink(projectDir);
768
- const abortController = new AbortController();
769
- const stopController = new AbortController();
770
- const { signal } = abortController;
771
- let readyStopScheduled = false;
772
- let readyStopTimer = null;
773
- // When set, the grace period is active — child exit should cancel the timer
774
- // so that the natural exit code flows through instead of being masked by SIGTERM.
775
- let graceActive = false;
414
+ // Cancels in-flight LLM calls, fetches and observes once the run is over.
415
+ const runEnded = new AbortController();
416
+ // Asks the program to stop once it has been ready for the grace period.
417
+ const readyStop = new AbortController();
418
+ let readyTimer = null;
419
+ let terminalSignal = null;
776
420
  const ctx = createContext(projectDir, loadState(projectDir), {
777
421
  maxIterations,
778
422
  argsOverride,
779
- onReady: stopOnReady ? () => {
780
- if (readyStopScheduled)
781
- return;
782
- readyStopScheduled = true;
783
- graceActive = true;
784
- readyStopTimer = setTimeout(() => {
785
- graceActive = false;
786
- stopController.abort();
787
- }, stopOnReady.graceMs);
788
- readyStopTimer.unref?.();
789
- } : undefined,
423
+ onReady: stopOnReady && (() => {
424
+ readyTimer ??= setTimeout(() => readyStop.abort(), stopOnReady.graceMs).unref();
425
+ }),
790
426
  });
791
- // Truncate logs only after preflight succeeds — preserves prior run's diagnostics
792
- // if scaffolding, state loading, or context creation fails.
427
+ // Truncate logs only after preflight succeeds — preserves the prior run's
428
+ // diagnostics if scaffolding, state loading, or context creation fails.
793
429
  writeFileSync(guardPath(projectDir, join("logs", "latest.jsonl")), "");
794
- const agentImpl = createAgent(adapter, signal);
795
- const toolsImpl = createTools(projectDir, signal);
796
- const workspaceImpl = workspaceDir ? createWorkspace(workspaceDir, signal) : null;
797
- const server = createIPCServer(ctx, agentImpl, toolsImpl, workspaceImpl, signalTracker);
798
- // Infrastructure setup — errors here are NOT program bugs.
799
- let port;
800
- try {
801
- port = await startServer(server);
802
- }
803
- catch (infraError) {
804
- await forceCloseServer(server, toolsImpl, abortController);
805
- throw infraError;
806
- }
807
- // Write init data to a temp file instead of env vars to avoid OS size limits.
808
- // Use mkdtempSync for an unpredictable path and mode 0o600 to prevent local disclosure.
809
- const initDir = mkdtempSync(join(tmpdir(), "trama-init-"));
810
- const initFile = join(initDir, "init.json");
811
- const fd = openSync(initFile, "w", 0o600);
430
+ const tools = createTools(projectDir, runEnded.signal);
431
+ // Known only to this run's program, through its init file.
432
+ const token = randomBytes(32).toString("hex");
433
+ const server = createIPCServer({
434
+ token,
435
+ ctx,
436
+ agent: createAgent(adapter, runEnded.signal),
437
+ tools,
438
+ workspace: workspaceDir ? createWorkspace(workspaceDir, runEnded.signal) : null,
439
+ // The first terminal signal wins; ctx itself rejects a conflicting second one.
440
+ onTerminalSignal: result => { terminalSignal ??= result; },
441
+ });
442
+ let initDir;
812
443
  try {
813
- writeFileSync(fd, JSON.stringify({
444
+ const port = await listen(server);
445
+ const init = writeInitFile({
446
+ token,
814
447
  input: ctx.input,
815
448
  state: ctx.state,
816
449
  iteration: ctx.iteration,
@@ -818,318 +451,167 @@ async function runProgramOnce(options) {
818
451
  workspace: workspaceDir ?? null,
819
452
  resumed: ctx.resumed,
820
453
  yieldReason: ctx.yieldReason,
821
- }));
822
- }
823
- finally {
824
- closeSync(fd);
825
- }
826
- let child;
827
- try {
828
- child = spawn(process.execPath, [TSX_CLI, guardPath(projectDir, "program.ts")], {
454
+ });
455
+ initDir = init.dir;
456
+ const child = spawn(process.execPath, [TSX_CLI, guardPath(projectDir, "program.ts")], {
829
457
  cwd: projectDir,
830
- env: {
831
- ...process.env,
832
- TRAMA_PORT: String(port),
833
- TRAMA_INIT: initFile,
834
- },
458
+ env: { ...process.env, TRAMA_PORT: String(port), TRAMA_INIT: init.file },
835
459
  stdio: ["ignore", "pipe", "pipe"],
836
460
  detached: true,
837
461
  });
838
- }
839
- catch (spawnError) {
840
- if (readyStopTimer)
841
- clearTimeout(readyStopTimer);
842
- await forceCloseServer(server, toolsImpl, abortController);
843
- try {
844
- rmSync(initDir, { recursive: true, force: true });
845
- }
846
- catch { /* best-effort */ }
847
- throw spawnError;
848
- }
849
- // If the child exits on its own during the grace period (before we send
850
- // SIGTERM), cancel the grace timer so the real exit code flows through
851
- // waitForChild instead of being masked by a subsequent SIGTERM.
852
- if (stopOnReady) {
853
- child.on("close", () => {
854
- if (graceActive && readyStopTimer) {
855
- clearTimeout(readyStopTimer);
856
- readyStopTimer = null;
857
- graceActive = false;
858
- }
859
- });
860
- }
861
- let result;
862
- try {
863
- result = await waitForChild(child, {
462
+ const exit = await superviseChild(child, {
864
463
  timeout,
865
- stopSignal: stopOnReady ? stopController.signal : undefined,
464
+ stopSignal: stopOnReady ? readyStop.signal : undefined,
866
465
  sinks: streamOutput ? {
867
466
  stdout: chunk => { process.stdout.write(chunk); },
868
467
  stderr: chunk => { process.stderr.write(chunk); },
869
468
  } : undefined,
870
469
  });
470
+ return { child: toChildResult(exit), terminalSignal };
871
471
  }
872
- catch (spawnError) {
873
- if (readyStopTimer)
874
- clearTimeout(readyStopTimer);
875
- await forceCloseServer(server, toolsImpl, abortController);
876
- try {
877
- rmSync(initDir, { recursive: true, force: true });
878
- }
879
- catch { /* best-effort */ }
880
- throw spawnError;
472
+ finally {
473
+ // The program is gone (or never started): cancel what it left in flight,
474
+ // kill shells it left running in the background, and drop its connections.
475
+ if (readyTimer)
476
+ clearTimeout(readyTimer);
477
+ runEnded.abort();
478
+ tools.killActiveShells();
479
+ server.closeAllConnections();
480
+ await closeServer(server).catch(() => { });
481
+ if (initDir)
482
+ removeTempDir(initDir);
881
483
  }
882
- if (readyStopTimer)
883
- clearTimeout(readyStopTimer);
884
- try {
885
- rmSync(initDir, { recursive: true, force: true });
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));
886
504
  }
887
- catch { /* best-effort */ }
888
- // Always kill background shells — even on success, spawned background
889
- // processes would otherwise outlive the runner and leak.
890
- toolsImpl.killActiveShells();
891
- if (result.exitCode === 0) {
892
- abortController.abort(); // cancel any in-flight LLM/fetch requests
505
+ return { status: "done" };
506
+ }
507
+ /**
508
+ * Ask the LLM for a fix. The repair agent has tools, so it works in a
509
+ * throwaway copy of the project — whatever it reads is real, whatever it
510
+ * writes is discarded; only the program text it returns is used. Bounded by
511
+ * its own timeout. Returns null (and records why) if no fix came back.
512
+ */
513
+ async function requestRepair(options, input, repairErrors) {
514
+ return withTempDir("trama-repair-", async (tempDir) => {
515
+ cpSync(options.projectDir, tempDir, { recursive: true });
516
+ const controller = new AbortController();
517
+ const timer = setTimeout(() => controller.abort(), options.timeout);
893
518
  try {
894
- await closeServer(server);
519
+ return await options.adapter.withCwd(tempDir).repair({ ...input, runtimeTypes: RUNTIME_TYPES }, controller.signal);
895
520
  }
896
- catch {
897
- await forceCloseServer(server, toolsImpl);
521
+ catch (err) {
522
+ repairErrors.push(err instanceof Error ? err.message : String(err));
523
+ return null;
898
524
  }
899
- }
900
- else {
901
- try {
902
- await forceCloseServer(server, toolsImpl, abortController);
525
+ finally {
526
+ clearTimeout(timer);
903
527
  }
904
- catch { /* best-effort */ }
905
- }
906
- return { child: result, signals: signalTracker };
528
+ });
907
529
  }
908
- const formatError = (r) => `program.ts exited with code ${r.exitCode}\nstdout: ${r.stdout}\nstderr: ${r.stderr}`;
909
530
  /**
910
- * Read persisted terminal signals from state.json after a program exits.
911
- * Uses the IPC signal tracker to distinguish "called during this run" from
912
- * "stale marker from a previous run".
913
- * Returns a ProgramResult based on markers and exit code, or null if no
914
- * terminal signal was found and exit code is non-zero (needs repair).
531
+ * Run a proposed fix. If it fails too, the project is rolled back to how it
532
+ * was before the fix and its workspace writes are dropped; if it succeeds,
533
+ * they are merged into the shared workspace.
915
534
  */
916
- function readTerminalSignal(projectDir, childResult, signals) {
917
- const state = loadState(projectDir);
918
- // Check done marker first — only if done was actually called this run
919
- if (signals.doneCalled) {
920
- const doneMarker = state.__trama_done;
921
- if (doneMarker != null) {
922
- return { status: "done", result: doneMarker.result ?? undefined };
923
- }
924
- }
925
- // Check yield marker — only if yield was actually called this run
926
- if (signals.yieldCalled) {
927
- const yieldMarker = state.__trama_yield;
928
- if (yieldMarker != null) {
929
- return { status: "yielded", reason: yieldMarker.reason };
930
- }
931
- }
932
- // No terminal signal called during this run
933
- if (childResult.exitCode === 0) {
934
- // Natural success — clear any stale yield marker
935
- clearStaleYieldMarker(projectDir, state);
936
- return { status: "done" };
937
- }
938
- // Non-zero exit, no terminal signal → needs repair
939
- return null;
535
+ async function applyRepair(options, fixed) {
536
+ const { projectDir } = options;
537
+ return withStagedWorkspace(options.workspaceDir, async (stagedWorkspace) => {
538
+ const value = await withSnapshot(projectDir, async () => {
539
+ writeFileSync(guardPath(projectDir, "program.ts"), fixed);
540
+ const run = await runProgramOnce({ ...options, streamOutput: true, workspaceDir: stagedWorkspace });
541
+ const outcome = settle(projectDir, run);
542
+ return { keep: outcome !== null, value: { outcome, error: formatError(run.child) } };
543
+ });
544
+ return { commit: value.outcome !== null, value };
545
+ });
940
546
  }
941
547
  /**
942
- * Clear stale yield marker from state.json when program exits normally without
943
- * calling any terminal signal. Prevents stale yield state from polluting future runs.
548
+ * Run a program to an outcome. If it crashes, ask the LLM to repair it and run
549
+ * the fix — up to maxRepairAttempts times. A fix that also fails leaves no
550
+ * trace: the project and the shared workspace are as they were before it ran.
944
551
  */
945
- function clearStaleYieldMarker(projectDir, state) {
946
- if (state.__trama_yield != null) {
947
- delete state.__trama_yield;
948
- const statePath = guardPath(projectDir, "state.json");
949
- writeFileSync(statePath, JSON.stringify(state, null, 2));
950
- }
951
- }
952
552
  async function executeProgram(options) {
953
- const { projectDir, adapter, maxRepairAttempts, timeout, maxIterations } = options;
954
- mkdirSync(guardPath(projectDir, "history"), { recursive: true });
955
- mkdirSync(guardPath(projectDir, "logs"), { recursive: true });
956
- // Phase 1: Run in the real project directory.
957
- const runResult = await runProgramOnce({
958
- projectDir, adapter, timeout, maxIterations,
959
- argsOverride: options.argsOverride,
960
- streamOutput: true,
961
- stopOnReady: options.stopOnReady,
962
- workspaceDir: options.workspaceDir,
963
- });
964
- // Check for persisted terminal signals before checking exit code
965
- const termSignal = readTerminalSignal(projectDir, runResult.child, runResult.signals);
966
- if (termSignal)
967
- return termSignal;
968
- // Non-zero exit with no terminal signal → attempt repair
553
+ const { projectDir, maxRepairAttempts } = options;
554
+ const firstRun = await runProgramOnce({ ...options, streamOutput: true });
555
+ const outcome = settle(projectDir, firstRun);
556
+ if (outcome)
557
+ return outcome;
558
+ let lastError = formatError(firstRun.child);
969
559
  if (maxRepairAttempts === 0) {
970
- return { status: "failed", reason: `Program failed (repair disabled): ${formatError(runResult.child)}` };
560
+ return { status: "failed", reason: `Program failed (repair disabled): ${lastError}` };
971
561
  }
972
- // Phase 2: Repair loop — both LLM repair call and verification run
973
- // are fully isolated in temp dirs to prevent side effects on the real project.
974
- let lastError = formatError(runResult.child);
975
- const originalSource = readFileSync(guardPath(projectDir, "program.ts"), "utf-8");
976
- let currentSource = originalSource;
562
+ // Each attempt builds on the previous one's source, even though a failed
563
+ // attempt is rolled back out of the real project.
564
+ let currentSource = readFileSync(guardPath(projectDir, "program.ts"), "utf-8");
977
565
  const repairErrors = [];
978
566
  const repairDetails = () => repairErrors.length > 0
979
567
  ? `\nRepair errors:\n${repairErrors.map((e, i) => ` [${i + 1}] ${e}`).join("\n")}` : "";
980
568
  for (let attempt = 0; attempt < maxRepairAttempts; attempt++) {
981
- const repairResult = await withTempDir("trama-repair-", async (tempDir) => {
982
- cpSync(projectDir, tempDir, { recursive: true });
983
- const tempAdapter = adapter.withCwd(tempDir);
984
- const fixed = await repairWithTimeout(tempAdapter, { programSource: currentSource, error: lastError, runtimeTypes: RUNTIME_TYPES }, timeout, repairErrors);
985
- if (!fixed)
986
- return null;
987
- writeFileSync(guardPath(tempDir, "program.ts"), fixed);
988
- // Verification runs use a temp workspace seeded from the real one,
989
- // so the repair can read existing artifacts but writes don't leak.
990
- let tempWorkspaceDir;
991
- if (options.workspaceDir) {
992
- tempWorkspaceDir = mkdtempSync(join(tmpdir(), "trama-repair-ws-"));
993
- cpSync(options.workspaceDir, tempWorkspaceDir, { recursive: true });
994
- }
995
- try {
996
- const verifyResult = await runProgramOnce({
997
- projectDir: tempDir, adapter: tempAdapter, timeout, maxIterations,
998
- argsOverride: options.argsOverride,
999
- stopOnReady: options.stopOnReady,
1000
- workspaceDir: tempWorkspaceDir,
1001
- });
1002
- // Read terminal signal while tempDir still exists
1003
- const verifySignal = readTerminalSignal(tempDir, verifyResult.child, verifyResult.signals);
1004
- return { fixed, verifyResult, verifySignal, tempDir };
1005
- }
1006
- finally {
1007
- if (tempWorkspaceDir) {
1008
- try {
1009
- rmSync(tempWorkspaceDir, { recursive: true, force: true });
1010
- }
1011
- catch { /* best-effort */ }
1012
- }
1013
- }
1014
- });
1015
- if (!repairResult) {
569
+ const fixed = await requestRepair(options, { programSource: currentSource, error: lastError }, repairErrors);
570
+ if (!fixed) {
1016
571
  return { status: "failed", reason: `Failed after ${attempt + 1} repair attempt(s): ${lastError}${repairDetails()}` };
1017
572
  }
1018
- // Terminal signal was read inside withTempDir while state.json still existed
1019
- const verifySignal = repairResult.verifySignal;
1020
- if (verifySignal && verifySignal.status !== "failed") {
1021
- // Repair verified in isolation — now run in the real project for actual output.
1022
- // For workspace: run against a temp workspace seeded from the real one.
1023
- // On success, commit new/changed artifacts back. On failure, discard the
1024
- // temp workspace — the real workspace is never touched, so concurrent
1025
- // writes from other participants are preserved.
1026
- let realRerunWsDir;
1027
- // Two snapshots for workspace three-way merge:
1028
- // - realSeedSnapshot: real workspace at seed time (for detecting concurrent changes)
1029
- // - tempBeforeSnapshot: temp workspace before rerun (for detecting rerun's changes)
1030
- let realSeedSnapshot;
1031
- let tempBeforeSnapshot;
1032
- if (options.workspaceDir) {
1033
- realSeedSnapshot = snapshotDir(options.workspaceDir);
1034
- realRerunWsDir = mkdtempSync(join(tmpdir(), "trama-repair-realws-"));
1035
- cpSync(options.workspaceDir, realRerunWsDir, { recursive: true });
1036
- tempBeforeSnapshot = snapshotDir(realRerunWsDir);
1037
- }
1038
- const { run: realRun, signal: realSignal } = await withSnapshot(projectDir, async () => {
1039
- writeFileSync(guardPath(projectDir, "program.ts"), repairResult.fixed);
1040
- const r = await runProgramOnce({
1041
- projectDir, adapter, timeout, maxIterations,
1042
- argsOverride: options.argsOverride,
1043
- streamOutput: true,
1044
- stopOnReady: options.stopOnReady,
1045
- workspaceDir: realRerunWsDir ?? options.workspaceDir,
1046
- });
1047
- const sig = readTerminalSignal(projectDir, r.child, r.signals);
1048
- return { keep: sig != null && sig.status !== "failed", value: { run: r, signal: sig } };
1049
- });
1050
- if (realSignal && realSignal.status !== "failed") {
1051
- // Success — commit only files that were created or modified during the
1052
- // rerun, with a three-way check to avoid overwriting concurrent updates.
1053
- if (realRerunWsDir && options.workspaceDir && tempBeforeSnapshot && realSeedSnapshot) {
1054
- commitWorkspaceChanges(realRerunWsDir, options.workspaceDir, tempBeforeSnapshot, realSeedSnapshot);
1055
- }
1056
- }
1057
- if (realRerunWsDir) {
1058
- try {
1059
- rmSync(realRerunWsDir, { recursive: true, force: true });
1060
- }
1061
- catch { /* best-effort */ }
573
+ currentSource = fixed;
574
+ const applied = await applyRepair(options, fixed);
575
+ if (applied.outcome) {
576
+ try {
577
+ // lastError is still the failure this repair fixed.
578
+ options.onRepair?.(attempt, maxRepairAttempts, lastError);
1062
579
  }
1063
- if (realSignal && realSignal.status !== "failed") {
1064
- try {
1065
- options.onRepair?.(attempt, maxRepairAttempts, lastError);
1066
- }
1067
- catch (bookkeepingErr) {
1068
- console.warn(`[trama] repair bookkeeping failed: ${bookkeepingErr instanceof Error ? bookkeepingErr.message : bookkeepingErr}`);
1069
- }
1070
- return realSignal;
580
+ catch (bookkeepingErr) {
581
+ console.warn(`[trama] repair bookkeeping failed: ${bookkeepingErr instanceof Error ? bookkeepingErr.message : bookkeepingErr}`);
1071
582
  }
1072
- currentSource = repairResult.fixed;
1073
- lastError = realSignal?.reason ?? formatError(realRun.child);
1074
- continue;
583
+ return applied.outcome;
1075
584
  }
1076
- currentSource = repairResult.fixed;
1077
- lastError = formatError(repairResult.verifyResult.child);
585
+ lastError = applied.error;
1078
586
  }
1079
587
  return { status: "failed", reason: `Failed after ${maxRepairAttempts} repair attempts: ${lastError}${repairDetails()}` };
1080
588
  }
1081
589
  // --- Smoke run (used by create and update) ---
1082
- /** Copy new history entries from src to dst (appends only entries added after the shared prefix). */
1083
- function propagateHistoryEntries(srcDir, dstDir) {
1084
- const srcPath = guardPath(srcDir, join("history", "index.jsonl"));
1085
- const dstPath = guardPath(dstDir, join("history", "index.jsonl"));
1086
- if (!existsSync(srcPath))
1087
- return;
1088
- const srcHistory = readFileSync(srcPath, "utf-8");
1089
- const dstHistory = existsSync(dstPath) ? readFileSync(dstPath, "utf-8") : "";
1090
- if (!srcHistory.startsWith(dstHistory))
1091
- return; // History diverged — cannot safely propagate
1092
- const newEntries = srcHistory.slice(dstHistory.length);
1093
- if (newEntries.length > 0) {
1094
- mkdirSync(guardPath(dstDir, "history"), { recursive: true });
1095
- appendFileSync(dstPath, newEntries);
1096
- }
1097
- }
1098
- const DEFAULT_SMOKE_TIMEOUT = 30_000;
1099
590
  const SMOKE_READY_GRACE_MS = 2_000;
1100
- export function resolveSmokeTimeout(timeout) {
1101
- return timeout ?? DEFAULT_SMOKE_TIMEOUT;
1102
- }
591
+ /**
592
+ * Validate a freshly generated program.ts by running it (with repair) in a
593
+ * throwaway copy of the project, so the validation run's file side effects
594
+ * don't persist. On success the validated — possibly repaired — program is
595
+ * copied back. Throws if it cannot be made to run.
596
+ */
1103
597
  export async function smokeRunAndRepair(projectDir, adapter, reason, options) {
1104
- const smokeTimeout = resolveSmokeTimeout(options?.timeout);
1105
- // Run validation in a temp copy so side effects don't persist in the real project
1106
598
  await withTempDir("trama-smoke-", async (smokeDir) => {
1107
599
  cpSync(projectDir, smokeDir, { recursive: true });
1108
- const smokeAdapter = adapter.withCwd(smokeDir);
1109
- try {
1110
- const smokeResult = await executeProgram({
1111
- projectDir: smokeDir,
1112
- adapter: smokeAdapter,
1113
- maxRepairAttempts: options?.maxRepairAttempts ?? 3,
1114
- timeout: smokeTimeout,
1115
- maxIterations: options?.maxIterations ?? 100,
1116
- stopOnReady: {
1117
- graceMs: SMOKE_READY_GRACE_MS,
1118
- },
1119
- onRepair(_attempt, _max, error) {
1120
- appendFileSync(guardPath(smokeDir, join("history", "index.jsonl")), JSON.stringify({ reason: `${reason}-repair`, timestamp: new Date().toISOString(), error }) + "\n");
1121
- },
1122
- });
1123
- if (smokeResult.status === "failed") {
1124
- throw new Error(`Program failed: ${smokeResult.reason}`);
1125
- }
1126
- // Smoke passed — copy back program.ts (may have been repaired)
1127
- copyFileSync(guardPath(smokeDir, "program.ts"), guardPath(projectDir, "program.ts"));
1128
- }
1129
- finally {
1130
- // Always propagate repair history, whether smoke passed or failed
1131
- propagateHistoryEntries(smokeDir, projectDir);
600
+ const result = await executeProgram({
601
+ projectDir: smokeDir,
602
+ adapter: adapter.withCwd(smokeDir),
603
+ maxRepairAttempts: options.maxRepairAttempts,
604
+ timeout: options.timeout,
605
+ maxIterations: options.maxIterations,
606
+ stopOnReady: { graceMs: SMOKE_READY_GRACE_MS },
607
+ onRepair(_attempt, _max, error) {
608
+ appendHistoryIndex(projectDir, { reason: `${reason}-repair`, timestamp: new Date().toISOString(), error });
609
+ },
610
+ });
611
+ if (result.status === "failed") {
612
+ throw new Error(`Program failed: ${result.reason}`);
1132
613
  }
614
+ copyFileSync(guardPath(smokeDir, "program.ts"), guardPath(projectDir, "program.ts"));
1133
615
  });
1134
616
  }
1135
617
  // --- Core execution ---
@@ -1139,37 +621,27 @@ export async function runProgram(options) {
1139
621
  throw new Error(`Project not found at ${projectDir}. ` +
1140
622
  `Run \`trama list\` to see available projects.`);
1141
623
  }
1142
- const config = loadConfig();
1143
- // Use per-project model/provider if saved, else fall back to global config
1144
- const metaPath = guardPath(projectDir, "meta.json");
1145
- const meta = JSON.parse(readFileSync(metaPath, "utf-8"));
1146
- if (meta.model)
1147
- config.model = meta.model;
1148
- if (meta.provider)
1149
- config.provider = meta.provider;
624
+ const config = loadProjectConfig(projectDir);
1150
625
  const maxRepairAttempts = options.maxRepairAttempts ?? config.maxRepairAttempts;
1151
626
  const timeout = options.timeout ?? config.defaultTimeout;
1152
- const maxIterations = config.defaultMaxIterations;
1153
627
  if (!Number.isFinite(timeout) || timeout <= 0) {
1154
628
  throw new Error(`Invalid timeout: ${timeout}. Must be a positive number.`);
1155
629
  }
1156
630
  if (!Number.isInteger(maxRepairAttempts) || maxRepairAttempts < 0) {
1157
631
  throw new Error(`Invalid maxRepairAttempts: ${maxRepairAttempts}. Must be a non-negative integer.`);
1158
632
  }
1159
- const adapter = new PiAdapter(config, projectDir);
1160
633
  return executeProgram({
1161
634
  projectDir,
1162
- adapter,
635
+ adapter: new PiAdapter(config, projectDir),
1163
636
  maxRepairAttempts,
1164
637
  timeout,
1165
- maxIterations,
638
+ maxIterations: config.defaultMaxIterations,
1166
639
  argsOverride: options.args,
1167
640
  workspaceDir: options.workspaceDir,
1168
641
  onRepair(attempt, max, error) {
1169
- // Log repair attempts (appends to already-open logs file)
1170
- const logsPath = guardPath(projectDir, join("logs", "latest.jsonl"));
642
+ // Runs after the repaired program's own run, so this lands at the end of its log.
1171
643
  const entry = { ts: Date.now(), message: `Repair attempt ${attempt + 1}/${max}`, data: { error } };
1172
- appendFileSync(logsPath, JSON.stringify(entry) + "\n");
644
+ appendFileSync(guardPath(projectDir, join("logs", "latest.jsonl")), JSON.stringify(entry) + "\n");
1173
645
  console.log(`[trama] Repair attempt ${attempt + 1}/${max}`);
1174
646
  copyToHistory(projectDir, "repair", error);
1175
647
  },