@trama-dev/runtime 0.1.5 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/dist/agent.js +3 -3
- package/dist/child-process.d.ts +40 -0
- package/dist/child-process.js +108 -0
- package/dist/client.js +46 -99
- package/dist/context.d.ts +11 -0
- package/dist/context.js +48 -62
- package/dist/index.d.ts +3 -1
- package/dist/index.js +36 -59
- package/dist/ipc-server.d.ts +22 -0
- package/dist/ipc-server.js +168 -0
- package/dist/path-guard.d.ts +16 -26
- package/dist/path-guard.js +42 -37
- package/dist/pi-adapter.d.ts +11 -2
- package/dist/pi-adapter.js +49 -6
- package/dist/runner-types.d.ts +29 -0
- package/dist/runner-types.js +3 -0
- package/dist/runner.d.ts +46 -35
- package/dist/runner.js +369 -897
- package/dist/tools.d.ts +3 -5
- package/dist/tools.js +70 -166
- package/dist/types.d.ts +2 -43
- package/dist/types.js +4 -1
- package/dist/workspace.js +76 -124
- package/package.json +6 -4
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@ The runtime behind [trama](https://github.com/NaNhkNaN/trama) — execution, sta
|
|
|
6
6
|
|
|
7
7
|
## Two surfaces
|
|
8
8
|
|
|
9
|
-
**Client** — what trama
|
|
9
|
+
**Client** — what trama programs import. Four objects: `ctx`, `agent`, `tools`, and — inside a session — `workspace`.
|
|
10
10
|
|
|
11
11
|
```typescript
|
|
12
12
|
import { ctx, agent, tools } from "@trama-dev/runtime";
|
|
@@ -17,7 +17,7 @@ await tools.write("report.md", report);
|
|
|
17
17
|
await ctx.done();
|
|
18
18
|
```
|
|
19
19
|
|
|
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.
|
|
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. `workspace` reads, writes and observes artifacts shared between the programs of a session.
|
|
21
21
|
|
|
22
22
|
**Runner** — what the CLI and programmatic callers use to create and execute programs.
|
|
23
23
|
|
|
@@ -30,9 +30,9 @@ import { createProject, runProgram, updateProject } from "@trama-dev/runtime/run
|
|
|
30
30
|
The runtime is what makes agent programs **self-contained and shareable**:
|
|
31
31
|
|
|
32
32
|
- **Execution** — child process spawning, streaming output, timeout management, background process cleanup.
|
|
33
|
-
- **IPC bridge** — local HTTP server
|
|
33
|
+
- **IPC bridge** — a local HTTP server that every `ctx`, `agent`, `tools` and `workspace` call goes through: one point where the runtime validates each request and can cancel work in flight when a run ends.
|
|
34
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
|
|
35
|
+
- **Auto-repair** — on crash, the runtime gets an LLM fix and runs it under snapshot protection, rolling the project back if the fix fails too. Up to 3 attempts.
|
|
36
36
|
- **Version history** — every create, update, and repair saves a snapshot to `history/`.
|
|
37
37
|
- **Scaffolding** — package.json, module symlinks, gitignore, logs. `git clone && trama run` just works.
|
|
38
38
|
|
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);
|
|
25
24
|
return {
|
|
26
|
-
instruct
|
|
27
|
-
|
|
25
|
+
async instruct(prompt, options) {
|
|
26
|
+
return adapter.ask(prompt, signal ? { ...options, signal } : options);
|
|
27
|
+
},
|
|
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}`;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { ChildProcess } from "child_process";
|
|
2
|
+
/** A string accumulator that stops growing (and says so) once it passes 10MB. */
|
|
3
|
+
export declare function cappedBuffer(): {
|
|
4
|
+
append(text: string): void;
|
|
5
|
+
readonly value: string;
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* Send a signal to a whole process group. Children spawned with `detached: true`
|
|
9
|
+
* lead their own group, so this also reaches whatever they started in the background.
|
|
10
|
+
* Signal 0 only probes. Returns false if the group no longer exists.
|
|
11
|
+
*/
|
|
12
|
+
export declare function signalGroup(pgid: number, signal: NodeJS.Signals | 0): boolean;
|
|
13
|
+
export interface SuperviseOptions {
|
|
14
|
+
/** Wall-clock limit in ms. On expiry the child's process group is terminated. */
|
|
15
|
+
timeout: number;
|
|
16
|
+
/** Receive output as it arrives, in addition to it being collected. */
|
|
17
|
+
sinks?: {
|
|
18
|
+
stdout?: (chunk: string) => void;
|
|
19
|
+
stderr?: (chunk: string) => void;
|
|
20
|
+
};
|
|
21
|
+
/** Aborting this asks the child to stop (same SIGTERM → SIGKILL sequence as a timeout). */
|
|
22
|
+
stopSignal?: AbortSignal;
|
|
23
|
+
}
|
|
24
|
+
export interface ChildExit {
|
|
25
|
+
code: number | null;
|
|
26
|
+
signal: NodeJS.Signals | null;
|
|
27
|
+
stdout: string;
|
|
28
|
+
stderr: string;
|
|
29
|
+
/** The timeout expired and the child was killed for it. */
|
|
30
|
+
timedOut: boolean;
|
|
31
|
+
/** `stopSignal` fired while the child was still running. */
|
|
32
|
+
stopped: boolean;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Collect a child's output and wait for it to exit, enforcing a wall-clock
|
|
36
|
+
* timeout and an optional stop request. Termination is SIGTERM to the child's
|
|
37
|
+
* process group, then SIGKILL if it is still alive after a grace period.
|
|
38
|
+
* Resolves on exit however it happened; rejects only if the child failed to spawn.
|
|
39
|
+
*/
|
|
40
|
+
export declare function superviseChild(child: ChildProcess, options: SuperviseOptions): Promise<ChildExit>;
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { StringDecoder } from "string_decoder";
|
|
2
|
+
const MAX_OUTPUT = 10 * 1024 * 1024; // 10 MB
|
|
3
|
+
/** How long a child gets to exit after SIGTERM before it is sent SIGKILL. */
|
|
4
|
+
const KILL_GRACE_MS = 5000;
|
|
5
|
+
/** A string accumulator that stops growing (and says so) once it passes 10MB. */
|
|
6
|
+
export function cappedBuffer() {
|
|
7
|
+
let buf = "";
|
|
8
|
+
let capped = false;
|
|
9
|
+
return {
|
|
10
|
+
append(text) {
|
|
11
|
+
if (capped)
|
|
12
|
+
return;
|
|
13
|
+
buf += text;
|
|
14
|
+
if (buf.length > MAX_OUTPUT) {
|
|
15
|
+
buf = buf.slice(0, MAX_OUTPUT) + "\n[trama] output truncated at 10MB";
|
|
16
|
+
capped = true;
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
get value() { return buf; },
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Send a signal to a whole process group. Children spawned with `detached: true`
|
|
24
|
+
* lead their own group, so this also reaches whatever they started in the background.
|
|
25
|
+
* Signal 0 only probes. Returns false if the group no longer exists.
|
|
26
|
+
*/
|
|
27
|
+
export function signalGroup(pgid, signal) {
|
|
28
|
+
try {
|
|
29
|
+
process.kill(-pgid, signal);
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Collect a child's output and wait for it to exit, enforcing a wall-clock
|
|
38
|
+
* timeout and an optional stop request. Termination is SIGTERM to the child's
|
|
39
|
+
* process group, then SIGKILL if it is still alive after a grace period.
|
|
40
|
+
* Resolves on exit however it happened; rejects only if the child failed to spawn.
|
|
41
|
+
*/
|
|
42
|
+
export function superviseChild(child, options) {
|
|
43
|
+
const { timeout, sinks, stopSignal } = options;
|
|
44
|
+
return new Promise((resolve, reject) => {
|
|
45
|
+
const out = cappedBuffer();
|
|
46
|
+
const err = cappedBuffer();
|
|
47
|
+
const outDecoder = new StringDecoder("utf-8");
|
|
48
|
+
const errDecoder = new StringDecoder("utf-8");
|
|
49
|
+
let timedOut = false;
|
|
50
|
+
let stopped = false;
|
|
51
|
+
let exited = false;
|
|
52
|
+
let killFallbackTimer = null;
|
|
53
|
+
const emitOut = (text) => { if (text) {
|
|
54
|
+
out.append(text);
|
|
55
|
+
sinks?.stdout?.(text);
|
|
56
|
+
} };
|
|
57
|
+
const emitErr = (text) => { if (text) {
|
|
58
|
+
err.append(text);
|
|
59
|
+
sinks?.stderr?.(text);
|
|
60
|
+
} };
|
|
61
|
+
const kill = (sig) => {
|
|
62
|
+
if (child.pid)
|
|
63
|
+
signalGroup(child.pid, sig);
|
|
64
|
+
else
|
|
65
|
+
child.kill(sig);
|
|
66
|
+
};
|
|
67
|
+
const terminate = () => {
|
|
68
|
+
kill("SIGTERM");
|
|
69
|
+
if (killFallbackTimer)
|
|
70
|
+
clearTimeout(killFallbackTimer);
|
|
71
|
+
killFallbackTimer = setTimeout(() => { if (!exited)
|
|
72
|
+
kill("SIGKILL"); }, KILL_GRACE_MS);
|
|
73
|
+
killFallbackTimer.unref();
|
|
74
|
+
};
|
|
75
|
+
const onStopRequest = () => {
|
|
76
|
+
if (exited || stopped || timedOut)
|
|
77
|
+
return;
|
|
78
|
+
stopped = true;
|
|
79
|
+
terminate();
|
|
80
|
+
};
|
|
81
|
+
stopSignal?.addEventListener("abort", onStopRequest, { once: true });
|
|
82
|
+
const timer = setTimeout(() => {
|
|
83
|
+
if (exited)
|
|
84
|
+
return;
|
|
85
|
+
timedOut = true;
|
|
86
|
+
terminate();
|
|
87
|
+
}, timeout);
|
|
88
|
+
const cleanup = () => {
|
|
89
|
+
clearTimeout(timer);
|
|
90
|
+
if (killFallbackTimer)
|
|
91
|
+
clearTimeout(killFallbackTimer);
|
|
92
|
+
stopSignal?.removeEventListener("abort", onStopRequest);
|
|
93
|
+
};
|
|
94
|
+
child.stdout?.on("data", (chunk) => emitOut(outDecoder.write(chunk)));
|
|
95
|
+
child.stderr?.on("data", (chunk) => emitErr(errDecoder.write(chunk)));
|
|
96
|
+
child.on("error", (spawnError) => {
|
|
97
|
+
cleanup();
|
|
98
|
+
reject(spawnError);
|
|
99
|
+
});
|
|
100
|
+
child.on("close", (code, signal) => {
|
|
101
|
+
exited = true;
|
|
102
|
+
cleanup();
|
|
103
|
+
emitOut(outDecoder.end());
|
|
104
|
+
emitErr(errDecoder.end());
|
|
105
|
+
resolve({ code, signal, stdout: out.value, stderr: err.value, timedOut, stopped });
|
|
106
|
+
});
|
|
107
|
+
});
|
|
108
|
+
}
|
package/dist/client.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// @trama-dev/runtime client — this is what program.ts imports.
|
|
2
|
-
//
|
|
2
|
+
// A thin wrapper that forwards every call to the runner's IPC server
|
|
3
|
+
// (ipc-server.ts), which does the real work.
|
|
3
4
|
import { readFileSync } from "fs";
|
|
4
5
|
import { assertSerializable } from "./serializable.js";
|
|
5
6
|
const PORT = process.env.TRAMA_PORT;
|
|
@@ -14,134 +15,80 @@ if (!INIT_PATH) {
|
|
|
14
15
|
}
|
|
15
16
|
const BASE = `http://127.0.0.1:${PORT}`;
|
|
16
17
|
const initData = JSON.parse(readFileSync(INIT_PATH, "utf-8"));
|
|
18
|
+
/** POST one call to the runner and return its result. */
|
|
17
19
|
async function call(endpoint, body) {
|
|
18
20
|
const res = await fetch(`${BASE}${endpoint}`, {
|
|
19
21
|
method: "POST",
|
|
20
|
-
headers: { "Content-Type": "application/json" },
|
|
22
|
+
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${initData.token}` },
|
|
21
23
|
body: JSON.stringify(body),
|
|
22
24
|
});
|
|
23
25
|
if (!res.ok)
|
|
24
26
|
throw new Error(`trama runtime error: ${await res.text()}`);
|
|
25
|
-
return res.json();
|
|
27
|
+
return (await res.json()).result;
|
|
26
28
|
}
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
29
|
+
/** Log payloads are best-effort: anything that can't be sent as JSON is replaced by its string form. */
|
|
30
|
+
function sendable(data) {
|
|
31
|
+
try {
|
|
32
|
+
JSON.stringify(data);
|
|
33
|
+
return data;
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return { __trama_unserializable: String(data) };
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
// The lifecycle rules (ready once, done once, done and yield mutually exclusive)
|
|
40
|
+
// are enforced by the runner. Here each call is checked for what only this
|
|
41
|
+
// process can see — whether the values survive JSON — and then forwarded.
|
|
30
42
|
export const ctx = {
|
|
31
43
|
input: initData.input,
|
|
32
44
|
state: initData.state,
|
|
33
45
|
iteration: initData.iteration,
|
|
34
46
|
maxIterations: initData.maxIterations,
|
|
35
|
-
resumed: initData.resumed
|
|
36
|
-
yieldReason: initData.yieldReason
|
|
47
|
+
resumed: initData.resumed,
|
|
48
|
+
yieldReason: initData.yieldReason,
|
|
37
49
|
async log(msg, data) {
|
|
38
|
-
|
|
39
|
-
try {
|
|
40
|
-
JSON.stringify(safeData);
|
|
41
|
-
}
|
|
42
|
-
catch {
|
|
43
|
-
safeData = { __trama_unserializable: String(data) };
|
|
44
|
-
}
|
|
45
|
-
await call("/ctx/log", { message: msg, data: safeData });
|
|
50
|
+
await call("/ctx/log", { message: msg, data: sendable(data) });
|
|
46
51
|
},
|
|
47
52
|
async ready(data) {
|
|
48
|
-
|
|
49
|
-
return;
|
|
50
|
-
let safeData = data;
|
|
51
|
-
try {
|
|
52
|
-
JSON.stringify(safeData);
|
|
53
|
-
}
|
|
54
|
-
catch {
|
|
55
|
-
safeData = { __trama_unserializable: String(data) };
|
|
56
|
-
}
|
|
57
|
-
await call("/ctx/ready", { data: safeData });
|
|
58
|
-
readyCalled = true;
|
|
53
|
+
await call("/ctx/ready", { data: sendable(data) });
|
|
59
54
|
},
|
|
60
55
|
async checkpoint() {
|
|
61
56
|
assertSerializable(ctx.state, "ctx.state");
|
|
62
|
-
await call("/ctx/checkpoint", { state: ctx.state });
|
|
63
|
-
ctx.iteration += 1;
|
|
57
|
+
ctx.iteration = await call("/ctx/checkpoint", { state: ctx.state });
|
|
64
58
|
},
|
|
65
59
|
async done(result) {
|
|
66
|
-
|
|
67
|
-
if (
|
|
68
|
-
|
|
69
|
-
}
|
|
70
|
-
// If a previous done() completed or is in flight, coalesce onto it.
|
|
71
|
-
// If a previous done() failed, allow retry (promise was cleared).
|
|
72
|
-
if (donePromise)
|
|
73
|
-
return donePromise;
|
|
74
|
-
terminalSignal = "done";
|
|
75
|
-
const run = async () => {
|
|
76
|
-
assertSerializable(ctx.state, "ctx.state");
|
|
77
|
-
if (result !== undefined)
|
|
78
|
-
assertSerializable(result, "ctx.done(result)");
|
|
79
|
-
await call("/ctx/done", { state: ctx.state, result });
|
|
80
|
-
ctx.iteration += 1;
|
|
81
|
-
};
|
|
82
|
-
donePromise = run();
|
|
83
|
-
try {
|
|
84
|
-
await donePromise;
|
|
85
|
-
}
|
|
86
|
-
catch (err) {
|
|
87
|
-
donePromise = null;
|
|
88
|
-
throw err;
|
|
89
|
-
}
|
|
60
|
+
assertSerializable(ctx.state, "ctx.state");
|
|
61
|
+
if (result !== undefined)
|
|
62
|
+
assertSerializable(result, "ctx.done(result)");
|
|
63
|
+
ctx.iteration = await call("/ctx/done", { state: ctx.state, result });
|
|
90
64
|
},
|
|
91
65
|
async yield(reason) {
|
|
92
|
-
// Mutual exclusivity: done() was already called
|
|
93
|
-
if (terminalSignal === "done") {
|
|
94
|
-
throw new Error("Cannot call ctx.yield() after ctx.done() — done already signaled.");
|
|
95
|
-
}
|
|
96
|
-
// Idempotent: second yield after successful persistence is a no-op
|
|
97
|
-
if (terminalSignal === "yielded") {
|
|
98
|
-
process.exit(0);
|
|
99
|
-
}
|
|
100
66
|
assertSerializable(ctx.state, "ctx.state");
|
|
101
|
-
// Set terminalSignal only after validation and HTTP call succeed,
|
|
102
|
-
// so a failed yield can be retried (mirrors done()'s retry pattern).
|
|
103
67
|
await call("/ctx/yield", { state: ctx.state, reason });
|
|
104
|
-
|
|
105
|
-
// Structured exit — the runner detects the yield marker in state.json
|
|
68
|
+
// The runner has recorded the yield; suspending means ending this process.
|
|
106
69
|
process.exit(0);
|
|
107
70
|
},
|
|
108
71
|
};
|
|
109
|
-
const instructImpl = (prompt, opts) => call("/agent/ask", { prompt, ...opts }).then(r => r.result);
|
|
110
72
|
export const agent = {
|
|
111
|
-
instruct:
|
|
112
|
-
|
|
113
|
-
generate: (input) => call("/agent/generate", input).then(r => r.result),
|
|
73
|
+
instruct: (prompt, opts) => call("/agent/instruct", { prompt, ...opts }),
|
|
74
|
+
generate: (input) => call("/agent/generate", input),
|
|
114
75
|
};
|
|
115
76
|
export const tools = {
|
|
116
|
-
read: (path) => call("/tools/read", { path })
|
|
117
|
-
write: (path, content) => call("/tools/write", { path, content })
|
|
118
|
-
shell: (cmd, opts) => call("/tools/shell", { command: cmd, ...opts })
|
|
119
|
-
fetch: (url, opts) => call("/tools/fetch", { url, ...opts })
|
|
77
|
+
read: (path) => call("/tools/read", { path }),
|
|
78
|
+
write: (path, content) => call("/tools/write", { path, content }),
|
|
79
|
+
shell: (cmd, opts) => call("/tools/shell", { command: cmd, ...opts }),
|
|
80
|
+
fetch: (url, opts) => call("/tools/fetch", { url, ...opts }),
|
|
120
81
|
};
|
|
121
|
-
|
|
122
|
-
function
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
};
|
|
128
|
-
return {
|
|
129
|
-
async read(path) {
|
|
130
|
-
throwIfNoWorkspace();
|
|
131
|
-
return call("/workspace/read", { path }).then(r => r.result);
|
|
132
|
-
},
|
|
133
|
-
async write(path, content) {
|
|
134
|
-
throwIfNoWorkspace();
|
|
135
|
-
return call("/workspace/write", { path, content }).then(r => r.result);
|
|
136
|
-
},
|
|
137
|
-
async list(pattern) {
|
|
138
|
-
throwIfNoWorkspace();
|
|
139
|
-
return call("/workspace/list", { pattern }).then(r => r.result);
|
|
140
|
-
},
|
|
141
|
-
async observe(pattern, options) {
|
|
142
|
-
throwIfNoWorkspace();
|
|
143
|
-
return call("/workspace/observe", { pattern, ...options }).then(r => r.result);
|
|
144
|
-
},
|
|
145
|
-
};
|
|
82
|
+
/** workspace.* exists only inside a session — everywhere else it fails clearly, without a round trip. */
|
|
83
|
+
async function workspaceCall(endpoint, body) {
|
|
84
|
+
if (!initData.workspace) {
|
|
85
|
+
throw new Error("workspace is only available when running in a session");
|
|
86
|
+
}
|
|
87
|
+
return call(endpoint, body);
|
|
146
88
|
}
|
|
147
|
-
export const workspace =
|
|
89
|
+
export const workspace = {
|
|
90
|
+
read: (path) => workspaceCall("/workspace/read", { path }),
|
|
91
|
+
write: (path, content) => workspaceCall("/workspace/write", { path, content }),
|
|
92
|
+
list: (pattern) => workspaceCall("/workspace/list", { pattern }),
|
|
93
|
+
observe: (pattern, options) => workspaceCall("/workspace/observe", { pattern, ...options }),
|
|
94
|
+
};
|
package/dist/context.d.ts
CHANGED
|
@@ -1,4 +1,15 @@
|
|
|
1
1
|
import type { Ctx } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* The runner-side ctx: owns state.json and the run log for one run of a
|
|
4
|
+
* program. The program's own `ctx` (client.ts) forwards to this over IPC.
|
|
5
|
+
*
|
|
6
|
+
* This is the one place the ctx lifecycle rules are enforced (ready once,
|
|
7
|
+
* done once, done and yield mutually exclusive) — the client only forwards.
|
|
8
|
+
*
|
|
9
|
+
* Bookkeeping lives in ctx.state under reserved `__trama_*` keys:
|
|
10
|
+
* `__trama_iteration` (progress counter) and `__trama_yield` (set while the
|
|
11
|
+
* program is suspended, cleared when it next advances).
|
|
12
|
+
*/
|
|
2
13
|
export declare function createContext(projectDir: string, initialState: Record<string, unknown>, options?: {
|
|
3
14
|
maxIterations?: number;
|
|
4
15
|
argsOverride?: Record<string, unknown>;
|
package/dist/context.js
CHANGED
|
@@ -2,32 +2,45 @@ import { readFileSync, writeFileSync, appendFileSync } from "fs";
|
|
|
2
2
|
import { join } from "path";
|
|
3
3
|
import { assertSerializable } from "./serializable.js";
|
|
4
4
|
import { guardPath } from "./path-guard.js";
|
|
5
|
+
/**
|
|
6
|
+
* The runner-side ctx: owns state.json and the run log for one run of a
|
|
7
|
+
* program. The program's own `ctx` (client.ts) forwards to this over IPC.
|
|
8
|
+
*
|
|
9
|
+
* This is the one place the ctx lifecycle rules are enforced (ready once,
|
|
10
|
+
* done once, done and yield mutually exclusive) — the client only forwards.
|
|
11
|
+
*
|
|
12
|
+
* Bookkeeping lives in ctx.state under reserved `__trama_*` keys:
|
|
13
|
+
* `__trama_iteration` (progress counter) and `__trama_yield` (set while the
|
|
14
|
+
* program is suspended, cleared when it next advances).
|
|
15
|
+
*/
|
|
5
16
|
export function createContext(projectDir, initialState, options) {
|
|
6
17
|
const logsPath = guardPath(projectDir, join("logs", "latest.jsonl"));
|
|
7
18
|
const statePath = guardPath(projectDir, "state.json");
|
|
8
19
|
const meta = JSON.parse(readFileSync(guardPath(projectDir, "meta.json"), "utf-8"));
|
|
9
20
|
let donePromise = null;
|
|
10
|
-
let doneLogged = false;
|
|
11
21
|
let readyCalled = false;
|
|
12
|
-
// Track terminal signal: null, "done", or "yielded"
|
|
13
22
|
let terminalSignal = null;
|
|
14
23
|
const input = options?.argsOverride
|
|
15
24
|
? { ...meta.input, args: { ...(meta.input.args ?? {}), ...options.argsOverride } }
|
|
16
25
|
: meta.input;
|
|
17
|
-
//
|
|
26
|
+
// A yield marker left by the previous run means this run is its resumption.
|
|
18
27
|
const yieldMarker = initialState.__trama_yield;
|
|
19
|
-
const
|
|
20
|
-
|
|
28
|
+
const savedIteration = initialState.__trama_iteration;
|
|
29
|
+
/** Write ctx.state to disk and advance the iteration counter. */
|
|
30
|
+
const persist = (ctx) => {
|
|
31
|
+
const nextIteration = ctx.iteration + 1;
|
|
32
|
+
ctx.state.__trama_iteration = nextIteration;
|
|
33
|
+
writeFileSync(statePath, JSON.stringify(ctx.state, null, 2));
|
|
34
|
+
ctx.iteration = nextIteration;
|
|
35
|
+
};
|
|
21
36
|
return {
|
|
22
37
|
input,
|
|
23
38
|
state: { ...initialState },
|
|
24
|
-
iteration: typeof
|
|
25
|
-
|
|
26
|
-
&& initialState.__trama_iteration >= 0
|
|
27
|
-
? initialState.__trama_iteration : 0,
|
|
39
|
+
iteration: typeof savedIteration === "number" && Number.isInteger(savedIteration) && savedIteration >= 0
|
|
40
|
+
? savedIteration : 0,
|
|
28
41
|
maxIterations: options?.maxIterations ?? 100,
|
|
29
|
-
resumed,
|
|
30
|
-
yieldReason,
|
|
42
|
+
resumed: yieldMarker != null,
|
|
43
|
+
yieldReason: yieldMarker?.reason ?? null,
|
|
31
44
|
async log(message, data) {
|
|
32
45
|
let safeData = data ?? null;
|
|
33
46
|
try {
|
|
@@ -49,83 +62,56 @@ export function createContext(projectDir, initialState, options) {
|
|
|
49
62
|
},
|
|
50
63
|
async checkpoint() {
|
|
51
64
|
assertSerializable(this.state, "ctx.state");
|
|
52
|
-
//
|
|
53
|
-
|
|
54
|
-
const nextIteration = this.iteration + 1;
|
|
55
|
-
this.state.__trama_iteration = nextIteration;
|
|
56
|
-
writeFileSync(statePath, JSON.stringify(this.state, null, 2));
|
|
57
|
-
this.iteration = nextIteration;
|
|
65
|
+
delete this.state.__trama_yield; // the program has moved on from its last yield
|
|
66
|
+
persist(this);
|
|
58
67
|
},
|
|
59
68
|
async done(result) {
|
|
60
|
-
// Mutual exclusivity: yield() was already called
|
|
61
69
|
if (terminalSignal === "yielded") {
|
|
62
70
|
throw new Error("Cannot call ctx.done() after ctx.yield() — yield already signaled.");
|
|
63
71
|
}
|
|
64
|
-
//
|
|
65
|
-
// If a previous done() is still in flight, coalesce onto it.
|
|
66
|
-
// If a previous done() failed (checkpoint threw), allow retry.
|
|
72
|
+
// A completed done() is a no-op; one still in flight is shared.
|
|
67
73
|
if (donePromise)
|
|
68
74
|
return donePromise;
|
|
75
|
+
// Claimed while in flight so a yield() cannot slip in alongside it.
|
|
69
76
|
terminalSignal = "done";
|
|
70
77
|
const run = async () => {
|
|
71
|
-
// Persist first — this is the critical action
|
|
72
|
-
this.state.__trama_done = { result: result ?? null };
|
|
73
|
-
// Clear any stale yield marker
|
|
74
|
-
delete this.state.__trama_yield;
|
|
75
78
|
await this.checkpoint();
|
|
76
|
-
//
|
|
77
|
-
//
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
try {
|
|
81
|
-
await this.log("done", result);
|
|
82
|
-
}
|
|
83
|
-
catch { /* best-effort */ }
|
|
84
|
-
doneLogged = true;
|
|
79
|
+
// Persistence is the critical part; a log failure must not turn a
|
|
80
|
+
// completed done() into an error.
|
|
81
|
+
try {
|
|
82
|
+
await this.log("done", result);
|
|
85
83
|
}
|
|
84
|
+
catch { /* best-effort */ }
|
|
86
85
|
};
|
|
87
86
|
donePromise = run();
|
|
88
87
|
try {
|
|
89
88
|
await donePromise;
|
|
90
89
|
}
|
|
91
90
|
catch (err) {
|
|
92
|
-
//
|
|
91
|
+
// Nothing was persisted, so nothing is settled: done() or yield() may be called again.
|
|
93
92
|
donePromise = null;
|
|
93
|
+
terminalSignal = null;
|
|
94
94
|
throw err;
|
|
95
95
|
}
|
|
96
96
|
},
|
|
97
97
|
async yield(reason) {
|
|
98
|
-
// Mutual exclusivity: done() was already called
|
|
99
98
|
if (terminalSignal === "done") {
|
|
100
99
|
throw new Error("Cannot call ctx.yield() after ctx.done() — done already signaled.");
|
|
101
100
|
}
|
|
102
|
-
//
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
this.state.__trama_iteration = nextIteration;
|
|
115
|
-
writeFileSync(statePath, JSON.stringify(this.state, null, 2));
|
|
116
|
-
// Set terminalSignal only after persistence succeeds,
|
|
117
|
-
// so a failed yield can be retried (mirrors done()'s pattern).
|
|
118
|
-
terminalSignal = "yielded";
|
|
119
|
-
// Log is best-effort: the critical action (state persistence) already
|
|
120
|
-
// succeeded. A log failure must not prevent the IPC handler from
|
|
121
|
-
// acknowledging the yield to the signal tracker.
|
|
122
|
-
try {
|
|
123
|
-
await this.log("yield", { reason });
|
|
101
|
+
// The client exits the process after its first successful yield; here a
|
|
102
|
+
// repeated call is simply a no-op.
|
|
103
|
+
if (terminalSignal !== "yielded") {
|
|
104
|
+
assertSerializable(this.state, "ctx.state");
|
|
105
|
+
this.state.__trama_yield = { reason };
|
|
106
|
+
persist(this);
|
|
107
|
+
// Settled only once persisted — a failed yield() leaves done() and yield() both open.
|
|
108
|
+
terminalSignal = "yielded";
|
|
109
|
+
try {
|
|
110
|
+
await this.log("yield", { reason });
|
|
111
|
+
}
|
|
112
|
+
catch { /* best-effort */ }
|
|
124
113
|
}
|
|
125
|
-
|
|
126
|
-
// In IPC mode, the client handles process.exit(0).
|
|
127
|
-
// Return never — the caller (IPC handler) responds to the client,
|
|
128
|
-
// and the client exits the child process.
|
|
114
|
+
// Exiting is the client's job: this returns so the IPC handler can answer first.
|
|
129
115
|
return undefined;
|
|
130
116
|
},
|
|
131
117
|
};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
export { runProgram } from "./runner.js";
|
|
2
|
-
export
|
|
2
|
+
export { createWorkspace } from "./workspace.js";
|
|
3
|
+
export type { ProgramResult, RunOptions } from "./runner-types.js";
|
|
4
|
+
export type { Workspace, ObserveResult } from "./types.js";
|
|
3
5
|
export declare function validateProjectName(name: string): void;
|
|
4
6
|
export declare function resolveProject(name: string): string;
|
|
5
7
|
export declare function createProject(name: string, prompt: string, options?: {
|