@trama-dev/runtime 0.1.2 → 0.1.4
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 +26 -7
- package/dist/agent.js +3 -3
- package/dist/client.js +39 -12
- package/dist/context.js +35 -16
- package/dist/index.js +23 -17
- 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 +7 -1
- package/dist/runner.js +142 -39
- package/dist/serializable.js +2 -1
- package/dist/tools.js +20 -47
- package/dist/types.d.ts +8 -2
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -1,24 +1,43 @@
|
|
|
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";
|
|
11
13
|
|
|
12
14
|
const data = await tools.read("input.csv");
|
|
13
|
-
const report = await agent.
|
|
15
|
+
const report = await agent.instruct(`Analyze this:\n${data}`);
|
|
14
16
|
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/agent.js
CHANGED
|
@@ -21,10 +21,10 @@ function validateShape(result, schema) {
|
|
|
21
21
|
return null;
|
|
22
22
|
}
|
|
23
23
|
export function createAgent(adapter, signal) {
|
|
24
|
+
const instructImpl = async (prompt, options) => adapter.ask(prompt, signal ? { ...options, signal } : options);
|
|
24
25
|
return {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
},
|
|
26
|
+
instruct: instructImpl,
|
|
27
|
+
ask: instructImpl,
|
|
28
28
|
async generate(input) {
|
|
29
29
|
const schemaInstruction = `Respond with ONLY a JSON object matching this shape:\n${JSON.stringify(input.schema, null, 2)}\nNo markdown. No explanation. Just the JSON.`;
|
|
30
30
|
const fullPrompt = `${input.prompt}\n\n${schemaInstruction}`;
|
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,18 +60,31 @@ 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
|
};
|
|
84
|
+
const instructImpl = (prompt, opts) => call("/agent/ask", { prompt, ...opts }).then(r => r.result);
|
|
59
85
|
export const agent = {
|
|
60
|
-
|
|
86
|
+
instruct: instructImpl,
|
|
87
|
+
ask: instructImpl,
|
|
61
88
|
generate: (input) => call("/agent/generate", input).then(r => r.result),
|
|
62
89
|
};
|
|
63
90
|
export const tools = {
|
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.
|
|
@@ -18,7 +19,7 @@ await ctx.done();
|
|
|
18
19
|
import { ctx, agent, tools } from "@trama-dev/runtime";
|
|
19
20
|
|
|
20
21
|
const data = await tools.read(ctx.input.args.file as string);
|
|
21
|
-
const summary = await agent.
|
|
22
|
+
const summary = await agent.instruct("Summarize this data concisely:\\n" + data);
|
|
22
23
|
await tools.write("summary.md", summary);
|
|
23
24
|
await ctx.done({ summaryLength: summary.length });
|
|
24
25
|
|
|
@@ -108,7 +109,7 @@ export function resolveProject(name) {
|
|
|
108
109
|
return dir;
|
|
109
110
|
}
|
|
110
111
|
// --- Helpers ---
|
|
111
|
-
/** Run an LLM
|
|
112
|
+
/** Run an LLM instruction in an isolated temp cwd so pi-coding-agent tools can't write into the real project. */
|
|
112
113
|
async function isolatedAsk(adapter, prompt, options) {
|
|
113
114
|
return withTempDir("trama-gen-", (dir) => adapter.withCwd(dir).ask(prompt, options));
|
|
114
115
|
}
|
|
@@ -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).
|
|
@@ -8,7 +13,7 @@ export declare const PI_VERSION: string;
|
|
|
8
13
|
* needs a concise reference, not the full implementation types.
|
|
9
14
|
* If types.ts changes, review whether this summary needs updating.
|
|
10
15
|
*/
|
|
11
|
-
export declare const RUNTIME_TYPES = "// @trama-dev/runtime - Complete API\n\nexport interface Ctx {\n input: { prompt: string; args: Record<string, unknown> };\n state: Record<string, unknown>;\n iteration: number;\n maxIterations: number;\n log(message: string, data?: Record<string, unknown>): Promise<void>;\n ready(data?: Record<string, unknown>): Promise<void>;\n checkpoint(): Promise<void>;\n done(result?: Record<string, unknown>): Promise<void>;\n}\n\nexport interface Agent {\n ask(prompt: string, options?: { system?: string }): Promise<string>;\n generate<T>(input: {\n prompt: string;\n schema: Record<string, string>;\n system?: string;\n }): Promise<T>;\n}\n\nexport interface ShellResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nexport interface Tools {\n read(path: string): Promise<string>;\n write(path: string, content: string): Promise<void>;\n shell(command: string, options?: { cwd?: string; timeout?: number }): Promise<ShellResult>;\n fetch(url: string, options?: {\n method?: string;\n headers?: Record<string, string>;\n body?: string;\n }): Promise<{ status: number; body: string; headers: Record<string, string> }>;\n}\n\nexport declare const ctx: Ctx;\nexport declare const agent: Agent;\nexport declare const tools: Tools;";
|
|
16
|
+
export declare const RUNTIME_TYPES = "// @trama-dev/runtime - Complete API\n\nexport interface Ctx {\n input: { prompt: string; args: Record<string, unknown> };\n state: Record<string, unknown>;\n iteration: number;\n maxIterations: number;\n log(message: string, data?: Record<string, unknown>): Promise<void>;\n ready(data?: Record<string, unknown>): Promise<void>;\n checkpoint(): Promise<void>;\n done(result?: Record<string, unknown>): Promise<void>;\n}\n\nexport interface Agent {\n instruct(prompt: string, options?: { system?: string }): Promise<string>;\n /** @deprecated Use instruct() instead */\n ask(prompt: string, options?: { system?: string }): Promise<string>;\n generate<T>(input: {\n prompt: string;\n schema: Record<string, string>;\n system?: string;\n }): Promise<T>;\n}\n\nexport interface ShellResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nexport interface Tools {\n read(path: string): Promise<string>;\n write(path: string, content: string): Promise<void>;\n shell(command: string, options?: { cwd?: string; timeout?: number }): Promise<ShellResult>;\n fetch(url: string, options?: {\n method?: string;\n headers?: Record<string, string>;\n body?: string;\n }): Promise<{ status: number; body: string; headers: Record<string, string> }>;\n}\n\nexport declare const ctx: Ctx;\nexport declare const agent: Agent;\nexport declare const tools: Tools;";
|
|
12
17
|
export declare function loadConfig(): TramaConfig;
|
|
13
18
|
export declare function loadState(projectDir: string): Record<string, unknown>;
|
|
14
19
|
/**
|
|
@@ -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");
|
|
@@ -124,6 +128,8 @@ export interface Ctx {
|
|
|
124
128
|
}
|
|
125
129
|
|
|
126
130
|
export interface Agent {
|
|
131
|
+
instruct(prompt: string, options?: { system?: string }): Promise<string>;
|
|
132
|
+
/** @deprecated Use instruct() instead */
|
|
127
133
|
ask(prompt: string, options?: { system?: string }): Promise<string>;
|
|
128
134
|
generate<T>(input: {
|
|
129
135
|
prompt: string;
|
|
@@ -199,7 +205,7 @@ export function loadConfig() {
|
|
|
199
205
|
return merged;
|
|
200
206
|
}
|
|
201
207
|
export function loadState(projectDir) {
|
|
202
|
-
const statePath =
|
|
208
|
+
const statePath = guardPath(projectDir, "state.json");
|
|
203
209
|
if (!existsSync(statePath))
|
|
204
210
|
return {};
|
|
205
211
|
const raw = readFileSync(statePath, "utf-8");
|
|
@@ -221,6 +227,21 @@ export function loadState(projectDir) {
|
|
|
221
227
|
}
|
|
222
228
|
// --- IPC Server ---
|
|
223
229
|
const MAX_IPC_BODY = 50 * 1024 * 1024; // 50 MB
|
|
230
|
+
/** Validate required fields in IPC request body. Returns error message or null. */
|
|
231
|
+
function validateIPC(data, fields) {
|
|
232
|
+
for (const [name, type] of Object.entries(fields)) {
|
|
233
|
+
const val = data[name];
|
|
234
|
+
if (type === "object") {
|
|
235
|
+
if (typeof val !== "object" || val === null || Array.isArray(val)) {
|
|
236
|
+
return `Missing or invalid field: ${name} (expected object)`;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
else if (typeof val !== type) {
|
|
240
|
+
return `Missing or invalid field: ${name} (expected ${type})`;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
return null;
|
|
244
|
+
}
|
|
224
245
|
function createIPCServer(ctx, agentImpl, toolsImpl) {
|
|
225
246
|
return createServer((req, res) => {
|
|
226
247
|
if (req.method !== "POST") {
|
|
@@ -249,6 +270,27 @@ function createIPCServer(ctx, agentImpl, toolsImpl) {
|
|
|
249
270
|
try {
|
|
250
271
|
const data = JSON.parse(Buffer.concat(chunks).toString("utf-8"));
|
|
251
272
|
let result;
|
|
273
|
+
// Per-endpoint field validation
|
|
274
|
+
const validationRules = {
|
|
275
|
+
"/agent/ask": { prompt: "string" },
|
|
276
|
+
"/agent/generate": { prompt: "string", schema: "object" },
|
|
277
|
+
"/tools/read": { path: "string" },
|
|
278
|
+
"/tools/write": { path: "string", content: "string" },
|
|
279
|
+
"/tools/shell": { command: "string" },
|
|
280
|
+
"/tools/fetch": { url: "string" },
|
|
281
|
+
"/ctx/checkpoint": { state: "object" },
|
|
282
|
+
"/ctx/log": { message: "string" },
|
|
283
|
+
"/ctx/done": { state: "object" },
|
|
284
|
+
};
|
|
285
|
+
const rules = req.url ? validationRules[req.url] : undefined;
|
|
286
|
+
if (rules) {
|
|
287
|
+
const validationError = validateIPC(data, rules);
|
|
288
|
+
if (validationError) {
|
|
289
|
+
res.writeHead(400);
|
|
290
|
+
res.end(validationError);
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
252
294
|
switch (req.url) {
|
|
253
295
|
case "/agent/ask":
|
|
254
296
|
result = await agentImpl.ask(data.prompt, { system: data.system });
|
|
@@ -283,6 +325,7 @@ function createIPCServer(ctx, agentImpl, toolsImpl) {
|
|
|
283
325
|
res.end(JSON.stringify({ result }));
|
|
284
326
|
break;
|
|
285
327
|
case "/ctx/checkpoint":
|
|
328
|
+
assertSerializable(data.state, "ctx.state");
|
|
286
329
|
ctx.state = data.state;
|
|
287
330
|
await ctx.checkpoint();
|
|
288
331
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
@@ -294,11 +337,17 @@ function createIPCServer(ctx, agentImpl, toolsImpl) {
|
|
|
294
337
|
res.end(JSON.stringify({ result: null }));
|
|
295
338
|
break;
|
|
296
339
|
case "/ctx/ready":
|
|
340
|
+
if (data.data !== undefined && (typeof data.data !== "object" || data.data === null || Array.isArray(data.data))) {
|
|
341
|
+
res.writeHead(400);
|
|
342
|
+
res.end("Invalid field: data (expected object or undefined)");
|
|
343
|
+
break;
|
|
344
|
+
}
|
|
297
345
|
await ctx.ready(data.data);
|
|
298
346
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
299
347
|
res.end(JSON.stringify({ result: null }));
|
|
300
348
|
break;
|
|
301
349
|
case "/ctx/done":
|
|
350
|
+
assertSerializable(data.state, "ctx.state");
|
|
302
351
|
ctx.state = data.state;
|
|
303
352
|
await ctx.done(data.result);
|
|
304
353
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
@@ -366,6 +415,17 @@ function waitForChild(child, options) {
|
|
|
366
415
|
let exited = false;
|
|
367
416
|
let stopRequested = false;
|
|
368
417
|
let killFallbackTimer = null;
|
|
418
|
+
const killChild = (sig) => {
|
|
419
|
+
if (child.pid) {
|
|
420
|
+
try {
|
|
421
|
+
process.kill(-child.pid, sig);
|
|
422
|
+
}
|
|
423
|
+
catch { /* already gone */ }
|
|
424
|
+
}
|
|
425
|
+
else {
|
|
426
|
+
child.kill(sig);
|
|
427
|
+
}
|
|
428
|
+
};
|
|
369
429
|
const scheduleKill = (reason) => {
|
|
370
430
|
if (exited)
|
|
371
431
|
return;
|
|
@@ -378,12 +438,12 @@ function waitForChild(child, options) {
|
|
|
378
438
|
else {
|
|
379
439
|
stopRequested = true;
|
|
380
440
|
}
|
|
381
|
-
|
|
441
|
+
killChild("SIGTERM");
|
|
382
442
|
if (killFallbackTimer)
|
|
383
443
|
clearTimeout(killFallbackTimer);
|
|
384
444
|
killFallbackTimer = setTimeout(() => {
|
|
385
445
|
if (!exited)
|
|
386
|
-
|
|
446
|
+
killChild("SIGKILL");
|
|
387
447
|
}, 5000);
|
|
388
448
|
killFallbackTimer.unref?.();
|
|
389
449
|
};
|
|
@@ -445,18 +505,21 @@ function waitForChild(child, options) {
|
|
|
445
505
|
* Create-time repairs go to index.jsonl only (reason: "create-repair").
|
|
446
506
|
*/
|
|
447
507
|
export function copyToHistory(projectDir, reason, detail) {
|
|
448
|
-
const historyDir =
|
|
508
|
+
const historyDir = guardPath(projectDir, "history");
|
|
449
509
|
const existing = readdirSync(historyDir).filter(f => /^\d+\.ts$/.test(f));
|
|
450
510
|
const nums = existing.map(f => parseInt(f.replace(".ts", ""), 10));
|
|
451
511
|
const nextNum = nums.length > 0 ? nums.reduce((a, b) => Math.max(a, b), 0) + 1 : 1;
|
|
452
512
|
const next = String(nextNum).padStart(Math.max(4, String(nextNum).length), "0");
|
|
453
|
-
|
|
513
|
+
const srcPath = guardPath(projectDir, "program.ts");
|
|
514
|
+
const dstPath = guardPath(projectDir, join("history", `${next}.ts`));
|
|
515
|
+
copyFileSync(srcPath, dstPath);
|
|
454
516
|
const entry = { version: nextNum, reason, timestamp: new Date().toISOString() };
|
|
455
517
|
if (reason === "repair" && detail)
|
|
456
518
|
entry.error = detail;
|
|
457
519
|
if (reason === "update" && detail)
|
|
458
520
|
entry.prompt = detail;
|
|
459
|
-
|
|
521
|
+
const indexPath = guardPath(projectDir, join("history", "index.jsonl"));
|
|
522
|
+
appendFileSync(indexPath, JSON.stringify(entry) + "\n");
|
|
460
523
|
}
|
|
461
524
|
// --- Helpers ---
|
|
462
525
|
/**
|
|
@@ -529,6 +592,9 @@ async function runProgramOnce(options) {
|
|
|
529
592
|
const { signal } = abortController;
|
|
530
593
|
let readyStopScheduled = false;
|
|
531
594
|
let readyStopTimer = null;
|
|
595
|
+
// When set, the grace period is active — child exit should cancel the timer
|
|
596
|
+
// so that the natural exit code flows through instead of being masked by SIGTERM.
|
|
597
|
+
let graceActive = false;
|
|
532
598
|
const ctx = createContext(projectDir, loadState(projectDir), {
|
|
533
599
|
maxIterations,
|
|
534
600
|
argsOverride,
|
|
@@ -536,7 +602,9 @@ async function runProgramOnce(options) {
|
|
|
536
602
|
if (readyStopScheduled)
|
|
537
603
|
return;
|
|
538
604
|
readyStopScheduled = true;
|
|
605
|
+
graceActive = true;
|
|
539
606
|
readyStopTimer = setTimeout(() => {
|
|
607
|
+
graceActive = false;
|
|
540
608
|
stopController.abort();
|
|
541
609
|
}, stopOnReady.graceMs);
|
|
542
610
|
readyStopTimer.unref?.();
|
|
@@ -544,7 +612,7 @@ async function runProgramOnce(options) {
|
|
|
544
612
|
});
|
|
545
613
|
// Truncate logs only after preflight succeeds — preserves prior run's diagnostics
|
|
546
614
|
// if scaffolding, state loading, or context creation fails.
|
|
547
|
-
writeFileSync(
|
|
615
|
+
writeFileSync(guardPath(projectDir, join("logs", "latest.jsonl")), "");
|
|
548
616
|
const agentImpl = createAgent(adapter, signal);
|
|
549
617
|
const toolsImpl = createTools(projectDir, signal);
|
|
550
618
|
const server = createIPCServer(ctx, agentImpl, toolsImpl);
|
|
@@ -573,15 +641,41 @@ async function runProgramOnce(options) {
|
|
|
573
641
|
finally {
|
|
574
642
|
closeSync(fd);
|
|
575
643
|
}
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
644
|
+
let child;
|
|
645
|
+
try {
|
|
646
|
+
child = spawn(process.execPath, [TSX_CLI, guardPath(projectDir, "program.ts")], {
|
|
647
|
+
cwd: projectDir,
|
|
648
|
+
env: {
|
|
649
|
+
...process.env,
|
|
650
|
+
TRAMA_PORT: String(port),
|
|
651
|
+
TRAMA_INIT: initFile,
|
|
652
|
+
},
|
|
653
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
654
|
+
detached: true,
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
catch (spawnError) {
|
|
658
|
+
if (readyStopTimer)
|
|
659
|
+
clearTimeout(readyStopTimer);
|
|
660
|
+
await forceCloseServer(server, toolsImpl, abortController);
|
|
661
|
+
try {
|
|
662
|
+
rmSync(initDir, { recursive: true, force: true });
|
|
663
|
+
}
|
|
664
|
+
catch { /* best-effort */ }
|
|
665
|
+
throw spawnError;
|
|
666
|
+
}
|
|
667
|
+
// If the child exits on its own during the grace period (before we send
|
|
668
|
+
// SIGTERM), cancel the grace timer so the real exit code flows through
|
|
669
|
+
// waitForChild instead of being masked by a subsequent SIGTERM.
|
|
670
|
+
if (stopOnReady) {
|
|
671
|
+
child.on("close", () => {
|
|
672
|
+
if (graceActive && readyStopTimer) {
|
|
673
|
+
clearTimeout(readyStopTimer);
|
|
674
|
+
readyStopTimer = null;
|
|
675
|
+
graceActive = false;
|
|
676
|
+
}
|
|
677
|
+
});
|
|
678
|
+
}
|
|
585
679
|
let result;
|
|
586
680
|
try {
|
|
587
681
|
result = await waitForChild(child, {
|
|
@@ -613,11 +707,12 @@ async function runProgramOnce(options) {
|
|
|
613
707
|
// processes would otherwise outlive the runner and leak.
|
|
614
708
|
toolsImpl.killActiveShells();
|
|
615
709
|
if (result.exitCode === 0) {
|
|
710
|
+
abortController.abort(); // cancel any in-flight LLM/fetch requests
|
|
616
711
|
try {
|
|
617
712
|
await closeServer(server);
|
|
618
713
|
}
|
|
619
714
|
catch {
|
|
620
|
-
await forceCloseServer(server, toolsImpl
|
|
715
|
+
await forceCloseServer(server, toolsImpl);
|
|
621
716
|
}
|
|
622
717
|
}
|
|
623
718
|
else {
|
|
@@ -631,8 +726,8 @@ async function runProgramOnce(options) {
|
|
|
631
726
|
const formatError = (r) => `program.ts exited with code ${r.exitCode}\nstdout: ${r.stdout}\nstderr: ${r.stderr}`;
|
|
632
727
|
async function executeProgram(options) {
|
|
633
728
|
const { projectDir, adapter, maxRepairAttempts, timeout, maxIterations } = options;
|
|
634
|
-
mkdirSync(
|
|
635
|
-
mkdirSync(
|
|
729
|
+
mkdirSync(guardPath(projectDir, "history"), { recursive: true });
|
|
730
|
+
mkdirSync(guardPath(projectDir, "logs"), { recursive: true });
|
|
636
731
|
// Phase 1: Run in the real project directory.
|
|
637
732
|
const result = await runProgramOnce({
|
|
638
733
|
projectDir, adapter, timeout, maxIterations,
|
|
@@ -643,12 +738,12 @@ async function executeProgram(options) {
|
|
|
643
738
|
if (result.exitCode === 0)
|
|
644
739
|
return;
|
|
645
740
|
if (maxRepairAttempts === 0) {
|
|
646
|
-
throw new Error(`
|
|
741
|
+
throw new Error(`Program failed (repair disabled): ${formatError(result)}`);
|
|
647
742
|
}
|
|
648
743
|
// Phase 2: Repair loop — both LLM repair call and verification run
|
|
649
744
|
// are fully isolated in temp dirs to prevent side effects on the real project.
|
|
650
745
|
let lastError = formatError(result);
|
|
651
|
-
const originalSource = readFileSync(
|
|
746
|
+
const originalSource = readFileSync(guardPath(projectDir, "program.ts"), "utf-8");
|
|
652
747
|
let currentSource = originalSource;
|
|
653
748
|
const repairErrors = [];
|
|
654
749
|
const repairDetails = () => repairErrors.length > 0
|
|
@@ -660,7 +755,7 @@ async function executeProgram(options) {
|
|
|
660
755
|
const fixed = await repairWithTimeout(tempAdapter, { programSource: currentSource, error: lastError, runtimeTypes: RUNTIME_TYPES }, timeout, repairErrors);
|
|
661
756
|
if (!fixed)
|
|
662
757
|
return null;
|
|
663
|
-
writeFileSync(
|
|
758
|
+
writeFileSync(guardPath(tempDir, "program.ts"), fixed);
|
|
664
759
|
const verifyResult = await runProgramOnce({
|
|
665
760
|
projectDir: tempDir, adapter: tempAdapter, timeout, maxIterations,
|
|
666
761
|
argsOverride: options.argsOverride,
|
|
@@ -676,7 +771,7 @@ async function executeProgram(options) {
|
|
|
676
771
|
// Repair verified in isolation — now run in the real project for actual output.
|
|
677
772
|
// Snapshot first so we can restore cleanly if the real run fails.
|
|
678
773
|
const realResult = await withSnapshot(projectDir, async () => {
|
|
679
|
-
writeFileSync(
|
|
774
|
+
writeFileSync(guardPath(projectDir, "program.ts"), repairResult.fixed);
|
|
680
775
|
const r = await runProgramOnce({
|
|
681
776
|
projectDir, adapter, timeout, maxIterations,
|
|
682
777
|
argsOverride: options.argsOverride,
|
|
@@ -710,8 +805,8 @@ async function executeProgram(options) {
|
|
|
710
805
|
// --- Smoke run (used by create and update) ---
|
|
711
806
|
/** Copy new history entries from src to dst (appends only entries added after the shared prefix). */
|
|
712
807
|
function propagateHistoryEntries(srcDir, dstDir) {
|
|
713
|
-
const srcPath =
|
|
714
|
-
const dstPath =
|
|
808
|
+
const srcPath = guardPath(srcDir, join("history", "index.jsonl"));
|
|
809
|
+
const dstPath = guardPath(dstDir, join("history", "index.jsonl"));
|
|
715
810
|
if (!existsSync(srcPath))
|
|
716
811
|
return;
|
|
717
812
|
const srcHistory = readFileSync(srcPath, "utf-8");
|
|
@@ -720,16 +815,17 @@ function propagateHistoryEntries(srcDir, dstDir) {
|
|
|
720
815
|
return; // History diverged — cannot safely propagate
|
|
721
816
|
const newEntries = srcHistory.slice(dstHistory.length);
|
|
722
817
|
if (newEntries.length > 0) {
|
|
723
|
-
mkdirSync(
|
|
818
|
+
mkdirSync(guardPath(dstDir, "history"), { recursive: true });
|
|
724
819
|
appendFileSync(dstPath, newEntries);
|
|
725
820
|
}
|
|
726
821
|
}
|
|
727
822
|
const DEFAULT_SMOKE_TIMEOUT = 30_000;
|
|
728
|
-
const
|
|
729
|
-
|
|
823
|
+
const SMOKE_READY_GRACE_MS = 2_000;
|
|
824
|
+
export function resolveSmokeTimeout(timeout) {
|
|
825
|
+
return timeout ?? DEFAULT_SMOKE_TIMEOUT;
|
|
826
|
+
}
|
|
730
827
|
export async function smokeRunAndRepair(projectDir, adapter, reason, options) {
|
|
731
|
-
const
|
|
732
|
-
const smokeTimeout = Math.min(requestedTimeout, MAX_SMOKE_TIMEOUT);
|
|
828
|
+
const smokeTimeout = resolveSmokeTimeout(options?.timeout);
|
|
733
829
|
// Run validation in a temp copy so side effects don't persist in the real project
|
|
734
830
|
await withTempDir("trama-smoke-", async (smokeDir) => {
|
|
735
831
|
cpSync(projectDir, smokeDir, { recursive: true });
|
|
@@ -745,11 +841,11 @@ export async function smokeRunAndRepair(projectDir, adapter, reason, options) {
|
|
|
745
841
|
graceMs: SMOKE_READY_GRACE_MS,
|
|
746
842
|
},
|
|
747
843
|
onRepair(_attempt, _max, error) {
|
|
748
|
-
appendFileSync(
|
|
844
|
+
appendFileSync(guardPath(smokeDir, join("history", "index.jsonl")), JSON.stringify({ reason: `${reason}-repair`, timestamp: new Date().toISOString(), error }) + "\n");
|
|
749
845
|
},
|
|
750
846
|
});
|
|
751
847
|
// Smoke passed — copy back program.ts (may have been repaired)
|
|
752
|
-
copyFileSync(
|
|
848
|
+
copyFileSync(guardPath(smokeDir, "program.ts"), guardPath(projectDir, "program.ts"));
|
|
753
849
|
}
|
|
754
850
|
finally {
|
|
755
851
|
// Always propagate repair history, whether smoke passed or failed
|
|
@@ -765,6 +861,13 @@ export async function runProgram(options) {
|
|
|
765
861
|
`Run \`trama list\` to see available projects.`);
|
|
766
862
|
}
|
|
767
863
|
const config = loadConfig();
|
|
864
|
+
// Use per-project model/provider if saved, else fall back to global config
|
|
865
|
+
const metaPath = guardPath(projectDir, "meta.json");
|
|
866
|
+
const meta = JSON.parse(readFileSync(metaPath, "utf-8"));
|
|
867
|
+
if (meta.model)
|
|
868
|
+
config.model = meta.model;
|
|
869
|
+
if (meta.provider)
|
|
870
|
+
config.provider = meta.provider;
|
|
768
871
|
const maxRepairAttempts = options.maxRepairAttempts ?? config.maxRepairAttempts;
|
|
769
872
|
const timeout = options.timeout ?? config.defaultTimeout;
|
|
770
873
|
const maxIterations = config.defaultMaxIterations;
|
|
@@ -784,7 +887,7 @@ export async function runProgram(options) {
|
|
|
784
887
|
argsOverride: options.args,
|
|
785
888
|
onRepair(attempt, max, error) {
|
|
786
889
|
// Log repair attempts (appends to already-open logs file)
|
|
787
|
-
const logsPath =
|
|
890
|
+
const logsPath = guardPath(projectDir, join("logs", "latest.jsonl"));
|
|
788
891
|
const entry = { ts: Date.now(), message: `Repair attempt ${attempt + 1}/${max}`, data: { error } };
|
|
789
892
|
appendFileSync(logsPath, JSON.stringify(entry) + "\n");
|
|
790
893
|
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>;
|
|
@@ -36,9 +37,14 @@ export interface Ctx {
|
|
|
36
37
|
}
|
|
37
38
|
export interface Agent {
|
|
38
39
|
/**
|
|
39
|
-
*
|
|
40
|
-
* The underlying
|
|
40
|
+
* Instruct the pi-coding-agent to perform a task. Returns plain text.
|
|
41
|
+
* The underlying agent may autonomously use its built-in tools
|
|
42
|
+
* (bash, file read/write/edit) to fulfill the instruction.
|
|
41
43
|
*/
|
|
44
|
+
instruct(prompt: string, options?: {
|
|
45
|
+
system?: string;
|
|
46
|
+
}): Promise<string>;
|
|
47
|
+
/** @deprecated Use instruct() instead. Alias kept for backwards compatibility. */
|
|
42
48
|
ask(prompt: string, options?: {
|
|
43
49
|
system?: string;
|
|
44
50
|
}): Promise<string>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trama-dev/runtime",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.4",
|
|
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",
|