@trama-dev/runtime 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +8 -9
- package/dist/client.js +7 -2
- package/dist/context.js +6 -42
- package/dist/index.d.ts +1 -0
- package/dist/index.js +71 -39
- package/dist/pi-adapter.d.ts +9 -1
- package/dist/pi-adapter.js +59 -9
- package/dist/runner.d.ts +14 -1
- package/dist/runner.js +267 -121
- package/dist/serializable.d.ts +8 -0
- package/dist/serializable.js +40 -0
- package/dist/tools.d.ts +5 -1
- package/dist/tools.js +177 -21
- package/package.json +1 -1
package/dist/agent.d.ts
CHANGED
package/dist/agent.js
CHANGED
|
@@ -7,30 +7,29 @@ function validateShape(result, schema) {
|
|
|
7
7
|
if (typeof result !== "object" || result === null)
|
|
8
8
|
return "response is not an object";
|
|
9
9
|
const obj = result;
|
|
10
|
+
const supportedTypes = new Set(["string", "number", "boolean"]);
|
|
10
11
|
for (const [key, typeDesc] of Object.entries(schema)) {
|
|
11
12
|
if (!(key in obj))
|
|
12
13
|
return `missing key: ${key}`;
|
|
13
14
|
const expectedType = typeDesc.split(":")[0].trim();
|
|
15
|
+
if (!supportedTypes.has(expectedType))
|
|
16
|
+
return `unsupported schema type "${expectedType}" for key "${key}"`;
|
|
14
17
|
const actual = typeof obj[key];
|
|
15
|
-
if (
|
|
16
|
-
return `${key}: expected
|
|
17
|
-
if (expectedType === "number" && actual !== "number")
|
|
18
|
-
return `${key}: expected number, got ${actual}`;
|
|
19
|
-
if (expectedType === "boolean" && actual !== "boolean")
|
|
20
|
-
return `${key}: expected boolean, got ${actual}`;
|
|
18
|
+
if (actual !== expectedType)
|
|
19
|
+
return `${key}: expected ${expectedType}, got ${actual}`;
|
|
21
20
|
}
|
|
22
21
|
return null;
|
|
23
22
|
}
|
|
24
|
-
export function createAgent(adapter) {
|
|
23
|
+
export function createAgent(adapter, signal) {
|
|
25
24
|
return {
|
|
26
25
|
async ask(prompt, options) {
|
|
27
|
-
return adapter.ask(prompt, options);
|
|
26
|
+
return adapter.ask(prompt, signal ? { ...options, signal } : options);
|
|
28
27
|
},
|
|
29
28
|
async generate(input) {
|
|
30
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.`;
|
|
31
30
|
const fullPrompt = `${input.prompt}\n\n${schemaInstruction}`;
|
|
32
31
|
const attempt = async (p) => {
|
|
33
|
-
const response = await adapter.ask(p, { system: input.system });
|
|
32
|
+
const response = await adapter.ask(p, signal ? { system: input.system, signal } : { system: input.system });
|
|
34
33
|
const cleaned = response
|
|
35
34
|
.trim()
|
|
36
35
|
.replace(/^```json\s*/i, "")
|
package/dist/client.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
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 { assertSerializable } from "./serializable.js";
|
|
3
4
|
const PORT = process.env.TRAMA_PORT;
|
|
4
5
|
if (!PORT) {
|
|
5
6
|
throw new Error("@trama-dev/runtime must be executed via `trama run`. " +
|
|
@@ -30,12 +31,16 @@ export const ctx = {
|
|
|
30
31
|
await call("/ctx/log", { message: msg, data });
|
|
31
32
|
},
|
|
32
33
|
async checkpoint() {
|
|
34
|
+
assertSerializable(ctx.state, "ctx.state");
|
|
33
35
|
await call("/ctx/checkpoint", { state: ctx.state });
|
|
34
36
|
ctx.iteration += 1;
|
|
35
37
|
},
|
|
36
38
|
async done(result) {
|
|
37
39
|
if (doneCalled)
|
|
38
40
|
return;
|
|
41
|
+
assertSerializable(ctx.state, "ctx.state");
|
|
42
|
+
if (result !== undefined)
|
|
43
|
+
assertSerializable(result, "ctx.done(result)");
|
|
39
44
|
await call("/ctx/done", { state: ctx.state, result });
|
|
40
45
|
doneCalled = true;
|
|
41
46
|
ctx.iteration += 1;
|
|
@@ -48,6 +53,6 @@ export const agent = {
|
|
|
48
53
|
export const tools = {
|
|
49
54
|
read: (path) => call("/tools/read", { path }).then(r => r.result),
|
|
50
55
|
write: (path, content) => call("/tools/write", { path, content }).then(r => r.result),
|
|
51
|
-
shell: (cmd, opts) => call("/tools/shell", { command: cmd, ...opts }),
|
|
52
|
-
fetch: (url, opts) => call("/tools/fetch", { url, ...opts }),
|
|
56
|
+
shell: (cmd, opts) => call("/tools/shell", { command: cmd, ...opts }).then(r => r.result),
|
|
57
|
+
fetch: (url, opts) => call("/tools/fetch", { url, ...opts }).then(r => r.result),
|
|
53
58
|
};
|
package/dist/context.js
CHANGED
|
@@ -1,45 +1,6 @@
|
|
|
1
1
|
import { readFileSync, writeFileSync, appendFileSync } from "fs";
|
|
2
2
|
import { join } from "path";
|
|
3
|
-
|
|
4
|
-
* Recursively check that a value is strictly JSON-serializable.
|
|
5
|
-
* Throws TypeError with the path to the offending value.
|
|
6
|
-
*
|
|
7
|
-
* Uses a stack (ancestor chain) instead of a flat set so that shared-but-
|
|
8
|
-
* non-circular structures like { a: shared, b: shared } pass validation.
|
|
9
|
-
*/
|
|
10
|
-
function assertSerializable(value, path, ancestors = new Set()) {
|
|
11
|
-
if (value === null || typeof value === "string" || typeof value === "boolean") {
|
|
12
|
-
return;
|
|
13
|
-
}
|
|
14
|
-
if (typeof value === "number") {
|
|
15
|
-
if (!Number.isFinite(value)) {
|
|
16
|
-
throw new TypeError(`${path} is not JSON-serializable (${value})`);
|
|
17
|
-
}
|
|
18
|
-
return;
|
|
19
|
-
}
|
|
20
|
-
if (typeof value === "undefined" || typeof value === "function" || typeof value === "symbol" || typeof value === "bigint") {
|
|
21
|
-
throw new TypeError(`${path} is not JSON-serializable (${typeof value})`);
|
|
22
|
-
}
|
|
23
|
-
if (ancestors.has(value)) {
|
|
24
|
-
throw new TypeError(`${path} contains a circular reference`);
|
|
25
|
-
}
|
|
26
|
-
ancestors.add(value);
|
|
27
|
-
if (Array.isArray(value)) {
|
|
28
|
-
for (let i = 0; i < value.length; i++) {
|
|
29
|
-
assertSerializable(value[i], `${path}[${i}]`, ancestors);
|
|
30
|
-
}
|
|
31
|
-
ancestors.delete(value);
|
|
32
|
-
return;
|
|
33
|
-
}
|
|
34
|
-
if (Object.getPrototypeOf(value) !== Object.prototype) {
|
|
35
|
-
const name = value.constructor?.name ?? "unknown";
|
|
36
|
-
throw new TypeError(`${path} is not a plain object (${name})`);
|
|
37
|
-
}
|
|
38
|
-
for (const [k, v] of Object.entries(value)) {
|
|
39
|
-
assertSerializable(v, `${path}.${k}`, ancestors);
|
|
40
|
-
}
|
|
41
|
-
ancestors.delete(value);
|
|
42
|
-
}
|
|
3
|
+
import { assertSerializable } from "./serializable.js";
|
|
43
4
|
export function createContext(projectDir, initialState, options) {
|
|
44
5
|
const logsPath = join(projectDir, "logs", "latest.jsonl");
|
|
45
6
|
const statePath = join(projectDir, "state.json");
|
|
@@ -68,11 +29,14 @@ export function createContext(projectDir, initialState, options) {
|
|
|
68
29
|
async done(result) {
|
|
69
30
|
if (doneCalled)
|
|
70
31
|
return;
|
|
71
|
-
if (
|
|
32
|
+
if (!doneLogged) {
|
|
72
33
|
await this.log("done", result);
|
|
73
|
-
doneLogged = true;
|
|
74
34
|
}
|
|
75
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;
|
|
76
40
|
doneCalled = true;
|
|
77
41
|
}
|
|
78
42
|
};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export { runProgram } from "./runner.js";
|
|
2
2
|
export declare function validateProjectName(name: string): void;
|
|
3
|
+
export declare function resolveProject(name: string): string;
|
|
3
4
|
export declare function createProject(name: string, prompt: string, options?: {
|
|
4
5
|
model?: string;
|
|
5
6
|
}): Promise<void>;
|
package/dist/index.js
CHANGED
|
@@ -3,10 +3,10 @@ import { readFileSync, writeFileSync, mkdirSync, readdirSync, existsSync, copyFi
|
|
|
3
3
|
import { join } from "path";
|
|
4
4
|
import { homedir, tmpdir } from "os";
|
|
5
5
|
import { PiAdapter } from "./pi-adapter.js";
|
|
6
|
-
import { loadConfig, loadState, smokeRunAndRepair, copyToHistory, RUNTIME_TYPES, PI_VERSION } from "./runner.js";
|
|
6
|
+
import { loadConfig, loadState, smokeRunAndRepair, copyToHistory, withTempDir, RUNTIME_TYPES, PI_VERSION } from "./runner.js";
|
|
7
7
|
export { runProgram } from "./runner.js";
|
|
8
8
|
// --- Example programs (included in system prompt during create/update) ---
|
|
9
|
-
const EXAMPLE_PROGRAMS = `// Example A: Simple
|
|
9
|
+
const EXAMPLE_PROGRAMS = `// Example A: Simple — one-shot action, no LLM needed.
|
|
10
10
|
import { ctx, tools } from "@trama-dev/runtime";
|
|
11
11
|
|
|
12
12
|
const content = "# Hello World\\nGenerated at " + new Date().toISOString();
|
|
@@ -14,7 +14,7 @@ await tools.write("hello.md", content);
|
|
|
14
14
|
await ctx.log("wrote hello.md");
|
|
15
15
|
await ctx.done();
|
|
16
16
|
|
|
17
|
-
// Example B: Medium
|
|
17
|
+
// Example B: Medium — use the LLM once to process data, write the result.
|
|
18
18
|
import { ctx, agent, tools } from "@trama-dev/runtime";
|
|
19
19
|
|
|
20
20
|
const data = await tools.read(ctx.input.args.file as string);
|
|
@@ -22,7 +22,10 @@ const summary = await agent.ask("Summarize this data concisely:\\n" + data);
|
|
|
22
22
|
await tools.write("summary.md", summary);
|
|
23
23
|
await ctx.done({ summaryLength: summary.length });
|
|
24
24
|
|
|
25
|
-
// Example C:
|
|
25
|
+
// Example C: Iterative optimization loop.
|
|
26
|
+
// Pattern: propose a change via LLM, evaluate it with a deterministic script,
|
|
27
|
+
// keep the change only if it improves the metric, repeat.
|
|
28
|
+
// ctx.state and ctx.iteration persist across runs so the loop can resume after interruption.
|
|
26
29
|
import { ctx, agent, tools } from "@trama-dev/runtime";
|
|
27
30
|
|
|
28
31
|
let code = (ctx.state.code as string | undefined) ?? await tools.read("target.ts");
|
|
@@ -35,7 +38,7 @@ for (let i = ctx.iteration; i < ctx.maxIterations; i++) {
|
|
|
35
38
|
});
|
|
36
39
|
|
|
37
40
|
await tools.write("candidate.ts", proposal.newCode);
|
|
38
|
-
const bench = await tools.shell("
|
|
41
|
+
const bench = await tools.shell("node benchmark.mjs candidate.ts");
|
|
39
42
|
|
|
40
43
|
if (bench.exitCode !== 0) {
|
|
41
44
|
await ctx.log("benchmark failed", { stderr: bench.stderr });
|
|
@@ -54,6 +57,13 @@ for (let i = ctx.iteration; i < ctx.maxIterations; i++) {
|
|
|
54
57
|
|
|
55
58
|
await tools.write("target.ts", code);
|
|
56
59
|
await ctx.done({ finalMetric: bestMetric });`;
|
|
60
|
+
function stripCodeFences(text) {
|
|
61
|
+
const trimmed = text.trim();
|
|
62
|
+
if (/^```/.test(trimmed) && /```$/.test(trimmed)) {
|
|
63
|
+
return trimmed.replace(/^```\w*\s*\n?/, "").replace(/\n?\s*```$/, "");
|
|
64
|
+
}
|
|
65
|
+
return text;
|
|
66
|
+
}
|
|
57
67
|
function getSystemPrompt() {
|
|
58
68
|
return (`You are generating a TypeScript program for the trama runtime.\n\n` +
|
|
59
69
|
`Runtime API:\n${RUNTIME_TYPES}\n\n` +
|
|
@@ -67,7 +77,7 @@ export function validateProjectName(name) {
|
|
|
67
77
|
throw new Error(`Invalid project name: "${name}". Must be a simple directory name without path separators.`);
|
|
68
78
|
}
|
|
69
79
|
}
|
|
70
|
-
function resolveProject(name) {
|
|
80
|
+
export function resolveProject(name) {
|
|
71
81
|
validateProjectName(name);
|
|
72
82
|
const dir = join(projectsDir(), name);
|
|
73
83
|
if (!existsSync(dir)) {
|
|
@@ -75,6 +85,37 @@ function resolveProject(name) {
|
|
|
75
85
|
}
|
|
76
86
|
return dir;
|
|
77
87
|
}
|
|
88
|
+
// --- Helpers ---
|
|
89
|
+
/** Run an LLM ask() in an isolated temp cwd so pi-coding-agent tools can't write into the real project. */
|
|
90
|
+
async function isolatedAsk(adapter, prompt, options) {
|
|
91
|
+
return withTempDir("trama-gen-", (dir) => adapter.withCwd(dir).ask(prompt, options));
|
|
92
|
+
}
|
|
93
|
+
/** Backup projectDir, run fn, restore on failure. Preserves new repair history entries across restore. */
|
|
94
|
+
async function withProjectBackup(projectDir, originalHistory, historyIndexPath, fn) {
|
|
95
|
+
const backupRoot = mkdtempSync(join(tmpdir(), "trama-update-backup-"));
|
|
96
|
+
const backupDir = join(backupRoot, "project");
|
|
97
|
+
cpSync(projectDir, backupDir, { recursive: true });
|
|
98
|
+
try {
|
|
99
|
+
await fn();
|
|
100
|
+
}
|
|
101
|
+
catch (err) {
|
|
102
|
+
// Restore from backup, preserving any new repair history entries
|
|
103
|
+
const failedHistory = existsSync(historyIndexPath) ? readFileSync(historyIndexPath, "utf-8") : "";
|
|
104
|
+
rmSync(projectDir, { recursive: true, force: true });
|
|
105
|
+
cpSync(backupDir, projectDir, { recursive: true });
|
|
106
|
+
if (failedHistory.startsWith(originalHistory)) {
|
|
107
|
+
const repairEntries = failedHistory.slice(originalHistory.length);
|
|
108
|
+
if (repairEntries.length > 0) {
|
|
109
|
+
appendFileSync(join(projectDir, "history", "index.jsonl"), repairEntries);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
throw new Error(`Update failed — project files have been restored to the previous version.\n` +
|
|
113
|
+
`${err instanceof Error ? err.message : err}`);
|
|
114
|
+
}
|
|
115
|
+
finally {
|
|
116
|
+
rmSync(backupRoot, { recursive: true, force: true });
|
|
117
|
+
}
|
|
118
|
+
}
|
|
78
119
|
// --- Public API ---
|
|
79
120
|
export async function createProject(name, prompt, options) {
|
|
80
121
|
validateProjectName(name);
|
|
@@ -100,11 +141,15 @@ export async function createProject(name, prompt, options) {
|
|
|
100
141
|
config.model = options.model;
|
|
101
142
|
const adapter = new PiAdapter(config, projectDir);
|
|
102
143
|
console.log(`Generating program for "${name}"...`);
|
|
103
|
-
const program = await adapter
|
|
144
|
+
const program = stripCodeFences(await isolatedAsk(adapter, `${prompt}\n\nOutput ONLY the TypeScript program. No markdown fences. No explanation.`, { system: getSystemPrompt() }));
|
|
104
145
|
writeFileSync(join(projectDir, "program.ts"), program);
|
|
105
146
|
keepProjectOnFailure = true;
|
|
106
147
|
console.log("Validating program...");
|
|
107
|
-
await smokeRunAndRepair(projectDir, adapter, "create"
|
|
148
|
+
await smokeRunAndRepair(projectDir, adapter, "create", {
|
|
149
|
+
timeout: config.defaultTimeout,
|
|
150
|
+
maxRepairAttempts: config.maxRepairAttempts,
|
|
151
|
+
maxIterations: config.defaultMaxIterations,
|
|
152
|
+
});
|
|
108
153
|
copyFileSync(join(projectDir, "program.ts"), join(projectDir, "history", "0001.ts"));
|
|
109
154
|
appendFileSync(join(projectDir, "history", "index.jsonl"), JSON.stringify({ version: 1, reason: "create", timestamp: new Date().toISOString(), prompt }) + "\n");
|
|
110
155
|
console.log(`Created ${name}. Run with: trama run ${name}`);
|
|
@@ -126,37 +171,24 @@ export async function updateProject(name, prompt) {
|
|
|
126
171
|
const originalHistory = existsSync(historyIndexPath) ? readFileSync(historyIndexPath, "utf-8") : "";
|
|
127
172
|
const config = loadConfig();
|
|
128
173
|
const adapter = new PiAdapter(config, projectDir);
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
if (failedHistory.startsWith(originalHistory)) {
|
|
148
|
-
const repairEntries = failedHistory.slice(originalHistory.length);
|
|
149
|
-
if (repairEntries.length > 0) {
|
|
150
|
-
appendFileSync(join(projectDir, "history", "index.jsonl"), repairEntries);
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
rmSync(backupRoot, { recursive: true, force: true });
|
|
154
|
-
throw new Error(`Update validation failed — project files have been restored to the previous version.\n` +
|
|
155
|
-
`${err instanceof Error ? err.message : err}`);
|
|
156
|
-
}
|
|
157
|
-
rmSync(backupRoot, { recursive: true, force: true });
|
|
158
|
-
copyToHistory(projectDir, "update", prompt);
|
|
159
|
-
console.log(`Updated ${name}. Run with: trama run ${name}`);
|
|
174
|
+
// Backup before any LLM calls, restore on any failure
|
|
175
|
+
await withProjectBackup(projectDir, originalHistory, historyIndexPath, async () => {
|
|
176
|
+
const systemPrompt = getSystemPrompt() +
|
|
177
|
+
`\n\nOriginal prompt: ${meta.input.prompt}` +
|
|
178
|
+
`\n\nCurrent program.ts:\n${originalSource}` +
|
|
179
|
+
(Object.keys(state).length > 0 ? `\n\nCurrent state:\n${JSON.stringify(state, null, 2)}` : "");
|
|
180
|
+
console.log(`Updating "${name}"...`);
|
|
181
|
+
const updated = stripCodeFences(await isolatedAsk(adapter, `${prompt}\n\nOutput the complete updated program.ts. No partial patches. No markdown fences. No explanation.`, { system: systemPrompt }));
|
|
182
|
+
writeFileSync(programPath, updated);
|
|
183
|
+
console.log("Validating updated program...");
|
|
184
|
+
await smokeRunAndRepair(projectDir, adapter, "update", {
|
|
185
|
+
timeout: config.defaultTimeout,
|
|
186
|
+
maxRepairAttempts: config.maxRepairAttempts,
|
|
187
|
+
maxIterations: config.defaultMaxIterations,
|
|
188
|
+
});
|
|
189
|
+
copyToHistory(projectDir, "update", prompt);
|
|
190
|
+
console.log(`Updated ${name}. Run with: trama run ${name}`);
|
|
191
|
+
});
|
|
160
192
|
}
|
|
161
193
|
export async function listProjects() {
|
|
162
194
|
const dir = projectsDir();
|
package/dist/pi-adapter.d.ts
CHANGED
|
@@ -3,10 +3,18 @@ export declare class PiAdapter {
|
|
|
3
3
|
private config;
|
|
4
4
|
private cwd;
|
|
5
5
|
constructor(config: PiAdapterConfig, cwd: string);
|
|
6
|
+
/** Create a copy of this adapter that operates in a different working directory. */
|
|
7
|
+
withCwd(cwd: string): PiAdapter;
|
|
6
8
|
private createSession;
|
|
7
9
|
private extractText;
|
|
10
|
+
/**
|
|
11
|
+
* Abort cancellation relies on session.dispose() interrupting session.prompt().
|
|
12
|
+
* This is an upstream contract of pi-coding-agent — if dispose() does not
|
|
13
|
+
* actually reject the in-flight prompt, the abort signal will not terminate the call.
|
|
14
|
+
*/
|
|
8
15
|
ask(prompt: string, options?: {
|
|
9
16
|
system?: string;
|
|
17
|
+
signal?: AbortSignal;
|
|
10
18
|
}): Promise<string>;
|
|
11
|
-
repair(input: RepairInput): Promise<string>;
|
|
19
|
+
repair(input: RepairInput, signal?: AbortSignal): Promise<string>;
|
|
12
20
|
}
|
package/dist/pi-adapter.js
CHANGED
|
@@ -7,21 +7,50 @@ export class PiAdapter {
|
|
|
7
7
|
this.config = config;
|
|
8
8
|
this.cwd = cwd;
|
|
9
9
|
}
|
|
10
|
-
|
|
10
|
+
/** Create a copy of this adapter that operates in a different working directory. */
|
|
11
|
+
withCwd(cwd) {
|
|
12
|
+
return new PiAdapter(this.config, cwd);
|
|
13
|
+
}
|
|
14
|
+
async createSession(systemPrompt, signal) {
|
|
15
|
+
if (signal?.aborted)
|
|
16
|
+
throw new Error("Aborted");
|
|
11
17
|
const resourceLoader = new DefaultResourceLoader({
|
|
12
18
|
cwd: this.cwd,
|
|
13
19
|
noExtensions: true,
|
|
14
20
|
noSkills: true,
|
|
15
21
|
...(systemPrompt && { appendSystemPrompt: systemPrompt }),
|
|
16
22
|
});
|
|
17
|
-
|
|
18
|
-
|
|
23
|
+
// Race an async step against the abort signal.
|
|
24
|
+
// Returns the result on success, or rejects with "Aborted" on abort.
|
|
25
|
+
const raceAbort = (promise) => {
|
|
26
|
+
if (!signal)
|
|
27
|
+
return promise;
|
|
28
|
+
return Promise.race([
|
|
29
|
+
promise,
|
|
30
|
+
new Promise((_resolve, reject) => {
|
|
31
|
+
signal.addEventListener("abort", () => reject(new Error("Aborted")), { once: true });
|
|
32
|
+
}),
|
|
33
|
+
]);
|
|
34
|
+
};
|
|
35
|
+
await raceAbort(resourceLoader.reload());
|
|
36
|
+
if (signal?.aborted)
|
|
37
|
+
throw new Error("Aborted");
|
|
38
|
+
// Keep a reference to the raw promise so we can clean up a late-arriving session
|
|
39
|
+
const sessionPromise = createAgentSession({
|
|
19
40
|
cwd: this.cwd,
|
|
20
41
|
model: getModel(this.config.provider, this.config.model),
|
|
21
42
|
sessionManager: SessionManager.inMemory(),
|
|
22
43
|
resourceLoader,
|
|
23
44
|
});
|
|
24
|
-
|
|
45
|
+
try {
|
|
46
|
+
const { session } = await raceAbort(sessionPromise);
|
|
47
|
+
return session;
|
|
48
|
+
}
|
|
49
|
+
catch (err) {
|
|
50
|
+
// If abort won the race, the real promise may still resolve later — dispose it
|
|
51
|
+
sessionPromise.then(({ session }) => session.dispose()).catch(() => { });
|
|
52
|
+
throw err;
|
|
53
|
+
}
|
|
25
54
|
}
|
|
26
55
|
extractText(session) {
|
|
27
56
|
const messages = session.state.messages;
|
|
@@ -36,9 +65,24 @@ export class PiAdapter {
|
|
|
36
65
|
}
|
|
37
66
|
return "";
|
|
38
67
|
}
|
|
68
|
+
/**
|
|
69
|
+
* Abort cancellation relies on session.dispose() interrupting session.prompt().
|
|
70
|
+
* This is an upstream contract of pi-coding-agent — if dispose() does not
|
|
71
|
+
* actually reject the in-flight prompt, the abort signal will not terminate the call.
|
|
72
|
+
*/
|
|
39
73
|
async ask(prompt, options) {
|
|
40
|
-
const
|
|
74
|
+
const signal = options?.signal;
|
|
75
|
+
if (signal?.aborted)
|
|
76
|
+
throw new Error("Aborted");
|
|
77
|
+
// Track session so abort can dispose it at any point — even during createSession
|
|
78
|
+
let session = null;
|
|
79
|
+
const onAbort = () => session?.dispose();
|
|
80
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
41
81
|
try {
|
|
82
|
+
session = await this.createSession(options?.system, signal);
|
|
83
|
+
// Re-check: abort may have fired during createSession (before session existed)
|
|
84
|
+
if (signal?.aborted)
|
|
85
|
+
throw new Error("Aborted");
|
|
42
86
|
await session.prompt(prompt);
|
|
43
87
|
const text = this.extractText(session);
|
|
44
88
|
if (!text)
|
|
@@ -46,14 +90,20 @@ export class PiAdapter {
|
|
|
46
90
|
return text;
|
|
47
91
|
}
|
|
48
92
|
finally {
|
|
49
|
-
|
|
93
|
+
signal?.removeEventListener("abort", onAbort);
|
|
94
|
+
session?.dispose();
|
|
50
95
|
}
|
|
51
96
|
}
|
|
52
|
-
async repair(input) {
|
|
53
|
-
|
|
97
|
+
async repair(input, signal) {
|
|
98
|
+
const response = await this.ask(`Fix this program so it runs.\n\n` +
|
|
54
99
|
`Runtime types:\n${input.runtimeTypes}\n\n` +
|
|
55
100
|
`Broken program:\n${input.programSource}\n\n` +
|
|
56
101
|
`Error:\n${input.error}\n\n` +
|
|
57
|
-
`Output ONLY the fixed program. No explanation.`, { system: "You are a TypeScript repair tool." });
|
|
102
|
+
`Output ONLY the fixed program. No explanation.`, { system: "You are a TypeScript repair tool.", signal });
|
|
103
|
+
const trimmed = response.trim();
|
|
104
|
+
if (/^```/.test(trimmed) && /```$/.test(trimmed)) {
|
|
105
|
+
return trimmed.replace(/^```\w*\s*\n?/, "").replace(/\n?\s*```$/, "");
|
|
106
|
+
}
|
|
107
|
+
return response;
|
|
58
108
|
}
|
|
59
109
|
}
|
package/dist/runner.d.ts
CHANGED
|
@@ -1,6 +1,13 @@
|
|
|
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
|
+
* Simplified API reference for LLM system prompts.
|
|
6
|
+
* NOT the canonical type definitions (those live in types.ts).
|
|
7
|
+
* Kept as a readable string rather than auto-generated, because the LLM
|
|
8
|
+
* needs a concise reference, not the full implementation types.
|
|
9
|
+
* If types.ts changes, review whether this summary needs updating.
|
|
10
|
+
*/
|
|
4
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 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;";
|
|
5
12
|
export declare function loadConfig(): TramaConfig;
|
|
6
13
|
export declare function loadState(projectDir: string): Record<string, unknown>;
|
|
@@ -11,5 +18,11 @@ export declare function loadState(projectDir: string): Record<string, unknown>;
|
|
|
11
18
|
* Create-time repairs go to index.jsonl only (reason: "create-repair").
|
|
12
19
|
*/
|
|
13
20
|
export declare function copyToHistory(projectDir: string, reason: string, detail?: string): void;
|
|
14
|
-
|
|
21
|
+
/** Run fn in a temp directory, clean up afterwards regardless of outcome. */
|
|
22
|
+
export declare function withTempDir<T>(prefix: string, fn: (dir: string) => Promise<T>): Promise<T>;
|
|
23
|
+
export declare function smokeRunAndRepair(projectDir: string, adapter: PiAdapter, reason: "create" | "update", options?: {
|
|
24
|
+
timeout?: number;
|
|
25
|
+
maxRepairAttempts?: number;
|
|
26
|
+
maxIterations?: number;
|
|
27
|
+
}): Promise<void>;
|
|
15
28
|
export declare function runProgram(options: RunOptions): Promise<void>;
|