@trama-dev/runtime 0.1.1 → 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/agent.js CHANGED
@@ -28,27 +28,43 @@ export function createAgent(adapter, signal) {
28
28
  async generate(input) {
29
29
  const schemaInstruction = `Respond with ONLY a JSON object matching this shape:\n${JSON.stringify(input.schema, null, 2)}\nNo markdown. No explanation. Just the JSON.`;
30
30
  const fullPrompt = `${input.prompt}\n\n${schemaInstruction}`;
31
- const attempt = async (p) => {
32
- const response = await adapter.ask(p, signal ? { system: input.system, signal } : { system: input.system });
33
- const cleaned = response
34
- .trim()
35
- .replace(/^```json\s*/i, "")
36
- .replace(/^```\s*/, "")
37
- .replace(/\s*```$/, "")
38
- .trim();
39
- const parsed = JSON.parse(cleaned);
31
+ const askOptions = signal ? { system: input.system, signal } : { system: input.system };
32
+ const parseAndValidate = (response) => {
33
+ const trimmed = response.trim();
34
+ // Try raw parse first — avoids mangling valid JSON that contains
35
+ // fenced code blocks inside string values.
36
+ let parsed;
37
+ try {
38
+ parsed = JSON.parse(trimmed);
39
+ }
40
+ catch {
41
+ const fenceMatch = trimmed.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);
42
+ parsed = JSON.parse(fenceMatch ? fenceMatch[1].trim() : trimmed);
43
+ }
40
44
  const error = validateShape(parsed, input.schema);
41
45
  if (error)
42
46
  throw new Error(`Schema validation failed: ${error}`);
43
- return parsed;
47
+ return stripToSchema(parsed, input.schema);
44
48
  };
49
+ // First attempt — adapter errors (network/auth) propagate immediately.
50
+ // Only parse/validation failures trigger a retry.
51
+ const response = await adapter.ask(fullPrompt, askOptions);
45
52
  try {
46
- return await attempt(fullPrompt);
53
+ return parseAndValidate(response);
47
54
  }
48
55
  catch (firstError) {
49
56
  const retryPrompt = `Your previous response failed validation: ${firstError}.\nTry again.\n\n${fullPrompt}`;
50
- return await attempt(retryPrompt);
57
+ const retryResponse = await adapter.ask(retryPrompt, askOptions);
58
+ return parseAndValidate(retryResponse);
51
59
  }
52
60
  }
53
61
  };
54
62
  }
63
+ /** Return a new object containing only the keys declared in the schema. */
64
+ function stripToSchema(obj, schema) {
65
+ const result = {};
66
+ for (const key of Object.keys(schema)) {
67
+ result[key] = obj[key];
68
+ }
69
+ return result;
70
+ }
package/dist/client.js CHANGED
@@ -1,16 +1,19 @@
1
1
  // @trama-dev/runtime client — this is what program.ts imports.
2
2
  // Thin HTTP wrapper that calls the runner's IPC server.
3
+ import { readFileSync } from "fs";
3
4
  import { assertSerializable } from "./serializable.js";
4
5
  const PORT = process.env.TRAMA_PORT;
5
6
  if (!PORT) {
6
7
  throw new Error("@trama-dev/runtime must be executed via `trama run`. " +
7
8
  "Direct execution is not supported (TRAMA_PORT env var missing).");
8
9
  }
9
- if (!process.env.TRAMA_INPUT) {
10
- throw new Error("@trama-dev/runtime: TRAMA_INPUT env var missing. " +
10
+ const INIT_PATH = process.env.TRAMA_INIT;
11
+ if (!INIT_PATH) {
12
+ throw new Error("@trama-dev/runtime: TRAMA_INIT env var missing. " +
11
13
  "This program must be launched by the trama runner.");
12
14
  }
13
15
  const BASE = `http://127.0.0.1:${PORT}`;
16
+ const initData = JSON.parse(readFileSync(INIT_PATH, "utf-8"));
14
17
  async function call(endpoint, body) {
15
18
  const res = await fetch(`${BASE}${endpoint}`, {
16
19
  method: "POST",
@@ -22,14 +25,21 @@ async function call(endpoint, body) {
22
25
  return res.json();
23
26
  }
24
27
  let doneCalled = false;
28
+ let readyCalled = false;
25
29
  export const ctx = {
26
- input: JSON.parse(process.env.TRAMA_INPUT),
27
- state: JSON.parse(process.env.TRAMA_STATE ?? "{}"),
28
- iteration: parseInt(process.env.TRAMA_ITERATION ?? "0"),
29
- maxIterations: parseInt(process.env.TRAMA_MAX_ITERATIONS ?? "100"),
30
+ input: initData.input,
31
+ state: initData.state,
32
+ iteration: initData.iteration,
33
+ maxIterations: initData.maxIterations,
30
34
  async log(msg, data) {
31
35
  await call("/ctx/log", { message: msg, data });
32
36
  },
37
+ async ready(data) {
38
+ if (readyCalled)
39
+ return;
40
+ await call("/ctx/ready", { data });
41
+ readyCalled = true;
42
+ },
33
43
  async checkpoint() {
34
44
  assertSerializable(ctx.state, "ctx.state");
35
45
  await call("/ctx/checkpoint", { state: ctx.state });
package/dist/context.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import type { Ctx } from "./types.js";
2
2
  export declare function createContext(projectDir: string, initialState: Record<string, unknown>, options?: {
3
3
  maxIterations?: number;
4
+ argsOverride?: Record<string, unknown>;
5
+ onReady?: (data?: Record<string, unknown>) => void;
4
6
  }): Ctx;
package/dist/context.js CHANGED
@@ -7,8 +7,12 @@ export function createContext(projectDir, initialState, options) {
7
7
  const meta = JSON.parse(readFileSync(join(projectDir, "meta.json"), "utf-8"));
8
8
  let doneCalled = false;
9
9
  let doneLogged = false;
10
+ let readyCalled = false;
11
+ const input = options?.argsOverride
12
+ ? { ...meta.input, args: { ...(meta.input.args ?? {}), ...options.argsOverride } }
13
+ : meta.input;
10
14
  return {
11
- input: meta.input,
15
+ input,
12
16
  state: { ...initialState },
13
17
  iteration: typeof initialState.__trama_iteration === "number"
14
18
  && Number.isFinite(initialState.__trama_iteration)
@@ -19,6 +23,13 @@ export function createContext(projectDir, initialState, options) {
19
23
  appendFileSync(logsPath, JSON.stringify(entry) + "\n");
20
24
  console.log(`[trama] ${message}`);
21
25
  },
26
+ async ready(data) {
27
+ if (readyCalled)
28
+ return;
29
+ await this.log("ready", data);
30
+ options?.onReady?.(data);
31
+ readyCalled = true;
32
+ },
22
33
  async checkpoint() {
23
34
  assertSerializable(this.state, "ctx.state");
24
35
  const nextIteration = this.iteration + 1;
package/dist/index.d.ts CHANGED
@@ -3,6 +3,7 @@ export declare function validateProjectName(name: string): void;
3
3
  export declare function resolveProject(name: string): string;
4
4
  export declare function createProject(name: string, prompt: string, options?: {
5
5
  model?: string;
6
+ args?: Record<string, unknown>;
6
7
  }): Promise<void>;
7
8
  export declare function updateProject(name: string, prompt: string): Promise<void>;
8
9
  export declare function listProjects(): Promise<void>;
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { readFileSync, writeFileSync, mkdirSync, readdirSync, existsSync, copyFileSync, appendFileSync, statSync, rmSync, cpSync, mkdtempSync } from "fs";
3
3
  import { join } from "path";
4
4
  import { homedir, tmpdir } from "os";
5
- import { PiAdapter } from "./pi-adapter.js";
5
+ import { PiAdapter, stripCodeFences } from "./pi-adapter.js";
6
6
  import { loadConfig, loadState, smokeRunAndRepair, copyToHistory, withTempDir, RUNTIME_TYPES, PI_VERSION } from "./runner.js";
7
7
  export { runProgram } from "./runner.js";
8
8
  // --- Example programs (included in system prompt during create/update) ---
@@ -56,16 +56,38 @@ for (let i = ctx.iteration; i < ctx.maxIterations; i++) {
56
56
  }
57
57
 
58
58
  await tools.write("target.ts", code);
59
- await ctx.done({ finalMetric: bestMetric });`;
60
- function stripCodeFences(text) {
61
- const trimmed = text.trim();
62
- if (/^```/.test(trimmed) && /```$/.test(trimmed)) {
63
- return trimmed.replace(/^```\w*\s*\n?/, "").replace(/\n?\s*```$/, "");
64
- }
65
- return text;
66
- }
59
+ await ctx.done({ finalMetric: bestMetric });
60
+
61
+ // Example D: Long-running server.
62
+ // Call ctx.ready() only after the server is actually listening.
63
+ // Handle SIGTERM/SIGINT so smoke validation can shut it down cleanly.
64
+ import { ctx } from "@trama-dev/runtime";
65
+ import { createServer } from "node:http";
66
+
67
+ const server = createServer((_req, res) => {
68
+ res.end("ok");
69
+ });
70
+
71
+ await new Promise<void>((resolve, reject) => {
72
+ server.once("error", reject);
73
+ server.listen(3000, "127.0.0.1", () => resolve());
74
+ });
75
+
76
+ await ctx.ready({ url: "http://127.0.0.1:3000" });
77
+
78
+ process.on("SIGTERM", () => {
79
+ server.close();
80
+ process.exit(0);
81
+ });
82
+ process.on("SIGINT", () => {
83
+ server.close();
84
+ process.exit(0);
85
+ });
86
+
87
+ await new Promise<void>(() => {});`;
67
88
  function getSystemPrompt() {
68
89
  return (`You are generating a TypeScript program for the trama runtime.\n\n` +
90
+ `If the program is long-running (for example an HTTP server), call ctx.ready(...) after startup completes and handle SIGTERM/SIGINT for clean shutdown.\n\n` +
69
91
  `Runtime API:\n${RUNTIME_TYPES}\n\n` +
70
92
  `Examples:\n${EXAMPLE_PROGRAMS}`);
71
93
  }
@@ -131,7 +153,7 @@ export async function createProject(name, prompt, options) {
131
153
  writeFileSync(join(projectDir, "package.json"), JSON.stringify({ type: "module" }, null, 2));
132
154
  writeFileSync(join(projectDir, ".gitignore"), "node_modules/\nstate.json\nlogs/\nhistory/\n");
133
155
  const meta = {
134
- input: { prompt, args: {} },
156
+ input: { prompt, args: options?.args ?? {} },
135
157
  createdAt: new Date().toISOString(),
136
158
  piVersion: PI_VERSION,
137
159
  };
@@ -1,4 +1,6 @@
1
1
  import type { PiAdapterConfig, RepairInput } from "./types.js";
2
+ /** Strip markdown code fences and trim whitespace. */
3
+ export declare function stripCodeFences(text: string): string;
2
4
  export declare class PiAdapter {
3
5
  private config;
4
6
  private cwd;
@@ -1,5 +1,13 @@
1
1
  import { createAgentSession, SessionManager, DefaultResourceLoader, } from "@mariozechner/pi-coding-agent";
2
2
  import { getModel } from "@mariozechner/pi-ai";
3
+ /** Strip markdown code fences and trim whitespace. */
4
+ export function stripCodeFences(text) {
5
+ const trimmed = text.trim();
6
+ if (/^```/.test(trimmed) && /```$/.test(trimmed)) {
7
+ return trimmed.replace(/^```\w*\s*\n?/, "").replace(/\n?\s*```$/, "");
8
+ }
9
+ return trimmed;
10
+ }
3
11
  export class PiAdapter {
4
12
  config;
5
13
  cwd;
@@ -100,10 +108,6 @@ export class PiAdapter {
100
108
  `Broken program:\n${input.programSource}\n\n` +
101
109
  `Error:\n${input.error}\n\n` +
102
110
  `Output ONLY the fixed program. No explanation.`, { system: "You are a TypeScript repair tool.", signal });
103
- const trimmed = response.trim();
104
- if (/^```/.test(trimmed) && /```$/.test(trimmed)) {
105
- return trimmed.replace(/^```\w*\s*\n?/, "").replace(/\n?\s*```$/, "");
106
- }
107
- return response;
111
+ return stripCodeFences(response);
108
112
  }
109
113
  }
package/dist/runner.d.ts CHANGED
@@ -8,7 +8,7 @@ export declare const PI_VERSION: string;
8
8
  * needs a concise reference, not the full implementation types.
9
9
  * If types.ts changes, review whether this summary needs updating.
10
10
  */
11
- export declare const RUNTIME_TYPES = "// @trama-dev/runtime - Complete API\n\nexport interface Ctx {\n input: { prompt: string; args: Record<string, unknown> };\n state: Record<string, unknown>;\n iteration: number;\n maxIterations: number;\n log(message: string, data?: Record<string, unknown>): Promise<void>;\n checkpoint(): Promise<void>;\n done(result?: Record<string, unknown>): Promise<void>;\n}\n\nexport interface Agent {\n ask(prompt: string, options?: { system?: string }): Promise<string>;\n generate<T>(input: {\n prompt: string;\n schema: Record<string, string>;\n system?: string;\n }): Promise<T>;\n}\n\nexport interface ShellResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nexport interface Tools {\n read(path: string): Promise<string>;\n write(path: string, content: string): Promise<void>;\n shell(command: string, options?: { cwd?: string; timeout?: number }): Promise<ShellResult>;\n fetch(url: string, options?: {\n method?: string;\n headers?: Record<string, string>;\n body?: string;\n }): Promise<{ status: number; body: string; headers: Record<string, string> }>;\n}\n\nexport declare const ctx: Ctx;\nexport declare const agent: Agent;\nexport declare const tools: Tools;";
11
+ export declare const RUNTIME_TYPES = "// @trama-dev/runtime - Complete API\n\nexport interface Ctx {\n input: { prompt: string; args: Record<string, unknown> };\n state: Record<string, unknown>;\n iteration: number;\n maxIterations: number;\n log(message: string, data?: Record<string, unknown>): Promise<void>;\n ready(data?: Record<string, unknown>): Promise<void>;\n checkpoint(): Promise<void>;\n done(result?: Record<string, unknown>): Promise<void>;\n}\n\nexport interface Agent {\n ask(prompt: string, options?: { system?: string }): Promise<string>;\n generate<T>(input: {\n prompt: string;\n schema: Record<string, string>;\n system?: string;\n }): Promise<T>;\n}\n\nexport interface ShellResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nexport interface Tools {\n read(path: string): Promise<string>;\n write(path: string, content: string): Promise<void>;\n shell(command: string, options?: { cwd?: string; timeout?: number }): Promise<ShellResult>;\n fetch(url: string, options?: {\n method?: string;\n headers?: Record<string, string>;\n body?: string;\n }): Promise<{ status: number; body: string; headers: Record<string, string> }>;\n}\n\nexport declare const ctx: Ctx;\nexport declare const agent: Agent;\nexport declare const tools: Tools;";
12
12
  export declare function loadConfig(): TramaConfig;
13
13
  export declare function loadState(projectDir: string): Record<string, unknown>;
14
14
  /**
@@ -18,6 +18,14 @@ export declare function loadState(projectDir: string): Record<string, unknown>;
18
18
  * Create-time repairs go to index.jsonl only (reason: "create-repair").
19
19
  */
20
20
  export declare function copyToHistory(projectDir: string, reason: string, detail?: string): void;
21
+ /**
22
+ * Snapshot a directory, run fn, restore from snapshot if fn returns false
23
+ * or if fn throws. Always cleans up the snapshot. Returns whatever fn returns.
24
+ */
25
+ export declare function withSnapshot<T>(dir: string, fn: () => Promise<{
26
+ keep: boolean;
27
+ value: T;
28
+ }>): Promise<T>;
21
29
  /** Run fn in a temp directory, clean up afterwards regardless of outcome. */
22
30
  export declare function withTempDir<T>(prefix: string, fn: (dir: string) => Promise<T>): Promise<T>;
23
31
  export declare function smokeRunAndRepair(projectDir: string, adapter: PiAdapter, reason: "create" | "update", options?: {
package/dist/runner.js CHANGED
@@ -1,9 +1,10 @@
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";
@@ -117,6 +118,7 @@ export interface Ctx {
117
118
  iteration: number;
118
119
  maxIterations: number;
119
120
  log(message: string, data?: Record<string, unknown>): Promise<void>;
121
+ ready(data?: Record<string, unknown>): Promise<void>;
120
122
  checkpoint(): Promise<void>;
121
123
  done(result?: Record<string, unknown>): Promise<void>;
122
124
  }
@@ -155,7 +157,7 @@ export function loadConfig() {
155
157
  const configPath = join(homedir(), ".trama", "config.json");
156
158
  const defaults = {
157
159
  provider: "anthropic",
158
- model: "claude-sonnet-4-20250514",
160
+ model: "claude-opus-4-6",
159
161
  maxRepairAttempts: 3,
160
162
  defaultTimeout: 300_000,
161
163
  defaultMaxIterations: 100,
@@ -218,6 +220,7 @@ export function loadState(projectDir) {
218
220
  return parsed;
219
221
  }
220
222
  // --- IPC Server ---
223
+ const MAX_IPC_BODY = 50 * 1024 * 1024; // 50 MB
221
224
  function createIPCServer(ctx, agentImpl, toolsImpl) {
222
225
  return createServer((req, res) => {
223
226
  if (req.method !== "POST") {
@@ -225,11 +228,26 @@ function createIPCServer(ctx, agentImpl, toolsImpl) {
225
228
  res.end("Method not allowed");
226
229
  return;
227
230
  }
228
- let body = "";
229
- 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
+ });
230
246
  req.on("end", async () => {
247
+ if (overflow)
248
+ return;
231
249
  try {
232
- const data = JSON.parse(body);
250
+ const data = JSON.parse(Buffer.concat(chunks).toString("utf-8"));
233
251
  let result;
234
252
  switch (req.url) {
235
253
  case "/agent/ask":
@@ -275,6 +293,11 @@ function createIPCServer(ctx, agentImpl, toolsImpl) {
275
293
  res.writeHead(200, { "Content-Type": "application/json" });
276
294
  res.end(JSON.stringify({ result: null }));
277
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;
278
301
  case "/ctx/done":
279
302
  ctx.state = data.state;
280
303
  await ctx.done(data.result);
@@ -332,46 +355,82 @@ function forceCloseServer(server, toolsImpl, abortController) {
332
355
  * Collect stdout/stderr as strings and wait for exit.
333
356
  * Enforces wall-clock timeout via explicit setTimeout + kill.
334
357
  */
335
- function waitForChild(child, timeout, sinks) {
358
+ function waitForChild(child, options) {
359
+ const { timeout, sinks, stopSignal } = options;
336
360
  return new Promise((resolve, reject) => {
337
361
  const out = cappedBuffer();
338
362
  const err = cappedBuffer();
363
+ const outDecoder = new StringDecoder("utf-8");
364
+ const errDecoder = new StringDecoder("utf-8");
339
365
  let timedOut = false;
340
366
  let exited = false;
367
+ let stopRequested = false;
341
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 });
342
392
  child.stdout?.on("data", (chunk) => {
343
- const text = chunk.toString();
393
+ const text = outDecoder.write(chunk);
344
394
  out.append(text);
345
395
  sinks?.stdout?.(text);
346
396
  });
347
397
  child.stderr?.on("data", (chunk) => {
348
- const text = chunk.toString();
398
+ const text = errDecoder.write(chunk);
349
399
  err.append(text);
350
400
  sinks?.stderr?.(text);
351
401
  });
352
402
  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?.();
403
+ scheduleKill("timeout");
360
404
  }, timeout);
361
405
  child.on("error", (err) => {
362
406
  clearTimeout(timer);
363
407
  if (killFallbackTimer)
364
408
  clearTimeout(killFallbackTimer);
409
+ stopSignal?.removeEventListener("abort", onStopRequest);
365
410
  reject(err);
366
411
  });
367
- child.on("close", (code) => {
412
+ child.on("close", (code, signal) => {
368
413
  exited = true;
369
414
  clearTimeout(timer);
370
415
  if (killFallbackTimer)
371
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
+ }
372
428
  if (timedOut) {
373
429
  resolve({ exitCode: 1, stdout: out.value, stderr: err.value + "\n[trama] program killed: timeout" });
374
430
  }
431
+ else if (stopRequested && (code === 0 || signal === "SIGTERM")) {
432
+ resolve({ exitCode: 0, stdout: out.value, stderr: err.value });
433
+ }
375
434
  else {
376
435
  resolve({ exitCode: code ?? 1, stdout: out.value, stderr: err.value });
377
436
  }
@@ -389,7 +448,7 @@ export function copyToHistory(projectDir, reason, detail) {
389
448
  const historyDir = join(projectDir, "history");
390
449
  const existing = readdirSync(historyDir).filter(f => /^\d+\.ts$/.test(f));
391
450
  const nums = existing.map(f => parseInt(f.replace(".ts", ""), 10));
392
- const nextNum = nums.length > 0 ? Math.max(...nums) + 1 : 1;
451
+ const nextNum = nums.length > 0 ? nums.reduce((a, b) => Math.max(a, b), 0) + 1 : 1;
393
452
  const next = String(nextNum).padStart(Math.max(4, String(nextNum).length), "0");
394
453
  copyFileSync(join(projectDir, "program.ts"), join(historyDir, `${next}.ts`));
395
454
  const entry = { version: nextNum, reason, timestamp: new Date().toISOString() };
@@ -400,6 +459,34 @@ export function copyToHistory(projectDir, reason, detail) {
400
459
  appendFileSync(join(historyDir, "index.jsonl"), JSON.stringify(entry) + "\n");
401
460
  }
402
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
+ }
403
490
  /** Run fn in a temp directory, clean up afterwards regardless of outcome. */
404
491
  export async function withTempDir(prefix, fn) {
405
492
  const dir = mkdtempSync(join(tmpdir(), prefix));
@@ -428,114 +515,197 @@ async function repairWithTimeout(adapter, input, timeout, repairErrors) {
428
515
  clearTimeout(timer);
429
516
  }
430
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;
525
+ ensureProjectScaffold(projectDir);
526
+ ensureRuntimeLink(projectDir);
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);
600
+ try {
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}`;
431
632
  async function executeProgram(options) {
432
633
  const { projectDir, adapter, maxRepairAttempts, timeout, maxIterations } = options;
433
634
  mkdirSync(join(projectDir, "history"), { recursive: true });
434
635
  mkdirSync(join(projectDir, "logs"), { recursive: true });
435
- ensureProjectScaffold(projectDir);
436
- ensureRuntimeLink(projectDir);
437
- writeFileSync(join(projectDir, "logs", "latest.jsonl"), "");
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);
438
651
  const originalSource = readFileSync(join(projectDir, "program.ts"), "utf-8");
652
+ let currentSource = originalSource;
439
653
  const repairErrors = [];
440
654
  const repairDetails = () => repairErrors.length > 0
441
655
  ? `\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"],
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,
473
668
  });
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); },
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,
482
685
  });
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.
686
+ return { keep: r.exitCode === 0, value: r };
687
+ });
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.
493
691
  try {
494
- await closeServer(server);
495
- }
496
- catch {
497
- await forceCloseServer(server, toolsImpl, abortController);
692
+ options.onRepair?.(attempt, maxRepairAttempts, lastError);
498
693
  }
499
- if (pendingRepair) {
500
- options.onRepair?.(pendingRepair.attempt, maxRepairAttempts, pendingRepair.error);
694
+ catch (bookkeepingErr) {
695
+ console.warn(`[trama] repair bookkeeping failed: ${bookkeepingErr instanceof Error ? bookkeepingErr.message : bookkeepingErr}`);
501
696
  }
502
697
  return;
503
698
  }
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
- }
699
+ // Passed in isolation but failed in real dir — project already restored by withSnapshot.
700
+ currentSource = repairResult.fixed;
701
+ lastError = formatError(realResult);
702
+ continue;
528
703
  }
704
+ // Repair produced broken code — update context for next attempt.
705
+ currentSource = repairResult.fixed;
706
+ lastError = formatError(repairResult.verifyResult);
529
707
  }
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
- }
708
+ throw new Error(`Failed after ${maxRepairAttempts} repair attempts: ${lastError}${repairDetails()}`);
539
709
  }
540
710
  // --- Smoke run (used by create and update) ---
541
711
  /** Copy new history entries from src to dst (appends only entries added after the shared prefix). */
@@ -554,8 +724,12 @@ function propagateHistoryEntries(srcDir, dstDir) {
554
724
  appendFileSync(dstPath, newEntries);
555
725
  }
556
726
  }
727
+ const DEFAULT_SMOKE_TIMEOUT = 30_000;
728
+ const MAX_SMOKE_TIMEOUT = 30_000;
729
+ const SMOKE_READY_GRACE_MS = 250;
557
730
  export async function smokeRunAndRepair(projectDir, adapter, reason, options) {
558
- const smokeTimeout = options?.timeout ?? 30_000;
731
+ const requestedTimeout = options?.timeout ?? DEFAULT_SMOKE_TIMEOUT;
732
+ const smokeTimeout = Math.min(requestedTimeout, MAX_SMOKE_TIMEOUT);
559
733
  // Run validation in a temp copy so side effects don't persist in the real project
560
734
  await withTempDir("trama-smoke-", async (smokeDir) => {
561
735
  cpSync(projectDir, smokeDir, { recursive: true });
@@ -567,6 +741,9 @@ export async function smokeRunAndRepair(projectDir, adapter, reason, options) {
567
741
  maxRepairAttempts: options?.maxRepairAttempts ?? 3,
568
742
  timeout: smokeTimeout,
569
743
  maxIterations: options?.maxIterations ?? 100,
744
+ stopOnReady: {
745
+ graceMs: SMOKE_READY_GRACE_MS,
746
+ },
570
747
  onRepair(_attempt, _max, error) {
571
748
  appendFileSync(join(smokeDir, "history", "index.jsonl"), JSON.stringify({ reason: `${reason}-repair`, timestamp: new Date().toISOString(), error }) + "\n");
572
749
  },
@@ -604,6 +781,7 @@ export async function runProgram(options) {
604
781
  maxRepairAttempts,
605
782
  timeout,
606
783
  maxIterations,
784
+ argsOverride: options.args,
607
785
  onRepair(attempt, max, error) {
608
786
  // Log repair attempts (appends to already-open logs file)
609
787
  const logsPath = join(projectDir, "logs", "latest.jsonl");
package/dist/tools.js CHANGED
@@ -1,6 +1,7 @@
1
- import { spawn, spawnSync } from "child_process";
1
+ import { spawn } from "child_process";
2
2
  import { readFileSync, writeFileSync, mkdirSync, realpathSync, readlinkSync, lstatSync, existsSync } from "fs";
3
3
  import { resolve, dirname, sep } from "path";
4
+ import { StringDecoder } from "string_decoder";
4
5
  const MAX_OUTPUT = 10 * 1024 * 1024; // 10 MB
5
6
  export function cappedBuffer() {
6
7
  let buf = "";
@@ -37,39 +38,23 @@ export function createTools(projectDir, signal) {
37
38
  sessionReapers.delete(sessionId);
38
39
  }
39
40
  };
40
- const listSessionPids = (sessionId) => {
41
- const result = spawnSync("ps", ["-o", "pid=", "-s", String(sessionId)], {
42
- encoding: "utf-8",
43
- });
44
- if (result.error)
45
- return [];
46
- return result.stdout
47
- .split("\n")
48
- .map(line => parseInt(line.trim(), 10))
49
- .filter(pid => Number.isInteger(pid) && pid > 0);
50
- };
51
41
  const killSession = (sessionId, signal) => {
52
- const pids = listSessionPids(sessionId);
53
- if (pids.length > 0) {
54
- for (const pid of pids) {
55
- try {
56
- process.kill(pid, signal);
57
- }
58
- catch { /* already exited */ }
59
- }
60
- return;
61
- }
62
42
  try {
63
43
  process.kill(-sessionId, signal);
64
44
  }
65
45
  catch { /* already exited */ }
66
46
  };
47
+ /** Poll until the process group is gone, then remove from tracking. */
67
48
  const reapSessionWhenGone = (sessionId) => {
68
49
  stopReapingSession(sessionId);
69
50
  const timer = setTimeout(() => {
70
51
  if (!activeSessions.has(sessionId))
71
52
  return;
72
- if (listSessionPids(sessionId).length === 0) {
53
+ try {
54
+ process.kill(-sessionId, 0); // signal 0: check if process group still exists
55
+ }
56
+ catch {
57
+ // ESRCH — process group gone
73
58
  activeSessions.delete(sessionId);
74
59
  sessionReapers.delete(sessionId);
75
60
  return;
@@ -180,11 +165,13 @@ export function createTools(projectDir, signal) {
180
165
  activeSessions.add(child.pid);
181
166
  const out = cappedBuffer();
182
167
  const err = cappedBuffer();
168
+ const outDecoder = new StringDecoder("utf-8");
169
+ const errDecoder = new StringDecoder("utf-8");
183
170
  let timedOut = false;
184
171
  let exited = false;
185
172
  let killFallbackTimer = null;
186
- child.stdout.on("data", (chunk) => { out.append(String(chunk)); });
187
- child.stderr.on("data", (chunk) => { err.append(String(chunk)); });
173
+ child.stdout.on("data", (chunk) => { out.append(outDecoder.write(chunk)); });
174
+ child.stderr.on("data", (chunk) => { err.append(errDecoder.write(chunk)); });
188
175
  const timer = setTimeout(() => {
189
176
  timedOut = true;
190
177
  if (child.pid) {
@@ -197,7 +184,7 @@ export function createTools(projectDir, signal) {
197
184
  }, 5000);
198
185
  killFallbackTimer.unref?.();
199
186
  }, timeout);
200
- child.on("error", (err) => {
187
+ child.on("error", (spawnError) => {
201
188
  clearTimeout(timer);
202
189
  if (killFallbackTimer)
203
190
  clearTimeout(killFallbackTimer);
@@ -206,7 +193,7 @@ export function createTools(projectDir, signal) {
206
193
  activeSessions.delete(child.pid);
207
194
  stopReapingSession(child.pid);
208
195
  }
209
- resolve({ exitCode: 1, stdout: out.value, stderr: err.message });
196
+ resolve({ exitCode: 1, stdout: out.value, stderr: spawnError.message });
210
197
  });
211
198
  child.on("close", (code) => {
212
199
  exited = true;
@@ -216,6 +203,12 @@ export function createTools(projectDir, signal) {
216
203
  clearTimeout(killFallbackTimer);
217
204
  if (child.pid)
218
205
  reapSessionWhenGone(child.pid);
206
+ const outFlush = outDecoder.end();
207
+ const errFlush = errDecoder.end();
208
+ if (outFlush)
209
+ out.append(outFlush);
210
+ if (errFlush)
211
+ err.append(errFlush);
219
212
  resolve({
220
213
  exitCode: timedOut ? 1 : (code ?? 1),
221
214
  stdout: out.value,
@@ -231,7 +224,10 @@ export function createTools(projectDir, signal) {
231
224
  body: options.body,
232
225
  signal,
233
226
  });
234
- const body = await response.text();
227
+ const raw = await response.text();
228
+ const body = raw.length > MAX_OUTPUT
229
+ ? raw.slice(0, MAX_OUTPUT) + "\n[trama] response body truncated at 10MB"
230
+ : raw;
235
231
  const headers = {};
236
232
  response.headers.forEach((v, k) => { headers[k] = v; });
237
233
  return { status: response.status, body, headers };
package/dist/types.d.ts CHANGED
@@ -19,6 +19,12 @@ export interface Ctx {
19
19
  maxIterations: number;
20
20
  /** Write a structured log entry */
21
21
  log(message: string, data?: Record<string, unknown>): Promise<void>;
22
+ /**
23
+ * Signal that a long-running program has finished startup and is now serving.
24
+ * Used by smoke validation to distinguish "started successfully" from "completed".
25
+ * Idempotent: second call is a no-op.
26
+ */
27
+ ready(data?: Record<string, unknown>): Promise<void>;
22
28
  /** Persist current ctx.state to disk */
23
29
  checkpoint(): Promise<void>;
24
30
  /**
@@ -81,6 +87,7 @@ export interface RunOptions {
81
87
  projectDir: string;
82
88
  maxRepairAttempts?: number;
83
89
  timeout?: number;
90
+ args?: Record<string, unknown>;
84
91
  }
85
92
  export interface RepairInput {
86
93
  programSource: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trama-dev/runtime",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -33,8 +33,8 @@
33
33
  "LICENSE"
34
34
  ],
35
35
  "dependencies": {
36
- "@mariozechner/pi-coding-agent": "0.63.1",
37
- "@mariozechner/pi-ai": "0.63.1",
38
- "tsx": "^4.0.0"
36
+ "@mariozechner/pi-coding-agent": "0.64.0",
37
+ "@mariozechner/pi-ai": "0.64.0",
38
+ "tsx": "^4.21.0"
39
39
  }
40
40
  }