@trama-dev/runtime 0.1.2 → 0.1.3
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/README.md +25 -6
- package/dist/client.js +36 -11
- package/dist/context.js +35 -16
- package/dist/index.js +21 -15
- package/dist/path-guard.d.ts +37 -0
- package/dist/path-guard.js +102 -0
- package/dist/pi-adapter.js +14 -4
- package/dist/runner.d.ts +6 -0
- package/dist/runner.js +140 -39
- package/dist/serializable.js +2 -1
- package/dist/tools.js +20 -47
- package/dist/types.d.ts +1 -0
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
# @trama-dev/runtime
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> Agents don't need frameworks. They need a runtime.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
The runtime behind [trama](https://github.com/NaNhkNaN/trama) — execution, state persistence, auto-repair, and version history for agent-authored programs.
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
## Two surfaces
|
|
8
|
+
|
|
9
|
+
**Client** — what trama-generated programs import. Three objects: `ctx`, `agent`, `tools`.
|
|
8
10
|
|
|
9
11
|
```typescript
|
|
10
12
|
import { ctx, agent, tools } from "@trama-dev/runtime";
|
|
@@ -15,10 +17,27 @@ await tools.write("report.md", report);
|
|
|
15
17
|
await ctx.done();
|
|
16
18
|
```
|
|
17
19
|
|
|
18
|
-
|
|
20
|
+
`ctx` manages lifecycle and persistent state. `agent` makes LLM calls (including autonomous tool use via pi-coding-agent). `tools` handles file I/O, shell commands, and HTTP requests.
|
|
21
|
+
|
|
22
|
+
**Runner** — what the CLI and programmatic callers use to create and execute programs.
|
|
19
23
|
|
|
20
24
|
```typescript
|
|
21
|
-
import { runProgram,
|
|
25
|
+
import { createProject, runProgram, updateProject } from "@trama-dev/runtime/runner";
|
|
22
26
|
```
|
|
23
27
|
|
|
24
|
-
|
|
28
|
+
## What the runtime provides
|
|
29
|
+
|
|
30
|
+
The runtime is what makes agent programs **self-contained and shareable**:
|
|
31
|
+
|
|
32
|
+
- **Execution** — child process spawning, streaming output, timeout management, background process cleanup.
|
|
33
|
+
- **IPC bridge** — local HTTP server mediating all LLM calls, file I/O, and shell commands. The runtime monitors and controls every operation.
|
|
34
|
+
- **State persistence** — `ctx.state` survives across runs. Programs can be long-running, interruptible, and resumable.
|
|
35
|
+
- **Auto-repair** — on crash, the runtime gets an LLM fix, validates it in isolation, applies it with snapshot protection. Up to 3 attempts.
|
|
36
|
+
- **Version history** — every create, update, and repair saves a snapshot to `history/`.
|
|
37
|
+
- **Scaffolding** — package.json, module symlinks, gitignore, logs. `git clone && trama run` just works.
|
|
38
|
+
|
|
39
|
+
## Self-orchestration
|
|
40
|
+
|
|
41
|
+
trama programs can create and run other trama programs through `tools.shell()`. The generated program becomes the orchestrator — decomposing tasks, spawning sub-programs, and synthesizing results. No orchestration framework needed. trama is the scheduler.
|
|
42
|
+
|
|
43
|
+
See the [main README](https://github.com/NaNhkNaN/trama) for examples, the full API reference, and design philosophy.
|
package/dist/client.js
CHANGED
|
@@ -24,7 +24,7 @@ async function call(endpoint, body) {
|
|
|
24
24
|
throw new Error(`trama runtime error: ${await res.text()}`);
|
|
25
25
|
return res.json();
|
|
26
26
|
}
|
|
27
|
-
let
|
|
27
|
+
let donePromise = null;
|
|
28
28
|
let readyCalled = false;
|
|
29
29
|
export const ctx = {
|
|
30
30
|
input: initData.input,
|
|
@@ -32,12 +32,26 @@ export const ctx = {
|
|
|
32
32
|
iteration: initData.iteration,
|
|
33
33
|
maxIterations: initData.maxIterations,
|
|
34
34
|
async log(msg, data) {
|
|
35
|
-
|
|
35
|
+
let safeData = data;
|
|
36
|
+
try {
|
|
37
|
+
JSON.stringify(safeData);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
safeData = { __trama_unserializable: String(data) };
|
|
41
|
+
}
|
|
42
|
+
await call("/ctx/log", { message: msg, data: safeData });
|
|
36
43
|
},
|
|
37
44
|
async ready(data) {
|
|
38
45
|
if (readyCalled)
|
|
39
46
|
return;
|
|
40
|
-
|
|
47
|
+
let safeData = data;
|
|
48
|
+
try {
|
|
49
|
+
JSON.stringify(safeData);
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
safeData = { __trama_unserializable: String(data) };
|
|
53
|
+
}
|
|
54
|
+
await call("/ctx/ready", { data: safeData });
|
|
41
55
|
readyCalled = true;
|
|
42
56
|
},
|
|
43
57
|
async checkpoint() {
|
|
@@ -46,14 +60,25 @@ export const ctx = {
|
|
|
46
60
|
ctx.iteration += 1;
|
|
47
61
|
},
|
|
48
62
|
async done(result) {
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
63
|
+
// If a previous done() completed or is in flight, coalesce onto it.
|
|
64
|
+
// If a previous done() failed, allow retry (promise was cleared).
|
|
65
|
+
if (donePromise)
|
|
66
|
+
return donePromise;
|
|
67
|
+
const run = async () => {
|
|
68
|
+
assertSerializable(ctx.state, "ctx.state");
|
|
69
|
+
if (result !== undefined)
|
|
70
|
+
assertSerializable(result, "ctx.done(result)");
|
|
71
|
+
await call("/ctx/done", { state: ctx.state, result });
|
|
72
|
+
ctx.iteration += 1;
|
|
73
|
+
};
|
|
74
|
+
donePromise = run();
|
|
75
|
+
try {
|
|
76
|
+
await donePromise;
|
|
77
|
+
}
|
|
78
|
+
catch (err) {
|
|
79
|
+
donePromise = null;
|
|
80
|
+
throw err;
|
|
81
|
+
}
|
|
57
82
|
},
|
|
58
83
|
};
|
|
59
84
|
export const agent = {
|
package/dist/context.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { readFileSync, writeFileSync, appendFileSync } from "fs";
|
|
2
2
|
import { join } from "path";
|
|
3
3
|
import { assertSerializable } from "./serializable.js";
|
|
4
|
+
import { guardPath } from "./path-guard.js";
|
|
4
5
|
export function createContext(projectDir, initialState, options) {
|
|
5
|
-
const logsPath =
|
|
6
|
-
const statePath =
|
|
7
|
-
const meta = JSON.parse(readFileSync(
|
|
8
|
-
let
|
|
6
|
+
const logsPath = guardPath(projectDir, join("logs", "latest.jsonl"));
|
|
7
|
+
const statePath = guardPath(projectDir, "state.json");
|
|
8
|
+
const meta = JSON.parse(readFileSync(guardPath(projectDir, "meta.json"), "utf-8"));
|
|
9
|
+
let donePromise = null;
|
|
9
10
|
let doneLogged = false;
|
|
10
11
|
let readyCalled = false;
|
|
11
12
|
const input = options?.argsOverride
|
|
@@ -15,11 +16,19 @@ export function createContext(projectDir, initialState, options) {
|
|
|
15
16
|
input,
|
|
16
17
|
state: { ...initialState },
|
|
17
18
|
iteration: typeof initialState.__trama_iteration === "number"
|
|
18
|
-
&& Number.
|
|
19
|
+
&& Number.isInteger(initialState.__trama_iteration)
|
|
20
|
+
&& initialState.__trama_iteration >= 0
|
|
19
21
|
? initialState.__trama_iteration : 0,
|
|
20
22
|
maxIterations: options?.maxIterations ?? 100,
|
|
21
23
|
async log(message, data) {
|
|
22
|
-
|
|
24
|
+
let safeData = data ?? null;
|
|
25
|
+
try {
|
|
26
|
+
JSON.stringify(safeData);
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
safeData = { __trama_unserializable: String(data) };
|
|
30
|
+
}
|
|
31
|
+
const entry = { ts: Date.now(), message, data: safeData };
|
|
23
32
|
appendFileSync(logsPath, JSON.stringify(entry) + "\n");
|
|
24
33
|
console.log(`[trama] ${message}`);
|
|
25
34
|
},
|
|
@@ -38,17 +47,27 @@ export function createContext(projectDir, initialState, options) {
|
|
|
38
47
|
this.iteration = nextIteration;
|
|
39
48
|
},
|
|
40
49
|
async done(result) {
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
50
|
+
// If a previous done() completed successfully, no-op.
|
|
51
|
+
// If a previous done() is still in flight, coalesce onto it.
|
|
52
|
+
// If a previous done() failed (checkpoint threw), allow retry.
|
|
53
|
+
if (donePromise)
|
|
54
|
+
return donePromise;
|
|
55
|
+
const run = async () => {
|
|
56
|
+
if (!doneLogged) {
|
|
57
|
+
await this.log("done", result);
|
|
58
|
+
}
|
|
59
|
+
await this.checkpoint();
|
|
60
|
+
doneLogged = true;
|
|
61
|
+
};
|
|
62
|
+
donePromise = run();
|
|
63
|
+
try {
|
|
64
|
+
await donePromise;
|
|
65
|
+
}
|
|
66
|
+
catch (err) {
|
|
67
|
+
// Checkpoint failed — clear promise so a retry is allowed.
|
|
68
|
+
donePromise = null;
|
|
69
|
+
throw err;
|
|
45
70
|
}
|
|
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;
|
|
51
|
-
doneCalled = true;
|
|
52
71
|
}
|
|
53
72
|
};
|
|
54
73
|
}
|
package/dist/index.js
CHANGED
|
@@ -3,7 +3,8 @@ import { readFileSync, writeFileSync, mkdirSync, readdirSync, existsSync, copyFi
|
|
|
3
3
|
import { join } from "path";
|
|
4
4
|
import { homedir, tmpdir } from "os";
|
|
5
5
|
import { PiAdapter, stripCodeFences } from "./pi-adapter.js";
|
|
6
|
-
import { loadConfig, loadState, smokeRunAndRepair, copyToHistory, withTempDir, RUNTIME_TYPES, PI_VERSION } from "./runner.js";
|
|
6
|
+
import { loadConfig, loadState, smokeRunAndRepair, copyToHistory, withTempDir, ensureProjectScaffold, RUNTIME_TYPES, PI_VERSION } from "./runner.js";
|
|
7
|
+
import { guardPath } from "./path-guard.js";
|
|
7
8
|
export { runProgram } from "./runner.js";
|
|
8
9
|
// --- Example programs (included in system prompt during create/update) ---
|
|
9
10
|
const EXAMPLE_PROGRAMS = `// Example A: Simple — one-shot action, no LLM needed.
|
|
@@ -128,7 +129,7 @@ async function withProjectBackup(projectDir, originalHistory, historyIndexPath,
|
|
|
128
129
|
if (failedHistory.startsWith(originalHistory)) {
|
|
129
130
|
const repairEntries = failedHistory.slice(originalHistory.length);
|
|
130
131
|
if (repairEntries.length > 0) {
|
|
131
|
-
appendFileSync(
|
|
132
|
+
appendFileSync(guardPath(projectDir, join("history", "index.jsonl")), repairEntries);
|
|
132
133
|
}
|
|
133
134
|
}
|
|
134
135
|
throw new Error(`Update failed — project files have been restored to the previous version.\n` +
|
|
@@ -150,17 +151,18 @@ export async function createProject(name, prompt, options) {
|
|
|
150
151
|
try {
|
|
151
152
|
mkdirSync(join(projectDir, "history"), { recursive: true });
|
|
152
153
|
mkdirSync(join(projectDir, "logs"), { recursive: true });
|
|
153
|
-
|
|
154
|
-
|
|
154
|
+
ensureProjectScaffold(projectDir);
|
|
155
|
+
const config = loadConfig();
|
|
156
|
+
if (options?.model)
|
|
157
|
+
config.model = options.model;
|
|
155
158
|
const meta = {
|
|
156
159
|
input: { prompt, args: options?.args ?? {} },
|
|
157
160
|
createdAt: new Date().toISOString(),
|
|
158
161
|
piVersion: PI_VERSION,
|
|
162
|
+
model: config.model,
|
|
163
|
+
provider: config.provider,
|
|
159
164
|
};
|
|
160
165
|
writeFileSync(join(projectDir, "meta.json"), JSON.stringify(meta, null, 2));
|
|
161
|
-
const config = loadConfig();
|
|
162
|
-
if (options?.model)
|
|
163
|
-
config.model = options.model;
|
|
164
166
|
const adapter = new PiAdapter(config, projectDir);
|
|
165
167
|
console.log(`Generating program for "${name}"...`);
|
|
166
168
|
const program = stripCodeFences(await isolatedAsk(adapter, `${prompt}\n\nOutput ONLY the TypeScript program. No markdown fences. No explanation.`, { system: getSystemPrompt() }));
|
|
@@ -185,13 +187,17 @@ export async function createProject(name, prompt, options) {
|
|
|
185
187
|
}
|
|
186
188
|
export async function updateProject(name, prompt) {
|
|
187
189
|
const projectDir = resolveProject(name);
|
|
188
|
-
const programPath =
|
|
190
|
+
const programPath = guardPath(projectDir, "program.ts");
|
|
189
191
|
const originalSource = readFileSync(programPath, "utf-8");
|
|
190
192
|
const state = loadState(projectDir);
|
|
191
|
-
const meta = JSON.parse(readFileSync(
|
|
192
|
-
const historyIndexPath =
|
|
193
|
+
const meta = JSON.parse(readFileSync(guardPath(projectDir, "meta.json"), "utf-8"));
|
|
194
|
+
const historyIndexPath = guardPath(projectDir, join("history", "index.jsonl"));
|
|
193
195
|
const originalHistory = existsSync(historyIndexPath) ? readFileSync(historyIndexPath, "utf-8") : "";
|
|
194
196
|
const config = loadConfig();
|
|
197
|
+
if (meta.model)
|
|
198
|
+
config.model = meta.model;
|
|
199
|
+
if (meta.provider)
|
|
200
|
+
config.provider = meta.provider;
|
|
195
201
|
const adapter = new PiAdapter(config, projectDir);
|
|
196
202
|
// Backup before any LLM calls, restore on any failure
|
|
197
203
|
await withProjectBackup(projectDir, originalHistory, historyIndexPath, async () => {
|
|
@@ -229,23 +235,23 @@ export async function listProjects() {
|
|
|
229
235
|
let prompt = "";
|
|
230
236
|
let modified = "";
|
|
231
237
|
try {
|
|
232
|
-
const meta = JSON.parse(readFileSync(
|
|
238
|
+
const meta = JSON.parse(readFileSync(guardPath(projectDir, "meta.json"), "utf-8"));
|
|
233
239
|
prompt = meta.input?.prompt ?? "";
|
|
234
240
|
if (prompt.length > 60)
|
|
235
241
|
prompt = prompt.slice(0, 57) + "...";
|
|
236
242
|
}
|
|
237
|
-
catch { /* no meta */ }
|
|
243
|
+
catch { /* no meta or symlink escape */ }
|
|
238
244
|
try {
|
|
239
|
-
const stat = statSync(
|
|
245
|
+
const stat = statSync(guardPath(projectDir, "program.ts"));
|
|
240
246
|
modified = stat.mtime.toISOString().slice(0, 19).replace("T", " ");
|
|
241
247
|
}
|
|
242
|
-
catch { /* no program.ts */ }
|
|
248
|
+
catch { /* no program.ts or symlink escape */ }
|
|
243
249
|
console.log(` ${entry.name} ${prompt} ${modified}`);
|
|
244
250
|
}
|
|
245
251
|
}
|
|
246
252
|
export async function showLogs(name) {
|
|
247
253
|
const projectDir = resolveProject(name);
|
|
248
|
-
const logsPath =
|
|
254
|
+
const logsPath = guardPath(projectDir, join("logs", "latest.jsonl"));
|
|
249
255
|
if (!existsSync(logsPath)) {
|
|
250
256
|
console.log("No logs found.");
|
|
251
257
|
return;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resolve a path within a project directory and verify it does not escape
|
|
3
|
+
* the project boundary — either via ".." segments or symlinks.
|
|
4
|
+
*
|
|
5
|
+
* Not a security sandbox — just a footgun guard against malicious shared
|
|
6
|
+
* projects where files like state.json or .gitignore are symlinks pointing
|
|
7
|
+
* outside the project directory.
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* Resolve `relativePath` against `projectDir` and verify the logical path
|
|
11
|
+
* stays within the project boundary. Returns the resolved absolute path.
|
|
12
|
+
*/
|
|
13
|
+
export declare function resolveBounded(projectDir: string, relativePath: string): string;
|
|
14
|
+
/**
|
|
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.
|
|
33
|
+
*
|
|
34
|
+
* For writes to paths that don't yet exist, checks the nearest existing
|
|
35
|
+
* ancestor to prevent side effects outside the project.
|
|
36
|
+
*/
|
|
37
|
+
export declare function guardPath(projectDir: string, relativePath: string): string;
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { existsSync, realpathSync, lstatSync, readlinkSync } from "fs";
|
|
2
|
+
import { resolve, dirname, sep } from "path";
|
|
3
|
+
/**
|
|
4
|
+
* Resolve a path within a project directory and verify it does not escape
|
|
5
|
+
* the project boundary — either via ".." segments or symlinks.
|
|
6
|
+
*
|
|
7
|
+
* Not a security sandbox — just a footgun guard against malicious shared
|
|
8
|
+
* projects where files like state.json or .gitignore are symlinks pointing
|
|
9
|
+
* outside the project directory.
|
|
10
|
+
*/
|
|
11
|
+
/**
|
|
12
|
+
* Resolve `relativePath` against `projectDir` and verify the logical path
|
|
13
|
+
* stays within the project boundary. Returns the resolved absolute path.
|
|
14
|
+
*/
|
|
15
|
+
export function resolveBounded(projectDir, relativePath) {
|
|
16
|
+
const normalizedDir = resolve(projectDir);
|
|
17
|
+
const resolved = resolve(normalizedDir, relativePath);
|
|
18
|
+
if (resolved !== normalizedDir && !resolved.startsWith(normalizedDir + sep)) {
|
|
19
|
+
throw new Error(`Path escapes project directory: ${relativePath}`);
|
|
20
|
+
}
|
|
21
|
+
return resolved;
|
|
22
|
+
}
|
|
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
|
+
throw new Error(`Path escapes project directory via symlink: ${originalPath}`);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Walk up from `resolved` to find the deepest existing ancestor,
|
|
33
|
+
* then verify its real path is inside the project dir.
|
|
34
|
+
* This catches symlink escapes BEFORE any mkdir side effects.
|
|
35
|
+
*/
|
|
36
|
+
export function verifyNearestAncestor(resolved, realProjectDir, originalPath) {
|
|
37
|
+
let cur = resolved;
|
|
38
|
+
while (!existsSync(cur)) {
|
|
39
|
+
const parent = dirname(cur);
|
|
40
|
+
if (parent === cur)
|
|
41
|
+
return; // reached filesystem root — nothing to verify
|
|
42
|
+
cur = parent;
|
|
43
|
+
}
|
|
44
|
+
verifyRealPath(realpathSync(cur), realProjectDir, originalPath);
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Verify that an existing symlink's target resolves inside the project dir.
|
|
48
|
+
* For dangling symlinks, falls back to verifyNearestAncestor on the link target.
|
|
49
|
+
*/
|
|
50
|
+
export function verifySymlink(target, realProjectDir, originalPath) {
|
|
51
|
+
try {
|
|
52
|
+
verifyRealPath(realpathSync(target), realProjectDir, originalPath);
|
|
53
|
+
}
|
|
54
|
+
catch (e) {
|
|
55
|
+
if (e.code !== "ENOENT")
|
|
56
|
+
throw e;
|
|
57
|
+
// Dangling symlink — resolve what we can via nearest existing ancestor
|
|
58
|
+
const linkDest = resolve(dirname(target), readlinkSync(target));
|
|
59
|
+
verifyNearestAncestor(linkDest, realProjectDir, originalPath);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
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;
|
|
73
|
+
try {
|
|
74
|
+
realDir = realpathSync(normalizedDir);
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
realDir = normalizedDir;
|
|
78
|
+
}
|
|
79
|
+
const resolved = resolveBounded(projectDir, relativePath);
|
|
80
|
+
// Use lstatSync (not existsSync) to detect dangling symlinks.
|
|
81
|
+
// existsSync returns false for dangling symlinks, which would skip the
|
|
82
|
+
// symlink check and allow writes to follow the link to an external target.
|
|
83
|
+
let stat;
|
|
84
|
+
try {
|
|
85
|
+
stat = lstatSync(resolved);
|
|
86
|
+
}
|
|
87
|
+
catch (e) {
|
|
88
|
+
if (e.code !== "ENOENT")
|
|
89
|
+
throw e;
|
|
90
|
+
// Path truly doesn't exist (not even as a dangling symlink)
|
|
91
|
+
// — verify nearest ancestor is inside project
|
|
92
|
+
verifyNearestAncestor(resolved, realDir, relativePath);
|
|
93
|
+
return resolved;
|
|
94
|
+
}
|
|
95
|
+
if (stat.isSymbolicLink()) {
|
|
96
|
+
verifySymlink(resolved, realDir, relativePath);
|
|
97
|
+
}
|
|
98
|
+
else {
|
|
99
|
+
verifyRealPath(realpathSync(resolved), realDir, relativePath);
|
|
100
|
+
}
|
|
101
|
+
return resolved;
|
|
102
|
+
}
|
package/dist/pi-adapter.js
CHANGED
|
@@ -3,8 +3,10 @@ import { getModel } from "@mariozechner/pi-ai";
|
|
|
3
3
|
/** Strip markdown code fences and trim whitespace. */
|
|
4
4
|
export function stripCodeFences(text) {
|
|
5
5
|
const trimmed = text.trim();
|
|
6
|
-
|
|
7
|
-
|
|
6
|
+
// Extract the last fenced code block (LLMs may prepend explanation or emit multiple blocks)
|
|
7
|
+
const matches = [...trimmed.matchAll(/```(?:\w*)\s*\n([\s\S]*?)\n\s*```/g)];
|
|
8
|
+
if (matches.length > 0) {
|
|
9
|
+
return matches[matches.length - 1][1].trim();
|
|
8
10
|
}
|
|
9
11
|
return trimmed;
|
|
10
12
|
}
|
|
@@ -33,10 +35,18 @@ export class PiAdapter {
|
|
|
33
35
|
const raceAbort = (promise) => {
|
|
34
36
|
if (!signal)
|
|
35
37
|
return promise;
|
|
38
|
+
let onAbort = null;
|
|
39
|
+
const cleanup = () => {
|
|
40
|
+
if (onAbort) {
|
|
41
|
+
signal.removeEventListener("abort", onAbort);
|
|
42
|
+
onAbort = null;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
36
45
|
return Promise.race([
|
|
37
|
-
promise,
|
|
46
|
+
promise.finally(cleanup),
|
|
38
47
|
new Promise((_resolve, reject) => {
|
|
39
|
-
|
|
48
|
+
onAbort = () => reject(new Error("Aborted"));
|
|
49
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
40
50
|
}),
|
|
41
51
|
]);
|
|
42
52
|
};
|
package/dist/runner.d.ts
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
import type { RunOptions, TramaConfig } from "./types.js";
|
|
2
2
|
import { PiAdapter } from "./pi-adapter.js";
|
|
3
3
|
export declare const PI_VERSION: string;
|
|
4
|
+
/**
|
|
5
|
+
* Ensure project has ESM package.json and .gitignore.
|
|
6
|
+
* If package.json exists but lacks "type": "module", patches it in.
|
|
7
|
+
*/
|
|
8
|
+
export declare function ensureProjectScaffold(projectDir: string): void;
|
|
4
9
|
/**
|
|
5
10
|
* Simplified API reference for LLM system prompts.
|
|
6
11
|
* NOT the canonical type definitions (those live in types.ts).
|
|
@@ -28,6 +33,7 @@ export declare function withSnapshot<T>(dir: string, fn: () => Promise<{
|
|
|
28
33
|
}>): Promise<T>;
|
|
29
34
|
/** Run fn in a temp directory, clean up afterwards regardless of outcome. */
|
|
30
35
|
export declare function withTempDir<T>(prefix: string, fn: (dir: string) => Promise<T>): Promise<T>;
|
|
36
|
+
export declare function resolveSmokeTimeout(timeout?: number): number;
|
|
31
37
|
export declare function smokeRunAndRepair(projectDir: string, adapter: PiAdapter, reason: "create" | "update", options?: {
|
|
32
38
|
timeout?: number;
|
|
33
39
|
maxRepairAttempts?: number;
|
package/dist/runner.js
CHANGED
|
@@ -9,6 +9,8 @@ import { PiAdapter } from "./pi-adapter.js";
|
|
|
9
9
|
import { createContext } from "./context.js";
|
|
10
10
|
import { createAgent } from "./agent.js";
|
|
11
11
|
import { createTools, cappedBuffer } from "./tools.js";
|
|
12
|
+
import { guardPath } from "./path-guard.js";
|
|
13
|
+
import { assertSerializable } from "./serializable.js";
|
|
12
14
|
// --- Module resolution for child processes ---
|
|
13
15
|
/**
|
|
14
16
|
* Find the node_modules directory that contains @trama-dev/runtime.
|
|
@@ -30,17 +32,19 @@ const TSX_CLI = join(TRAMA_NODE_MODULES, "tsx", "dist", "cli.mjs");
|
|
|
30
32
|
export const PI_VERSION = JSON.parse(readFileSync(join(TRAMA_NODE_MODULES, "@mariozechner", "pi-coding-agent", "package.json"), "utf-8")).version;
|
|
31
33
|
/**
|
|
32
34
|
* Ensure the project directory has a node_modules symlink to @trama-dev/runtime.
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
+
* Replaces any existing symlink whose target differs (including user-managed ones).
|
|
36
|
+
* Only refuses to touch a real directory/file to avoid destroying user content.
|
|
35
37
|
*/
|
|
36
38
|
function ensureRuntimeLink(projectDir) {
|
|
39
|
+
// node_modules/@trama-dev/runtime is deliberately a symlink pointing OUTSIDE
|
|
40
|
+
// the project (to the global trama install). Do not apply guardPath here.
|
|
37
41
|
const linkDir = join(projectDir, "node_modules", "@trama-dev");
|
|
38
42
|
const linkPath = join(linkDir, "runtime");
|
|
39
43
|
const target = join(TRAMA_NODE_MODULES, "@trama-dev", "runtime");
|
|
40
44
|
try {
|
|
41
45
|
const stat = lstatSync(linkPath);
|
|
42
46
|
if (stat.isSymbolicLink()) {
|
|
43
|
-
//
|
|
47
|
+
// Symlink exists — replace if target doesn't match
|
|
44
48
|
if (readlinkSync(linkPath) === target)
|
|
45
49
|
return;
|
|
46
50
|
rmSync(linkPath);
|
|
@@ -64,8 +68,8 @@ function ensureRuntimeLink(projectDir) {
|
|
|
64
68
|
* Ensure project has ESM package.json and .gitignore.
|
|
65
69
|
* If package.json exists but lacks "type": "module", patches it in.
|
|
66
70
|
*/
|
|
67
|
-
function ensureProjectScaffold(projectDir) {
|
|
68
|
-
const pkgPath =
|
|
71
|
+
export function ensureProjectScaffold(projectDir) {
|
|
72
|
+
const pkgPath = guardPath(projectDir, "package.json");
|
|
69
73
|
if (existsSync(pkgPath)) {
|
|
70
74
|
let pkg;
|
|
71
75
|
try {
|
|
@@ -88,7 +92,7 @@ function ensureProjectScaffold(projectDir) {
|
|
|
88
92
|
else {
|
|
89
93
|
writeFileSync(pkgPath, JSON.stringify({ type: "module" }, null, 2));
|
|
90
94
|
}
|
|
91
|
-
const giPath =
|
|
95
|
+
const giPath = guardPath(projectDir, ".gitignore");
|
|
92
96
|
const requiredEntries = ["node_modules/", "state.json", "logs/", "history/"];
|
|
93
97
|
if (existsSync(giPath)) {
|
|
94
98
|
const existing = readFileSync(giPath, "utf-8");
|
|
@@ -199,7 +203,7 @@ export function loadConfig() {
|
|
|
199
203
|
return merged;
|
|
200
204
|
}
|
|
201
205
|
export function loadState(projectDir) {
|
|
202
|
-
const statePath =
|
|
206
|
+
const statePath = guardPath(projectDir, "state.json");
|
|
203
207
|
if (!existsSync(statePath))
|
|
204
208
|
return {};
|
|
205
209
|
const raw = readFileSync(statePath, "utf-8");
|
|
@@ -221,6 +225,21 @@ export function loadState(projectDir) {
|
|
|
221
225
|
}
|
|
222
226
|
// --- IPC Server ---
|
|
223
227
|
const MAX_IPC_BODY = 50 * 1024 * 1024; // 50 MB
|
|
228
|
+
/** Validate required fields in IPC request body. Returns error message or null. */
|
|
229
|
+
function validateIPC(data, fields) {
|
|
230
|
+
for (const [name, type] of Object.entries(fields)) {
|
|
231
|
+
const val = data[name];
|
|
232
|
+
if (type === "object") {
|
|
233
|
+
if (typeof val !== "object" || val === null || Array.isArray(val)) {
|
|
234
|
+
return `Missing or invalid field: ${name} (expected object)`;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
else if (typeof val !== type) {
|
|
238
|
+
return `Missing or invalid field: ${name} (expected ${type})`;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
return null;
|
|
242
|
+
}
|
|
224
243
|
function createIPCServer(ctx, agentImpl, toolsImpl) {
|
|
225
244
|
return createServer((req, res) => {
|
|
226
245
|
if (req.method !== "POST") {
|
|
@@ -249,6 +268,27 @@ function createIPCServer(ctx, agentImpl, toolsImpl) {
|
|
|
249
268
|
try {
|
|
250
269
|
const data = JSON.parse(Buffer.concat(chunks).toString("utf-8"));
|
|
251
270
|
let result;
|
|
271
|
+
// Per-endpoint field validation
|
|
272
|
+
const validationRules = {
|
|
273
|
+
"/agent/ask": { prompt: "string" },
|
|
274
|
+
"/agent/generate": { prompt: "string", schema: "object" },
|
|
275
|
+
"/tools/read": { path: "string" },
|
|
276
|
+
"/tools/write": { path: "string", content: "string" },
|
|
277
|
+
"/tools/shell": { command: "string" },
|
|
278
|
+
"/tools/fetch": { url: "string" },
|
|
279
|
+
"/ctx/checkpoint": { state: "object" },
|
|
280
|
+
"/ctx/log": { message: "string" },
|
|
281
|
+
"/ctx/done": { state: "object" },
|
|
282
|
+
};
|
|
283
|
+
const rules = req.url ? validationRules[req.url] : undefined;
|
|
284
|
+
if (rules) {
|
|
285
|
+
const validationError = validateIPC(data, rules);
|
|
286
|
+
if (validationError) {
|
|
287
|
+
res.writeHead(400);
|
|
288
|
+
res.end(validationError);
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
252
292
|
switch (req.url) {
|
|
253
293
|
case "/agent/ask":
|
|
254
294
|
result = await agentImpl.ask(data.prompt, { system: data.system });
|
|
@@ -283,6 +323,7 @@ function createIPCServer(ctx, agentImpl, toolsImpl) {
|
|
|
283
323
|
res.end(JSON.stringify({ result }));
|
|
284
324
|
break;
|
|
285
325
|
case "/ctx/checkpoint":
|
|
326
|
+
assertSerializable(data.state, "ctx.state");
|
|
286
327
|
ctx.state = data.state;
|
|
287
328
|
await ctx.checkpoint();
|
|
288
329
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
@@ -294,11 +335,17 @@ function createIPCServer(ctx, agentImpl, toolsImpl) {
|
|
|
294
335
|
res.end(JSON.stringify({ result: null }));
|
|
295
336
|
break;
|
|
296
337
|
case "/ctx/ready":
|
|
338
|
+
if (data.data !== undefined && (typeof data.data !== "object" || data.data === null || Array.isArray(data.data))) {
|
|
339
|
+
res.writeHead(400);
|
|
340
|
+
res.end("Invalid field: data (expected object or undefined)");
|
|
341
|
+
break;
|
|
342
|
+
}
|
|
297
343
|
await ctx.ready(data.data);
|
|
298
344
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
299
345
|
res.end(JSON.stringify({ result: null }));
|
|
300
346
|
break;
|
|
301
347
|
case "/ctx/done":
|
|
348
|
+
assertSerializable(data.state, "ctx.state");
|
|
302
349
|
ctx.state = data.state;
|
|
303
350
|
await ctx.done(data.result);
|
|
304
351
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
@@ -366,6 +413,17 @@ function waitForChild(child, options) {
|
|
|
366
413
|
let exited = false;
|
|
367
414
|
let stopRequested = false;
|
|
368
415
|
let killFallbackTimer = null;
|
|
416
|
+
const killChild = (sig) => {
|
|
417
|
+
if (child.pid) {
|
|
418
|
+
try {
|
|
419
|
+
process.kill(-child.pid, sig);
|
|
420
|
+
}
|
|
421
|
+
catch { /* already gone */ }
|
|
422
|
+
}
|
|
423
|
+
else {
|
|
424
|
+
child.kill(sig);
|
|
425
|
+
}
|
|
426
|
+
};
|
|
369
427
|
const scheduleKill = (reason) => {
|
|
370
428
|
if (exited)
|
|
371
429
|
return;
|
|
@@ -378,12 +436,12 @@ function waitForChild(child, options) {
|
|
|
378
436
|
else {
|
|
379
437
|
stopRequested = true;
|
|
380
438
|
}
|
|
381
|
-
|
|
439
|
+
killChild("SIGTERM");
|
|
382
440
|
if (killFallbackTimer)
|
|
383
441
|
clearTimeout(killFallbackTimer);
|
|
384
442
|
killFallbackTimer = setTimeout(() => {
|
|
385
443
|
if (!exited)
|
|
386
|
-
|
|
444
|
+
killChild("SIGKILL");
|
|
387
445
|
}, 5000);
|
|
388
446
|
killFallbackTimer.unref?.();
|
|
389
447
|
};
|
|
@@ -445,18 +503,21 @@ function waitForChild(child, options) {
|
|
|
445
503
|
* Create-time repairs go to index.jsonl only (reason: "create-repair").
|
|
446
504
|
*/
|
|
447
505
|
export function copyToHistory(projectDir, reason, detail) {
|
|
448
|
-
const historyDir =
|
|
506
|
+
const historyDir = guardPath(projectDir, "history");
|
|
449
507
|
const existing = readdirSync(historyDir).filter(f => /^\d+\.ts$/.test(f));
|
|
450
508
|
const nums = existing.map(f => parseInt(f.replace(".ts", ""), 10));
|
|
451
509
|
const nextNum = nums.length > 0 ? nums.reduce((a, b) => Math.max(a, b), 0) + 1 : 1;
|
|
452
510
|
const next = String(nextNum).padStart(Math.max(4, String(nextNum).length), "0");
|
|
453
|
-
|
|
511
|
+
const srcPath = guardPath(projectDir, "program.ts");
|
|
512
|
+
const dstPath = guardPath(projectDir, join("history", `${next}.ts`));
|
|
513
|
+
copyFileSync(srcPath, dstPath);
|
|
454
514
|
const entry = { version: nextNum, reason, timestamp: new Date().toISOString() };
|
|
455
515
|
if (reason === "repair" && detail)
|
|
456
516
|
entry.error = detail;
|
|
457
517
|
if (reason === "update" && detail)
|
|
458
518
|
entry.prompt = detail;
|
|
459
|
-
|
|
519
|
+
const indexPath = guardPath(projectDir, join("history", "index.jsonl"));
|
|
520
|
+
appendFileSync(indexPath, JSON.stringify(entry) + "\n");
|
|
460
521
|
}
|
|
461
522
|
// --- Helpers ---
|
|
462
523
|
/**
|
|
@@ -529,6 +590,9 @@ async function runProgramOnce(options) {
|
|
|
529
590
|
const { signal } = abortController;
|
|
530
591
|
let readyStopScheduled = false;
|
|
531
592
|
let readyStopTimer = null;
|
|
593
|
+
// When set, the grace period is active — child exit should cancel the timer
|
|
594
|
+
// so that the natural exit code flows through instead of being masked by SIGTERM.
|
|
595
|
+
let graceActive = false;
|
|
532
596
|
const ctx = createContext(projectDir, loadState(projectDir), {
|
|
533
597
|
maxIterations,
|
|
534
598
|
argsOverride,
|
|
@@ -536,7 +600,9 @@ async function runProgramOnce(options) {
|
|
|
536
600
|
if (readyStopScheduled)
|
|
537
601
|
return;
|
|
538
602
|
readyStopScheduled = true;
|
|
603
|
+
graceActive = true;
|
|
539
604
|
readyStopTimer = setTimeout(() => {
|
|
605
|
+
graceActive = false;
|
|
540
606
|
stopController.abort();
|
|
541
607
|
}, stopOnReady.graceMs);
|
|
542
608
|
readyStopTimer.unref?.();
|
|
@@ -544,7 +610,7 @@ async function runProgramOnce(options) {
|
|
|
544
610
|
});
|
|
545
611
|
// Truncate logs only after preflight succeeds — preserves prior run's diagnostics
|
|
546
612
|
// if scaffolding, state loading, or context creation fails.
|
|
547
|
-
writeFileSync(
|
|
613
|
+
writeFileSync(guardPath(projectDir, join("logs", "latest.jsonl")), "");
|
|
548
614
|
const agentImpl = createAgent(adapter, signal);
|
|
549
615
|
const toolsImpl = createTools(projectDir, signal);
|
|
550
616
|
const server = createIPCServer(ctx, agentImpl, toolsImpl);
|
|
@@ -573,15 +639,41 @@ async function runProgramOnce(options) {
|
|
|
573
639
|
finally {
|
|
574
640
|
closeSync(fd);
|
|
575
641
|
}
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
642
|
+
let child;
|
|
643
|
+
try {
|
|
644
|
+
child = spawn(process.execPath, [TSX_CLI, guardPath(projectDir, "program.ts")], {
|
|
645
|
+
cwd: projectDir,
|
|
646
|
+
env: {
|
|
647
|
+
...process.env,
|
|
648
|
+
TRAMA_PORT: String(port),
|
|
649
|
+
TRAMA_INIT: initFile,
|
|
650
|
+
},
|
|
651
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
652
|
+
detached: true,
|
|
653
|
+
});
|
|
654
|
+
}
|
|
655
|
+
catch (spawnError) {
|
|
656
|
+
if (readyStopTimer)
|
|
657
|
+
clearTimeout(readyStopTimer);
|
|
658
|
+
await forceCloseServer(server, toolsImpl, abortController);
|
|
659
|
+
try {
|
|
660
|
+
rmSync(initDir, { recursive: true, force: true });
|
|
661
|
+
}
|
|
662
|
+
catch { /* best-effort */ }
|
|
663
|
+
throw spawnError;
|
|
664
|
+
}
|
|
665
|
+
// If the child exits on its own during the grace period (before we send
|
|
666
|
+
// SIGTERM), cancel the grace timer so the real exit code flows through
|
|
667
|
+
// waitForChild instead of being masked by a subsequent SIGTERM.
|
|
668
|
+
if (stopOnReady) {
|
|
669
|
+
child.on("close", () => {
|
|
670
|
+
if (graceActive && readyStopTimer) {
|
|
671
|
+
clearTimeout(readyStopTimer);
|
|
672
|
+
readyStopTimer = null;
|
|
673
|
+
graceActive = false;
|
|
674
|
+
}
|
|
675
|
+
});
|
|
676
|
+
}
|
|
585
677
|
let result;
|
|
586
678
|
try {
|
|
587
679
|
result = await waitForChild(child, {
|
|
@@ -613,11 +705,12 @@ async function runProgramOnce(options) {
|
|
|
613
705
|
// processes would otherwise outlive the runner and leak.
|
|
614
706
|
toolsImpl.killActiveShells();
|
|
615
707
|
if (result.exitCode === 0) {
|
|
708
|
+
abortController.abort(); // cancel any in-flight LLM/fetch requests
|
|
616
709
|
try {
|
|
617
710
|
await closeServer(server);
|
|
618
711
|
}
|
|
619
712
|
catch {
|
|
620
|
-
await forceCloseServer(server, toolsImpl
|
|
713
|
+
await forceCloseServer(server, toolsImpl);
|
|
621
714
|
}
|
|
622
715
|
}
|
|
623
716
|
else {
|
|
@@ -631,8 +724,8 @@ async function runProgramOnce(options) {
|
|
|
631
724
|
const formatError = (r) => `program.ts exited with code ${r.exitCode}\nstdout: ${r.stdout}\nstderr: ${r.stderr}`;
|
|
632
725
|
async function executeProgram(options) {
|
|
633
726
|
const { projectDir, adapter, maxRepairAttempts, timeout, maxIterations } = options;
|
|
634
|
-
mkdirSync(
|
|
635
|
-
mkdirSync(
|
|
727
|
+
mkdirSync(guardPath(projectDir, "history"), { recursive: true });
|
|
728
|
+
mkdirSync(guardPath(projectDir, "logs"), { recursive: true });
|
|
636
729
|
// Phase 1: Run in the real project directory.
|
|
637
730
|
const result = await runProgramOnce({
|
|
638
731
|
projectDir, adapter, timeout, maxIterations,
|
|
@@ -643,12 +736,12 @@ async function executeProgram(options) {
|
|
|
643
736
|
if (result.exitCode === 0)
|
|
644
737
|
return;
|
|
645
738
|
if (maxRepairAttempts === 0) {
|
|
646
|
-
throw new Error(`
|
|
739
|
+
throw new Error(`Program failed (repair disabled): ${formatError(result)}`);
|
|
647
740
|
}
|
|
648
741
|
// Phase 2: Repair loop — both LLM repair call and verification run
|
|
649
742
|
// are fully isolated in temp dirs to prevent side effects on the real project.
|
|
650
743
|
let lastError = formatError(result);
|
|
651
|
-
const originalSource = readFileSync(
|
|
744
|
+
const originalSource = readFileSync(guardPath(projectDir, "program.ts"), "utf-8");
|
|
652
745
|
let currentSource = originalSource;
|
|
653
746
|
const repairErrors = [];
|
|
654
747
|
const repairDetails = () => repairErrors.length > 0
|
|
@@ -660,7 +753,7 @@ async function executeProgram(options) {
|
|
|
660
753
|
const fixed = await repairWithTimeout(tempAdapter, { programSource: currentSource, error: lastError, runtimeTypes: RUNTIME_TYPES }, timeout, repairErrors);
|
|
661
754
|
if (!fixed)
|
|
662
755
|
return null;
|
|
663
|
-
writeFileSync(
|
|
756
|
+
writeFileSync(guardPath(tempDir, "program.ts"), fixed);
|
|
664
757
|
const verifyResult = await runProgramOnce({
|
|
665
758
|
projectDir: tempDir, adapter: tempAdapter, timeout, maxIterations,
|
|
666
759
|
argsOverride: options.argsOverride,
|
|
@@ -676,7 +769,7 @@ async function executeProgram(options) {
|
|
|
676
769
|
// Repair verified in isolation — now run in the real project for actual output.
|
|
677
770
|
// Snapshot first so we can restore cleanly if the real run fails.
|
|
678
771
|
const realResult = await withSnapshot(projectDir, async () => {
|
|
679
|
-
writeFileSync(
|
|
772
|
+
writeFileSync(guardPath(projectDir, "program.ts"), repairResult.fixed);
|
|
680
773
|
const r = await runProgramOnce({
|
|
681
774
|
projectDir, adapter, timeout, maxIterations,
|
|
682
775
|
argsOverride: options.argsOverride,
|
|
@@ -710,8 +803,8 @@ async function executeProgram(options) {
|
|
|
710
803
|
// --- Smoke run (used by create and update) ---
|
|
711
804
|
/** Copy new history entries from src to dst (appends only entries added after the shared prefix). */
|
|
712
805
|
function propagateHistoryEntries(srcDir, dstDir) {
|
|
713
|
-
const srcPath =
|
|
714
|
-
const dstPath =
|
|
806
|
+
const srcPath = guardPath(srcDir, join("history", "index.jsonl"));
|
|
807
|
+
const dstPath = guardPath(dstDir, join("history", "index.jsonl"));
|
|
715
808
|
if (!existsSync(srcPath))
|
|
716
809
|
return;
|
|
717
810
|
const srcHistory = readFileSync(srcPath, "utf-8");
|
|
@@ -720,16 +813,17 @@ function propagateHistoryEntries(srcDir, dstDir) {
|
|
|
720
813
|
return; // History diverged — cannot safely propagate
|
|
721
814
|
const newEntries = srcHistory.slice(dstHistory.length);
|
|
722
815
|
if (newEntries.length > 0) {
|
|
723
|
-
mkdirSync(
|
|
816
|
+
mkdirSync(guardPath(dstDir, "history"), { recursive: true });
|
|
724
817
|
appendFileSync(dstPath, newEntries);
|
|
725
818
|
}
|
|
726
819
|
}
|
|
727
820
|
const DEFAULT_SMOKE_TIMEOUT = 30_000;
|
|
728
|
-
const
|
|
729
|
-
|
|
821
|
+
const SMOKE_READY_GRACE_MS = 2_000;
|
|
822
|
+
export function resolveSmokeTimeout(timeout) {
|
|
823
|
+
return timeout ?? DEFAULT_SMOKE_TIMEOUT;
|
|
824
|
+
}
|
|
730
825
|
export async function smokeRunAndRepair(projectDir, adapter, reason, options) {
|
|
731
|
-
const
|
|
732
|
-
const smokeTimeout = Math.min(requestedTimeout, MAX_SMOKE_TIMEOUT);
|
|
826
|
+
const smokeTimeout = resolveSmokeTimeout(options?.timeout);
|
|
733
827
|
// Run validation in a temp copy so side effects don't persist in the real project
|
|
734
828
|
await withTempDir("trama-smoke-", async (smokeDir) => {
|
|
735
829
|
cpSync(projectDir, smokeDir, { recursive: true });
|
|
@@ -745,11 +839,11 @@ export async function smokeRunAndRepair(projectDir, adapter, reason, options) {
|
|
|
745
839
|
graceMs: SMOKE_READY_GRACE_MS,
|
|
746
840
|
},
|
|
747
841
|
onRepair(_attempt, _max, error) {
|
|
748
|
-
appendFileSync(
|
|
842
|
+
appendFileSync(guardPath(smokeDir, join("history", "index.jsonl")), JSON.stringify({ reason: `${reason}-repair`, timestamp: new Date().toISOString(), error }) + "\n");
|
|
749
843
|
},
|
|
750
844
|
});
|
|
751
845
|
// Smoke passed — copy back program.ts (may have been repaired)
|
|
752
|
-
copyFileSync(
|
|
846
|
+
copyFileSync(guardPath(smokeDir, "program.ts"), guardPath(projectDir, "program.ts"));
|
|
753
847
|
}
|
|
754
848
|
finally {
|
|
755
849
|
// Always propagate repair history, whether smoke passed or failed
|
|
@@ -765,6 +859,13 @@ export async function runProgram(options) {
|
|
|
765
859
|
`Run \`trama list\` to see available projects.`);
|
|
766
860
|
}
|
|
767
861
|
const config = loadConfig();
|
|
862
|
+
// Use per-project model/provider if saved, else fall back to global config
|
|
863
|
+
const metaPath = guardPath(projectDir, "meta.json");
|
|
864
|
+
const meta = JSON.parse(readFileSync(metaPath, "utf-8"));
|
|
865
|
+
if (meta.model)
|
|
866
|
+
config.model = meta.model;
|
|
867
|
+
if (meta.provider)
|
|
868
|
+
config.provider = meta.provider;
|
|
768
869
|
const maxRepairAttempts = options.maxRepairAttempts ?? config.maxRepairAttempts;
|
|
769
870
|
const timeout = options.timeout ?? config.defaultTimeout;
|
|
770
871
|
const maxIterations = config.defaultMaxIterations;
|
|
@@ -784,7 +885,7 @@ export async function runProgram(options) {
|
|
|
784
885
|
argsOverride: options.args,
|
|
785
886
|
onRepair(attempt, max, error) {
|
|
786
887
|
// Log repair attempts (appends to already-open logs file)
|
|
787
|
-
const logsPath =
|
|
888
|
+
const logsPath = guardPath(projectDir, join("logs", "latest.jsonl"));
|
|
788
889
|
const entry = { ts: Date.now(), message: `Repair attempt ${attempt + 1}/${max}`, data: { error } };
|
|
789
890
|
appendFileSync(logsPath, JSON.stringify(entry) + "\n");
|
|
790
891
|
console.log(`[trama] Repair attempt ${attempt + 1}/${max}`);
|
package/dist/serializable.js
CHANGED
|
@@ -29,7 +29,8 @@ export function assertSerializable(value, path, ancestors = new Set()) {
|
|
|
29
29
|
ancestors.delete(value);
|
|
30
30
|
return;
|
|
31
31
|
}
|
|
32
|
-
|
|
32
|
+
const proto = Object.getPrototypeOf(value);
|
|
33
|
+
if (proto !== Object.prototype && proto !== null) {
|
|
33
34
|
const name = value.constructor?.name ?? "unknown";
|
|
34
35
|
throw new TypeError(`${path} is not a plain object (${name})`);
|
|
35
36
|
}
|
package/dist/tools.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { spawn } from "child_process";
|
|
2
|
-
import { readFileSync, writeFileSync, mkdirSync, realpathSync,
|
|
3
|
-
import { resolve, dirname
|
|
2
|
+
import { readFileSync, writeFileSync, mkdirSync, realpathSync, lstatSync } from "fs";
|
|
3
|
+
import { resolve, dirname } from "path";
|
|
4
4
|
import { StringDecoder } from "string_decoder";
|
|
5
|
+
import { resolveBounded, verifyRealPath, verifyNearestAncestor, verifySymlink } from "./path-guard.js";
|
|
5
6
|
const MAX_OUTPUT = 10 * 1024 * 1024; // 10 MB
|
|
6
7
|
export function cappedBuffer() {
|
|
7
8
|
let buf = "";
|
|
@@ -64,39 +65,9 @@ export function createTools(projectDir, signal) {
|
|
|
64
65
|
timer.unref?.();
|
|
65
66
|
sessionReapers.set(sessionId, timer);
|
|
66
67
|
};
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
* Not a security sandbox — just a footgun guard.
|
|
71
|
-
*/
|
|
72
|
-
const resolvePath = (p) => {
|
|
73
|
-
const resolved = resolve(normalizedProjectDir, p);
|
|
74
|
-
if (resolved !== normalizedProjectDir && !resolved.startsWith(normalizedProjectDir + sep)) {
|
|
75
|
-
throw new Error(`Path escapes project directory: ${p}`);
|
|
76
|
-
}
|
|
77
|
-
return resolved;
|
|
78
|
-
};
|
|
79
|
-
/** Verify that an existing path's real location is inside the project dir. */
|
|
80
|
-
const verifyRealPath = (real, original) => {
|
|
81
|
-
if (real !== realProjectDir && !real.startsWith(realProjectDir + sep)) {
|
|
82
|
-
throw new Error(`Path escapes project directory via symlink: ${original}`);
|
|
83
|
-
}
|
|
84
|
-
};
|
|
85
|
-
/**
|
|
86
|
-
* Walk up from `resolved` to find the deepest existing ancestor,
|
|
87
|
-
* then verify its real path is inside the project dir.
|
|
88
|
-
* This catches symlink escapes BEFORE any mkdir side effects.
|
|
89
|
-
*/
|
|
90
|
-
const verifyNearestAncestor = (resolved, original) => {
|
|
91
|
-
let cur = resolved;
|
|
92
|
-
while (!existsSync(cur)) {
|
|
93
|
-
const parent = dirname(cur);
|
|
94
|
-
if (parent === cur)
|
|
95
|
-
return; // reached filesystem root — nothing to verify
|
|
96
|
-
cur = parent;
|
|
97
|
-
}
|
|
98
|
-
verifyRealPath(realpathSync(cur), original);
|
|
99
|
-
};
|
|
68
|
+
const resolvePath = (p) => resolveBounded(normalizedProjectDir, p);
|
|
69
|
+
const checkRealPath = (real, original) => verifyRealPath(real, realProjectDir, original);
|
|
70
|
+
const checkNearestAncestor = (resolved, original) => verifyNearestAncestor(resolved, realProjectDir, original);
|
|
100
71
|
return {
|
|
101
72
|
killActiveShells() {
|
|
102
73
|
for (const proc of activeShells) {
|
|
@@ -116,24 +87,26 @@ export function createTools(projectDir, signal) {
|
|
|
116
87
|
},
|
|
117
88
|
async read(path) {
|
|
118
89
|
const target = resolvePath(path);
|
|
119
|
-
|
|
90
|
+
let real;
|
|
91
|
+
try {
|
|
92
|
+
real = realpathSync(target);
|
|
93
|
+
}
|
|
94
|
+
catch (e) {
|
|
95
|
+
if (e.code === "ENOENT") {
|
|
96
|
+
throw new Error(`File not found: ${path}`);
|
|
97
|
+
}
|
|
98
|
+
throw e;
|
|
99
|
+
}
|
|
100
|
+
checkRealPath(real, path);
|
|
120
101
|
return readFileSync(target, "utf-8");
|
|
121
102
|
},
|
|
122
103
|
async write(path, content) {
|
|
123
104
|
const target = resolvePath(path);
|
|
124
|
-
|
|
105
|
+
checkNearestAncestor(target, path); // before mkdir — prevents side effects outside project
|
|
125
106
|
mkdirSync(dirname(target), { recursive: true });
|
|
126
107
|
try {
|
|
127
108
|
if (lstatSync(target).isSymbolicLink()) {
|
|
128
|
-
|
|
129
|
-
verifyRealPath(realpathSync(target), path);
|
|
130
|
-
}
|
|
131
|
-
catch (e) {
|
|
132
|
-
if (e.code !== "ENOENT")
|
|
133
|
-
throw e;
|
|
134
|
-
// Dangling symlink — resolve what we can via nearest existing ancestor
|
|
135
|
-
verifyNearestAncestor(resolve(dirname(target), readlinkSync(target)), path);
|
|
136
|
-
}
|
|
109
|
+
verifySymlink(target, realProjectDir, path);
|
|
137
110
|
}
|
|
138
111
|
}
|
|
139
112
|
catch (e) {
|
|
@@ -147,7 +120,7 @@ export function createTools(projectDir, signal) {
|
|
|
147
120
|
const cwd = options.cwd ? resolvePath(options.cwd) : normalizedProjectDir;
|
|
148
121
|
try {
|
|
149
122
|
if (options.cwd)
|
|
150
|
-
|
|
123
|
+
checkRealPath(realpathSync(cwd), options.cwd);
|
|
151
124
|
}
|
|
152
125
|
catch (err) {
|
|
153
126
|
if (err.code !== "ENOENT")
|
package/dist/types.d.ts
CHANGED
|
@@ -22,6 +22,7 @@ export interface Ctx {
|
|
|
22
22
|
/**
|
|
23
23
|
* Signal that a long-running program has finished startup and is now serving.
|
|
24
24
|
* Used by smoke validation to distinguish "started successfully" from "completed".
|
|
25
|
+
* This marks startup success only; it is not a guarantee about long-term health.
|
|
25
26
|
* Idempotent: second call is a no-op.
|
|
26
27
|
*/
|
|
27
28
|
ready(data?: Record<string, unknown>): Promise<void>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trama-dev/runtime",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"exports": {
|
|
6
6
|
".": {
|
|
@@ -32,6 +32,7 @@
|
|
|
32
32
|
"README.md",
|
|
33
33
|
"LICENSE"
|
|
34
34
|
],
|
|
35
|
+
"os": ["darwin", "linux"],
|
|
35
36
|
"dependencies": {
|
|
36
37
|
"@mariozechner/pi-coding-agent": "0.64.0",
|
|
37
38
|
"@mariozechner/pi-ai": "0.64.0",
|