@trama-dev/runtime 0.1.4 → 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.d.ts +2 -1
- package/dist/client.js +52 -53
- package/dist/context.d.ts +11 -0
- package/dist/context.js +62 -17
- package/dist/index.d.ts +3 -0
- package/dist/index.js +39 -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 +58 -21
- package/dist/runner.js +426 -674
- package/dist/tools.d.ts +3 -5
- package/dist/tools.js +70 -166
- package/dist/types.d.ts +35 -29
- package/dist/types.js +4 -1
- package/dist/workspace.d.ts +2 -0
- package/dist/workspace.js +209 -0
- 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.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import type { Ctx, Agent, Tools } from "./types.js";
|
|
1
|
+
import type { Ctx, Agent, Tools, Workspace } from "./types.js";
|
|
2
2
|
export declare const ctx: Ctx;
|
|
3
3
|
export declare const agent: Agent;
|
|
4
4
|
export declare const tools: Tools;
|
|
5
|
+
export declare const workspace: Workspace;
|
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,82 +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
|
+
/** 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.
|
|
29
42
|
export const ctx = {
|
|
30
43
|
input: initData.input,
|
|
31
44
|
state: initData.state,
|
|
32
45
|
iteration: initData.iteration,
|
|
33
46
|
maxIterations: initData.maxIterations,
|
|
47
|
+
resumed: initData.resumed,
|
|
48
|
+
yieldReason: initData.yieldReason,
|
|
34
49
|
async log(msg, data) {
|
|
35
|
-
|
|
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 });
|
|
50
|
+
await call("/ctx/log", { message: msg, data: sendable(data) });
|
|
43
51
|
},
|
|
44
52
|
async ready(data) {
|
|
45
|
-
|
|
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;
|
|
53
|
+
await call("/ctx/ready", { data: sendable(data) });
|
|
56
54
|
},
|
|
57
55
|
async checkpoint() {
|
|
58
56
|
assertSerializable(ctx.state, "ctx.state");
|
|
59
|
-
await call("/ctx/checkpoint", { state: ctx.state });
|
|
60
|
-
ctx.iteration += 1;
|
|
57
|
+
ctx.iteration = await call("/ctx/checkpoint", { state: ctx.state });
|
|
61
58
|
},
|
|
62
59
|
async done(result) {
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
};
|
|
74
|
-
donePromise = run();
|
|
75
|
-
try {
|
|
76
|
-
await donePromise;
|
|
77
|
-
}
|
|
78
|
-
catch (err) {
|
|
79
|
-
donePromise = null;
|
|
80
|
-
throw err;
|
|
81
|
-
}
|
|
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 });
|
|
64
|
+
},
|
|
65
|
+
async yield(reason) {
|
|
66
|
+
assertSerializable(ctx.state, "ctx.state");
|
|
67
|
+
await call("/ctx/yield", { state: ctx.state, reason });
|
|
68
|
+
// The runner has recorded the yield; suspending means ending this process.
|
|
69
|
+
process.exit(0);
|
|
82
70
|
},
|
|
83
71
|
};
|
|
84
|
-
const instructImpl = (prompt, opts) => call("/agent/ask", { prompt, ...opts }).then(r => r.result);
|
|
85
72
|
export const agent = {
|
|
86
|
-
instruct:
|
|
87
|
-
|
|
88
|
-
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),
|
|
89
75
|
};
|
|
90
76
|
export const tools = {
|
|
91
|
-
read: (path) => call("/tools/read", { path })
|
|
92
|
-
write: (path, content) => call("/tools/write", { path, content })
|
|
93
|
-
shell: (cmd, opts) => call("/tools/shell", { command: cmd, ...opts })
|
|
94
|
-
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 }),
|
|
81
|
+
};
|
|
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);
|
|
88
|
+
}
|
|
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 }),
|
|
95
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,24 +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;
|
|
22
|
+
let terminalSignal = null;
|
|
12
23
|
const input = options?.argsOverride
|
|
13
24
|
? { ...meta.input, args: { ...(meta.input.args ?? {}), ...options.argsOverride } }
|
|
14
25
|
: meta.input;
|
|
26
|
+
// A yield marker left by the previous run means this run is its resumption.
|
|
27
|
+
const yieldMarker = initialState.__trama_yield;
|
|
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
|
+
};
|
|
15
36
|
return {
|
|
16
37
|
input,
|
|
17
38
|
state: { ...initialState },
|
|
18
|
-
iteration: typeof
|
|
19
|
-
|
|
20
|
-
&& initialState.__trama_iteration >= 0
|
|
21
|
-
? initialState.__trama_iteration : 0,
|
|
39
|
+
iteration: typeof savedIteration === "number" && Number.isInteger(savedIteration) && savedIteration >= 0
|
|
40
|
+
? savedIteration : 0,
|
|
22
41
|
maxIterations: options?.maxIterations ?? 100,
|
|
42
|
+
resumed: yieldMarker != null,
|
|
43
|
+
yieldReason: yieldMarker?.reason ?? null,
|
|
23
44
|
async log(message, data) {
|
|
24
45
|
let safeData = data ?? null;
|
|
25
46
|
try {
|
|
@@ -41,33 +62,57 @@ export function createContext(projectDir, initialState, options) {
|
|
|
41
62
|
},
|
|
42
63
|
async checkpoint() {
|
|
43
64
|
assertSerializable(this.state, "ctx.state");
|
|
44
|
-
|
|
45
|
-
this
|
|
46
|
-
writeFileSync(statePath, JSON.stringify(this.state, null, 2));
|
|
47
|
-
this.iteration = nextIteration;
|
|
65
|
+
delete this.state.__trama_yield; // the program has moved on from its last yield
|
|
66
|
+
persist(this);
|
|
48
67
|
},
|
|
49
68
|
async done(result) {
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
69
|
+
if (terminalSignal === "yielded") {
|
|
70
|
+
throw new Error("Cannot call ctx.done() after ctx.yield() — yield already signaled.");
|
|
71
|
+
}
|
|
72
|
+
// A completed done() is a no-op; one still in flight is shared.
|
|
53
73
|
if (donePromise)
|
|
54
74
|
return donePromise;
|
|
75
|
+
// Claimed while in flight so a yield() cannot slip in alongside it.
|
|
76
|
+
terminalSignal = "done";
|
|
55
77
|
const run = async () => {
|
|
56
|
-
|
|
78
|
+
await this.checkpoint();
|
|
79
|
+
// Persistence is the critical part; a log failure must not turn a
|
|
80
|
+
// completed done() into an error.
|
|
81
|
+
try {
|
|
57
82
|
await this.log("done", result);
|
|
58
83
|
}
|
|
59
|
-
|
|
60
|
-
doneLogged = true;
|
|
84
|
+
catch { /* best-effort */ }
|
|
61
85
|
};
|
|
62
86
|
donePromise = run();
|
|
63
87
|
try {
|
|
64
88
|
await donePromise;
|
|
65
89
|
}
|
|
66
90
|
catch (err) {
|
|
67
|
-
//
|
|
91
|
+
// Nothing was persisted, so nothing is settled: done() or yield() may be called again.
|
|
68
92
|
donePromise = null;
|
|
93
|
+
terminalSignal = null;
|
|
69
94
|
throw err;
|
|
70
95
|
}
|
|
71
|
-
}
|
|
96
|
+
},
|
|
97
|
+
async yield(reason) {
|
|
98
|
+
if (terminalSignal === "done") {
|
|
99
|
+
throw new Error("Cannot call ctx.yield() after ctx.done() — done already signaled.");
|
|
100
|
+
}
|
|
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 */ }
|
|
113
|
+
}
|
|
114
|
+
// Exiting is the client's job: this returns so the IPC handler can answer first.
|
|
115
|
+
return undefined;
|
|
116
|
+
},
|
|
72
117
|
};
|
|
73
118
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
export { runProgram } from "./runner.js";
|
|
2
|
+
export { createWorkspace } from "./workspace.js";
|
|
3
|
+
export type { ProgramResult, RunOptions } from "./runner-types.js";
|
|
4
|
+
export type { Workspace, ObserveResult } from "./types.js";
|
|
2
5
|
export declare function validateProjectName(name: string): void;
|
|
3
6
|
export declare function resolveProject(name: string): string;
|
|
4
7
|
export declare function createProject(name: string, prompt: string, options?: {
|
package/dist/index.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
// @trama-dev/runtime runner surface — exported via "@trama-dev/runtime/runner"
|
|
2
|
-
import { readFileSync, writeFileSync, mkdirSync, readdirSync, existsSync,
|
|
2
|
+
import { readFileSync, writeFileSync, mkdirSync, readdirSync, existsSync, statSync, rmSync } from "fs";
|
|
3
3
|
import { join } from "path";
|
|
4
|
-
import { homedir
|
|
5
|
-
import { PiAdapter, stripCodeFences } from "./pi-adapter.js";
|
|
6
|
-
import { loadConfig, loadState, smokeRunAndRepair, copyToHistory, withTempDir, ensureProjectScaffold, RUNTIME_TYPES,
|
|
4
|
+
import { homedir } from "os";
|
|
5
|
+
import { PiAdapter, PI_VERSION, stripCodeFences } from "./pi-adapter.js";
|
|
6
|
+
import { loadConfig, loadProjectConfig, loadState, smokeRunAndRepair, copyToHistory, withSnapshot, withTempDir, ensureProjectScaffold, RUNTIME_TYPES, } from "./runner.js";
|
|
7
7
|
import { guardPath } from "./path-guard.js";
|
|
8
8
|
export { runProgram } from "./runner.js";
|
|
9
|
+
export { createWorkspace } from "./workspace.js";
|
|
9
10
|
// --- Example programs (included in system prompt during create/update) ---
|
|
10
11
|
const EXAMPLE_PROGRAMS = `// Example A: Simple — one-shot action, no LLM needed.
|
|
11
12
|
import { ctx, tools } from "@trama-dev/runtime";
|
|
@@ -89,6 +90,9 @@ await new Promise<void>(() => {});`;
|
|
|
89
90
|
function getSystemPrompt() {
|
|
90
91
|
return (`You are generating a TypeScript program for the trama runtime.\n\n` +
|
|
91
92
|
`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` +
|
|
93
|
+
`The workspace object is available when running in a session (shared artifact I/O between agents). ` +
|
|
94
|
+
`ctx.yield(reason) suspends the program cooperatively — persists state and exits. ` +
|
|
95
|
+
`ctx.resumed is true if this run follows a yield; ctx.yieldReason has the reason.\n\n` +
|
|
92
96
|
`Runtime API:\n${RUNTIME_TYPES}\n\n` +
|
|
93
97
|
`Examples:\n${EXAMPLE_PROGRAMS}`);
|
|
94
98
|
}
|
|
@@ -113,32 +117,6 @@ export function resolveProject(name) {
|
|
|
113
117
|
async function isolatedAsk(adapter, prompt, options) {
|
|
114
118
|
return withTempDir("trama-gen-", (dir) => adapter.withCwd(dir).ask(prompt, options));
|
|
115
119
|
}
|
|
116
|
-
/** Backup projectDir, run fn, restore on failure. Preserves new repair history entries across restore. */
|
|
117
|
-
async function withProjectBackup(projectDir, originalHistory, historyIndexPath, fn) {
|
|
118
|
-
const backupRoot = mkdtempSync(join(tmpdir(), "trama-update-backup-"));
|
|
119
|
-
const backupDir = join(backupRoot, "project");
|
|
120
|
-
cpSync(projectDir, backupDir, { recursive: true });
|
|
121
|
-
try {
|
|
122
|
-
await fn();
|
|
123
|
-
}
|
|
124
|
-
catch (err) {
|
|
125
|
-
// Restore from backup, preserving any new repair history entries
|
|
126
|
-
const failedHistory = existsSync(historyIndexPath) ? readFileSync(historyIndexPath, "utf-8") : "";
|
|
127
|
-
rmSync(projectDir, { recursive: true, force: true });
|
|
128
|
-
cpSync(backupDir, projectDir, { recursive: true });
|
|
129
|
-
if (failedHistory.startsWith(originalHistory)) {
|
|
130
|
-
const repairEntries = failedHistory.slice(originalHistory.length);
|
|
131
|
-
if (repairEntries.length > 0) {
|
|
132
|
-
appendFileSync(guardPath(projectDir, join("history", "index.jsonl")), repairEntries);
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
throw new Error(`Update failed — project files have been restored to the previous version.\n` +
|
|
136
|
-
`${err instanceof Error ? err.message : err}`);
|
|
137
|
-
}
|
|
138
|
-
finally {
|
|
139
|
-
rmSync(backupRoot, { recursive: true, force: true });
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
120
|
// --- Public API ---
|
|
143
121
|
export async function createProject(name, prompt, options) {
|
|
144
122
|
validateProjectName(name);
|
|
@@ -149,8 +127,6 @@ export async function createProject(name, prompt, options) {
|
|
|
149
127
|
}
|
|
150
128
|
mkdirSync(projectDir, { recursive: true });
|
|
151
129
|
try {
|
|
152
|
-
mkdirSync(join(projectDir, "history"), { recursive: true });
|
|
153
|
-
mkdirSync(join(projectDir, "logs"), { recursive: true });
|
|
154
130
|
ensureProjectScaffold(projectDir);
|
|
155
131
|
const config = loadConfig();
|
|
156
132
|
if (options?.model)
|
|
@@ -174,8 +150,7 @@ export async function createProject(name, prompt, options) {
|
|
|
174
150
|
maxRepairAttempts: config.maxRepairAttempts,
|
|
175
151
|
maxIterations: config.defaultMaxIterations,
|
|
176
152
|
});
|
|
177
|
-
|
|
178
|
-
appendFileSync(join(projectDir, "history", "index.jsonl"), JSON.stringify({ version: 1, reason: "create", timestamp: new Date().toISOString(), prompt }) + "\n");
|
|
153
|
+
copyToHistory(projectDir, "create", prompt);
|
|
179
154
|
console.log(`Created ${name}. Run with: trama run ${name}`);
|
|
180
155
|
}
|
|
181
156
|
catch (err) {
|
|
@@ -187,36 +162,40 @@ export async function createProject(name, prompt, options) {
|
|
|
187
162
|
}
|
|
188
163
|
export async function updateProject(name, prompt) {
|
|
189
164
|
const projectDir = resolveProject(name);
|
|
165
|
+
// A hand-written project may never have been run: give it history/ and the rest first.
|
|
166
|
+
ensureProjectScaffold(projectDir);
|
|
190
167
|
const programPath = guardPath(projectDir, "program.ts");
|
|
191
168
|
const originalSource = readFileSync(programPath, "utf-8");
|
|
192
169
|
const state = loadState(projectDir);
|
|
193
170
|
const meta = JSON.parse(readFileSync(guardPath(projectDir, "meta.json"), "utf-8"));
|
|
194
|
-
const
|
|
195
|
-
const originalHistory = existsSync(historyIndexPath) ? readFileSync(historyIndexPath, "utf-8") : "";
|
|
196
|
-
const config = loadConfig();
|
|
197
|
-
if (meta.model)
|
|
198
|
-
config.model = meta.model;
|
|
199
|
-
if (meta.provider)
|
|
200
|
-
config.provider = meta.provider;
|
|
171
|
+
const config = loadProjectConfig(projectDir);
|
|
201
172
|
const adapter = new PiAdapter(config, projectDir);
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
173
|
+
const systemPrompt = getSystemPrompt() +
|
|
174
|
+
`\n\nOriginal prompt: ${meta.input.prompt}` +
|
|
175
|
+
`\n\nCurrent program.ts:\n${originalSource}` +
|
|
176
|
+
(Object.keys(state).length > 0 ? `\n\nCurrent state:\n${JSON.stringify(state, null, 2)}` : "");
|
|
177
|
+
// All-or-nothing: if generation or validation fails, the whole project
|
|
178
|
+
// directory — program, state, history — goes back to how it was.
|
|
179
|
+
try {
|
|
180
|
+
await withSnapshot(projectDir, async () => {
|
|
181
|
+
console.log(`Updating "${name}"...`);
|
|
182
|
+
const updated = stripCodeFences(await isolatedAsk(adapter, `${prompt}\n\nOutput the complete updated program.ts. No partial patches. No markdown fences. No explanation.`, { system: systemPrompt }));
|
|
183
|
+
writeFileSync(programPath, updated);
|
|
184
|
+
console.log("Validating updated program...");
|
|
185
|
+
await smokeRunAndRepair(projectDir, adapter, "update", {
|
|
186
|
+
timeout: config.defaultTimeout,
|
|
187
|
+
maxRepairAttempts: config.maxRepairAttempts,
|
|
188
|
+
maxIterations: config.defaultMaxIterations,
|
|
189
|
+
});
|
|
190
|
+
copyToHistory(projectDir, "update", prompt);
|
|
191
|
+
return { keep: true, value: undefined };
|
|
216
192
|
});
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
193
|
+
}
|
|
194
|
+
catch (err) {
|
|
195
|
+
throw new Error(`Update failed — project files have been restored to the previous version.\n` +
|
|
196
|
+
`${err instanceof Error ? err.message : err}`);
|
|
197
|
+
}
|
|
198
|
+
console.log(`Updated ${name}. Run with: trama run ${name}`);
|
|
220
199
|
}
|
|
221
200
|
export async function listProjects() {
|
|
222
201
|
const dir = projectsDir();
|
|
@@ -224,8 +203,9 @@ export async function listProjects() {
|
|
|
224
203
|
console.log("No projects found.");
|
|
225
204
|
return;
|
|
226
205
|
}
|
|
206
|
+
// Dot-directories are not projects (a rollback snapshot is kept beside its project while a run is in flight).
|
|
227
207
|
const entries = readdirSync(dir, { withFileTypes: true })
|
|
228
|
-
.filter(e => e.isDirectory());
|
|
208
|
+
.filter(e => e.isDirectory() && !e.name.startsWith("."));
|
|
229
209
|
if (entries.length === 0) {
|
|
230
210
|
console.log("No projects found.");
|
|
231
211
|
return;
|