@trama-dev/runtime 0.1.5 → 0.2.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
@@ -1,11 +1,12 @@
1
1
  // @trama-dev/runtime runner surface — exported via "@trama-dev/runtime/runner"
2
- import { readFileSync, writeFileSync, mkdirSync, readdirSync, existsSync, copyFileSync, appendFileSync, statSync, rmSync, cpSync, mkdtempSync } from "fs";
2
+ import { readFileSync, writeFileSync, mkdirSync, readdirSync, existsSync, statSync, rmSync } from "fs";
3
3
  import { join } from "path";
4
- import { homedir, tmpdir } from "os";
5
- import { PiAdapter, stripCodeFences } from "./pi-adapter.js";
6
- import { loadConfig, loadState, smokeRunAndRepair, copyToHistory, withTempDir, ensureProjectScaffold, RUNTIME_TYPES, PI_VERSION } from "./runner.js";
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";
7
7
  import { guardPath } from "./path-guard.js";
8
8
  export { runProgram } from "./runner.js";
9
+ export { createWorkspace } from "./workspace.js";
9
10
  // --- Example programs (included in system prompt during create/update) ---
10
11
  const EXAMPLE_PROGRAMS = `// Example A: Simple — one-shot action, no LLM needed.
11
12
  import { ctx, tools } from "@trama-dev/runtime";
@@ -116,32 +117,6 @@ export function resolveProject(name) {
116
117
  async function isolatedAsk(adapter, prompt, options) {
117
118
  return withTempDir("trama-gen-", (dir) => adapter.withCwd(dir).ask(prompt, options));
118
119
  }
119
- /** Backup projectDir, run fn, restore on failure. Preserves new repair history entries across restore. */
120
- async function withProjectBackup(projectDir, originalHistory, historyIndexPath, fn) {
121
- const backupRoot = mkdtempSync(join(tmpdir(), "trama-update-backup-"));
122
- const backupDir = join(backupRoot, "project");
123
- cpSync(projectDir, backupDir, { recursive: true });
124
- try {
125
- await fn();
126
- }
127
- catch (err) {
128
- // Restore from backup, preserving any new repair history entries
129
- const failedHistory = existsSync(historyIndexPath) ? readFileSync(historyIndexPath, "utf-8") : "";
130
- rmSync(projectDir, { recursive: true, force: true });
131
- cpSync(backupDir, projectDir, { recursive: true });
132
- if (failedHistory.startsWith(originalHistory)) {
133
- const repairEntries = failedHistory.slice(originalHistory.length);
134
- if (repairEntries.length > 0) {
135
- appendFileSync(guardPath(projectDir, join("history", "index.jsonl")), repairEntries);
136
- }
137
- }
138
- throw new Error(`Update failed — project files have been restored to the previous version.\n` +
139
- `${err instanceof Error ? err.message : err}`);
140
- }
141
- finally {
142
- rmSync(backupRoot, { recursive: true, force: true });
143
- }
144
- }
145
120
  // --- Public API ---
146
121
  export async function createProject(name, prompt, options) {
147
122
  validateProjectName(name);
@@ -152,8 +127,6 @@ export async function createProject(name, prompt, options) {
152
127
  }
153
128
  mkdirSync(projectDir, { recursive: true });
154
129
  try {
155
- mkdirSync(join(projectDir, "history"), { recursive: true });
156
- mkdirSync(join(projectDir, "logs"), { recursive: true });
157
130
  ensureProjectScaffold(projectDir);
158
131
  const config = loadConfig();
159
132
  if (options?.model)
@@ -177,8 +150,7 @@ export async function createProject(name, prompt, options) {
177
150
  maxRepairAttempts: config.maxRepairAttempts,
178
151
  maxIterations: config.defaultMaxIterations,
179
152
  });
180
- copyFileSync(join(projectDir, "program.ts"), join(projectDir, "history", "0001.ts"));
181
- appendFileSync(join(projectDir, "history", "index.jsonl"), JSON.stringify({ version: 1, reason: "create", timestamp: new Date().toISOString(), prompt }) + "\n");
153
+ copyToHistory(projectDir, "create", prompt);
182
154
  console.log(`Created ${name}. Run with: trama run ${name}`);
183
155
  }
184
156
  catch (err) {
@@ -190,36 +162,40 @@ export async function createProject(name, prompt, options) {
190
162
  }
191
163
  export async function updateProject(name, prompt) {
192
164
  const projectDir = resolveProject(name);
165
+ // A hand-written project may never have been run: give it history/ and the rest first.
166
+ ensureProjectScaffold(projectDir);
193
167
  const programPath = guardPath(projectDir, "program.ts");
194
168
  const originalSource = readFileSync(programPath, "utf-8");
195
169
  const state = loadState(projectDir);
196
170
  const meta = JSON.parse(readFileSync(guardPath(projectDir, "meta.json"), "utf-8"));
197
- const historyIndexPath = guardPath(projectDir, join("history", "index.jsonl"));
198
- const originalHistory = existsSync(historyIndexPath) ? readFileSync(historyIndexPath, "utf-8") : "";
199
- const config = loadConfig();
200
- if (meta.model)
201
- config.model = meta.model;
202
- if (meta.provider)
203
- config.provider = meta.provider;
171
+ const config = loadProjectConfig(projectDir);
204
172
  const adapter = new PiAdapter(config, projectDir);
205
- // Backup before any LLM calls, restore on any failure
206
- await withProjectBackup(projectDir, originalHistory, historyIndexPath, async () => {
207
- const systemPrompt = getSystemPrompt() +
208
- `\n\nOriginal prompt: ${meta.input.prompt}` +
209
- `\n\nCurrent program.ts:\n${originalSource}` +
210
- (Object.keys(state).length > 0 ? `\n\nCurrent state:\n${JSON.stringify(state, null, 2)}` : "");
211
- console.log(`Updating "${name}"...`);
212
- const updated = stripCodeFences(await isolatedAsk(adapter, `${prompt}\n\nOutput the complete updated program.ts. No partial patches. No markdown fences. No explanation.`, { system: systemPrompt }));
213
- writeFileSync(programPath, updated);
214
- console.log("Validating updated program...");
215
- await smokeRunAndRepair(projectDir, adapter, "update", {
216
- timeout: config.defaultTimeout,
217
- maxRepairAttempts: config.maxRepairAttempts,
218
- maxIterations: config.defaultMaxIterations,
173
+ const systemPrompt = getSystemPrompt() +
174
+ `\n\nOriginal prompt: ${meta.input.prompt}` +
175
+ `\n\nCurrent program.ts:\n${originalSource}` +
176
+ (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.
179
+ 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 };
219
192
  });
220
- copyToHistory(projectDir, "update", prompt);
221
- console.log(`Updated ${name}. Run with: trama run ${name}`);
222
- });
193
+ }
194
+ catch (err) {
195
+ throw new Error(`Update failed — project files have been restored to the previous version.\n` +
196
+ `${err instanceof Error ? err.message : err}`);
197
+ }
198
+ console.log(`Updated ${name}. Run with: trama run ${name}`);
223
199
  }
224
200
  export async function listProjects() {
225
201
  const dir = projectsDir();
@@ -227,8 +203,9 @@ export async function listProjects() {
227
203
  console.log("No projects found.");
228
204
  return;
229
205
  }
206
+ // Dot-directories are not projects (a rollback snapshot is kept beside its project while a run is in flight).
230
207
  const entries = readdirSync(dir, { withFileTypes: true })
231
- .filter(e => e.isDirectory());
208
+ .filter(e => e.isDirectory() && !e.name.startsWith("."));
232
209
  if (entries.length === 0) {
233
210
  console.log("No projects found.");
234
211
  return;
@@ -0,0 +1,22 @@
1
+ import { type Server } from "http";
2
+ import type { Ctx, Agent, Tools, Workspace } from "./types.js";
3
+ import type { ProgramResult } from "./runner-types.js";
4
+ export interface IpcBackends {
5
+ /**
6
+ * The secret only this run's program knows. Every request must present it:
7
+ * the server listens on a loopback port that any local process — or a web
8
+ * page the user happens to have open — could otherwise send commands to.
9
+ */
10
+ token: string;
11
+ ctx: Ctx;
12
+ agent: Agent;
13
+ tools: Tools;
14
+ /** Null when the program is not running in a session. */
15
+ workspace: Workspace | null;
16
+ /** Called once ctx.done() or ctx.yield() has been persisted for this run. */
17
+ onTerminalSignal(result: ProgramResult): void;
18
+ }
19
+ export declare function createIPCServer(backends: IpcBackends): Server;
20
+ /** Start listening on an ephemeral loopback port and return it. */
21
+ export declare function listen(server: Server): Promise<number>;
22
+ export declare function closeServer(server: Server): Promise<void>;
@@ -0,0 +1,168 @@
1
+ // The runner side of the IPC bridge. A running program.ts reaches ctx, agent,
2
+ // tools and workspace by POSTing JSON to this local HTTP server (see client.ts
3
+ // for the other end).
4
+ import { createServer } from "http";
5
+ import { timingSafeEqual } from "crypto";
6
+ import { assertSerializable } from "./serializable.js";
7
+ const MAX_IPC_BODY = 50 * 1024 * 1024; // 50 MB
8
+ /** A request the program got wrong — answered with 400 rather than 500. */
9
+ class BadRequest extends Error {
10
+ }
11
+ const isPlainObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
12
+ function validate(body, fields) {
13
+ for (const [name, type] of Object.entries(fields)) {
14
+ const value = body[name];
15
+ if (type === "optional object") {
16
+ if (value !== undefined && !isPlainObject(value)) {
17
+ throw new BadRequest(`Invalid field: ${name} (expected object or undefined)`);
18
+ }
19
+ }
20
+ else if (type === "object" ? !isPlainObject(value) : typeof value !== type) {
21
+ throw new BadRequest(`Missing or invalid field: ${name} (expected ${type})`);
22
+ }
23
+ }
24
+ }
25
+ /** Whether a request carries `Authorization: Bearer <token>`, compared in constant time. */
26
+ function isAuthorized(header, token) {
27
+ const expected = Buffer.from(`Bearer ${token}`);
28
+ const actual = Buffer.from(header ?? "");
29
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
30
+ }
31
+ function buildRoutes({ ctx, agent, tools, workspace, onTerminalSignal }) {
32
+ /** The program owns ctx.state; each persisting call hands over its current copy. */
33
+ const adoptState = (state) => {
34
+ assertSerializable(state, "ctx.state");
35
+ ctx.state = state;
36
+ };
37
+ const inSession = () => {
38
+ if (!workspace)
39
+ throw new BadRequest("Workspace is only available when running in a session");
40
+ return workspace;
41
+ };
42
+ return {
43
+ "/agent/instruct": {
44
+ fields: { prompt: "string" },
45
+ handle: b => agent.instruct(b.prompt, { system: b.system }),
46
+ },
47
+ "/agent/generate": {
48
+ fields: { prompt: "string", schema: "object" },
49
+ handle: b => agent.generate(b),
50
+ },
51
+ "/tools/read": { fields: { path: "string" }, handle: b => tools.read(b.path) },
52
+ "/tools/write": { fields: { path: "string", content: "string" }, handle: b => tools.write(b.path, b.content) },
53
+ "/tools/shell": {
54
+ fields: { command: "string" },
55
+ handle: b => tools.shell(b.command, { cwd: b.cwd, timeout: b.timeout }),
56
+ },
57
+ "/tools/fetch": {
58
+ fields: { url: "string" },
59
+ handle: b => tools.fetch(b.url, { method: b.method, headers: b.headers, body: b.body }),
60
+ },
61
+ "/ctx/log": { fields: { message: "string" }, handle: b => ctx.log(b.message, b.data) },
62
+ "/ctx/ready": { fields: { data: "optional object" }, handle: b => ctx.ready(b.data) },
63
+ "/ctx/checkpoint": {
64
+ fields: { state: "object" },
65
+ handle: async (b) => {
66
+ adoptState(b.state);
67
+ await ctx.checkpoint();
68
+ return ctx.iteration;
69
+ },
70
+ },
71
+ "/ctx/done": {
72
+ fields: { state: "object" },
73
+ handle: async (b) => {
74
+ adoptState(b.state);
75
+ await ctx.done(b.result);
76
+ onTerminalSignal({ status: "done", result: b.result ?? undefined });
77
+ return ctx.iteration;
78
+ },
79
+ },
80
+ "/ctx/yield": {
81
+ fields: { state: "object", reason: "string" },
82
+ handle: async (b) => {
83
+ adoptState(b.state);
84
+ // Persists the yield marker and returns; the program exits itself once we answer.
85
+ await ctx.yield(b.reason);
86
+ onTerminalSignal({ status: "yielded", reason: b.reason });
87
+ },
88
+ },
89
+ "/workspace/read": { fields: { path: "string" }, handle: b => inSession().read(b.path) },
90
+ "/workspace/write": {
91
+ fields: { path: "string", content: "string" },
92
+ handle: b => inSession().write(b.path, b.content),
93
+ },
94
+ "/workspace/list": { fields: { pattern: "string" }, handle: b => inSession().list(b.pattern) },
95
+ "/workspace/observe": {
96
+ fields: { pattern: "string" },
97
+ handle: b => inSession().observe(b.pattern, { expect: b.expect, timeout: b.timeout }),
98
+ },
99
+ };
100
+ }
101
+ export function createIPCServer(backends) {
102
+ const routes = buildRoutes(backends);
103
+ return createServer((req, res) => {
104
+ const reply = (status, body, json = false) => {
105
+ res.writeHead(status, json ? { "Content-Type": "application/json" } : undefined);
106
+ res.end(body);
107
+ };
108
+ if (req.method !== "POST")
109
+ return reply(405, "Method not allowed");
110
+ if (!isAuthorized(req.headers.authorization, backends.token)) {
111
+ req.resume(); // discard the body
112
+ return reply(401, "Missing or invalid IPC token");
113
+ }
114
+ const chunks = [];
115
+ let byteCount = 0;
116
+ let overflow = false;
117
+ req.on("data", (chunk) => {
118
+ if (overflow)
119
+ return;
120
+ chunks.push(chunk);
121
+ byteCount += chunk.length;
122
+ if (byteCount > MAX_IPC_BODY) {
123
+ overflow = true;
124
+ reply(413, "IPC request body exceeds 50MB limit");
125
+ req.destroy();
126
+ }
127
+ });
128
+ req.on("end", async () => {
129
+ if (overflow)
130
+ return;
131
+ try {
132
+ const body = JSON.parse(Buffer.concat(chunks).toString("utf-8"));
133
+ const route = req.url ? routes[req.url] : undefined;
134
+ if (!route)
135
+ return reply(404, "Not found");
136
+ validate(body, route.fields);
137
+ const result = await route.handle(body);
138
+ reply(200, JSON.stringify({ result: result ?? null }), true);
139
+ }
140
+ catch (err) {
141
+ reply(err instanceof BadRequest ? 400 : 500, err instanceof BadRequest ? err.message : String(err));
142
+ }
143
+ });
144
+ });
145
+ }
146
+ /** Start listening on an ephemeral loopback port and return it. */
147
+ export function listen(server) {
148
+ return new Promise((resolve, reject) => {
149
+ server.once("error", reject);
150
+ server.listen(0, "127.0.0.1", () => {
151
+ const addr = server.address();
152
+ if (addr && typeof addr === "object")
153
+ resolve(addr.port);
154
+ else
155
+ reject(new Error("Failed to get server port"));
156
+ });
157
+ });
158
+ }
159
+ export function closeServer(server) {
160
+ return new Promise((resolve, reject) => {
161
+ server.close(err => {
162
+ if (!err || err.code === "ERR_SERVER_NOT_RUNNING")
163
+ resolve();
164
+ else
165
+ reject(err);
166
+ });
167
+ });
168
+ }
@@ -1,37 +1,27 @@
1
1
  /**
2
- * Resolve a path within a project directory and verify it does not escape
3
- * the project boundary — either via ".." segments or symlinks.
2
+ * Keep file access inside a bounded root directory (a project directory or a
3
+ * session workspace) — rejecting escapes via ".." segments or symlinks.
4
4
  *
5
5
  * Not a security sandbox — just a footgun guard against malicious shared
6
6
  * projects where files like state.json or .gitignore are symlinks pointing
7
7
  * outside the project directory.
8
8
  */
9
+ /** True if `path` is `root` itself or lies underneath it. Both must already be normalized. */
10
+ export declare function isInside(path: string, root: string): boolean;
9
11
  /**
10
- * Resolve `relativePath` against `projectDir` and verify the logical path
11
- * stays within the project boundary. Returns the resolved absolute path.
12
+ * Resolve `relativePath` against `rootDir` and verify the logical path
13
+ * stays within the root. Returns the resolved absolute path.
14
+ * Catches ".." traversal only — use guardPath to also catch symlink escapes.
12
15
  */
13
- export declare function resolveBounded(projectDir: string, relativePath: string): string;
16
+ export declare function resolveBounded(rootDir: string, relativePath: string): string;
17
+ /** The real (symlink-resolved) location of a root directory, or its normalized path if it doesn't exist yet. */
18
+ export declare function realRootOf(rootDir: string): string;
14
19
  /**
15
- * Verify that `realPath` (the output of realpathSync) is inside `realProjectDir`.
16
- */
17
- export declare function verifyRealPath(realPath: string, realProjectDir: string, originalPath: string): void;
18
- /**
19
- * Walk up from `resolved` to find the deepest existing ancestor,
20
- * then verify its real path is inside the project dir.
21
- * This catches symlink escapes BEFORE any mkdir side effects.
22
- */
23
- export declare function verifyNearestAncestor(resolved: string, realProjectDir: string, originalPath: string): void;
24
- /**
25
- * Verify that an existing symlink's target resolves inside the project dir.
26
- * For dangling symlinks, falls back to verifyNearestAncestor on the link target.
27
- */
28
- export declare function verifySymlink(target: string, realProjectDir: string, originalPath: string): void;
29
- /**
30
- * All-in-one guard for reading/writing a file in a project directory.
31
- * Checks both logical path (.. segments) and symlink resolution.
32
- * Returns the resolved absolute path.
20
+ * The guard for reading or writing a path under a bounded root.
21
+ * Checks both the logical path (".." segments) and symlink resolution,
22
+ * and returns the resolved absolute path.
33
23
  *
34
- * For writes to paths that don't yet exist, checks the nearest existing
35
- * ancestor to prevent side effects outside the project.
24
+ * For paths that don't exist yet, checks the nearest existing ancestor —
25
+ * so a caller can safely mkdir and write afterwards.
36
26
  */
37
- export declare function guardPath(projectDir: string, relativePath: string): string;
27
+ export declare function guardPath(rootDir: string, relativePath: string): string;
@@ -1,39 +1,41 @@
1
1
  import { existsSync, realpathSync, lstatSync, readlinkSync } from "fs";
2
2
  import { resolve, dirname, sep } from "path";
3
3
  /**
4
- * Resolve a path within a project directory and verify it does not escape
5
- * the project boundary — either via ".." segments or symlinks.
4
+ * Keep file access inside a bounded root directory (a project directory or a
5
+ * session workspace) — rejecting escapes via ".." segments or symlinks.
6
6
  *
7
7
  * Not a security sandbox — just a footgun guard against malicious shared
8
8
  * projects where files like state.json or .gitignore are symlinks pointing
9
9
  * outside the project directory.
10
10
  */
11
+ /** True if `path` is `root` itself or lies underneath it. Both must already be normalized. */
12
+ export function isInside(path, root) {
13
+ return path === root || path.startsWith(root + sep);
14
+ }
11
15
  /**
12
- * Resolve `relativePath` against `projectDir` and verify the logical path
13
- * stays within the project boundary. Returns the resolved absolute path.
16
+ * Resolve `relativePath` against `rootDir` and verify the logical path
17
+ * stays within the root. Returns the resolved absolute path.
18
+ * Catches ".." traversal only — use guardPath to also catch symlink escapes.
14
19
  */
15
- export function resolveBounded(projectDir, relativePath) {
16
- const normalizedDir = resolve(projectDir);
20
+ export function resolveBounded(rootDir, relativePath) {
21
+ const normalizedDir = resolve(rootDir);
17
22
  const resolved = resolve(normalizedDir, relativePath);
18
- if (resolved !== normalizedDir && !resolved.startsWith(normalizedDir + sep)) {
23
+ if (!isInside(resolved, normalizedDir)) {
19
24
  throw new Error(`Path escapes project directory: ${relativePath}`);
20
25
  }
21
26
  return resolved;
22
27
  }
23
- /**
24
- * Verify that `realPath` (the output of realpathSync) is inside `realProjectDir`.
25
- */
26
- export function verifyRealPath(realPath, realProjectDir, originalPath) {
27
- if (realPath !== realProjectDir && !realPath.startsWith(realProjectDir + sep)) {
28
+ function verifyRealPath(realPath, realRoot, originalPath) {
29
+ if (!isInside(realPath, realRoot)) {
28
30
  throw new Error(`Path escapes project directory via symlink: ${originalPath}`);
29
31
  }
30
32
  }
31
33
  /**
32
34
  * Walk up from `resolved` to find the deepest existing ancestor,
33
- * then verify its real path is inside the project dir.
35
+ * then verify its real path is inside the root.
34
36
  * This catches symlink escapes BEFORE any mkdir side effects.
35
37
  */
36
- export function verifyNearestAncestor(resolved, realProjectDir, originalPath) {
38
+ function verifyNearestAncestor(resolved, realRoot, originalPath) {
37
39
  let cur = resolved;
38
40
  while (!existsSync(cur)) {
39
41
  const parent = dirname(cur);
@@ -41,42 +43,45 @@ export function verifyNearestAncestor(resolved, realProjectDir, originalPath) {
41
43
  return; // reached filesystem root — nothing to verify
42
44
  cur = parent;
43
45
  }
44
- verifyRealPath(realpathSync(cur), realProjectDir, originalPath);
46
+ verifyRealPath(realpathSync(cur), realRoot, originalPath);
45
47
  }
46
48
  /**
47
- * Verify that an existing symlink's target resolves inside the project dir.
49
+ * Verify that an existing symlink's target resolves inside the root.
48
50
  * For dangling symlinks, falls back to verifyNearestAncestor on the link target.
49
51
  */
50
- export function verifySymlink(target, realProjectDir, originalPath) {
52
+ function verifySymlink(target, realRoot, originalPath) {
51
53
  try {
52
- verifyRealPath(realpathSync(target), realProjectDir, originalPath);
54
+ verifyRealPath(realpathSync(target), realRoot, originalPath);
53
55
  }
54
56
  catch (e) {
55
57
  if (e.code !== "ENOENT")
56
58
  throw e;
57
59
  // Dangling symlink — resolve what we can via nearest existing ancestor
58
60
  const linkDest = resolve(dirname(target), readlinkSync(target));
59
- verifyNearestAncestor(linkDest, realProjectDir, originalPath);
61
+ verifyNearestAncestor(linkDest, realRoot, originalPath);
60
62
  }
61
63
  }
62
- /**
63
- * All-in-one guard for reading/writing a file in a project directory.
64
- * Checks both logical path (.. segments) and symlink resolution.
65
- * Returns the resolved absolute path.
66
- *
67
- * For writes to paths that don't yet exist, checks the nearest existing
68
- * ancestor to prevent side effects outside the project.
69
- */
70
- export function guardPath(projectDir, relativePath) {
71
- const normalizedDir = resolve(projectDir);
72
- let realDir;
64
+ /** The real (symlink-resolved) location of a root directory, or its normalized path if it doesn't exist yet. */
65
+ export function realRootOf(rootDir) {
66
+ const normalizedDir = resolve(rootDir);
73
67
  try {
74
- realDir = realpathSync(normalizedDir);
68
+ return realpathSync(normalizedDir);
75
69
  }
76
70
  catch {
77
- realDir = normalizedDir;
71
+ return normalizedDir;
78
72
  }
79
- const resolved = resolveBounded(projectDir, relativePath);
73
+ }
74
+ /**
75
+ * The guard for reading or writing a path under a bounded root.
76
+ * Checks both the logical path (".." segments) and symlink resolution,
77
+ * and returns the resolved absolute path.
78
+ *
79
+ * For paths that don't exist yet, checks the nearest existing ancestor —
80
+ * so a caller can safely mkdir and write afterwards.
81
+ */
82
+ export function guardPath(rootDir, relativePath) {
83
+ const realRoot = realRootOf(rootDir);
84
+ const resolved = resolveBounded(rootDir, relativePath);
80
85
  // Use lstatSync (not existsSync) to detect dangling symlinks.
81
86
  // existsSync returns false for dangling symlinks, which would skip the
82
87
  // symlink check and allow writes to follow the link to an external target.
@@ -88,15 +93,15 @@ export function guardPath(projectDir, relativePath) {
88
93
  if (e.code !== "ENOENT")
89
94
  throw e;
90
95
  // Path truly doesn't exist (not even as a dangling symlink)
91
- // — verify nearest ancestor is inside project
92
- verifyNearestAncestor(resolved, realDir, relativePath);
96
+ // — verify nearest ancestor is inside the root
97
+ verifyNearestAncestor(resolved, realRoot, relativePath);
93
98
  return resolved;
94
99
  }
95
100
  if (stat.isSymbolicLink()) {
96
- verifySymlink(resolved, realDir, relativePath);
101
+ verifySymlink(resolved, realRoot, relativePath);
97
102
  }
98
103
  else {
99
- verifyRealPath(realpathSync(resolved), realDir, relativePath);
104
+ verifyRealPath(realpathSync(resolved), realRoot, relativePath);
100
105
  }
101
106
  return resolved;
102
107
  }
@@ -1,4 +1,6 @@
1
- import type { PiAdapterConfig, RepairInput } from "./types.js";
1
+ import type { PiAdapterConfig, RepairInput } from "./runner-types.js";
2
+ /** The pi version this runtime is built against (recorded in each project's meta.json). */
3
+ export { VERSION as PI_VERSION } from "@earendil-works/pi-coding-agent";
2
4
  /** Strip markdown code fences and trim whitespace. */
3
5
  export declare function stripCodeFences(text: string): string;
4
6
  export declare class PiAdapter {
@@ -8,11 +10,18 @@ export declare class PiAdapter {
8
10
  /** Create a copy of this adapter that operates in a different working directory. */
9
11
  withCwd(cwd: string): PiAdapter;
10
12
  private createSession;
13
+ /**
14
+ * The configured provider/model is not in pi's catalog, so pi picked a model
15
+ * on its own. Say so once — otherwise a typo silently runs a different model.
16
+ */
17
+ private warnUnknownModel;
11
18
  private extractText;
12
19
  /**
13
20
  * Abort cancellation relies on session.dispose() interrupting session.prompt().
14
21
  * 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.
22
+ * actually settle the in-flight prompt, the abort signal will not terminate the call.
23
+ * pi 1.x settles the prompt by resolving it (not rejecting), so abort is
24
+ * re-checked after prompt() returns.
16
25
  */
17
26
  ask(prompt: string, options?: {
18
27
  system?: string;