@trama-dev/runtime 0.1.1 → 0.1.3

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,13 +1,16 @@
1
1
  import { createServer } from "http";
2
2
  import { spawn } from "child_process";
3
- import { readFileSync, writeFileSync, appendFileSync, readdirSync, copyFileSync, mkdirSync, existsSync, symlinkSync, rmSync, lstatSync, readlinkSync, cpSync, mkdtempSync, } from "fs";
3
+ import { readFileSync, writeFileSync, appendFileSync, readdirSync, copyFileSync, mkdirSync, existsSync, symlinkSync, rmSync, lstatSync, readlinkSync, cpSync, mkdtempSync, openSync, closeSync, } from "fs";
4
4
  import { join, dirname } from "path";
5
5
  import { homedir, tmpdir } from "os";
6
6
  import { fileURLToPath } from "url";
7
+ import { StringDecoder } from "string_decoder";
7
8
  import { PiAdapter } from "./pi-adapter.js";
8
9
  import { createContext } from "./context.js";
9
10
  import { createAgent } from "./agent.js";
10
11
  import { createTools, cappedBuffer } from "./tools.js";
12
+ import { guardPath } from "./path-guard.js";
13
+ import { assertSerializable } from "./serializable.js";
11
14
  // --- Module resolution for child processes ---
12
15
  /**
13
16
  * Find the node_modules directory that contains @trama-dev/runtime.
@@ -29,17 +32,19 @@ const TSX_CLI = join(TRAMA_NODE_MODULES, "tsx", "dist", "cli.mjs");
29
32
  export const PI_VERSION = JSON.parse(readFileSync(join(TRAMA_NODE_MODULES, "@mariozechner", "pi-coding-agent", "package.json"), "utf-8")).version;
30
33
  /**
31
34
  * Ensure the project directory has a node_modules symlink to @trama-dev/runtime.
32
- * Only replaces the path if it is a symlink (ours) or doesn't exist.
33
- * Refuses to touch a real directory to avoid destroying user content.
35
+ * Replaces any existing symlink whose target differs (including user-managed ones).
36
+ * Only refuses to touch a real directory/file to avoid destroying user content.
34
37
  */
