@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/agent.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  import type { Agent } from "./types.js";
2
2
  import type { PiAdapter } from "./pi-adapter.js";
3
- export declare function createAgent(adapter: PiAdapter): Agent;
3
+ export declare function createAgent(adapter: PiAdapter, signal?: AbortSignal): Agent;
package/dist/agent.js CHANGED
@@ -7,49 +7,64 @@ function validateShape(result, schema) {
7
7
  if (typeof result !== "object" || result === null)
8
8
  return "response is not an object";
9
9
  const obj = result;
10
+ const supportedTypes = new Set(["string", "number", "boolean"]);
10
11
  for (const [key, typeDesc] of Object.entries(schema)) {
11
12
  if (!(key in obj))
12
13
  return `missing key: ${key}`;
13
14
  const expectedType = typeDesc.split(":")[0].trim();
15
+ if (!supportedTypes.has(expectedType))
16
+ return `unsupported schema type "${expectedType}" for key "${key}"`;
14
17
  const actual = typeof obj[key];
15
- if (expectedType === "string" && actual !== "string")
16
- return `${key}: expected string, got ${actual}`;
17
- if (expectedType === "number" && actual !== "number")
18
- return `${key}: expected number, got ${actual}`;
19
- if (expectedType === "boolean" && actual !== "boolean")
20
- return `${key}: expected boolean, got ${actual}`;
18
+ if (actual !== expectedType)
19
+ return `${key}: expected ${expectedType}, got ${actual}`;
21
20
  }
22
21
  return null;
23
22
  }
24
- export function createAgent(adapter) {
23
+ export function createAgent(adapter, signal) {
25
24
  return {
26
25
  async ask(prompt, options) {
27
- return adapter.ask(prompt, options);
26
+ return adapter.ask(prompt, signal ? { ...options, signal } : options);
28
27
  },
29
28
  async generate(input) {
30
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.`;
31
30
  const fullPrompt = `${input.prompt}\n\n${schemaInstruction}`;
32
- const attempt = async (p) => {
33
- const response = await adapter.ask(p, { system: input.system });
34
- const cleaned = response
35
- .trim()
36
- .replace(/^```json\s*/i, "")
37
- .replace(/^```\s*/, "")
38
- .replace(/\s*```$/, "")
39
- .trim();
40
- 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
+ }
41
44
  const error = validateShape(parsed, input.schema);
42
45
  if (error)
43
46
  throw new Error(`Schema validation failed: ${error}`);
44
- return parsed;
47
+ return stripToSchema(parsed, input.schema);
45
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);
46
52
  try {
47
- return await attempt(fullPrompt);
53
+ return parseAndValidate(response);
48
54
  }
49
55
  catch (firstError) {
50
56
  const retryPrompt = `Your previous response failed validation: ${firstError}.\nTry again.\n\n${fullPrompt}`;
51
- return await attempt(retryPrompt);
57
+ const retryResponse = await adapter.ask(retryPrompt, askOptions);
58
+ return parseAndValidate(retryResponse);
52
59
  }
53
60
  }
54
61
  };
55
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,15 +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";
4
+ import { assertSerializable } from "./serializable.js";
3
5
  const PORT = process.env.TRAMA_PORT;
4
6
  if (!PORT) {
5
7
  throw new Error("@trama-dev/runtime must be executed via `trama run`. " +
6
8
  "Direct execution is not supported (TRAMA_PORT env var missing).");
7
9
  }
8
- if (!process.env.TRAMA_INPUT) {
9
- 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. " +
10
13
  "This program must be launched by the trama runner.");
11
14
  }
12
15
  const BASE = `http://127.0.0.1:${PORT}`;
