@trama-dev/runtime 0.1.1 → 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/agent.js +28 -12
- package/dist/client.js +51 -16
- package/dist/context.d.ts +2 -0
- package/dist/context.js +47 -17
- package/dist/index.d.ts +1 -0
- package/dist/index.js +53 -25
- package/dist/path-guard.d.ts +37 -0
- package/dist/path-guard.js +102 -0
- package/dist/pi-adapter.d.ts +2 -0
- package/dist/pi-adapter.js +21 -7
- package/dist/runner.d.ts +15 -1
- package/dist/runner.js +407 -128
- package/dist/serializable.js +2 -1
- package/dist/tools.js +44 -75
- package/dist/types.d.ts +8 -0
- package/package.json +5 -4
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/agent.js
CHANGED
|
@@ -28,27 +28,43 @@ export function createAgent(adapter, signal) {
|
|
|
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}`;
|
|
31
|
-
const
|
|
32
|
-
|
|
33
|
-
const
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
.
|
|
39
|
-
|
|
31
|
+
const askOptions = signal ? { system: input.system, signal } : { system: input.system };
|
|
32
|
+
const parseAndValidate = (response) => {
|
|
33
|
+
const trimmed = response.trim();
|
|
34
|
+
// Try raw parse first — avoids mangling valid JSON that contains
|
|
35
|
+
// fenced code blocks inside string values.
|
|
36
|
+
let parsed;
|
|
37
|
+
try {
|
|
38
|
+
parsed = JSON.parse(trimmed);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
const fenceMatch = trimmed.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);
|
|
42
|
+
parsed = JSON.parse(fenceMatch ? fenceMatch[1].trim() : trimmed);
|
|
43
|
+
}
|
|
40
44
|
const error = validateShape(parsed, input.schema);
|
|
41
45
|
if (error)
|
|
42
46
|
throw new Error(`Schema validation failed: ${error}`);
|
|
43
|
-
return parsed;
|
|
47
|
+
return stripToSchema(parsed, input.schema);
|
|
44
48
|
};
|
|
49
|
+
// First attempt — adapter errors (network/auth) propagate immediately.
|
|
50
|
+
// Only parse/validation failures trigger a retry.
|
|
51
|
+
const response = await adapter.ask(fullPrompt, askOptions);
|
|
45
52
|
try {
|
|
46
|
-
return
|
|
53
|
+
return parseAndValidate(response);
|
|
47
54
|
}
|
|
48
55
|
catch (firstError) {
|
|
49
56
|
const retryPrompt = `Your previous response failed validation: ${firstError}.\nTry again.\n\n${fullPrompt}`;
|
|
50
|
-
|
|
57
|
+
const retryResponse = await adapter.ask(retryPrompt, askOptions);
|
|
58
|
+
return parseAndValidate(retryResponse);
|
|
51
59
|
}
|
|
52
60
|
}
|
|
53
61
|
};
|
|
54
62
|
}
|
|
63
|
+
/** Return a new object containing only the keys declared in the schema. */
|
|
64
|
+
function stripToSchema(obj, schema) {
|
|
65
|
+
const result = {};
|
|
66
|
+
for (const key of Object.keys(schema)) {
|
|
67
|
+
result[key] = obj[key];
|
|
68
|
+
}
|
|
69
|
+
return result;
|
|
70
|
+
}
|
package/dist/client.js
CHANGED
|
@@ -1,16 +1,19 @@
|
|
|
1
1
|
// @trama-dev/runtime client — this is what program.ts imports.
|
|
2
2
|
// Thin HTTP wrapper that calls the runner's IPC server.
|
|
3
|
+
import { readFileSync } from "fs";
|
|
3
4
|
import { assertSerializable } from "./serializable.js";
|
|
4
5
|
const PORT = process.env.TRAMA_PORT;
|
|
5
6
|
if (!PORT) {
|
|
6
7
|
throw new Error("@trama-dev/runtime must be executed via `trama run`. " +
|
|
7
8
|
"Direct execution is not supported (TRAMA_PORT env var missing).");
|
|
8
9
|
}
|
|
9
|
-
|
|
10
|
-
|
|
10
|
+
const INIT_PATH = process.env.TRAMA_INIT;
|
|
11
|
+
if (!INIT_PATH) {
|
|
12
|
+
throw new Error("@trama-dev/runtime: TRAMA_INIT env var missing. " +
|
|
11
13
|
"This program must be launched by the trama runner.");
|
|
12
14
|
}
|
|
13
15
|
const BASE = `http://127.0.0.1:${PORT}`;
|
|
16
|
+
const initData = JSON.parse(readFileSync(INIT_PATH, "utf-8"));
|
|
14
17
|
async function call(endpoint, body) {
|
|
15
18
|
const res = await fetch(`${BASE}${endpoint}`, {
|
|
16
19
|
method: "POST",
|
|
@@ -21,14 +24,35 @@ async function call(endpoint, body) {
|
|
|
21
24
|
throw new Error(`trama runtime error: ${await res.text()}`);
|
|
22
25
|
return res.json();
|
|
23
26
|
}
|
|
24
|
-
let
|
|
27
|
+
let donePromise = null;
|
|
28
|
+
let readyCalled = false;
|
|
25
29
|
export const ctx = {
|
|
26
|
-
input:
|
|
27
|
-
state:
|
|
28
|
-
iteration:
|
|
29
|
-
maxIterations:
|
|
30
|
+
input: initData.input,
|
|
31
|
+
state: initData.state,
|
|
32
|
+
iteration: initData.iteration,
|
|
33
|
+
maxIterations: initData.maxIterations,
|
|
30
34
|
async log(msg, data) {
|
|
31
|
-
|
|
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 });
|
|
43
|
+
},
|
|
44
|
+
async ready(data) {
|
|
45
|
+
if (readyCalled)
|
|
46
|
+
return;
|
|
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 });
|
|
55
|
+
readyCalled = true;
|
|
32
56
|
},
|
|
33
57
|
async checkpoint() {
|
|
34
58
|
assertSerializable(ctx.state, "ctx.state");
|
|
@@ -36,14 +60,25 @@ export const ctx = {
|
|
|
36
60
|
ctx.iteration += 1;
|
|
37
61
|
},
|
|
38
62
|
async done(result) {
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
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
|
+
}
|
|
47
82
|
},
|
|
48
83
|
};
|
|
49
84
|
export const agent = {
|
package/dist/context.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import type { Ctx } from "./types.js";
|
|
2
2
|
export declare function createContext(projectDir: string, initialState: Record<string, unknown>, options?: {
|
|
3
3
|
maxIterations?: number;
|
|
4
|
+
argsOverride?: Record<string, unknown>;
|
|
5
|
+
onReady?: (data?: Record<string, unknown>) => void;
|
|
4
6
|
}): Ctx;
|
package/dist/context.js
CHANGED
|
@@ -1,24 +1,44 @@
|
|
|
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;
|
|
11
|
+
let readyCalled = false;
|
|
12
|
+
const input = options?.argsOverride
|
|
13
|
+
? { ...meta.input, args: { ...(meta.input.args ?? {}), ...options.argsOverride } }
|
|
14
|
+
: meta.input;
|
|
10
15
|
return {
|
|
11
|
-
input
|
|
16
|
+
input,
|
|
12
17
|
state: { ...initialState },
|
|
13
18
|
iteration: typeof initialState.__trama_iteration === "number"
|
|
14
|
-
&& Number.
|
|
19
|
+
&& Number.isInteger(initialState.__trama_iteration)
|
|
20
|
+
&& initialState.__trama_iteration >= 0
|
|
15
21
|
? initialState.__trama_iteration : 0,
|
|
16
22
|
maxIterations: options?.maxIterations ?? 100,
|
|
17
23
|
async log(message, data) {
|
|
18
|
-
|
|
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 };
|
|
19
32
|
appendFileSync(logsPath, JSON.stringify(entry) + "\n");
|
|
20
33
|
console.log(`[trama] ${message}`);
|
|
21
34
|
},
|
|
35
|
+
async ready(data) {
|
|
36
|
+
if (readyCalled)
|
|
37
|
+
return;
|
|
38
|
+
await this.log("ready", data);
|
|
39
|
+
options?.onReady?.(data);
|
|
40
|
+
readyCalled = true;
|
|
41
|
+
},
|
|
22
42
|
async checkpoint() {
|
|
23
43
|
assertSerializable(this.state, "ctx.state");
|
|
24
44
|
const nextIteration = this.iteration + 1;
|
|
@@ -27,17 +47,27 @@ export function createContext(projectDir, initialState, options) {
|
|
|
27
47
|
this.iteration = nextIteration;
|
|
28
48
|
},
|
|
29
49
|
async done(result) {
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
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;
|
|
34
70
|
}
|
|
35
|
-
await this.checkpoint();
|
|
36
|
-
// Only mark as complete after checkpoint succeeds.
|
|
37
|
-
// If checkpoint throws, a retry will re-log "done" (acceptable)
|
|
38
|
-
// and retry the checkpoint.
|
|
39
|
-
doneLogged = true;
|
|
40
|
-
doneCalled = true;
|
|
41
71
|
}
|
|
42
72
|
};
|
|
43
73
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ export declare function validateProjectName(name: string): void;
|
|
|
3
3
|
export declare function resolveProject(name: string): string;
|
|
4
4
|
export declare function createProject(name: string, prompt: string, options?: {
|
|
5
5
|
model?: string;
|
|
6
|
+
args?: Record<string, unknown>;
|
|
6
7
|
}): Promise<void>;
|
|
7
8
|
export declare function updateProject(name: string, prompt: string): Promise<void>;
|
|
8
9
|
export declare function listProjects(): Promise<void>;
|
package/dist/index.js
CHANGED
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
import { readFileSync, writeFileSync, mkdirSync, readdirSync, existsSync, copyFileSync, appendFileSync, statSync, rmSync, cpSync, mkdtempSync } from "fs";
|
|
3
3
|
import { join } from "path";
|
|
4
4
|
import { homedir, tmpdir } from "os";
|
|
5
|
-
import { PiAdapter } from "./pi-adapter.js";
|
|
6
|
-
import { loadConfig, loadState, smokeRunAndRepair, copyToHistory, withTempDir, RUNTIME_TYPES, PI_VERSION } from "./runner.js";
|
|
5
|
+
import { PiAdapter, stripCodeFences } from "./pi-adapter.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.
|
|
@@ -56,16 +57,38 @@ for (let i = ctx.iteration; i < ctx.maxIterations; i++) {
|
|
|
56
57
|
}
|
|
57
58
|
|
|
58
59
|
await tools.write("target.ts", code);
|
|
59
|
-
await ctx.done({ finalMetric: bestMetric })
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
60
|
+
await ctx.done({ finalMetric: bestMetric });
|
|
61
|
+
|
|
62
|
+
// Example D: Long-running server.
|
|
63
|
+
// Call ctx.ready() only after the server is actually listening.
|
|
64
|
+
// Handle SIGTERM/SIGINT so smoke validation can shut it down cleanly.
|
|
65
|
+
import { ctx } from "@trama-dev/runtime";
|
|
66
|
+
import { createServer } from "node:http";
|
|
67
|
+
|
|
68
|
+
const server = createServer((_req, res) => {
|
|
69
|
+
res.end("ok");
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
await new Promise<void>((resolve, reject) => {
|
|
73
|
+
server.once("error", reject);
|
|
74
|
+
server.listen(3000, "127.0.0.1", () => resolve());
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
await ctx.ready({ url: "http://127.0.0.1:3000" });
|
|
78
|
+
|
|
79
|
+
process.on("SIGTERM", () => {
|
|
80
|
+
server.close();
|
|
81
|
+
process.exit(0);
|
|
82
|
+
});
|
|
83
|
+
process.on("SIGINT", () => {
|
|
84
|
+
server.close();
|
|
85
|
+
process.exit(0);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
await new Promise<void>(() => {});`;
|
|
67
89
|
function getSystemPrompt() {
|
|
68
90
|
return (`You are generating a TypeScript program for the trama runtime.\n\n` +
|
|
91
|
+
`If the program is long-running (for example an HTTP server), call ctx.ready(...) after startup completes and handle SIGTERM/SIGINT for clean shutdown.\n\n` +
|
|
69
92
|
`Runtime API:\n${RUNTIME_TYPES}\n\n` +
|
|
70
93
|
`Examples:\n${EXAMPLE_PROGRAMS}`);
|
|
71
94
|
}
|
|
@@ -106,7 +129,7 @@ async function withProjectBackup(projectDir, originalHistory, historyIndexPath,
|
|
|
106
129
|
if (failedHistory.startsWith(originalHistory)) {
|
|
107
130
|
const repairEntries = failedHistory.slice(originalHistory.length);
|
|
108
131
|
if (repairEntries.length > 0) {
|
|
109
|
-
appendFileSync(
|
|
132
|
+
appendFileSync(guardPath(projectDir, join("history", "index.jsonl")), repairEntries);
|
|
110
133
|
}
|
|
111
134
|
}
|
|
112
135
|
throw new Error(`Update failed — project files have been restored to the previous version.\n` +
|
|
@@ -128,17 +151,18 @@ export async function createProject(name, prompt, options) {
|
|
|
128
151
|
try {
|
|
129
152
|
mkdirSync(join(projectDir, "history"), { recursive: true });
|
|
130
153
|
mkdirSync(join(projectDir, "logs"), { recursive: true });
|
|
131
|
-
|
|
132
|
-
|
|
154
|
+
ensureProjectScaffold(projectDir);
|
|
155
|
+
const config = loadConfig();
|
|
156
|
+
if (options?.model)
|
|
157
|
+
config.model = options.model;
|
|
133
158
|
const meta = {
|
|
134
|
-
input: { prompt, args: {} },
|
|
159
|
+
input: { prompt, args: options?.args ?? {} },
|
|
135
160
|
createdAt: new Date().toISOString(),
|
|
136
161
|
piVersion: PI_VERSION,
|
|
162
|
+
model: config.model,
|
|
163
|
+
provider: config.provider,
|
|
137
164
|
};
|
|
138
165
|
writeFileSync(join(projectDir, "meta.json"), JSON.stringify(meta, null, 2));
|
|
139
|
-
const config = loadConfig();
|
|
140
|
-
if (options?.model)
|
|
141
|
-
config.model = options.model;
|
|
142
166
|
const adapter = new PiAdapter(config, projectDir);
|
|
143
167
|
console.log(`Generating program for "${name}"...`);
|
|
144
168
|
const program = stripCodeFences(await isolatedAsk(adapter, `${prompt}\n\nOutput ONLY the TypeScript program. No markdown fences. No explanation.`, { system: getSystemPrompt() }));
|
|
@@ -163,13 +187,17 @@ export async function createProject(name, prompt, options) {
|
|
|
163
187
|
}
|
|
164
188
|
export async function updateProject(name, prompt) {
|
|
165
189
|
const projectDir = resolveProject(name);
|
|
166
|
-
const programPath =
|
|
190
|
+
const programPath = guardPath(projectDir, "program.ts");
|
|
167
191
|
const originalSource = readFileSync(programPath, "utf-8");
|
|
168
192
|
const state = loadState(projectDir);
|
|
169
|
-
const meta = JSON.parse(readFileSync(
|
|
170
|
-
const historyIndexPath =
|
|
193
|
+
const meta = JSON.parse(readFileSync(guardPath(projectDir, "meta.json"), "utf-8"));
|
|
194
|
+
const historyIndexPath = guardPath(projectDir, join("history", "index.jsonl"));
|
|
171
195
|
const originalHistory = existsSync(historyIndexPath) ? readFileSync(historyIndexPath, "utf-8") : "";
|
|
172
196
|
const config = loadConfig();
|
|
197
|
+
if (meta.model)
|
|
198
|
+
config.model = meta.model;
|
|
199
|
+
if (meta.provider)
|
|
200
|
+
config.provider = meta.provider;
|
|
173
201
|
const adapter = new PiAdapter(config, projectDir);
|
|
174
202
|
// Backup before any LLM calls, restore on any failure
|
|
175
203
|
await withProjectBackup(projectDir, originalHistory, historyIndexPath, async () => {
|
|
@@ -207,23 +235,23 @@ export async function listProjects() {
|
|
|
207
235
|
let prompt = "";
|
|
208
236
|
let modified = "";
|
|
209
237
|
try {
|
|
210
|
-
const meta = JSON.parse(readFileSync(
|
|
238
|
+
const meta = JSON.parse(readFileSync(guardPath(projectDir, "meta.json"), "utf-8"));
|
|
211
239
|
prompt = meta.input?.prompt ?? "";
|
|
212
240
|
if (prompt.length > 60)
|
|
213
241
|
prompt = prompt.slice(0, 57) + "...";
|
|
214
242
|
}
|
|
215
|
-
catch { /* no meta */ }
|
|
243
|
+
catch { /* no meta or symlink escape */ }
|
|
216
244
|
try {
|
|
217
|
-
const stat = statSync(
|
|
245
|
+
const stat = statSync(guardPath(projectDir, "program.ts"));
|
|
218
246
|
modified = stat.mtime.toISOString().slice(0, 19).replace("T", " ");
|
|
219
247
|
}
|
|
220
|
-
catch { /* no program.ts */ }
|
|
248
|
+
catch { /* no program.ts or symlink escape */ }
|
|
221
249
|
console.log(` ${entry.name} ${prompt} ${modified}`);
|
|
222
250
|
}
|
|
223
251
|
}
|
|
224
252
|
export async function showLogs(name) {
|
|
225
253
|
const projectDir = resolveProject(name);
|
|
226
|
-
const logsPath =
|
|
254
|
+
const logsPath = guardPath(projectDir, join("logs", "latest.jsonl"));
|
|
227
255
|
if (!existsSync(logsPath)) {
|
|
228
256
|
console.log("No logs found.");
|
|
229
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.d.ts
CHANGED
package/dist/pi-adapter.js
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
import { createAgentSession, SessionManager, DefaultResourceLoader, } from "@mariozechner/pi-coding-agent";
|
|
2
2
|
import { getModel } from "@mariozechner/pi-ai";
|
|
3
|
+
/** Strip markdown code fences and trim whitespace. */
|
|
4
|
+
export function stripCodeFences(text) {
|
|
5
|
+
const trimmed = text.trim();
|
|
6
|
+
// 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();
|
|
10
|
+
}
|
|
11
|
+
return trimmed;
|
|
12
|
+
}
|
|
3
13
|
export class PiAdapter {
|
|
4
14
|
config;
|
|
5
15
|
cwd;
|
|
@@ -25,10 +35,18 @@ export class PiAdapter {
|
|
|
25
35
|
const raceAbort = (promise) => {
|
|
26
36
|
if (!signal)
|
|
27
37
|
return promise;
|
|
38
|
+
let onAbort = null;
|
|
39
|
+
const cleanup = () => {
|
|
40
|
+
if (onAbort) {
|
|
41
|
+
signal.removeEventListener("abort", onAbort);
|
|
42
|
+
onAbort = null;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
28
45
|
return Promise.race([
|
|
29
|
-
promise,
|
|
46
|
+
promise.finally(cleanup),
|
|
30
47
|
new Promise((_resolve, reject) => {
|
|
31
|
-
|
|
48
|
+
onAbort = () => reject(new Error("Aborted"));
|
|
49
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
32
50
|
}),
|
|
33
51
|
]);
|
|
34
52
|
};
|
|
@@ -100,10 +118,6 @@ export class PiAdapter {
|
|
|
100
118
|
`Broken program:\n${input.programSource}\n\n` +
|
|
101
119
|
`Error:\n${input.error}\n\n` +
|
|
102
120
|
`Output ONLY the fixed program. No explanation.`, { system: "You are a TypeScript repair tool.", signal });
|
|
103
|
-
|
|
104
|
-
if (/^```/.test(trimmed) && /```$/.test(trimmed)) {
|
|
105
|
-
return trimmed.replace(/^```\w*\s*\n?/, "").replace(/\n?\s*```$/, "");
|
|
106
|
-
}
|
|
107
|
-
return response;
|
|
121
|
+
return stripCodeFences(response);
|
|
108
122
|
}
|
|
109
123
|
}
|