@trama-dev/runtime 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/runner.js CHANGED
@@ -1,13 +1,14 @@
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, } 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
- import { homedir } from "os";
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
- import { createTools } from "./tools.js";
11
+ import { createTools, cappedBuffer } from "./tools.js";
11
12
  // --- Module resolution for child processes ---
12
13
  /**
13
14
  * Find the node_modules directory that contains @trama-dev/runtime.
@@ -52,8 +53,7 @@ function ensureRuntimeLink(projectDir) {
52
53
  }
53
54
  }
54
55
  catch (err) {
55
- // Re-throw if it's our own error (not ENOENT)
56
- if (err instanceof Error && !("code" in err))
56
+ if (err.code !== "ENOENT")
57
57
  throw err;
58
58
  // ENOENT — path doesn't exist, proceed to create
59
59
  }
@@ -67,18 +67,23 @@ function ensureRuntimeLink(projectDir) {
67
67
  function ensureProjectScaffold(projectDir) {
68
68
  const pkgPath = join(projectDir, "package.json");
69
69
  if (existsSync(pkgPath)) {
70
+ let pkg;
70
71
  try {
71
- const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
72
- if (pkg.type !== "module") {
73
- pkg.type = "module";
74
- writeFileSync(pkgPath, JSON.stringify(pkg, null, 2));
75
- }
72
+ pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
76
73
  }
77
74
  catch (err) {
78
75
  throw new Error(`Malformed package.json at ${pkgPath}. ` +
79
76
  `trama will not overwrite it automatically; fix or remove it and try again.\n` +
80
77
  `Parse error: ${err instanceof Error ? err.message : err}`);
81
78
  }
79
+ if (typeof pkg !== "object" || pkg === null || Array.isArray(pkg)) {
80
+ 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.`);
81
+ }
82
+ const pkgObj = pkg;
83
+ if (pkgObj.type !== "module") {
84
+ pkgObj.type = "module";
85
+ writeFileSync(pkgPath, JSON.stringify(pkgObj, null, 2));
86
+ }
82
87
  }
83
88
  else {
84
89
  writeFileSync(pkgPath, JSON.stringify({ type: "module" }, null, 2));
@@ -98,6 +103,13 @@ function ensureProjectScaffold(projectDir) {
98
103
  }
99
104
  }
100
105
  // --- Runtime type definitions (included in system prompts) ---
106
+ /**
107
+ * Simplified API reference for LLM system prompts.
108
+ * NOT the canonical type definitions (those live in types.ts).
109
+ * Kept as a readable string rather than auto-generated, because the LLM
110
+ * needs a concise reference, not the full implementation types.
111
+ * If types.ts changes, review whether this summary needs updating.
112
+ */
101
113
  export const RUNTIME_TYPES = `// @trama-dev/runtime - Complete API
102
114
 
103
115
  export interface Ctx {
@@ -106,6 +118,7 @@ export interface Ctx {
106
118
  iteration: number;
107
119
  maxIterations: number;
108
120
  log(message: string, data?: Record<string, unknown>): Promise<void>;
121
+ ready(data?: Record<string, unknown>): Promise<void>;
109
122
  checkpoint(): Promise<void>;
110
123
  done(result?: Record<string, unknown>): Promise<void>;
111
124
  }
@@ -144,33 +157,70 @@ export function loadConfig() {
144
157
  const configPath = join(homedir(), ".trama", "config.json");
145
158
  const defaults = {
146
159
  provider: "anthropic",
147
- model: "claude-sonnet-4-20250514",
160
+ model: "claude-opus-4-6",
148
161
  maxRepairAttempts: 3,
149
162
  defaultTimeout: 300_000,
150
163
  defaultMaxIterations: 100,
151
164
  };
165
+ let raw;
166
+ try {
167
+ raw = readFileSync(configPath, "utf-8");
168
+ }
169
+ catch (err) {
170
+ if (err.code === "ENOENT")
171
+ return defaults;
172
+ throw err;
173
+ }
174
+ let parsed;
152
175
  try {
153
- return { ...defaults, ...JSON.parse(readFileSync(configPath, "utf-8")) };
176
+ parsed = JSON.parse(raw);
154
177
  }
155
- catch {
156
- return defaults;
178
+ catch (err) {
179
+ throw new Error(`Malformed config at ${configPath} — fix or delete it.\n` +
180
+ `Parse error: ${err instanceof Error ? err.message : err}`);
181
+ }
182
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
183
+ throw new Error(`Malformed config at ${configPath} — expected a JSON object but got ${Array.isArray(parsed) ? "an array" : typeof parsed}. Fix or delete it to proceed.`);
184
+ }
185
+ const merged = { ...defaults, ...parsed };
186
+ const s = (v) => typeof v === "string" && v.length > 0;
187
+ const pint = (v) => Number.isInteger(v) && v > 0;
188
+ const checks = [
189
+ [s(merged.provider), `"provider" must be a non-empty string (got ${JSON.stringify(merged.provider)})`],
190
+ [s(merged.model), `"model" must be a non-empty string (got ${JSON.stringify(merged.model)})`],
191
+ [Number.isInteger(merged.maxRepairAttempts) && merged.maxRepairAttempts >= 0, `"maxRepairAttempts" must be a non-negative integer (got ${merged.maxRepairAttempts})`],
192
+ [Number.isFinite(merged.defaultTimeout) && merged.defaultTimeout > 0, `"defaultTimeout" must be a positive number (got ${merged.defaultTimeout})`],
193
+ [pint(merged.defaultMaxIterations), `"defaultMaxIterations" must be a positive integer (got ${merged.defaultMaxIterations})`],
194
+ ];
195
+ for (const [ok, msg] of checks) {
196
+ if (!ok)
197
+ throw new Error(`Invalid config: ${msg}`);
157
198
  }
199
+ return merged;
158
200
  }
159
201
  export function loadState(projectDir) {
160
202
  const statePath = join(projectDir, "state.json");
161
203
  if (!existsSync(statePath))
162
204
  return {};
163
205
  const raw = readFileSync(statePath, "utf-8");
206
+ const fail = (reason) => {
207
+ throw new Error(`Corrupt state.json in ${projectDir} — cannot safely continue.\n${reason}\n` +
208
+ `Back up or delete state.json to reset state.`);
209
+ };
210
+ let parsed;
164
211
  try {
165
- return JSON.parse(raw);
212
+ parsed = JSON.parse(raw);
166
213
  }
167
214
  catch (err) {
168
- throw new Error(`Corrupt state.json in ${projectDir} — cannot safely continue.\n` +
169
- `Parse error: ${err instanceof Error ? err.message : err}\n` +
170
- `Back up or delete state.json to reset state.`);
215
+ fail(`Parse error: ${err instanceof Error ? err.message : err}`);
216
+ }
217
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
218
+ fail(`Expected a JSON object but got ${Array.isArray(parsed) ? "array" : typeof parsed}.`);
171
219
  }
220
+ return parsed;
172
221
  }
173
222
  // --- IPC Server ---
223
+ const MAX_IPC_BODY = 50 * 1024 * 1024; // 50 MB
174
224
  function createIPCServer(ctx, agentImpl, toolsImpl) {
175
225
  return createServer((req, res) => {
176
226
  if (req.method !== "POST") {
@@ -178,11 +228,26 @@ function createIPCServer(ctx, agentImpl, toolsImpl) {
178
228
  res.end("Method not allowed");
179
229
  return;
180
230
  }
181
- let body = "";
182
- req.on("data", (chunk) => { body += chunk; });
231
+ const chunks = [];
232
+ let byteCount = 0;
233
+ let overflow = false;
234
+ req.on("data", (chunk) => {
235
+ if (overflow)
236
+ return;
237
+ chunks.push(chunk);
238
+ byteCount += chunk.length;
239
+ if (byteCount > MAX_IPC_BODY) {
240
+ overflow = true;
241
+ res.writeHead(413);
242
+ res.end("IPC request body exceeds 50MB limit");
243
+ req.destroy();
244
+ }
245
+ });
183
246
  req.on("end", async () => {
247
+ if (overflow)
248
+ return;
184
249
  try {
185
- const data = JSON.parse(body);
250
+ const data = JSON.parse(Buffer.concat(chunks).toString("utf-8"));
186
251
  let result;
187
252
  switch (req.url) {
188
253
  case "/agent/ask":
@@ -208,14 +273,14 @@ function createIPCServer(ctx, agentImpl, toolsImpl) {
208
273
  case "/tools/shell":
209
274
  result = await toolsImpl.shell(data.command, { cwd: data.cwd, timeout: data.timeout });
210
275
  res.writeHead(200, { "Content-Type": "application/json" });
211
- res.end(JSON.stringify(result));
276
+ res.end(JSON.stringify({ result }));
212
277
  break;
213
278
  case "/tools/fetch":
214
279
  result = await toolsImpl.fetch(data.url, {
215
280
  method: data.method, headers: data.headers, body: data.body,
216
281
  });
217
282
  res.writeHead(200, { "Content-Type": "application/json" });
218
- res.end(JSON.stringify(result));
283
+ res.end(JSON.stringify({ result }));
219
284
  break;
220
285
  case "/ctx/checkpoint":
221
286
  ctx.state = data.state;
@@ -228,6 +293,11 @@ function createIPCServer(ctx, agentImpl, toolsImpl) {
228
293
  res.writeHead(200, { "Content-Type": "application/json" });
229
294
  res.end(JSON.stringify({ result: null }));
230
295
  break;
296
+ case "/ctx/ready":
297
+ await ctx.ready(data.data);
298
+ res.writeHead(200, { "Content-Type": "application/json" });
299
+ res.end(JSON.stringify({ result: null }));
300
+ break;
231
301
  case "/ctx/done":
232
302
  ctx.state = data.state;
233
303
  await ctx.done(data.result);
@@ -240,7 +310,8 @@ function createIPCServer(ctx, agentImpl, toolsImpl) {
240
310
  }
241
311
  }
242
312
  catch (err) {
243
- res.writeHead(500);
313
+ if (!res.headersSent)
314
+ res.writeHead(500);
244
315
  res.end(String(err));
245
316
  }
246
317
  });
@@ -262,11 +333,19 @@ function startServer(server) {
262
333
  }
263
334
  function closeServer(server) {
264
335
  return new Promise((resolve, reject) => {
265
- server.close(err => (err ? reject(err) : resolve()));
336
+ server.close(err => {
337
+ if (!err || err.code === "ERR_SERVER_NOT_RUNNING") {
338
+ resolve();
339
+ }
340
+ else {
341
+ reject(err);
342
+ }
343
+ });
266
344
  });
267
345
  }
268
- /** Kill orphan shell processes, drop all HTTP connections, then close. */
269
- function forceCloseServer(server, toolsImpl) {
346
+ /** Abort in-flight operations, kill orphan shells, drop HTTP connections, then close. */
347
+ function forceCloseServer(server, toolsImpl, abortController) {
348
+ abortController?.abort();
270
349
  toolsImpl.killActiveShells();
271
350
  server.closeAllConnections();
272
351
  return closeServer(server);
@@ -276,42 +355,84 @@ function forceCloseServer(server, toolsImpl) {
276
355
  * Collect stdout/stderr as strings and wait for exit.
277
356
  * Enforces wall-clock timeout via explicit setTimeout + kill.
278
357
  */
279
- function waitForChild(child, timeout, sinks) {
358
+ function waitForChild(child, options) {
359
+ const { timeout, sinks, stopSignal } = options;
280
360
  return new Promise((resolve, reject) => {
281
- let stdout = "";
282
- let stderr = "";
361
+ const out = cappedBuffer();
362
+ const err = cappedBuffer();
363
+ const outDecoder = new StringDecoder("utf-8");
364
+ const errDecoder = new StringDecoder("utf-8");
283
365
  let timedOut = false;
284
366
  let exited = false;
367
+ let stopRequested = false;
368
+ let killFallbackTimer = null;
369
+ const scheduleKill = (reason) => {
370
+ if (exited)
371
+ return;
372
+ if (reason === "timeout") {
373
+ timedOut = true;
374
+ }
375
+ else if (stopRequested || timedOut) {
376
+ return;
377
+ }
378
+ else {
379
+ stopRequested = true;
380
+ }
381
+ child.kill("SIGTERM");
382
+ if (killFallbackTimer)
383
+ clearTimeout(killFallbackTimer);
384
+ killFallbackTimer = setTimeout(() => {
385
+ if (!exited)
386
+ child.kill("SIGKILL");
387
+ }, 5000);
388
+ killFallbackTimer.unref?.();
389
+ };
390
+ const onStopRequest = () => scheduleKill("stop-request");
391
+ stopSignal?.addEventListener("abort", onStopRequest, { once: true });
285
392
  child.stdout?.on("data", (chunk) => {
286
- const text = chunk.toString();
287
- stdout += text;
393
+ const text = outDecoder.write(chunk);
394
+ out.append(text);
288
395
  sinks?.stdout?.(text);
289
396
  });
290
397
  child.stderr?.on("data", (chunk) => {
291
- const text = chunk.toString();
292
- stderr += text;
398
+ const text = errDecoder.write(chunk);
399
+ err.append(text);
293
400
  sinks?.stderr?.(text);
294
401
  });
295
402
  const timer = setTimeout(() => {
296
- timedOut = true;
297
- child.kill("SIGTERM");
298
- setTimeout(() => {
299
- if (!exited)
300
- child.kill("SIGKILL");
301
- }, 5000);
403
+ scheduleKill("timeout");
302
404
  }, timeout);
303
405
  child.on("error", (err) => {
304
406
  clearTimeout(timer);
407
+ if (killFallbackTimer)
408
+ clearTimeout(killFallbackTimer);
409
+ stopSignal?.removeEventListener("abort", onStopRequest);
305
410
  reject(err);
306
411
  });
307
- child.on("close", (code) => {
412
+ child.on("close", (code, signal) => {
308
413
  exited = true;
309
414
  clearTimeout(timer);
415
+ if (killFallbackTimer)
416
+ clearTimeout(killFallbackTimer);
417
+ stopSignal?.removeEventListener("abort", onStopRequest);
418
+ const outFlush = outDecoder.end();
419
+ const errFlush = errDecoder.end();
420
+ if (outFlush) {
421
+ out.append(outFlush);
422
+ sinks?.stdout?.(outFlush);
423
+ }
424
+ if (errFlush) {
425
+ err.append(errFlush);
426
+ sinks?.stderr?.(errFlush);
427
+ }
310
428
  if (timedOut) {
311
- resolve({ exitCode: 1, stdout, stderr: stderr + "\n[trama] program killed: timeout" });
429
+ resolve({ exitCode: 1, stdout: out.value, stderr: err.value + "\n[trama] program killed: timeout" });
430
+ }
431
+ else if (stopRequested && (code === 0 || signal === "SIGTERM")) {
432
+ resolve({ exitCode: 0, stdout: out.value, stderr: err.value });
312
433
  }
313
434
  else {
314
- resolve({ exitCode: code ?? 1, stdout, stderr });
435
+ resolve({ exitCode: code ?? 1, stdout: out.value, stderr: err.value });
315
436
  }
316
437
  });
317
438
  });
@@ -325,10 +446,10 @@ function waitForChild(child, timeout, sinks) {
325
446
  */
326
447
  export function copyToHistory(projectDir, reason, detail) {
327
448
  const historyDir = join(projectDir, "history");
328
- const existing = readdirSync(historyDir).filter(f => /^\d{4}\.ts$/.test(f));
449
+ const existing = readdirSync(historyDir).filter(f => /^\d+\.ts$/.test(f));
329
450
  const nums = existing.map(f => parseInt(f.replace(".ts", ""), 10));
330
- const nextNum = nums.length > 0 ? Math.max(...nums) + 1 : 1;
331
- const next = String(nextNum).padStart(4, "0");
451
+ const nextNum = nums.length > 0 ? nums.reduce((a, b) => Math.max(a, b), 0) + 1 : 1;
452
+ const next = String(nextNum).padStart(Math.max(4, String(nextNum).length), "0");
332
453
  copyFileSync(join(projectDir, "program.ts"), join(historyDir, `${next}.ts`));
333
454
  const entry = { version: nextNum, reason, timestamp: new Date().toISOString() };
334
455
  if (reason === "repair" && detail)
@@ -337,63 +458,304 @@ export function copyToHistory(projectDir, reason, detail) {
337
458
  entry.prompt = detail;
338
459
  appendFileSync(join(historyDir, "index.jsonl"), JSON.stringify(entry) + "\n");
339
460
  }
340
- // --- Smoke run (used by create and update) ---
341
- export async function smokeRunAndRepair(projectDir, adapter, reason) {
342
- mkdirSync(join(projectDir, "history"), { recursive: true });
343
- mkdirSync(join(projectDir, "logs"), { recursive: true });
461
+ // --- Helpers ---
462
+ /**
463
+ * Snapshot a directory, run fn, restore from snapshot if fn returns false
464
+ * or if fn throws. Always cleans up the snapshot. Returns whatever fn returns.
465
+ */
466
+ export async function withSnapshot(dir, fn) {
467
+ const snap = mkdtempSync(join(tmpdir(), "trama-snapshot-"));
468
+ const restore = () => {
469
+ rmSync(dir, { recursive: true, force: true });
470
+ cpSync(snap, dir, { recursive: true });
471
+ };
472
+ try {
473
+ cpSync(dir, snap, { recursive: true });
474
+ let result;
475
+ try {
476
+ result = await fn();
477
+ }
478
+ catch (err) {
479
+ restore();
480
+ throw err;
481
+ }
482
+ if (!result.keep)
483
+ restore();
484
+ return result.value;
485
+ }
486
+ finally {
487
+ rmSync(snap, { recursive: true, force: true });
488
+ }
489
+ }
490
+ /** Run fn in a temp directory, clean up afterwards regardless of outcome. */
491
+ export async function withTempDir(prefix, fn) {
492
+ const dir = mkdtempSync(join(tmpdir(), prefix));
493
+ try {
494
+ return await fn(dir);
495
+ }
496
+ finally {
497
+ rmSync(dir, { recursive: true, force: true });
498
+ }
499
+ }
500
+ /**
501
+ * Attempt a single repair call with its own timeout and cancellation.
502
+ * Returns true if repair succeeded, false if it failed (error is appended to repairErrors).
503
+ */
504
+ async function repairWithTimeout(adapter, input, timeout, repairErrors) {
505
+ const controller = new AbortController();
506
+ const timer = setTimeout(() => controller.abort(), timeout);
507
+ try {
508
+ return await adapter.repair(input, controller.signal);
509
+ }
510
+ catch (err) {
511
+ repairErrors.push(err instanceof Error ? err.message : String(err));
512
+ return null;
513
+ }
514
+ finally {
515
+ clearTimeout(timer);
516
+ }
517
+ }
518
+ /**
519
+ * Run program.ts once in the given directory. Sets up scaffolding, IPC server,
520
+ * writes init file, spawns child, waits for result, and cleans up.
521
+ * Returns the child process result — does NOT throw on non-zero exit.
522
+ */
523
+ async function runProgramOnce(options) {
524
+ const { projectDir, adapter, timeout, maxIterations, argsOverride, streamOutput, stopOnReady } = options;
344
525
  ensureProjectScaffold(projectDir);
345
526
  ensureRuntimeLink(projectDir);
346
- const maxAttempts = 3;
347
- for (let attempt = 0; attempt <= maxAttempts; attempt++) {
348
- const ctx = createContext(projectDir, loadState(projectDir));
349
- const agentImpl = createAgent(adapter);
350
- const toolsImpl = createTools(projectDir);
351
- writeFileSync(join(projectDir, "logs", "latest.jsonl"), "");
352
- const server = createIPCServer(ctx, agentImpl, toolsImpl);
353
- const port = await startServer(server);
527
+ const abortController = new AbortController();
528
+ const stopController = new AbortController();
529
+ const { signal } = abortController;
530
+ let readyStopScheduled = false;
531
+ let readyStopTimer = null;
532
+ const ctx = createContext(projectDir, loadState(projectDir), {
533
+ maxIterations,
534
+ argsOverride,
535
+ onReady: stopOnReady ? () => {
536
+ if (readyStopScheduled)
537
+ return;
538
+ readyStopScheduled = true;
539
+ readyStopTimer = setTimeout(() => {
540
+ stopController.abort();
541
+ }, stopOnReady.graceMs);
542
+ readyStopTimer.unref?.();
543
+ } : undefined,
544
+ });
545
+ // Truncate logs only after preflight succeeds — preserves prior run's diagnostics
546
+ // if scaffolding, state loading, or context creation fails.
547
+ writeFileSync(join(projectDir, "logs", "latest.jsonl"), "");
548
+ const agentImpl = createAgent(adapter, signal);
549
+ const toolsImpl = createTools(projectDir, signal);
550
+ const server = createIPCServer(ctx, agentImpl, toolsImpl);
551
+ // Infrastructure setup — errors here are NOT program bugs.
552
+ let port;
553
+ try {
554
+ port = await startServer(server);
555
+ }
556
+ catch (infraError) {
557
+ await forceCloseServer(server, toolsImpl, abortController);
558
+ throw infraError;
559
+ }
560
+ // Write init data to a temp file instead of env vars to avoid OS size limits.
561
+ // Use mkdtempSync for an unpredictable path and mode 0o600 to prevent local disclosure.
562
+ const initDir = mkdtempSync(join(tmpdir(), "trama-init-"));
563
+ const initFile = join(initDir, "init.json");
564
+ const fd = openSync(initFile, "w", 0o600);
565
+ try {
566
+ writeFileSync(fd, JSON.stringify({
567
+ input: ctx.input,
568
+ state: ctx.state,
569
+ iteration: ctx.iteration,
570
+ maxIterations: ctx.maxIterations,
571
+ }));
572
+ }
573
+ finally {
574
+ closeSync(fd);
575
+ }
576
+ const child = spawn(process.execPath, [TSX_CLI, join(projectDir, "program.ts")], {
577
+ cwd: projectDir,
578
+ env: {
579
+ ...process.env,
580
+ TRAMA_PORT: String(port),
581
+ TRAMA_INIT: initFile,
582
+ },
583
+ stdio: ["pipe", "pipe", "pipe"],
584
+ });
585
+ let result;
586
+ try {
587
+ result = await waitForChild(child, {
588
+ timeout,
589
+ stopSignal: stopOnReady ? stopController.signal : undefined,
590
+ sinks: streamOutput ? {
591
+ stdout: chunk => { process.stdout.write(chunk); },
592
+ stderr: chunk => { process.stderr.write(chunk); },
593
+ } : undefined,
594
+ });
595
+ }
596
+ catch (spawnError) {
597
+ if (readyStopTimer)
598
+ clearTimeout(readyStopTimer);
599
+ await forceCloseServer(server, toolsImpl, abortController);
354
600
  try {
355
- const meta = JSON.parse(readFileSync(join(projectDir, "meta.json"), "utf-8"));
356
- const child = spawn(process.execPath, [TSX_CLI, join(projectDir, "program.ts")], {
357
- cwd: projectDir,
358
- env: {
359
- ...process.env,
360
- TRAMA_PORT: String(port),
361
- TRAMA_INPUT: JSON.stringify(meta.input),
362
- TRAMA_STATE: JSON.stringify(ctx.state),
363
- TRAMA_ITERATION: String(ctx.iteration),
364
- TRAMA_MAX_ITERATIONS: String(ctx.maxIterations),
365
- },
366
- stdio: ["pipe", "pipe", "pipe"],
601
+ rmSync(initDir, { recursive: true, force: true });
602
+ }
603
+ catch { /* best-effort */ }
604
+ throw spawnError;
605
+ }
606
+ if (readyStopTimer)
607
+ clearTimeout(readyStopTimer);
608
+ try {
609
+ rmSync(initDir, { recursive: true, force: true });
610
+ }
611
+ catch { /* best-effort */ }
612
+ // Always kill background shells — even on success, spawned background
613
+ // processes would otherwise outlive the runner and leak.
614
+ toolsImpl.killActiveShells();
615
+ if (result.exitCode === 0) {
616
+ try {
617
+ await closeServer(server);
618
+ }
619
+ catch {
620
+ await forceCloseServer(server, toolsImpl, abortController);
621
+ }
622
+ }
623
+ else {
624
+ try {
625
+ await forceCloseServer(server, toolsImpl, abortController);
626
+ }
627
+ catch { /* best-effort */ }
628
+ }
629
+ return result;
630
+ }
631
+ const formatError = (r) => `program.ts exited with code ${r.exitCode}\nstdout: ${r.stdout}\nstderr: ${r.stderr}`;
632
+ async function executeProgram(options) {
633
+ const { projectDir, adapter, maxRepairAttempts, timeout, maxIterations } = options;
634
+ mkdirSync(join(projectDir, "history"), { recursive: true });
635
+ mkdirSync(join(projectDir, "logs"), { recursive: true });
636
+ // Phase 1: Run in the real project directory.
637
+ const result = await runProgramOnce({
638
+ projectDir, adapter, timeout, maxIterations,
639
+ argsOverride: options.argsOverride,
640
+ streamOutput: true,
641
+ stopOnReady: options.stopOnReady,
642
+ });
643
+ if (result.exitCode === 0)
644
+ return;
645
+ if (maxRepairAttempts === 0) {
646
+ throw new Error(`Failed after 0 repair attempts: ${formatError(result)}`);
647
+ }
648
+ // Phase 2: Repair loop — both LLM repair call and verification run
649
+ // are fully isolated in temp dirs to prevent side effects on the real project.
650
+ let lastError = formatError(result);
651
+ const originalSource = readFileSync(join(projectDir, "program.ts"), "utf-8");
652
+ let currentSource = originalSource;
653
+ const repairErrors = [];
654
+ const repairDetails = () => repairErrors.length > 0
655
+ ? `\nRepair errors:\n${repairErrors.map((e, i) => ` [${i + 1}] ${e}`).join("\n")}` : "";
656
+ for (let attempt = 0; attempt < maxRepairAttempts; attempt++) {
657
+ const repairResult = await withTempDir("trama-repair-", async (tempDir) => {
658
+ cpSync(projectDir, tempDir, { recursive: true });
659
+ const tempAdapter = adapter.withCwd(tempDir);
660
+ const fixed = await repairWithTimeout(tempAdapter, { programSource: currentSource, error: lastError, runtimeTypes: RUNTIME_TYPES }, timeout, repairErrors);
661
+ if (!fixed)
662
+ return null;
663
+ writeFileSync(join(tempDir, "program.ts"), fixed);
664
+ const verifyResult = await runProgramOnce({
665
+ projectDir: tempDir, adapter: tempAdapter, timeout, maxIterations,
666
+ argsOverride: options.argsOverride,
667
+ stopOnReady: options.stopOnReady,
367
668
  });
368
- const result = await waitForChild(child, 5000, {
369
- stdout: chunk => { process.stdout.write(chunk); },
669
+ return { fixed, verifyResult };
670
+ });
671
+ if (!repairResult) {
672
+ // Repair LLM call itself failed — don't re-run the same broken program.
673
+ throw new Error(`Failed after ${attempt + 1} repair attempt(s): ${lastError}${repairDetails()}`);
674
+ }
675
+ if (repairResult.verifyResult.exitCode === 0) {
676
+ // Repair verified in isolation — now run in the real project for actual output.
677
+ // Snapshot first so we can restore cleanly if the real run fails.
678
+ const realResult = await withSnapshot(projectDir, async () => {
679
+ writeFileSync(join(projectDir, "program.ts"), repairResult.fixed);
680
+ const r = await runProgramOnce({
681
+ projectDir, adapter, timeout, maxIterations,
682
+ argsOverride: options.argsOverride,
683
+ streamOutput: true,
684
+ stopOnReady: options.stopOnReady,
685
+ });
686
+ return { keep: r.exitCode === 0, value: r };
370
687
  });
371
- if (result.exitCode === 0) {
372
- await closeServer(server);
688
+ if (realResult.exitCode === 0) {
689
+ // Bookkeeping is best-effort — program already succeeded and side effects
690
+ // are committed. Don't mask success with a history/log write failure.
691
+ try {
692
+ options.onRepair?.(attempt, maxRepairAttempts, lastError);
693
+ }
694
+ catch (bookkeepingErr) {
695
+ console.warn(`[trama] repair bookkeeping failed: ${bookkeepingErr instanceof Error ? bookkeepingErr.message : bookkeepingErr}`);
696
+ }
373
697
  return;
374
698
  }
375
- throw new Error(`Smoke run failed (exit ${result.exitCode})\nstdout: ${result.stdout}\nstderr: ${result.stderr}`);
699
+ // Passed in isolation but failed in real dir — project already restored by withSnapshot.
700
+ currentSource = repairResult.fixed;
701
+ lastError = formatError(realResult);
702
+ continue;
376
703
  }
377
- catch (error) {
378
- if (attempt === maxAttempts) {
379
- await forceCloseServer(server, toolsImpl);
380
- throw new Error(`Smoke run failed after ${maxAttempts} repair attempts: ${error}`);
381
- }
382
- appendFileSync(join(projectDir, "history", "index.jsonl"), JSON.stringify({
383
- reason: `${reason}-repair`,
384
- timestamp: new Date().toISOString(),
385
- error: String(error),
386
- }) + "\n");
387
- const source = readFileSync(join(projectDir, "program.ts"), "utf-8");
388
- const fixed = await adapter.repair({
389
- programSource: source,
390
- error: String(error),
391
- runtimeTypes: RUNTIME_TYPES,
704
+ // Repair produced broken code — update context for next attempt.
705
+ currentSource = repairResult.fixed;
706
+ lastError = formatError(repairResult.verifyResult);
707
+ }
708
+ throw new Error(`Failed after ${maxRepairAttempts} repair attempts: ${lastError}${repairDetails()}`);
709
+ }
710
+ // --- Smoke run (used by create and update) ---
711
+ /** Copy new history entries from src to dst (appends only entries added after the shared prefix). */
712
+ function propagateHistoryEntries(srcDir, dstDir) {
713
+ const srcPath = join(srcDir, "history", "index.jsonl");
714
+ const dstPath = join(dstDir, "history", "index.jsonl");
715
+ if (!existsSync(srcPath))
716
+ return;
717
+ const srcHistory = readFileSync(srcPath, "utf-8");
718
+ const dstHistory = existsSync(dstPath) ? readFileSync(dstPath, "utf-8") : "";
719
+ if (!srcHistory.startsWith(dstHistory))
720
+ return; // History diverged — cannot safely propagate
721
+ const newEntries = srcHistory.slice(dstHistory.length);
722
+ if (newEntries.length > 0) {
723
+ mkdirSync(join(dstDir, "history"), { recursive: true });
724
+ appendFileSync(dstPath, newEntries);
725
+ }
726
+ }
727
+ const DEFAULT_SMOKE_TIMEOUT = 30_000;
728
+ const MAX_SMOKE_TIMEOUT = 30_000;
729
+ const SMOKE_READY_GRACE_MS = 250;
730
+ export async function smokeRunAndRepair(projectDir, adapter, reason, options) {
731
+ const requestedTimeout = options?.timeout ?? DEFAULT_SMOKE_TIMEOUT;
732
+ const smokeTimeout = Math.min(requestedTimeout, MAX_SMOKE_TIMEOUT);
733
+ // Run validation in a temp copy so side effects don't persist in the real project
734
+ await withTempDir("trama-smoke-", async (smokeDir) => {
735
+ cpSync(projectDir, smokeDir, { recursive: true });
736
+ const smokeAdapter = adapter.withCwd(smokeDir);
737
+ try {
738
+ await executeProgram({
739
+ projectDir: smokeDir,
740
+ adapter: smokeAdapter,
741
+ maxRepairAttempts: options?.maxRepairAttempts ?? 3,
742
+ timeout: smokeTimeout,
743
+ maxIterations: options?.maxIterations ?? 100,
744
+ stopOnReady: {
745
+ graceMs: SMOKE_READY_GRACE_MS,
746
+ },
747
+ onRepair(_attempt, _max, error) {
748
+ appendFileSync(join(smokeDir, "history", "index.jsonl"), JSON.stringify({ reason: `${reason}-repair`, timestamp: new Date().toISOString(), error }) + "\n");
749
+ },
392
750
  });
393
- writeFileSync(join(projectDir, "program.ts"), fixed);
394
- await forceCloseServer(server, toolsImpl);
751
+ // Smoke passed — copy back program.ts (may have been repaired)
752
+ copyFileSync(join(smokeDir, "program.ts"), join(projectDir, "program.ts"));
395
753
  }
396
- }
754
+ finally {
755
+ // Always propagate repair history, whether smoke passed or failed
756
+ propagateHistoryEntries(smokeDir, projectDir);
757
+ }
758
+ });
397
759
  }
398
760
  // --- Core execution ---
399
761
  export async function runProgram(options) {
@@ -412,59 +774,21 @@ export async function runProgram(options) {
412
774
  if (!Number.isInteger(maxRepairAttempts) || maxRepairAttempts < 0) {
413
775
  throw new Error(`Invalid maxRepairAttempts: ${maxRepairAttempts}. Must be a non-negative integer.`);
414
776
  }
415
- mkdirSync(join(projectDir, "history"), { recursive: true });
416
- mkdirSync(join(projectDir, "logs"), { recursive: true });
417
- ensureProjectScaffold(projectDir);
418
- ensureRuntimeLink(projectDir);
419
777
  const adapter = new PiAdapter(config, projectDir);
420
- for (let attempt = 0; attempt <= maxRepairAttempts; attempt++) {
421
- const ctx = createContext(projectDir, loadState(projectDir), { maxIterations });
422
- const agentImpl = createAgent(adapter);
423
- const toolsImpl = createTools(projectDir);
424
- const logsPath = join(projectDir, "logs", "latest.jsonl");
425
- writeFileSync(logsPath, "");
426
- const server = createIPCServer(ctx, agentImpl, toolsImpl);
427
- const port = await startServer(server);
428
- try {
429
- const meta = JSON.parse(readFileSync(join(projectDir, "meta.json"), "utf-8"));
430
- const child = spawn(process.execPath, [TSX_CLI, join(projectDir, "program.ts")], {
431
- cwd: projectDir,
432
- env: {
433
- ...process.env,
434
- TRAMA_PORT: String(port),
435
- TRAMA_INPUT: JSON.stringify(meta.input),
436
- TRAMA_STATE: JSON.stringify(ctx.state),
437
- TRAMA_ITERATION: String(ctx.iteration),
438
- TRAMA_MAX_ITERATIONS: String(ctx.maxIterations),
439
- },
440
- stdio: ["pipe", "pipe", "pipe"],
441
- });
442
- const result = await waitForChild(child, timeout, {
443
- stdout: chunk => { process.stdout.write(chunk); },
444
- });
445
- if (result.exitCode === 0) {
446
- await closeServer(server);
447
- return;
448
- }
449
- throw new Error(`program.ts exited with code ${result.exitCode}\n` +
450
- `stdout: ${result.stdout}\n` +
451
- `stderr: ${result.stderr}`);
452
- }
453
- catch (error) {
454
- if (attempt === maxRepairAttempts) {
455
- await forceCloseServer(server, toolsImpl);
456
- throw new Error(`Failed after ${maxRepairAttempts} repair attempts: ${error}`);
457
- }
458
- await ctx.log(`Repair attempt ${attempt + 1}/${maxRepairAttempts}`, { error: String(error) });
459
- const source = readFileSync(join(projectDir, "program.ts"), "utf-8");
460
- const fixed = await adapter.repair({
461
- programSource: source,
462
- error: String(error),
463
- runtimeTypes: RUNTIME_TYPES,
464
- });
465
- writeFileSync(join(projectDir, "program.ts"), fixed);
466
- copyToHistory(projectDir, "repair", String(error));
467
- await forceCloseServer(server, toolsImpl);
468
- }
469
- }
778
+ await executeProgram({
779
+ projectDir,
780
+ adapter,
781
+ maxRepairAttempts,
782
+ timeout,
783
+ maxIterations,
784
+ argsOverride: options.args,
785
+ onRepair(attempt, max, error) {
786
+ // Log repair attempts (appends to already-open logs file)
787
+ const logsPath = join(projectDir, "logs", "latest.jsonl");
788
+ const entry = { ts: Date.now(), message: `Repair attempt ${attempt + 1}/${max}`, data: { error } };
789
+ appendFileSync(logsPath, JSON.stringify(entry) + "\n");
790
+ console.log(`[trama] Repair attempt ${attempt + 1}/${max}`);
791
+ copyToHistory(projectDir, "repair", error);
792
+ },
793
+ });
470
794
  }