16
+ const initData = JSON.parse(readFileSync(INIT_PATH, "utf-8"));
13
17
  async function call(endpoint, body) {
14
18
  const res = await fetch(`${BASE}${endpoint}`, {
15
19
  method: "POST",
@@ -21,21 +25,32 @@ async function call(endpoint, body) {
21
25
  return res.json();
22
26
  }
23
27
  let doneCalled = false;
28
+ let readyCalled = false;
24
29
  export const ctx = {
25
- input: JSON.parse(process.env.TRAMA_INPUT),
26
- state: JSON.parse(process.env.TRAMA_STATE ?? "{}"),
27
- iteration: parseInt(process.env.TRAMA_ITERATION ?? "0"),
28
- maxIterations: parseInt(process.env.TRAMA_MAX_ITERATIONS ?? "100"),
30
+ input: initData.input,
31
+ state: initData.state,
32
+ iteration: initData.iteration,
33
+ maxIterations: initData.maxIterations,
29
34
  async log(msg, data) {
30
35
  await call("/ctx/log", { message: msg, data });
31
36
  },
37
+ async ready(data) {
38
+ if (readyCalled)
39
+ return;
40
+ await call("/ctx/ready", { data });
41
+ readyCalled = true;
42
+ },
32
43
  async checkpoint() {
44
+ assertSerializable(ctx.state, "ctx.state");
33
45
  await call("/ctx/checkpoint", { state: ctx.state });
34
46
  ctx.iteration += 1;
35
47
  },
36
48
  async done(result) {
37
49
  if (doneCalled)
38
50
  return;
51
+ assertSerializable(ctx.state, "ctx.state");
52
+ if (result !== undefined)
53
+ assertSerializable(result, "ctx.done(result)");
39
54
  await call("/ctx/done", { state: ctx.state, result });
40
55
  doneCalled = true;
41
56
  ctx.iteration += 1;
@@ -48,6 +63,6 @@ export const agent = {
48
63
  export const tools = {
49
64
  read: (path) => call("/tools/read", { path }).then(r => r.result),
50
65
  write: (path, content) => call("/tools/write", { path, content }).then(r => r.result),
51
- shell: (cmd, opts) => call("/tools/shell", { command: cmd, ...opts }),
52
- fetch: (url, opts) => call("/tools/fetch", { url, ...opts }),
66
+ shell: (cmd, opts) => call("/tools/shell", { command: cmd, ...opts }).then(r => r.result),
67
+ fetch: (url, opts) => call("/tools/fetch", { url, ...opts }).then(r => r.result),
53
68
  };
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
@@ -1,53 +1,18 @@
1
1
  import { readFileSync, writeFileSync, appendFileSync } from "fs";
2
2
  import { join } from "path";
3
- /**
4
- * Recursively check that a value is strictly JSON-serializable.
5
- * Throws TypeError with the path to the offending value.
6
- *
7
- * Uses a stack (ancestor chain) instead of a flat set so that shared-but-
8
- * non-circular structures like { a: shared, b: shared } pass validation.
9
- */
10
- function assertSerializable(value, path, ancestors = new Set()) {
11
- if (value === null || typeof value === "string" || typeof value === "boolean") {
12
- return;
13
- }
14
- if (typeof value === "number") {
15
- if (!Number.isFinite(value)) {
16
- throw new TypeError(`${path} is not JSON-serializable (${value})`);
17
- }
18
- return;
19
- }
20
- if (typeof value === "undefined" || typeof value === "function" || typeof value === "symbol" || typeof value === "bigint") {
21
- throw new TypeError(`${path} is not JSON-serializable (${typeof value})`);
22
- }
23
- if (ancestors.has(value)) {
24
- throw new TypeError(`${path} contains a circular reference`);
25
- }
26
- ancestors.add(value);
27
- if (Array.isArray(value)) {
28
- for (let i = 0; i < value.length; i++) {
29
- assertSerializable(value[i], `${path}[${i}]`, ancestors);
30
- }
31
- ancestors.delete(value);
32
- return;
33
- }
34
- if (Object.getPrototypeOf(value) !== Object.prototype) {
35
- const name = value.constructor?.name ?? "unknown";
36
- throw new TypeError(`${path} is not a plain object (${name})`);
37
- }
38
- for (const [k, v] of Object.entries(value)) {
39
- assertSerializable(v, `${path}.${k}`, ancestors);
40
- }
41
- ancestors.delete(value);
42
- }
3
+ import { assertSerializable } from "./serializable.js";
43
4
  export function createContext(projectDir, initialState, options) {
44
5
  const logsPath = join(projectDir, "logs", "latest.jsonl");
45
6
  const statePath = join(projectDir, "state.json");
46
7
  const meta = JSON.parse(readFileSync(join(projectDir, "meta.json"), "utf-8"));
47
8
  let doneCalled = false;
48
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;
49
14
  return {
50
- input: meta.input,
15
+ input,
51
16
  state: { ...initialState },
52
17
  iteration: typeof initialState.__trama_iteration === "number"
53
18
  && Number.isFinite(initialState.__trama_iteration)
@@ -58,6 +23,13 @@ export function createContext(projectDir, initialState, options) {
58
23
  appendFileSync(logsPath, JSON.stringify(entry) + "\n");
59
24
  console.log(`[trama] ${message}`);
60
25
  },
26
+ async ready(data) {
27
+ if (readyCalled)
28
+ return;
29
+ await this.log("ready", data);
30
+ options?.onReady?.(data);
31
+ readyCalled = true;
32
+ },
61
33
  async checkpoint() {
62
34
  assertSerializable(this.state, "ctx.state");
63
35
  const nextIteration = this.iteration + 1;
@@ -68,11 +40,14 @@ export function createContext(projectDir, initialState, options) {
68
40
  async done(result) {
69
41
  if (doneCalled)
70
42
  return;
71
- if (result && !doneLogged) {
43
+ if (!doneLogged) {
72
44
  await this.log("done", result);
73
- doneLogged = true;
74
45
  }
75
46
  await this.checkpoint();
47
+ // Only mark as complete after checkpoint succeeds.
48
+ // If checkpoint throws, a retry will re-log "done" (acceptable)
49
+ // and retry the checkpoint.
50
+ doneLogged = true;
76
51
  doneCalled = true;
77
52
  }
78
53
  };
package/dist/index.d.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  export { runProgram } from "./runner.js";
2
2
  export declare function validateProjectName(name: string): void;
3
+ export declare function resolveProject(name: string): string;
3
4
  export declare function createProject(name: string, prompt: string, options?: {
4
5
  model?: string;
6
+ args?: Record<string, unknown>;
5
7
  }): Promise<void>;
6
8
  export declare function updateProject(name: string, prompt: string): Promise<void>;
7
9
  export declare function listProjects(): Promise<void>;
package/dist/index.js CHANGED
@@ -2,11 +2,11 @@
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";
6
- import { loadConfig, loadState, smokeRunAndRepair, copyToHistory, RUNTIME_TYPES, PI_VERSION } from "./runner.js";
5
+ import { PiAdapter, stripCodeFences } from "./pi-adapter.js";
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) ---
9
- const EXAMPLE_PROGRAMS = `// Example A: Simple (single action)
9
+ const EXAMPLE_PROGRAMS = `// Example A: Simple — one-shot action, no LLM needed.
10
10
  import { ctx, tools } from "@trama-dev/runtime";
11
11
 
12
12
  const content = "# Hello World\\nGenerated at " + new Date().toISOString();
@@ -14,7 +14,7 @@ await tools.write("hello.md", content);
14
14
  await ctx.log("wrote hello.md");
15
15
  await ctx.done();
16
16
 
17
- // Example B: Medium (LLM + tools)
17
+ // Example B: Medium — use the LLM once to process data, write the result.
18
18
  import { ctx, agent, tools } from "@trama-dev/runtime";
19
19
 
20
20
  const data = await tools.read(ctx.input.args.file as string);
@@ -22,7 +22,10 @@ const summary = await agent.ask("Summarize this data concisely:\\n" + data);
22
22
  await tools.write("summary.md", summary);
23
23
  await ctx.done({ summaryLength: summary.length });
24
24
 
25
- // Example C: Complex (autoresearch loop)
25
+ // Example C: Iterative optimization loop.
26
+ // Pattern: propose a change via LLM, evaluate it with a deterministic script,
27
+ // keep the change only if it improves the metric, repeat.
28
+ // ctx.state and ctx.iteration persist across runs so the loop can resume after interruption.
26
29
  import { ctx, agent, tools } from "@trama-dev/runtime";
27
30
 
28
31
  let code = (ctx.state.code as string | undefined) ?? await tools.read("target.ts");
@@ -35,7 +38,7 @@ for (let i = ctx.iteration; i < ctx.maxIterations; i++) {
35
38
  });
36
39
 
37
40
  await tools.write("candidate.ts", proposal.newCode);
38
- const bench = await tools.shell("npx tsx benchmark.ts candidate.ts");
41
+ const bench = await tools.shell("node benchmark.mjs candidate.ts");
39
42
 
40
43
  if (bench.exitCode !== 0) {
41
44
  await ctx.log("benchmark failed", { stderr: bench.stderr });
@@ -53,9 +56,38 @@ for (let i = ctx.iteration; i < ctx.maxIterations; i++) {
53
56
  }
54
57
 
55
58
  await tools.write("target.ts", code);
56
- await ctx.done({ finalMetric: bestMetric });`;
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>(() => {});`;
57
88
  function getSystemPrompt() {
58
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` +
59
91
  `Runtime API:\n${RUNTIME_TYPES}\n\n` +
60
92
  `Examples:\n${EXAMPLE_PROGRAMS}`);
61
93
  }
@@ -67,7 +99,7 @@ export function validateProjectName(name) {
67
99
  throw new Error(`Invalid project name: "${name}". Must be a simple directory name without path separators.`);
68
100
  }
69
101
  }
70
- function resolveProject(name) {
102
+ export function resolveProject(name) {
71
103
  validateProjectName(name);
72
104
  const dir = join(projectsDir(), name);
73
105
  if (!existsSync(dir)) {
@@ -75,6 +107,37 @@ function resolveProject(name) {
75
107
  }
76
108
  return dir;
77
109
  }
110
+ // --- Helpers ---
111
+ /** Run an LLM ask() in an isolated temp cwd so pi-coding-agent tools can't write into the real project. */
112
+ async function isolatedAsk(adapter, prompt, options) {
113
+ return withTempDir("trama-gen-", (dir) => adapter.withCwd(dir).ask(prompt, options));
114
+ }
115
+ /** Backup projectDir, run fn, restore on failure. Preserves new repair history entries across restore. */
116
+ async function withProjectBackup(projectDir, originalHistory, historyIndexPath, fn) {
117
+ const backupRoot = mkdtempSync(join(tmpdir(), "trama-update-backup-"));
118
+ const backupDir = join(backupRoot, "project");
119
+ cpSync(projectDir, backupDir, { recursive: true });
120
+ try {
121
+ await fn();
122
+ }
123
+ catch (err) {
124
+ // Restore from backup, preserving any new repair history entries
125
+ const failedHistory = existsSync(historyIndexPath) ? readFileSync(historyIndexPath, "utf-8") : "";
126
+ rmSync(projectDir, { recursive: true, force: true });
127
+ cpSync(backupDir, projectDir, { recursive: true });
128
+ if (failedHistory.startsWith(originalHistory)) {
129
+ const repairEntries = failedHistory.slice(originalHistory.length);
130
+ if (repairEntries.length > 0) {
131
+ appendFileSync(join(projectDir, "history", "index.jsonl"), repairEntries);
132
+ }
133
+ }
134
+ throw new Error(`Update failed — project files have been restored to the previous version.\n` +
135
+ `${err instanceof Error ? err.message : err}`);
136
+ }
137
+ finally {
138
+ rmSync(backupRoot, { recursive: true, force: true });
139
+ }
140
+ }
78
141
  // --- Public API ---
79
142
  export async function createProject(name, prompt, options) {
80
143
  validateProjectName(name);
@@ -90,7 +153,7 @@ export async function createProject(name, prompt, options) {
90
153
  writeFileSync(join(projectDir, "package.json"), JSON.stringify({ type: "module" }, null, 2));
91
154
  writeFileSync(join(projectDir, ".gitignore"), "node_modules/\nstate.json\nlogs/\nhistory/\n");
92
155
  const meta = {
93
- input: { prompt, args: {} },
156
+ input: { prompt, args: options?.args ?? {} },
94
157
  createdAt: new Date().toISOString(),
95
158
  piVersion: PI_VERSION,
96
159
  };
@@ -100,11 +163,15 @@ export async function createProject(name, prompt, options) {
100
163
  config.model = options.model;
101
164
  const adapter = new PiAdapter(config, projectDir);
102
165
  console.log(`Generating program for "${name}"...`);
103
- const program = await adapter.ask(`${prompt}\n\nOutput ONLY the TypeScript program. No markdown fences. No explanation.`, { system: getSystemPrompt() });
166
+ const program = stripCodeFences(await isolatedAsk(adapter, `${prompt}\n\nOutput ONLY the TypeScript program. No markdown fences. No explanation.`, { system: getSystemPrompt() }));
104
167
  writeFileSync(join(projectDir, "program.ts"), program);
105
168
  keepProjectOnFailure = true;
106
169
  console.log("Validating program...");
107
- await smokeRunAndRepair(projectDir, adapter, "create");
170
+ await smokeRunAndRepair(projectDir, adapter, "create", {
171
+ timeout: config.defaultTimeout,
172
+ maxRepairAttempts: config.maxRepairAttempts,
173
+ maxIterations: config.defaultMaxIterations,
174
+ });
108
175
  copyFileSync(join(projectDir, "program.ts"), join(projectDir, "history", "0001.ts"));
109
176
  appendFileSync(join(projectDir, "history", "index.jsonl"), JSON.stringify({ version: 1, reason: "create", timestamp: new Date().toISOString(), prompt }) + "\n");
110
177
  console.log(`Created ${name}. Run with: trama run ${name}`);
@@ -126,37 +193,24 @@ export async function updateProject(name, prompt) {
126
193
  const originalHistory = existsSync(historyIndexPath) ? readFileSync(historyIndexPath, "utf-8") : "";
127
194
  const config = loadConfig();
128
195
  const adapter = new PiAdapter(config, projectDir);
129
- const systemPrompt = getSystemPrompt() +
130
- `\n\nOriginal prompt: ${meta.input.prompt}` +
131
- `\n\nCurrent program.ts:\n${originalSource}` +
132
- (Object.keys(state).length > 0 ? `\n\nCurrent state:\n${JSON.stringify(state, null, 2)}` : "");
133
- console.log(`Updating "${name}"...`);
134
- const updated = await adapter.ask(`${prompt}\n\nOutput the complete updated program.ts. No partial patches. No markdown fences. No explanation.`, { system: systemPrompt });
135
- const backupRoot = mkdtempSync(join(tmpdir(), "trama-update-backup-"));
136
- const backupDir = join(backupRoot, "project");
137
- cpSync(projectDir, backupDir, { recursive: true });
138
- writeFileSync(programPath, updated);
139
- console.log("Validating updated program...");
140
- try {
141
- await smokeRunAndRepair(projectDir, adapter, "update");
142
- }
143
- catch (err) {
144
- const failedHistory = existsSync(historyIndexPath) ? readFileSync(historyIndexPath, "utf-8") : "";
145
- rmSync(projectDir, { recursive: true, force: true });
146
- cpSync(backupDir, projectDir, { recursive: true });
147
- if (failedHistory.startsWith(originalHistory)) {
148
- const repairEntries = failedHistory.slice(originalHistory.length);
149
- if (repairEntries.length > 0) {
150
- appendFileSync(join(projectDir, "history", "index.jsonl"), repairEntries);
151
- }
152
- }
153
- rmSync(backupRoot, { recursive: true, force: true });
154
- throw new Error(`Update validation failed — project files have been restored to the previous version.\n` +
155
- `${err instanceof Error ? err.message : err}`);
156
- }
157
- rmSync(backupRoot, { recursive: true, force: true });
158
- copyToHistory(projectDir, "update", prompt);
159
- console.log(`Updated ${name}. Run with: trama run ${name}`);
196
+ // Backup before any LLM calls, restore on any failure
197
+ await withProjectBackup(projectDir, originalHistory, historyIndexPath, async () => {
198
+ const systemPrompt = getSystemPrompt() +
199
+ `\n\nOriginal prompt: ${meta.input.prompt}` +
200
+ `\n\nCurrent program.ts:\n${originalSource}` +
201
+ (Object.keys(state).length > 0 ? `\n\nCurrent state:\n${JSON.stringify(state, null, 2)}` : "");
202
+ console.log(`Updating "${name}"...`);
203
+ const updated = stripCodeFences(await isolatedAsk(adapter, `${prompt}\n\nOutput the complete updated program.ts. No partial patches. No markdown fences. No explanation.`, { system: systemPrompt }));
204
+ writeFileSync(programPath, updated);
205
+ console.log("Validating updated program...");
206
+ await smokeRunAndRepair(projectDir, adapter, "update", {
207
+ timeout: config.defaultTimeout,
208
+ maxRepairAttempts: config.maxRepairAttempts,
209
+ maxIterations: config.defaultMaxIterations,
210
+ });
211
+ copyToHistory(projectDir, "update", prompt);
212
+ console.log(`Updated ${name}. Run with: trama run ${name}`);
213
+ });
160
214
  }
161
215
  export async function listProjects() {
162
216
  const dir = projectsDir();
@@ -1,12 +1,22 @@
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;
5
7
  constructor(config: PiAdapterConfig, cwd: string);
8
+ /** Create a copy of this adapter that operates in a different working directory. */
9
+ withCwd(cwd: string): PiAdapter;
6
10
  private createSession;
7
11
  private extractText;
12
+ /**
13
+ * Abort cancellation relies on session.dispose() interrupting session.prompt().
14
+ * This is an upstream contract of pi-coding-agent — if dispose() does not
15
+ * actually reject the in-flight prompt, the abort signal will not terminate the call.
16
+ */
8
17
  ask(prompt: string, options?: {
9
18
  system?: string;
19
+ signal?: AbortSignal;
10
20
  }): Promise<string>;
11
- repair(input: RepairInput): Promise<string>;
21
+ repair(input: RepairInput, signal?: AbortSignal): Promise<string>;
12
22
  }
@@ -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;
@@ -7,21 +15,50 @@ export class PiAdapter {
7
15
  this.config = config;
8
16
  this.cwd = cwd;
9
17
  }
10
- async createSession(systemPrompt) {
18
+ /** Create a copy of this adapter that operates in a different working directory. */
19
+ withCwd(cwd) {
20
+ return new PiAdapter(this.config, cwd);
21
+ }
22
+ async createSession(systemPrompt, signal) {
23
+ if (signal?.aborted)
24
+ throw new Error("Aborted");
11
25
  const resourceLoader = new DefaultResourceLoader({
12
26
  cwd: this.cwd,
13
27
  noExtensions: true,
14
28
  noSkills: true,
15
29
  ...(systemPrompt && { appendSystemPrompt: systemPrompt }),
16
30
  });
17
- await resourceLoader.reload();
18
- const { session } = await createAgentSession({
31
+ // Race an async step against the abort signal.
32
+ // Returns the result on success, or rejects with "Aborted" on abort.
33
+ const raceAbort = (promise) => {
34
+ if (!signal)
35
+ return promise;
36
+ return Promise.race([
37
+ promise,
38
+ new Promise((_resolve, reject) => {
39
+ signal.addEventListener("abort", () => reject(new Error("Aborted")), { once: true });
40
+ }),
41
+ ]);
42
+ };
43
+ await raceAbort(resourceLoader.reload());
44
+ if (signal?.aborted)
45
+ throw new Error("Aborted");
46
+ // Keep a reference to the raw promise so we can clean up a late-arriving session
47
+ const sessionPromise = createAgentSession({
19
48
  cwd: this.cwd,
20
49
  model: getModel(this.config.provider, this.config.model),
21
50
  sessionManager: SessionManager.inMemory(),
22
51
  resourceLoader,
23
52
  });
24
- return session;
53
+ try {
54
+ const { session } = await raceAbort(sessionPromise);
55
+ return session;
56
+ }
57
+ catch (err) {
58
+ // If abort won the race, the real promise may still resolve later — dispose it
59
+ sessionPromise.then(({ session }) => session.dispose()).catch(() => { });
60
+ throw err;
61
+ }
25
62
  }
26
63
  extractText(session) {
27
64
  const messages = session.state.messages;
@@ -36,9 +73,24 @@ export class PiAdapter {
36
73
  }
37
74
  return "";
38
75
  }
76
+ /**
77
+ * Abort cancellation relies on session.dispose() interrupting session.prompt().
78
+ * This is an upstream contract of pi-coding-agent — if dispose() does not
79
+ * actually reject the in-flight prompt, the abort signal will not terminate the call.
80
+ */
39
81
  async ask(prompt, options) {
40
- const session = await this.createSession(options?.system);
82
+ const signal = options?.signal;
83
+ if (signal?.aborted)
84
+ throw new Error("Aborted");
85
+ // Track session so abort can dispose it at any point — even during createSession
86
+ let session = null;
87
+ const onAbort = () => session?.dispose();
88
+ signal?.addEventListener("abort", onAbort, { once: true });
41
89
  try {
90
+ session = await this.createSession(options?.system, signal);
91
+ // Re-check: abort may have fired during createSession (before session existed)
92
+ if (signal?.aborted)
93
+ throw new Error("Aborted");
42
94
  await session.prompt(prompt);
43
95
  const text = this.extractText(session);
44
96
  if (!text)
@@ -46,14 +98,16 @@ export class PiAdapter {
46
98
  return text;
47
99
  }
48
100
  finally {
49
- session.dispose();
101
+ signal?.removeEventListener("abort", onAbort);
102
+ session?.dispose();
50
103
  }
51
104
  }
52
- async repair(input) {
53
- return this.ask(`Fix this program so it runs.\n\n` +
105
+ async repair(input, signal) {
106
+ const response = await this.ask(`Fix this program so it runs.\n\n` +
54
107
  `Runtime types:\n${input.runtimeTypes}\n\n` +
55
108
  `Broken program:\n${input.programSource}\n\n` +
56
109
  `Error:\n${input.error}\n\n` +
57
- `Output ONLY the fixed program. No explanation.`, { system: "You are a TypeScript repair tool." });
110
+ `Output ONLY the fixed program. No explanation.`, { system: "You are a TypeScript repair tool.", signal });
111
+ return stripCodeFences(response);
58
112
  }
59
113
  }