35
38
  function ensureRuntimeLink(projectDir) {
39
+ // node_modules/@trama-dev/runtime is deliberately a symlink pointing OUTSIDE
40
+ // the project (to the global trama install). Do not apply guardPath here.
36
41
  const linkDir = join(projectDir, "node_modules", "@trama-dev");
37
42
  const linkPath = join(linkDir, "runtime");
38
43
  const target = join(TRAMA_NODE_MODULES, "@trama-dev", "runtime");
39
44
  try {
40
45
  const stat = lstatSync(linkPath);
41
46
  if (stat.isSymbolicLink()) {
42
- // Ours — check if already correct
47
+ // Symlink exists — replace if target doesn't match
43
48
  if (readlinkSync(linkPath) === target)
44
49
  return;
45
50
  rmSync(linkPath);
@@ -63,8 +68,8 @@ function ensureRuntimeLink(projectDir) {
63
68
  * Ensure project has ESM package.json and .gitignore.
64
69
  * If package.json exists but lacks "type": "module", patches it in.
65
70
  */
66
- function ensureProjectScaffold(projectDir) {
67
- const pkgPath = join(projectDir, "package.json");
71
+ export function ensureProjectScaffold(projectDir) {
72
+ const pkgPath = guardPath(projectDir, "package.json");
68
73
  if (existsSync(pkgPath)) {
69
74
  let pkg;
70
75
  try {
@@ -87,7 +92,7 @@ function ensureProjectScaffold(projectDir) {
87
92
  else {
88
93
  writeFileSync(pkgPath, JSON.stringify({ type: "module" }, null, 2));
89
94
  }
90
- const giPath = join(projectDir, ".gitignore");
95
+ const giPath = guardPath(projectDir, ".gitignore");
91
96
  const requiredEntries = ["node_modules/", "state.json", "logs/", "history/"];
92
97
  if (existsSync(giPath)) {
93
98
  const existing = readFileSync(giPath, "utf-8");
@@ -117,6 +122,7 @@ export interface Ctx {
117
122
  iteration: number;
118
123
  maxIterations: number;
119
124
  log(message: string, data?: Record<string, unknown>): Promise<void>;
125
+ ready(data?: Record<string, unknown>): Promise<void>;
120
126
  checkpoint(): Promise<void>;
121
127
  done(result?: Record<string, unknown>): Promise<void>;
122
128
  }
@@ -155,7 +161,7 @@ export function loadConfig() {
155
161
  const configPath = join(homedir(), ".trama", "config.json");
156
162
  const defaults = {
157
163
  provider: "anthropic",
158
- model: "claude-sonnet-4-20250514",
164
+ model: "claude-opus-4-6",
159
165
  maxRepairAttempts: 3,
160
166
  defaultTimeout: 300_000,
161
167
  defaultMaxIterations: 100,
@@ -197,7 +203,7 @@ export function loadConfig() {
197
203
  return merged;
198
204
  }
199
205
  export function loadState(projectDir) {
200
- const statePath = join(projectDir, "state.json");
206
+ const statePath = guardPath(projectDir, "state.json");
201
207
  if (!existsSync(statePath))
202
208
  return {};
203
209
  const raw = readFileSync(statePath, "utf-8");
@@ -218,6 +224,22 @@ export function loadState(projectDir) {
218
224
  return parsed;
219
225
  }
220
226
  // --- IPC Server ---
227
+ const MAX_IPC_BODY = 50 * 1024 * 1024; // 50 MB
228
+ /** Validate required fields in IPC request body. Returns error message or null. */
229
+ function validateIPC(data, fields) {
230
+ for (const [name, type] of Object.entries(fields)) {
231
+ const val = data[name];
232
+ if (type === "object") {
233
+ if (typeof val !== "object" || val === null || Array.isArray(val)) {
234
+ return `Missing or invalid field: ${name} (expected object)`;
235
+ }
236
+ }
237
+ else if (typeof val !== type) {
238
+ return `Missing or invalid field: ${name} (expected ${type})`;
239
+ }
240
+ }
241
+ return null;
242
+ }
221
243
  function createIPCServer(ctx, agentImpl, toolsImpl) {
222
244
  return createServer((req, res) => {
223
245
  if (req.method !== "POST") {
@@ -225,12 +247,48 @@ function createIPCServer(ctx, agentImpl, toolsImpl) {
225
247
  res.end("Method not allowed");
226
248
  return;
227
249
  }
228
- let body = "";
229
- req.on("data", (chunk) => { body += chunk; });
250
+ const chunks = [];
251
+ let byteCount = 0;
252
+ let overflow = false;
253
+ req.on("data", (chunk) => {
254
+ if (overflow)
255
+ return;
256
+ chunks.push(chunk);
257
+ byteCount += chunk.length;
258
+ if (byteCount > MAX_IPC_BODY) {
259
+ overflow = true;
260
+ res.writeHead(413);
261
+ res.end("IPC request body exceeds 50MB limit");
262
+ req.destroy();
263
+ }
264
+ });
230
265
  req.on("end", async () => {
266
+ if (overflow)
267
+ return;
231
268
  try {
232
- const data = JSON.parse(body);
269
+ const data = JSON.parse(Buffer.concat(chunks).toString("utf-8"));
233
270
  let result;
271
+ // Per-endpoint field validation
272
+ const validationRules = {
273
+ "/agent/ask": { prompt: "string" },
274
+ "/agent/generate": { prompt: "string", schema: "object" },
275
+ "/tools/read": { path: "string" },
276
+ "/tools/write": { path: "string", content: "string" },
277
+ "/tools/shell": { command: "string" },
278
+ "/tools/fetch": { url: "string" },
279
+ "/ctx/checkpoint": { state: "object" },
280
+ "/ctx/log": { message: "string" },
281
+ "/ctx/done": { state: "object" },
282
+ };
283
+ const rules = req.url ? validationRules[req.url] : undefined;
284
+ if (rules) {
285
+ const validationError = validateIPC(data, rules);
286
+ if (validationError) {
287
+ res.writeHead(400);
288
+ res.end(validationError);
289
+ return;
290
+ }
291
+ }
234
292
  switch (req.url) {
235
293
  case "/agent/ask":
236
294
  result = await agentImpl.ask(data.prompt, { system: data.system });
@@ -265,6 +323,7 @@ function createIPCServer(ctx, agentImpl, toolsImpl) {
265
323
  res.end(JSON.stringify({ result }));
266
324
  break;
267
325
  case "/ctx/checkpoint":
326
+ assertSerializable(data.state, "ctx.state");
268
327
  ctx.state = data.state;
269
328
  await ctx.checkpoint();
270
329
  res.writeHead(200, { "Content-Type": "application/json" });
@@ -275,7 +334,18 @@ function createIPCServer(ctx, agentImpl, toolsImpl) {
275
334
  res.writeHead(200, { "Content-Type": "application/json" });
276
335
  res.end(JSON.stringify({ result: null }));
277
336
  break;
337
+ case "/ctx/ready":
338
+ if (data.data !== undefined && (typeof data.data !== "object" || data.data === null || Array.isArray(data.data))) {
339
+ res.writeHead(400);
340
+ res.end("Invalid field: data (expected object or undefined)");
341
+ break;
342
+ }
343
+ await ctx.ready(data.data);
344
+ res.writeHead(200, { "Content-Type": "application/json" });
345
+ res.end(JSON.stringify({ result: null }));
346
+ break;
278
347
  case "/ctx/done":
348
+ assertSerializable(data.state, "ctx.state");
279
349
  ctx.state = data.state;
280
350
  await ctx.done(data.result);
281
351
  res.writeHead(200, { "Content-Type": "application/json" });
@@ -332,46 +402,93 @@ function forceCloseServer(server, toolsImpl, abortController) {
332
402
  * Collect stdout/stderr as strings and wait for exit.
333
403
  * Enforces wall-clock timeout via explicit setTimeout + kill.
334
404
  */
335
- function waitForChild(child, timeout, sinks) {
405
+ function waitForChild(child, options) {
406
+ const { timeout, sinks, stopSignal } = options;
336
407
  return new Promise((resolve, reject) => {
337
408
  const out = cappedBuffer();
338
409
  const err = cappedBuffer();
410
+ const outDecoder = new StringDecoder("utf-8");
411
+ const errDecoder = new StringDecoder("utf-8");
339
412
  let timedOut = false;
340
413
  let exited = false;
414
+ let stopRequested = false;
341
415
  let killFallbackTimer = null;
416
+ const killChild = (sig) => {
417
+ if (child.pid) {
418
+ try {
419
+ process.kill(-child.pid, sig);
420
+ }
421
+ catch { /* already gone */ }
422
+ }
423
+ else {
424
+ child.kill(sig);
425
+ }
426
+ };
427
+ const scheduleKill = (reason) => {
428
+ if (exited)
429
+ return;
430
+ if (reason === "timeout") {
431
+ timedOut = true;
432
+ }
433
+ else if (stopRequested || timedOut) {
434
+ return;
435
+ }
436
+ else {
437
+ stopRequested = true;
438
+ }
439
+ killChild("SIGTERM");
440
+ if (killFallbackTimer)
441
+ clearTimeout(killFallbackTimer);
442
+ killFallbackTimer = setTimeout(() => {
443
+ if (!exited)
444
+ killChild("SIGKILL");
445
+ }, 5000);
446
+ killFallbackTimer.unref?.();
447
+ };
448
+ const onStopRequest = () => scheduleKill("stop-request");
449
+ stopSignal?.addEventListener("abort", onStopRequest, { once: true });
342
450
  child.stdout?.on("data", (chunk) => {
343
- const text = chunk.toString();
451
+ const text = outDecoder.write(chunk);
344
452
  out.append(text);
345
453
  sinks?.stdout?.(text);
346
454
  });
347
455
  child.stderr?.on("data", (chunk) => {
348
- const text = chunk.toString();
456
+ const text = errDecoder.write(chunk);
349
457
  err.append(text);
350
458
  sinks?.stderr?.(text);
351
459
  });
352
460
  const timer = setTimeout(() => {
353
- timedOut = true;
354
- child.kill("SIGTERM");
355
- killFallbackTimer = setTimeout(() => {
356
- if (!exited)
357
- child.kill("SIGKILL");
358
- }, 5000);
359
- killFallbackTimer.unref?.();
461
+ scheduleKill("timeout");
360
462
  }, timeout);
361
463
  child.on("error", (err) => {
362
464
  clearTimeout(timer);
363
465
  if (killFallbackTimer)
364
466
  clearTimeout(killFallbackTimer);
467
+ stopSignal?.removeEventListener("abort", onStopRequest);
365
468
  reject(err);
366
469
  });
367
- child.on("close", (code) => {
470
+ child.on("close", (code, signal) => {
368
471
  exited = true;
369
472
  clearTimeout(timer);
370
473
  if (killFallbackTimer)
371
474
  clearTimeout(killFallbackTimer);
475
+ stopSignal?.removeEventListener("abort", onStopRequest);
476
+ const outFlush = outDecoder.end();
477
+ const errFlush = errDecoder.end();
478
+ if (outFlush) {
479
+ out.append(outFlush);
480
+ sinks?.stdout?.(outFlush);
481
+ }
482
+ if (errFlush) {
483
+ err.append(errFlush);
484
+ sinks?.stderr?.(errFlush);
485
+ }
372
486
  if (timedOut) {
373
487
  resolve({ exitCode: 1, stdout: out.value, stderr: err.value + "\n[trama] program killed: timeout" });
374
488
  }
489
+ else if (stopRequested && (code === 0 || signal === "SIGTERM")) {
490
+ resolve({ exitCode: 0, stdout: out.value, stderr: err.value });
491
+ }
375
492
  else {
376
493
  resolve({ exitCode: code ?? 1, stdout: out.value, stderr: err.value });
377
494
  }
@@ -386,20 +503,51 @@ function waitForChild(child, timeout, sinks) {
386
503
  * Create-time repairs go to index.jsonl only (reason: "create-repair").
387
504
  */
388
505
  export function copyToHistory(projectDir, reason, detail) {
389
- const historyDir = join(projectDir, "history");
506
+ const historyDir = guardPath(projectDir, "history");
390
507
  const existing = readdirSync(historyDir).filter(f => /^\d+\.ts$/.test(f));
391
508
  const nums = existing.map(f => parseInt(f.replace(".ts", ""), 10));
392
- const nextNum = nums.length > 0 ? Math.max(...nums) + 1 : 1;
509
+ const nextNum = nums.length > 0 ? nums.reduce((a, b) => Math.max(a, b), 0) + 1 : 1;
393
510
  const next = String(nextNum).padStart(Math.max(4, String(nextNum).length), "0");
394
- copyFileSync(join(projectDir, "program.ts"), join(historyDir, `${next}.ts`));
511
+ const srcPath = guardPath(projectDir, "program.ts");
512
+ const dstPath = guardPath(projectDir, join("history", `${next}.ts`));
513
+ copyFileSync(srcPath, dstPath);
395
514
  const entry = { version: nextNum, reason, timestamp: new Date().toISOString() };
396
515
  if (reason === "repair" && detail)
397
516
  entry.error = detail;
398
517
  if (reason === "update" && detail)
399
518
  entry.prompt = detail;
400
- appendFileSync(join(historyDir, "index.jsonl"), JSON.stringify(entry) + "\n");
519
+ const indexPath = guardPath(projectDir, join("history", "index.jsonl"));
520
+ appendFileSync(indexPath, JSON.stringify(entry) + "\n");
401
521
  }
402
522
  // --- Helpers ---
523
+ /**
524
+ * Snapshot a directory, run fn, restore from snapshot if fn returns false
525
+ * or if fn throws. Always cleans up the snapshot. Returns whatever fn returns.
526
+ */
527
+ export async function withSnapshot(dir, fn) {
528
+ const snap = mkdtempSync(join(tmpdir(), "trama-snapshot-"));
529
+ const restore = () => {
530
+ rmSync(dir, { recursive: true, force: true });
531
+ cpSync(snap, dir, { recursive: true });
532
+ };
533
+ try {
534
+ cpSync(dir, snap, { recursive: true });
535
+ let result;
536
+ try {
537
+ result = await fn();
538
+ }
539
+ catch (err) {
540
+ restore();
541
+ throw err;
542
+ }
543
+ if (!result.keep)
544
+ restore();
545
+ return result.value;
546
+ }
547
+ finally {
548
+ rmSync(snap, { recursive: true, force: true });
549
+ }
550
+ }
403
551
  /** Run fn in a temp directory, clean up afterwards regardless of outcome. */
404
552
  export async function withTempDir(prefix, fn) {
405
553
  const dir = mkdtempSync(join(tmpdir(), prefix));
@@ -428,120 +576,235 @@ async function repairWithTimeout(adapter, input, timeout, repairErrors) {
428
576
  clearTimeout(timer);
429
577
  }
430
578
  }
431
- async function executeProgram(options) {
432
- const { projectDir, adapter, maxRepairAttempts, timeout, maxIterations } = options;
433
- mkdirSync(join(projectDir, "history"), { recursive: true });
434
- mkdirSync(join(projectDir, "logs"), { recursive: true });
579
+ /**
580
+ * Run program.ts once in the given directory. Sets up scaffolding, IPC server,
581
+ * writes init file, spawns child, waits for result, and cleans up.
582
+ * Returns the child process result — does NOT throw on non-zero exit.
583
+ */
584
+ async function runProgramOnce(options) {
585
+ const { projectDir, adapter, timeout, maxIterations, argsOverride, streamOutput, stopOnReady } = options;
435
586
  ensureProjectScaffold(projectDir);
436
587
  ensureRuntimeLink(projectDir);
437
- writeFileSync(join(projectDir, "logs", "latest.jsonl"), "");
438
- const originalSource = readFileSync(join(projectDir, "program.ts"), "utf-8");
588
+ const abortController = new AbortController();
589
+ const stopController = new AbortController();
590
+ const { signal } = abortController;
591
+ let readyStopScheduled = false;
592
+ let readyStopTimer = null;
593
+ // When set, the grace period is active — child exit should cancel the timer
594
+ // so that the natural exit code flows through instead of being masked by SIGTERM.
595
+ let graceActive = false;
596
+ const ctx = createContext(projectDir, loadState(projectDir), {
597
+ maxIterations,
598
+ argsOverride,
599
+ onReady: stopOnReady ? () => {
600
+ if (readyStopScheduled)
601
+ return;
602
+ readyStopScheduled = true;
603
+ graceActive = true;
604
+ readyStopTimer = setTimeout(() => {
605
+ graceActive = false;
606
+ stopController.abort();
607
+ }, stopOnReady.graceMs);
608
+ readyStopTimer.unref?.();
609
+ } : undefined,
610
+ });
611
+ // Truncate logs only after preflight succeeds — preserves prior run's diagnostics
612
+ // if scaffolding, state loading, or context creation fails.
613
+ writeFileSync(guardPath(projectDir, join("logs", "latest.jsonl")), "");
614
+ const agentImpl = createAgent(adapter, signal);
615
+ const toolsImpl = createTools(projectDir, signal);
616
+ const server = createIPCServer(ctx, agentImpl, toolsImpl);
617
+ // Infrastructure setup — errors here are NOT program bugs.
618
+ let port;
619
+ try {
620
+ port = await startServer(server);
621
+ }
622
+ catch (infraError) {
623
+ await forceCloseServer(server, toolsImpl, abortController);
624
+ throw infraError;
625
+ }
626
+ // Write init data to a temp file instead of env vars to avoid OS size limits.
627
+ // Use mkdtempSync for an unpredictable path and mode 0o600 to prevent local disclosure.
628
+ const initDir = mkdtempSync(join(tmpdir(), "trama-init-"));
629
+ const initFile = join(initDir, "init.json");
630
+ const fd = openSync(initFile, "w", 0o600);
631
+ try {
632
+ writeFileSync(fd, JSON.stringify({
633
+ input: ctx.input,
634
+ state: ctx.state,
635
+ iteration: ctx.iteration,
636
+ maxIterations: ctx.maxIterations,
637
+ }));
638
+ }
639
+ finally {
640
+ closeSync(fd);
641
+ }
642
+ let child;
643
+ try {
644
+ child = spawn(process.execPath, [TSX_CLI, guardPath(projectDir, "program.ts")], {
645
+ cwd: projectDir,
646
+ env: {
647
+ ...process.env,
648
+ TRAMA_PORT: String(port),
649
+ TRAMA_INIT: initFile,
650
+ },
651
+ stdio: ["ignore", "pipe", "pipe"],
652
+ detached: true,
653
+ });
654
+ }
655
+ catch (spawnError) {
656
+ if (readyStopTimer)
657
+ clearTimeout(readyStopTimer);
658
+ await forceCloseServer(server, toolsImpl, abortController);
659
+ try {
660
+ rmSync(initDir, { recursive: true, force: true });
661
+ }
662
+ catch { /* best-effort */ }
663
+ throw spawnError;
664
+ }
665
+ // If the child exits on its own during the grace period (before we send
666
+ // SIGTERM), cancel the grace timer so the real exit code flows through
667
+ // waitForChild instead of being masked by a subsequent SIGTERM.
668
+ if (stopOnReady) {
669
+ child.on("close", () => {
670
+ if (graceActive && readyStopTimer) {
671
+ clearTimeout(readyStopTimer);
672
+ readyStopTimer = null;
673
+ graceActive = false;
674
+ }
675
+ });
676
+ }
677
+ let result;
678
+ try {
679
+ result = await waitForChild(child, {
680
+ timeout,
681
+ stopSignal: stopOnReady ? stopController.signal : undefined,
682
+ sinks: streamOutput ? {
683
+ stdout: chunk => { process.stdout.write(chunk); },
684
+ stderr: chunk => { process.stderr.write(chunk); },
685
+ } : undefined,
686
+ });
687
+ }
688
+ catch (spawnError) {
689
+ if (readyStopTimer)
690
+ clearTimeout(readyStopTimer);
691
+ await forceCloseServer(server, toolsImpl, abortController);
692
+ try {
693
+ rmSync(initDir, { recursive: true, force: true });
694
+ }
695
+ catch { /* best-effort */ }
696
+ throw spawnError;
697
+ }
698
+ if (readyStopTimer)
699
+ clearTimeout(readyStopTimer);
700
+ try {
701
+ rmSync(initDir, { recursive: true, force: true });
702
+ }
703
+ catch { /* best-effort */ }
704
+ // Always kill background shells — even on success, spawned background
705
+ // processes would otherwise outlive the runner and leak.
706
+ toolsImpl.killActiveShells();
707
+ if (result.exitCode === 0) {
708
+ abortController.abort(); // cancel any in-flight LLM/fetch requests
709
+ try {
710
+ await closeServer(server);
711
+ }
712
+ catch {
713
+ await forceCloseServer(server, toolsImpl);
714
+ }
715
+ }
716
+ else {
717
+ try {
718
+ await forceCloseServer(server, toolsImpl, abortController);
719
+ }
720
+ catch { /* best-effort */ }
721
+ }
722
+ return result;
723
+ }
724
+ const formatError = (r) => `program.ts exited with code ${r.exitCode}\nstdout: ${r.stdout}\nstderr: ${r.stderr}`;
725
+ async function executeProgram(options) {
726
+ const { projectDir, adapter, maxRepairAttempts, timeout, maxIterations } = options;
727
+ mkdirSync(guardPath(projectDir, "history"), { recursive: true });
728
+ mkdirSync(guardPath(projectDir, "logs"), { recursive: true });
729
+ // Phase 1: Run in the real project directory.
730
+ const result = await runProgramOnce({
731
+ projectDir, adapter, timeout, maxIterations,
732
+ argsOverride: options.argsOverride,
733
+ streamOutput: true,
734
+ stopOnReady: options.stopOnReady,
735
+ });
736
+ if (result.exitCode === 0)
737
+ return;
738
+ if (maxRepairAttempts === 0) {
739
+ throw new Error(`Program failed (repair disabled): ${formatError(result)}`);
740
+ }
741
+ // Phase 2: Repair loop — both LLM repair call and verification run
742
+ // are fully isolated in temp dirs to prevent side effects on the real project.
743
+ let lastError = formatError(result);
744
+ const originalSource = readFileSync(guardPath(projectDir, "program.ts"), "utf-8");
745
+ let currentSource = originalSource;
439
746
  const repairErrors = [];
440
747
  const repairDetails = () => repairErrors.length > 0
441
748
  ? `\nRepair errors:\n${repairErrors.map((e, i) => ` [${i + 1}] ${e}`).join("\n")}` : "";
442
- let pendingRepair = null;
443
- let programModified = false;
444
- try {
445
- for (let attempt = 0; attempt <= maxRepairAttempts; attempt++) {
446
- const abortController = new AbortController();
447
- const { signal } = abortController;
448
- const ctx = createContext(projectDir, loadState(projectDir), { maxIterations });
449
- const agentImpl = createAgent(adapter, signal);
450
- const toolsImpl = createTools(projectDir, signal);
451
- const server = createIPCServer(ctx, agentImpl, toolsImpl);
452
- // Phase A: Infrastructure setup — errors here are NOT program bugs,
453
- // so they must NOT trigger the repair loop. (H1 fix)
454
- let port;
455
- try {
456
- port = await startServer(server);
457
- }
458
- catch (infraError) {
459
- await forceCloseServer(server, toolsImpl, abortController);
460
- throw infraError;
461
- }
462
- const child = spawn(process.execPath, [TSX_CLI, join(projectDir, "program.ts")], {
463
- cwd: projectDir,
464
- env: {
465
- ...process.env,
466
- TRAMA_PORT: String(port),
467
- TRAMA_INPUT: JSON.stringify(ctx.input),
468
- TRAMA_STATE: JSON.stringify(ctx.state),
469
- TRAMA_ITERATION: String(ctx.iteration),
470
- TRAMA_MAX_ITERATIONS: String(ctx.maxIterations),
471
- },
472
- stdio: ["pipe", "pipe", "pipe"],
749
+ for (let attempt = 0; attempt < maxRepairAttempts; attempt++) {
750
+ const repairResult = await withTempDir("trama-repair-", async (tempDir) => {
751
+ cpSync(projectDir, tempDir, { recursive: true });
752
+ const tempAdapter = adapter.withCwd(tempDir);
753
+ const fixed = await repairWithTimeout(tempAdapter, { programSource: currentSource, error: lastError, runtimeTypes: RUNTIME_TYPES }, timeout, repairErrors);
754
+ if (!fixed)
755
+ return null;
756
+ writeFileSync(guardPath(tempDir, "program.ts"), fixed);
757
+ const verifyResult = await runProgramOnce({
758
+ projectDir: tempDir, adapter: tempAdapter, timeout, maxIterations,
759
+ argsOverride: options.argsOverride,
760
+ stopOnReady: options.stopOnReady,
473
761
  });
474
- // Phase B: Program execution.
475
- // waitForChild rejects on spawn errors (ENOENT, EACCES) — those are
476
- // infrastructure failures and must NOT trigger repair.
477
- let result;
478
- try {
479
- result = await waitForChild(child, timeout, {
480
- stdout: chunk => { process.stdout.write(chunk); },
481
- stderr: chunk => { process.stderr.write(chunk); },
762
+ return { fixed, verifyResult };
763
+ });
764
+ if (!repairResult) {
765
+ // Repair LLM call itself failed — don't re-run the same broken program.
766
+ throw new Error(`Failed after ${attempt + 1} repair attempt(s): ${lastError}${repairDetails()}`);
767
+ }
768
+ if (repairResult.verifyResult.exitCode === 0) {
769
+ // Repair verified in isolation — now run in the real project for actual output.
770
+ // Snapshot first so we can restore cleanly if the real run fails.
771
+ const realResult = await withSnapshot(projectDir, async () => {
772
+ writeFileSync(guardPath(projectDir, "program.ts"), repairResult.fixed);
773
+ const r = await runProgramOnce({
774
+ projectDir, adapter, timeout, maxIterations,
775
+ argsOverride: options.argsOverride,
776
+ streamOutput: true,
777
+ stopOnReady: options.stopOnReady,
482
778
  });
483
- }
484
- catch (spawnError) {
485
- // Child process failed to start — not a program bug.
486
- await forceCloseServer(server, toolsImpl, abortController);
487
- throw spawnError;
488
- }
489
- if (result.exitCode === 0) {
490
- // Repair is verified — program.ts is now the canonical source.
491
- programModified = false;
492
- // Program succeeded. Server cleanup failure is not a program bug.
779
+ return { keep: r.exitCode === 0, value: r };
780
+ });
781
+ if (realResult.exitCode === 0) {
782
+ // Bookkeeping is best-effort — program already succeeded and side effects
783
+ // are committed. Don't mask success with a history/log write failure.
493
784
  try {
494
- await closeServer(server);
785
+ options.onRepair?.(attempt, maxRepairAttempts, lastError);
495
786
  }
496
- catch {
497
- await forceCloseServer(server, toolsImpl, abortController);
498
- }
499
- if (pendingRepair) {
500
- options.onRepair?.(pendingRepair.attempt, maxRepairAttempts, pendingRepair.error);
787
+ catch (bookkeepingErr) {
788
+ console.warn(`[trama] repair bookkeeping failed: ${bookkeepingErr instanceof Error ? bookkeepingErr.message : bookkeepingErr}`);
501
789
  }
502
790
  return;
503
791
  }
504
- // Program failed — this is the only path that may trigger repair.
505
- try {
506
- await forceCloseServer(server, toolsImpl, abortController);
507
- }
508
- catch { /* best-effort cleanup */ }
509
- const programError = new Error(`program.ts exited with code ${result.exitCode}\n` +
510
- `stdout: ${result.stdout}\n` +
511
- `stderr: ${result.stderr}`);
512
- // Previous repair candidate failed — don't record it.
513
- pendingRepair = null;
514
- if (attempt === maxRepairAttempts) {
515
- throw new Error(`Failed after ${maxRepairAttempts} repair attempts: ${programError}${repairDetails()}`);
516
- }
517
- const source = readFileSync(join(projectDir, "program.ts"), "utf-8");
518
- const fixed = await repairWithTimeout(adapter, { programSource: source, error: String(programError), runtimeTypes: RUNTIME_TYPES }, timeout, repairErrors);
519
- if (fixed !== null) {
520
- writeFileSync(join(projectDir, "program.ts"), fixed);
521
- programModified = true;
522
- pendingRepair = { attempt, error: String(programError) };
523
- }
524
- else {
525
- // Repair LLM call itself failed — don't re-run the same broken program.
526
- throw new Error(`Failed after ${attempt + 1} repair attempt(s): ${programError}${repairDetails()}`);
527
- }
792
+ // Passed in isolation but failed in real dir — project already restored by withSnapshot.
793
+ currentSource = repairResult.fixed;
794
+ lastError = formatError(realResult);
795
+ continue;
528
796
  }
797
+ // Repair produced broken code — update context for next attempt.
798
+ currentSource = repairResult.fixed;
799
+ lastError = formatError(repairResult.verifyResult);
529
800
  }
530
- catch (err) {
531
- if (programModified) {
532
- try {
533
- writeFileSync(join(projectDir, "program.ts"), originalSource);
534
- }
535
- catch { /* best-effort */ }
536
- }
537
- throw err;
538
- }
801
+ throw new Error(`Failed after ${maxRepairAttempts} repair attempts: ${lastError}${repairDetails()}`);
539
802
  }
540
803
  // --- Smoke run (used by create and update) ---
541
804
  /** Copy new history entries from src to dst (appends only entries added after the shared prefix). */
542
805
  function propagateHistoryEntries(srcDir, dstDir) {
543
- const srcPath = join(srcDir, "history", "index.jsonl");
544
- const dstPath = join(dstDir, "history", "index.jsonl");
806
+ const srcPath = guardPath(srcDir, join("history", "index.jsonl"));
807
+ const dstPath = guardPath(dstDir, join("history", "index.jsonl"));
545
808
  if (!existsSync(srcPath))
546
809
  return;
547
810
  const srcHistory = readFileSync(srcPath, "utf-8");
@@ -550,12 +813,17 @@ function propagateHistoryEntries(srcDir, dstDir) {
550
813
  return; // History diverged — cannot safely propagate
551
814
  const newEntries = srcHistory.slice(dstHistory.length);
552
815
  if (newEntries.length > 0) {
553
- mkdirSync(join(dstDir, "history"), { recursive: true });
816
+ mkdirSync(guardPath(dstDir, "history"), { recursive: true });
554
817
  appendFileSync(dstPath, newEntries);
555
818
  }
556
819
  }
820
+ const DEFAULT_SMOKE_TIMEOUT = 30_000;
821
+ const SMOKE_READY_GRACE_MS = 2_000;
822
+ export function resolveSmokeTimeout(timeout) {
823
+ return timeout ?? DEFAULT_SMOKE_TIMEOUT;
824
+ }
557
825
  export async function smokeRunAndRepair(projectDir, adapter, reason, options) {
558
- const smokeTimeout = options?.timeout ?? 30_000;
826
+ const smokeTimeout = resolveSmokeTimeout(options?.timeout);
559
827
  // Run validation in a temp copy so side effects don't persist in the real project
560
828
  await withTempDir("trama-smoke-", async (smokeDir) => {
561
829
  cpSync(projectDir, smokeDir, { recursive: true });
@@ -567,12 +835,15 @@ export async function smokeRunAndRepair(projectDir, adapter, reason, options) {
567
835
  maxRepairAttempts: options?.maxRepairAttempts ?? 3,
568
836
  timeout: smokeTimeout,
569
837
  maxIterations: options?.maxIterations ?? 100,
838
+ stopOnReady: {
839
+ graceMs: SMOKE_READY_GRACE_MS,
840
+ },
570
841
  onRepair(_attempt, _max, error) {
571
- appendFileSync(join(smokeDir, "history", "index.jsonl"), JSON.stringify({ reason: `${reason}-repair`, timestamp: new Date().toISOString(), error }) + "\n");
842
+ appendFileSync(guardPath(smokeDir, join("history", "index.jsonl")), JSON.stringify({ reason: `${reason}-repair`, timestamp: new Date().toISOString(), error }) + "\n");
572
843
  },
573
844
  });
574
845
  // Smoke passed — copy back program.ts (may have been repaired)
575
- copyFileSync(join(smokeDir, "program.ts"), join(projectDir, "program.ts"));
846
+ copyFileSync(guardPath(smokeDir, "program.ts"), guardPath(projectDir, "program.ts"));
576
847
  }
577
848
  finally {
578
849
  // Always propagate repair history, whether smoke passed or failed
@@ -588,6 +859,13 @@ export async function runProgram(options) {
588
859
  `Run \`trama list\` to see available projects.`);
589
860
  }
590
861
  const config = loadConfig();
862
+ // Use per-project model/provider if saved, else fall back to global config
863
+ const metaPath = guardPath(projectDir, "meta.json");
864
+ const meta = JSON.parse(readFileSync(metaPath, "utf-8"));
865
+ if (meta.model)
866
+ config.model = meta.model;
867
+ if (meta.provider)
868
+ config.provider = meta.provider;
591
869
  const maxRepairAttempts = options.maxRepairAttempts ?? config.maxRepairAttempts;
592
870
  const timeout = options.timeout ?? config.defaultTimeout;
593
871
  const maxIterations = config.defaultMaxIterations;
@@ -604,9 +882,10 @@ export async function runProgram(options) {
604
882
  maxRepairAttempts,
605
883
  timeout,
606
884
  maxIterations,
885
+ argsOverride: options.args,
607
886
  onRepair(attempt, max, error) {
608
887
  // Log repair attempts (appends to already-open logs file)
609
- const logsPath = join(projectDir, "logs", "latest.jsonl");
888
+ const logsPath = guardPath(projectDir, join("logs", "latest.jsonl"));
610
889
  const entry = { ts: Date.now(), message: `Repair attempt ${attempt + 1}/${max}`, data: { error } };
611
890
  appendFileSync(logsPath, JSON.stringify(entry) + "\n");
612
891
  console.log(`[trama] Repair attempt ${attempt + 1}/${max}`);