@trama-dev/runtime 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2,8 +2,9 @@
2
2
  import { readFileSync, writeFileSync, mkdirSync, readdirSync, existsSync, statSync, rmSync } from "fs";
3
3
  import { join } from "path";
4
4
  import { homedir } from "os";
5
- import { PiAdapter, PI_VERSION, stripCodeFences } from "./pi-adapter.js";
6
- import { loadConfig, loadProjectConfig, loadState, smokeRunAndRepair, copyToHistory, withSnapshot, withTempDir, ensureProjectScaffold, RUNTIME_TYPES, } from "./runner.js";
5
+ import { PI_VERSION } from "./pi-adapter.js";
6
+ import { stripCodeFences } from "./agent.js";
7
+ import { loadConfig, loadProjectConfig, loadState, createBackend, validateProgram, installValidatedProgram, withTempDir, ensureProjectScaffold, RUNTIME_TYPES, } from "./runner.js";
7
8
  import { guardPath } from "./path-guard.js";
8
9
  export { runProgram } from "./runner.js";
9
10
  export { createWorkspace } from "./workspace.js";
@@ -113,10 +114,15 @@ export function resolveProject(name) {
113
114
  return dir;
114
115
  }
115
116
  // --- Helpers ---
116
- /** Run an LLM instruction in an isolated temp cwd so pi-coding-agent tools can't write into the real project. */
117
- async function isolatedAsk(adapter, prompt, options) {
118
- return withTempDir("trama-gen-", (dir) => adapter.withCwd(dir).ask(prompt, options));
117
+ /** Ask in an empty throwaway directory, so the agent's tools cannot write into the real project. */
118
+ async function isolatedAsk(backend, prompt, system) {
119
+ return withTempDir("trama-gen-", (cwd) => backend.ask(prompt, { cwd, system }));
119
120
  }
121
+ const validationOptions = (config) => ({
122
+ timeout: config.defaultTimeout,
123
+ maxRepairAttempts: config.maxRepairAttempts,
124
+ maxIterations: config.defaultMaxIterations,
125
+ });
120
126
  // --- Public API ---
121
127
  export async function createProject(name, prompt, options) {
122
128
  validateProjectName(name);
@@ -139,18 +145,16 @@ export async function createProject(name, prompt, options) {
139
145
  provider: config.provider,
140
146
  };
141
147
  writeFileSync(join(projectDir, "meta.json"), JSON.stringify(meta, null, 2));
142
- const adapter = new PiAdapter(config, projectDir);
148
+ const backend = createBackend(config);
143
149
  console.log(`Generating program for "${name}"...`);
144
- const program = stripCodeFences(await isolatedAsk(adapter, `${prompt}\n\nOutput ONLY the TypeScript program. No markdown fences. No explanation.`, { system: getSystemPrompt() }));
145
- writeFileSync(join(projectDir, "program.ts"), program);
150
+ const candidate = stripCodeFences(await isolatedAsk(backend, `${prompt}\n\nOutput ONLY the TypeScript program. No markdown fences. No explanation.`, getSystemPrompt()));
151
+ // From here on the project is kept even if validation fails, so the
152
+ // generated program can be inspected and fixed by hand.
153
+ writeFileSync(join(projectDir, "program.ts"), candidate);
146
154
  keepProjectOnFailure = true;
147
155
  console.log("Validating program...");
148
- await smokeRunAndRepair(projectDir, adapter, "create", {
149
- timeout: config.defaultTimeout,
150
- maxRepairAttempts: config.maxRepairAttempts,
151
- maxIterations: config.defaultMaxIterations,
152
- });
153
- copyToHistory(projectDir, "create", prompt);
156
+ const validated = await validateProgram(projectDir, backend, candidate, validationOptions(config));
157
+ installValidatedProgram(projectDir, validated, "create", prompt);
154
158
  console.log(`Created ${name}. Run with: trama run ${name}`);
155
159
  }
156
160
  catch (err) {
@@ -169,30 +173,29 @@ export async function updateProject(name, prompt) {
169
173
  const state = loadState(projectDir);
170
174
  const meta = JSON.parse(readFileSync(guardPath(projectDir, "meta.json"), "utf-8"));
171
175
  const config = loadProjectConfig(projectDir);
172
- const adapter = new PiAdapter(config, projectDir);
176
+ const backend = createBackend(config);
173
177
  const systemPrompt = getSystemPrompt() +
174
178
  `\n\nOriginal prompt: ${meta.input.prompt}` +
175
179
  `\n\nCurrent program.ts:\n${originalSource}` +
176
180
  (Object.keys(state).length > 0 ? `\n\nCurrent state:\n${JSON.stringify(state, null, 2)}` : "");
177
- // All-or-nothing: if generation or validation fails, the whole project
178
- // directory — program, state, history — goes back to how it was.
181
+ // The new program is generated and validated off to the side. The project is
182
+ // only written to once there is a program that works, so a failed update has
183
+ // nothing to undo.
179
184
  try {
180
- await withSnapshot(projectDir, async () => {
181
- console.log(`Updating "${name}"...`);
182
- const updated = stripCodeFences(await isolatedAsk(adapter, `${prompt}\n\nOutput the complete updated program.ts. No partial patches. No markdown fences. No explanation.`, { system: systemPrompt }));
183
- writeFileSync(programPath, updated);
184
- console.log("Validating updated program...");
185
- await smokeRunAndRepair(projectDir, adapter, "update", {
186
- timeout: config.defaultTimeout,
187
- maxRepairAttempts: config.maxRepairAttempts,
188
- maxIterations: config.defaultMaxIterations,
189
- });
190
- copyToHistory(projectDir, "update", prompt);
191
- return { keep: true, value: undefined };
192
- });
185
+ console.log(`Updating "${name}"...`);
186
+ const candidate = stripCodeFences(await isolatedAsk(backend, `${prompt}\n\nOutput the complete updated program.ts. No partial patches. No markdown fences. No explanation.`, systemPrompt));
187
+ console.log("Validating updated program...");
188
+ const validated = await validateProgram(projectDir, backend, candidate, validationOptions(config));
189
+ try {
190
+ installValidatedProgram(projectDir, validated, "update", prompt);
191
+ }
192
+ catch (err) {
193
+ writeFileSync(programPath, originalSource); // recording the version failed: don't leave an unrecorded program behind
194
+ throw err;
195
+ }
193
196
  }
194
197
  catch (err) {
195
- throw new Error(`Update failed — project files have been restored to the previous version.\n` +
198
+ throw new Error(`Update failed — the project is unchanged.\n` +
196
199
  `${err instanceof Error ? err.message : err}`);
197
200
  }
198
201
  console.log(`Updated ${name}. Run with: trama run ${name}`);
@@ -203,9 +206,8 @@ export async function listProjects() {
203
206
  console.log("No projects found.");
204
207
  return;
205
208
  }
206
- // Dot-directories are not projects (a rollback snapshot is kept beside its project while a run is in flight).
207
209
  const entries = readdirSync(dir, { withFileTypes: true })
208
- .filter(e => e.isDirectory() && !e.name.startsWith("."));
210
+ .filter(e => e.isDirectory());
209
211
  if (entries.length === 0) {
210
212
  console.log("No projects found.");
211
213
  return;
@@ -15,6 +15,8 @@ export interface IpcBackends {
15
15
  workspace: Workspace | null;
16
16
  /** Called once ctx.done() or ctx.yield() has been persisted for this run. */
17
17
  onTerminalSignal(result: ProgramResult): void;
18
+ /** Stop the program's clock until the returned function is called (see Allowance). */
19
+ holdClock(): () => void;
18
20
  }
19
21
  export declare function createIPCServer(backends: IpcBackends): Server;
20
22
  /** Start listening on an ephemeral loopback port and return it. */
@@ -28,7 +28,7 @@ function isAuthorized(header, token) {
28
28
  const actual = Buffer.from(header ?? "");
29
29
  return actual.length === expected.length && timingSafeEqual(actual, expected);
30
30
  }
31
- function buildRoutes({ ctx, agent, tools, workspace, onTerminalSignal }) {
31
+ function buildRoutes({ ctx, agent, tools, workspace, onTerminalSignal, holdClock }) {
32
32
  /** The program owns ctx.state; each persisting call hands over its current copy. */
33
33
  const adoptState = (state) => {
34
34
  assertSerializable(state, "ctx.state");
@@ -86,6 +86,18 @@ function buildRoutes({ ctx, agent, tools, workspace, onTerminalSignal }) {
86
86
  onTerminalSignal({ status: "yielded", reason: b.reason });
87
87
  },
88
88
  },
89
+ // A run the program starts — a session participant — is under a timeout
90
+ // of its own, and the program's clock stops while it lasts (see
91
+ // holdParentClock). The hold is the connection: it ends when the caller
92
+ // closes it, and cannot outlast a caller that dies without doing so.
93
+ "/clock/hold": {
94
+ fields: {},
95
+ handle: async (_body, connectionClosed) => {
96
+ const release = holdClock();
97
+ await connectionClosed;
98
+ release();
99
+ },
100
+ },
89
101
  "/workspace/read": { fields: { path: "string" }, handle: b => inSession().read(b.path) },
90
102
  "/workspace/write": {
91
103
  fields: { path: "string", content: "string" },
@@ -101,7 +113,10 @@ function buildRoutes({ ctx, agent, tools, workspace, onTerminalSignal }) {
101
113
  export function createIPCServer(backends) {
102
114
  const routes = buildRoutes(backends);
103
115
  return createServer((req, res) => {
116
+ const connectionClosed = new Promise(resolve => res.once("close", resolve));
104
117
  const reply = (status, body, json = false) => {
118
+ if (res.writableEnded || res.destroyed)
119
+ return; // answered already, or nobody left to answer
105
120
  res.writeHead(status, json ? { "Content-Type": "application/json" } : undefined);
106
121
  res.end(body);
107
122
  };
@@ -120,9 +135,12 @@ export function createIPCServer(backends) {
120
135
  chunks.push(chunk);
121
136
  byteCount += chunk.length;
122
137
  if (byteCount > MAX_IPC_BODY) {
138
+ // Answer now, and let the rest of the body arrive and be discarded.
139
+ // Cutting the connection instead would race the answer: a sender still
140
+ // writing sees a broken connection, not the reason for it.
123
141
  overflow = true;
142
+ chunks.length = 0;
124
143
  reply(413, "IPC request body exceeds 50MB limit");
125
- req.destroy();
126
144
  }
127
145
  });
128
146
  req.on("end", async () => {
@@ -134,7 +152,7 @@ export function createIPCServer(backends) {
134
152
  if (!route)
135
153
  return reply(404, "Not found");
136
154
  validate(body, route.fields);
137
- const result = await route.handle(body);
155
+ const result = await route.handle(body, connectionClosed);
138
156
  reply(200, JSON.stringify({ result: result ?? null }), true);
139
157
  }
140
158
  catch (err) {
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Register a process group this process started: if this process ends before
3
+ * the returned function is called, the group is stopped (see stopGroupsOnExit).
4
+ */
5
+ export declare function stopWithThisProcess(pgid: number): () => void;
6
+ /**
7
+ * Register a temp directory this process created: if this process ends before
8
+ * the returned function is called, the directory is removed.
9
+ */
10
+ export declare function removeWithThisProcess(dir: string): () => void;
11
+ /** Remove a temp directory. Best-effort: failing to clean up must never change a run's outcome. */
12
+ export declare function removeTempDir(dir: string): void;
@@ -0,0 +1,85 @@
1
+ // What this process must undo if it ends while a run is still in flight:
2
+ // stop the processes it started, and delete what it left in the temp directory.
3
+ //
4
+ // A program, and every shell command it runs, leads its own process group — so
5
+ // that a timeout can take down everything it started. The cost is that none of
6
+ // them die with the runner: without this, Ctrl-C on `trama run` would leave the
7
+ // program running, and a program that coordinates others (a session) would
8
+ // leave them running when it ended.
9
+ import { rmSync } from "fs";
10
+ import { stopGroupsOnExit } from "./child-process.js";
11
+ const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
12
+ const pendingGroups = new Set();
13
+ const pendingDirs = new Set();
14
+ let installed = false;
15
+ function runPending() {
16
+ const groups = [...pendingGroups];
17
+ const dirs = [...pendingDirs];
18
+ pendingGroups.clear();
19
+ pendingDirs.clear();
20
+ // The groups are asked to stop and given a moment; whatever sees that through
21
+ // also removes the directories again once they are gone, in case they were
22
+ // still writing to them.
23
+ stopGroupsOnExit(groups, dirs);
24
+ for (const dir of dirs)
25
+ removeTempDir(dir);
26
+ }
27
+ function onSignal(signal) {
28
+ runPending();
29
+ // Having a handler at all cancelled the signal's default action. Step aside
30
+ // and send it again, so that what happens next is what would have happened
31
+ // had this handler never been installed: the process dies of it, or whoever
32
+ // else handles the signal decides. (Common libraries only act on a signal
33
+ // when they are its sole listener, so simply staying out of the way is not
34
+ // enough — the signal has to arrive once more without us.)
35
+ uninstall();
36
+ process.kill(process.pid, signal);
37
+ }
38
+ function install() {
39
+ if (installed)
40
+ return;
41
+ installed = true;
42
+ process.on("exit", runPending);
43
+ for (const signal of SIGNALS)
44
+ process.on(signal, onSignal);
45
+ }
46
+ /** Leave the host process's signal handling untouched whenever nothing is in flight. */
47
+ function uninstall() {
48
+ if (!installed)
49
+ return;
50
+ installed = false;
51
+ process.removeListener("exit", runPending);
52
+ for (const signal of SIGNALS)
53
+ process.removeListener(signal, onSignal);
54
+ }
55
+ /** Keep `item` pending until the returned function is called. */
56
+ function track(pending, item) {
57
+ pending.add(item);
58
+ install();
59
+ return () => {
60
+ pending.delete(item);
61
+ if (pendingGroups.size === 0 && pendingDirs.size === 0)
62
+ uninstall();
63
+ };
64
+ }
65
+ /**
66
+ * Register a process group this process started: if this process ends before
67
+ * the returned function is called, the group is stopped (see stopGroupsOnExit).
68
+ */
69
+ export function stopWithThisProcess(pgid) {
70
+ return track(pendingGroups, pgid);
71
+ }
72
+ /**
73
+ * Register a temp directory this process created: if this process ends before
74
+ * the returned function is called, the directory is removed.
75
+ */
76
+ export function removeWithThisProcess(dir) {
77
+ return track(pendingDirs, dir);
78
+ }
79
+ /** Remove a temp directory. Best-effort: failing to clean up must never change a run's outcome. */
80
+ export function removeTempDir(dir) {
81
+ try {
82
+ rmSync(dir, { recursive: true, force: true });
83
+ }
84
+ catch { /* left for the OS to reap */ }
85
+ }
@@ -1,14 +1,11 @@
1
- import type { PiAdapterConfig, RepairInput } from "./runner-types.js";
1
+ import type { AgentBackend, AgentCall } from "./agent-backend.js";
2
+ import type { ModelConfig } from "./runner-types.js";
2
3
  /** The pi version this runtime is built against (recorded in each project's meta.json). */
3
4
  export { VERSION as PI_VERSION } from "@earendil-works/pi-coding-agent";
4
- /** Strip markdown code fences and trim whitespace. */
5
- export declare function stripCodeFences(text: string): string;
6
- export declare class PiAdapter {
5
+ /** The pi coding agent, run in-process: a fresh in-memory session for every call. */
6
+ export declare class PiAdapter implements AgentBackend {
7
7
  private config;
8
- private cwd;
9
- constructor(config: PiAdapterConfig, cwd: string);
10
- /** Create a copy of this adapter that operates in a different working directory. */
11
- withCwd(cwd: string): PiAdapter;
8
+ constructor(config: ModelConfig);
12
9
  private createSession;
13
10
  /**
14
11
  * The configured provider/model is not in pi's catalog, so pi picked a model
@@ -23,9 +20,5 @@ export declare class PiAdapter {
23
20
  * pi 1.x settles the prompt by resolving it (not rejecting), so abort is
24
21
  * re-checked after prompt() returns.
25
22
  */
26
- ask(prompt: string, options?: {
27
- system?: string;
28
- signal?: AbortSignal;
29
- }): Promise<string>;
30
- repair(input: RepairInput, signal?: AbortSignal): Promise<string>;
23
+ ask(prompt: string, call: AgentCall): Promise<string>;
31
24
  }
@@ -1,35 +1,20 @@
1
1
  import { createAgentSession, SessionManager, DefaultResourceLoader, ModelRuntime, getAgentDir, } from "@earendil-works/pi-coding-agent";
2
2
  /** The pi version this runtime is built against (recorded in each project's meta.json). */
3
3
  export { VERSION as PI_VERSION } from "@earendil-works/pi-coding-agent";
4
- /** Strip markdown code fences and trim whitespace. */
5
- export function stripCodeFences(text) {
6
- const trimmed = text.trim();
7
- // Extract the last fenced code block (LLMs may prepend explanation or emit multiple blocks)
8
- const matches = [...trimmed.matchAll(/```(?:\w*)\s*\n([\s\S]*?)\n\s*```/g)];
9
- if (matches.length > 0) {
10
- return matches[matches.length - 1][1].trim();
11
- }
12
- return trimmed;
13
- }
14
4
  /** provider/model pairs already warned about, so a loop of agent calls warns once per process. */
15
5
  const warnedUnknownModels = new Set();
6
+ /** The pi coding agent, run in-process: a fresh in-memory session for every call. */
16
7
  export class PiAdapter {
17
8
  config;
18
- cwd;
19
- constructor(config, cwd) {
9
+ constructor(config) {
20
10
  this.config = config;
21
- this.cwd = cwd;
22
11
  }
23
- /** Create a copy of this adapter that operates in a different working directory. */
24
- withCwd(cwd) {
25
- return new PiAdapter(this.config, cwd);
26
- }
27
- async createSession(systemPrompt, signal) {
12
+ async createSession(cwd, systemPrompt, signal) {
28
13
  if (signal?.aborted)
29
14
  throw new Error("Aborted");
30
15
  const agentDir = getAgentDir();
31
16
  const resourceLoader = new DefaultResourceLoader({
32
- cwd: this.cwd,
17
+ cwd,
33
18
  agentDir,
34
19
  noExtensions: true,
35
20
  noSkills: true,
@@ -67,11 +52,11 @@ export class PiAdapter {
67
52
  const model = modelRuntime.getModel(this.config.provider, this.config.model);
68
53
  // Keep a reference to the raw promise so we can clean up a late-arriving session
69
54
  const sessionPromise = createAgentSession({
70
- cwd: this.cwd,
55
+ cwd,
71
56
  agentDir,
72
57
  modelRuntime,
73
58
  model,
74
- sessionManager: SessionManager.inMemory(this.cwd),
59
+ sessionManager: SessionManager.inMemory(cwd),
75
60
  resourceLoader,
76
61
  });
77
62
  try {
@@ -127,8 +112,8 @@ export class PiAdapter {
127
112
  * pi 1.x settles the prompt by resolving it (not rejecting), so abort is
128
113
  * re-checked after prompt() returns.
129
114
  */
130
- async ask(prompt, options) {
131
- const signal = options?.signal;
115
+ async ask(prompt, call) {
116
+ const { cwd, system, signal } = call;
132
117
  if (signal?.aborted)
133
118
  throw new Error("Aborted");
134
119
  // Track session so abort can dispose it at any point — even during createSession
@@ -136,7 +121,7 @@ export class PiAdapter {
136
121
  const onAbort = () => session?.dispose();
137
122
  signal?.addEventListener("abort", onAbort, { once: true });
138
123
  try {
139
- session = await this.createSession(options?.system, signal);
124
+ session = await this.createSession(cwd, system, signal);
140
125
  // Re-check: abort may have fired during createSession (before session existed)
141
126
  if (signal?.aborted)
142
127
  throw new Error("Aborted");
@@ -155,12 +140,4 @@ export class PiAdapter {
155
140
  session?.dispose();
156
141
  }
157
142
  }
158
- async repair(input, signal) {
159
- const response = await this.ask(`Fix this program so it runs.\n\n` +
160
- `Runtime types:\n${input.runtimeTypes}\n\n` +
161
- `Broken program:\n${input.programSource}\n\n` +
162
- `Error:\n${input.error}\n\n` +
163
- `Output ONLY the fixed program. No explanation.`, { system: "You are a TypeScript repair tool.", signal });
164
- return stripCodeFences(response);
165
- }
166
143
  }
@@ -5,24 +5,26 @@ export interface ProgramResult {
5
5
  /** From ctx.done(result), if provided. */
6
6
  result?: unknown;
7
7
  }
8
- export interface PiAdapterConfig {
8
+ /** Which model serves a project's LLM calls. */
9
+ export interface ModelConfig {
9
10
  provider: string;
10
11
  model: string;
11
12
  }
12
13
  export interface RunOptions {
13
14
  projectDir: string;
14
15
  maxRepairAttempts?: number;
16
+ /**
17
+ * Per-phase limit in ms on the program's own time, for each run and each
18
+ * repair attempt. Time during which a run the program started with
19
+ * runProgram() — a session participant — is in flight is not counted: that
20
+ * run has a timeout of its own.
21
+ */
15
22
  timeout?: number;
16
23
  args?: Record<string, unknown>;
17
24
  /** Shared workspace directory. When set, workspace.* API is enabled for the program. */
18
25
  workspaceDir?: string;
19
26
  }
20
- export interface RepairInput {
21
- programSource: string;
22
- error: string;
23
- runtimeTypes: string;
24
- }
25
- export interface TramaConfig extends PiAdapterConfig {
27
+ export interface TramaConfig extends ModelConfig {
26
28
  maxRepairAttempts: number;
27
29
  defaultTimeout: number;
28
30
  defaultMaxIterations: number;
package/dist/runner.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { RunOptions, TramaConfig, ProgramResult } from "./runner-types.js";
2
- import { PiAdapter } from "./pi-adapter.js";
2
+ import type { AgentBackend } from "./agent-backend.js";
3
3
  /**
4
4
  * Everything a project directory needs around program.ts before it can run:
5
5
  * history/ and logs/, an ESM package.json, .gitignore entries, and links to the
@@ -16,14 +16,17 @@ export declare const RUNTIME_TYPES: string;
16
16
  export declare function loadConfig(): TramaConfig;
17
17
  /** The global config, with the model/provider a project was created with taking precedence. */
18
18
  export declare function loadProjectConfig(projectDir: string): TramaConfig;
19
+ /**
20
+ * What does the LLM work for a project. The only place that picks a backend:
21
+ * everything else is handed one and does not know which it is.
22
+ */
23
+ export declare function createBackend(config: TramaConfig): AgentBackend;
19
24
  export declare function loadState(projectDir: string): Record<string, unknown>;
20
25
  /**
21
26
  * Save the current program.ts as the next version: copy it to history/NNNN.ts
22
27
  * and record why in index.jsonl.
23
28
  *
24
- * Repairs made while validating a create or update are NOT versions of their
25
- * own — they are noted in index.jsonl only (reason "create-repair" /
26
- * "update-repair"), and the validated program becomes the create/update version.
29
+ * (See installValidatedProgram for how a create or update is recorded.)
27
30
  */
28
31
  export declare function copyToHistory(projectDir: string, reason: string, detail?: string): void;
29
32
  type DirSnapshot = Map<string, {
@@ -33,47 +36,51 @@ type DirSnapshot = Map<string, {
33
36
  /** Record all files in a directory with their size and mtime for change detection. */
34
37
  export declare function snapshotDir(dir: string, prefix?: string): DirSnapshot;
35
38
  /**
36
- * Commit workspace changes from a temp workspace back to the real workspace,
37
- * using a three-way check to avoid overwriting concurrent updates by other participants.
38
- *
39
- * @param tempDir - temp workspace after the run (source of changes)
40
- * @param realDir - real shared workspace (destination)
41
- * @param tempBefore - temp workspace snapshot before the run (detects what the run changed)
42
- * @param realSeed - real workspace snapshot at seed time (detects concurrent changes)
39
+ * Merge what a run did to a staged copy back into the real directory, with a
40
+ * three-way check so that nothing changed in the real directory meanwhile —
41
+ * by the user, or by another run of the same project — is overwritten.
43
42
  *
44
- * For each file the run created or modified in the temp workspace:
45
- * - New file: copied unless that path has meanwhile appeared in the real workspace.
46
- * - Modified file: copied only if the real workspace's copy still matches realSeed.
47
- * If it doesn't, another participant changed or removed it concurrently — skip.
48
- * Best-effort: anything that cannot be committed safely is skipped, never thrown.
49
- */
50
- export declare function commitWorkspaceChanges(tempDir: string, realDir: string, tempBefore: DirSnapshot, realSeed: DirSnapshot): void;
51
- /**
52
- * Run fn against a directory that can be put back exactly as it was: if fn
53
- * returns keep:false or throws, the directory is rolled back. Returns fn's value.
43
+ * @param stagedDir - the copy after the run (source of changes)
44
+ * @param realDir - the real directory (destination)
45
+ * @param stagedBefore - snapshot of the copy before the run (detects what the run changed)
46
+ * @param realSeed - snapshot of the real directory when the copy was taken (detects concurrent changes)
54
47
  *
55
- * The snapshot is a hidden copy next to the directory, on the same file
56
- * system, so rolling back is two renames — move the directory aside, move the
57
- * snapshot into its place — and at no point does the content exist nowhere.
58
- * (If the process is killed outright, the snapshot is left behind beside the
59
- * directory: it is the pre-change state.)
48
+ * For each file the run touched in the copy:
49
+ * - Created: copied, unless that path has meanwhile appeared in the real directory.
50
+ * - Modified: copied only if the real file still matches realSeed.
51
+ * - Deleted: deleted only if the real file still matches realSeed.
52
+ * Best-effort: anything that cannot be merged safely is skipped, never thrown.
60
53
  */
61
- export declare function withSnapshot<T>(dir: string, fn: () => Promise<{
62
- keep: boolean;
63
- value: T;
64
- }>): Promise<T>;
65
- /** Run fn in a temp directory, clean up afterwards regardless of outcome. */
54
+ export declare function commitStagedChanges(stagedDir: string, realDir: string, stagedBefore: DirSnapshot, realSeed: DirSnapshot): void;
55
+ /** Run fn in a temp directory, clean up afterwards regardless of outcome — including this process being stopped. */
66
56
  export declare function withTempDir<T>(prefix: string, fn: (dir: string) => Promise<T>): Promise<T>;
57
+ /** The instructions a request for a fix is made under. (Exported so the tests' stand-in LLM can tell one from any other call.) */
58
+ export declare const REPAIR_SYSTEM_PROMPT = "You are a TypeScript repair tool.";
67
59
  /**
68
- * Validate a freshly generated program.ts by running it (with repair) in a
69
- * throwaway copy of the project, so the validation run's file side effects
70
- * don't persist. On success the validated — possibly repaired — program is
71
- * copied back. Throws if it cannot be made to run.
60
+ * Validate a candidate program.ts for a project without touching the project:
61
+ * run it (with repair) in a throwaway copy. Returns the program that worked —
62
+ * the candidate itself, or a repaired version of it, with the failure that was
63
+ * repaired. Throws if it cannot be made to run.
64
+ *
65
+ * Only the project's own files are shielded. What the program does beyond
66
+ * them — network calls, shell commands, other projects it runs — is real.
72
67
  */
73
- export declare function smokeRunAndRepair(projectDir: string, adapter: PiAdapter, reason: "create" | "update", options: {
68
+ export declare function validateProgram(projectDir: string, backend: AgentBackend, candidate: string, options: {
74
69
  timeout: number;
75
70
  maxRepairAttempts: number;
76
71
  maxIterations: number;
77
- }): Promise<void>;
72
+ }): Promise<{
73
+ source: string;
74
+ repairedError?: string;
75
+ }>;
76
+ /**
77
+ * Make a validated program the project's program.ts and record it as a new
78
+ * version. A repair made while validating is not a version of its own — it is
79
+ * noted in the history index only.
80
+ */
81
+ export declare function installValidatedProgram(projectDir: string, validated: {
82
+ source: string;
83
+ repairedError?: string;
84
+ }, reason: "create" | "update", prompt: string): void;
78
85
  export declare function runProgram(options: RunOptions): Promise<ProgramResult>;
79
86
  export {};