@trama-dev/runtime 0.4.0 → 0.5.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 -3
- package/dist/abort.d.ts +12 -0
- package/dist/abort.js +31 -0
- package/dist/agent-backend.d.ts +0 -6
- package/dist/agent-backend.js +1 -21
- package/dist/agent.d.ts +16 -1
- package/dist/agent.js +108 -35
- package/dist/bridge-client.js +44 -14
- package/dist/child-process.js +9 -9
- package/dist/client.d.ts +2 -1
- package/dist/client.js +5 -15
- package/dist/context.d.ts +36 -7
- package/dist/context.js +83 -92
- package/dist/errors.d.ts +2 -0
- package/dist/errors.js +2 -0
- package/dist/index.d.ts +4 -1
- package/dist/index.js +84 -53
- package/dist/ipc-server.d.ts +4 -4
- package/dist/ipc-server.js +104 -137
- package/dist/journal-view.js +12 -4
- package/dist/journal.d.ts +15 -5
- package/dist/journal.js +209 -77
- package/dist/meta.d.ts +18 -0
- package/dist/meta.js +29 -0
- package/dist/path-guard.d.ts +128 -19
- package/dist/path-guard.js +384 -68
- package/dist/pi-adapter.d.ts +7 -6
- package/dist/pi-adapter.js +15 -26
- package/dist/replace-file.d.ts +31 -0
- package/dist/replace-file.js +75 -0
- package/dist/runner.d.ts +17 -31
- package/dist/runner.js +414 -201
- package/dist/serializable.d.ts +10 -4
- package/dist/serializable.js +56 -31
- package/dist/stopping.d.ts +4 -1
- package/dist/stopping.js +48 -10
- package/dist/tools.js +40 -10
- package/dist/tree.d.ts +234 -0
- package/dist/tree.js +1409 -0
- package/dist/types.d.ts +6 -3
- package/dist/workspace.d.ts +7 -0
- package/dist/workspace.js +93 -104
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -29,8 +29,9 @@ import { createProject, runProgram, updateProject } from "@trama-dev/runtime/run
|
|
|
29
29
|
|
|
30
30
|
The runtime is what makes agent programs **self-contained and shareable**:
|
|
31
31
|
|
|
32
|
-
- **Execution** — child process spawning, streaming output, timeout management, background process cleanup.
|
|
33
|
-
- **IPC bridge** — a local HTTP server that every `ctx`, `agent`, `tools` and
|
|
32
|
+
- **Execution** — child process spawning, streaming output, timeout management, watchdog-backed background process cleanup.
|
|
33
|
+
- **IPC bridge** — a local HTTP server that every `ctx`, `agent`, `tools`, `workspace`, and nested run call goes through: one point where a single runner validates each request, records the tree of runs, and cancels work in flight when a run ends.
|
|
34
|
+
- **Run journal** — an append-only per-run record (`logs/journal/*.jsonl`, viewable via `trama journal`) of every bridge call, attempt, repair, and exit.
|
|
34
35
|
- **State persistence** — `ctx.state` survives across runs. Programs can be long-running, interruptible, and resumable.
|
|
35
36
|
- **Auto-repair** — on crash, the runtime gets an LLM fix and tries it on a private copy of the project, installing it only if it works. Up to 3 attempts.
|
|
36
37
|
- **Version history** — every create, update, and repair saves a snapshot to `history/`.
|
|
@@ -38,6 +39,6 @@ The runtime is what makes agent programs **self-contained and shareable**:
|
|
|
38
39
|
|
|
39
40
|
## Self-orchestration
|
|
40
41
|
|
|
41
|
-
trama programs can
|
|
42
|
+
trama programs can coordinate other trama programs — through `@trama-dev/session` (carried over the parent runner's bridge with a shared workspace and structured lifecycle) or through `tools.shell("trama ...")` for standalone CLI invocations. The generated program becomes the orchestrator — decomposing tasks, spawning sub-programs, and synthesizing results. No orchestration framework needed. trama is the scheduler.
|
|
42
43
|
|
|
43
44
|
See the [main README](https://github.com/NaNhkNaN/trama) for examples, the full API reference, and design philosophy.
|
package/dist/abort.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run `fn` once if `signal` is already aborted or when it aborts, and return
|
|
3
|
+
* a cleanup function that detaches the listener.
|
|
4
|
+
*/
|
|
5
|
+
export declare function onAbort(signal: AbortSignal | undefined, fn: () => void): () => void;
|
|
6
|
+
/** Go no further where `signal` is aborted. (The system's own `throwIfAborted` says it in other words.) */
|
|
7
|
+
export declare function throwIfAborted(signal: AbortSignal | undefined): void;
|
|
8
|
+
/**
|
|
9
|
+
* Reject as soon as `signal` is aborted, whether or not `work` itself notices.
|
|
10
|
+
* What `work` goes on to do after that is no longer waited for.
|
|
11
|
+
*/
|
|
12
|
+
export declare function rejectOnAbort<T>(work: Promise<T>, signal?: AbortSignal): Promise<T>;
|
package/dist/abort.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run `fn` once if `signal` is already aborted or when it aborts, and return
|
|
3
|
+
* a cleanup function that detaches the listener.
|
|
4
|
+
*/
|
|
5
|
+
export function onAbort(signal, fn) {
|
|
6
|
+
if (!signal)
|
|
7
|
+
return () => { };
|
|
8
|
+
if (signal.aborted) {
|
|
9
|
+
fn();
|
|
10
|
+
return () => { };
|
|
11
|
+
}
|
|
12
|
+
signal.addEventListener("abort", fn, { once: true });
|
|
13
|
+
return () => signal.removeEventListener("abort", fn);
|
|
14
|
+
}
|
|
15
|
+
/** Go no further where `signal` is aborted. (The system's own `throwIfAborted` says it in other words.) */
|
|
16
|
+
export function throwIfAborted(signal) {
|
|
17
|
+
if (signal?.aborted)
|
|
18
|
+
throw new Error("Aborted");
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Reject as soon as `signal` is aborted, whether or not `work` itself notices.
|
|
22
|
+
* What `work` goes on to do after that is no longer waited for.
|
|
23
|
+
*/
|
|
24
|
+
export function rejectOnAbort(work, signal) {
|
|
25
|
+
if (!signal)
|
|
26
|
+
return work;
|
|
27
|
+
return new Promise((resolve, reject) => {
|
|
28
|
+
const off = onAbort(signal, () => reject(new Error("Aborted")));
|
|
29
|
+
work.then(value => { off(); resolve(value); }, err => { off(); reject(err); });
|
|
30
|
+
});
|
|
31
|
+
}
|
package/dist/agent-backend.d.ts
CHANGED
|
@@ -16,9 +16,3 @@ export interface AgentBackend {
|
|
|
16
16
|
*/
|
|
17
17
|
ask(prompt: string, call: AgentCall): Promise<string>;
|
|
18
18
|
}
|
|
19
|
-
/**
|
|
20
|
-
* Hold a piece of work to the promise above: reject as soon as `signal` is
|
|
21
|
-
* aborted, whether or not the work itself notices. What the work goes on to do
|
|
22
|
-
* after that is no longer waited for.
|
|
23
|
-
*/
|
|
24
|
-
export declare function rejectOnAbort<T>(work: Promise<T>, signal?: AbortSignal): Promise<T>;
|
package/dist/agent-backend.js
CHANGED
|
@@ -6,24 +6,4 @@
|
|
|
6
6
|
// request; what to ask for, and what to make of the reply, is decided by the
|
|
7
7
|
// caller. Nothing outside the backend's own file knows which agent, harness or
|
|
8
8
|
// model is behind it.
|
|
9
|
-
|
|
10
|
-
* Hold a piece of work to the promise above: reject as soon as `signal` is
|
|
11
|
-
* aborted, whether or not the work itself notices. What the work goes on to do
|
|
12
|
-
* after that is no longer waited for.
|
|
13
|
-
*/
|
|
14
|
-
export function rejectOnAbort(work, signal) {
|
|
15
|
-
if (!signal)
|
|
16
|
-
return work;
|
|
17
|
-
return new Promise((resolve, reject) => {
|
|
18
|
-
const onAbort = () => reject(new Error("Aborted"));
|
|
19
|
-
if (signal.aborted)
|
|
20
|
-
onAbort();
|
|
21
|
-
else
|
|
22
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
23
|
-
const settle = (pass) => (value) => {
|
|
24
|
-
signal.removeEventListener("abort", onAbort);
|
|
25
|
-
pass(value);
|
|
26
|
-
};
|
|
27
|
-
work.then(settle(resolve), settle(reject));
|
|
28
|
-
});
|
|
29
|
-
}
|
|
9
|
+
export {};
|
package/dist/agent.d.ts
CHANGED
|
@@ -3,7 +3,22 @@ import type { AgentBackend } from "./agent-backend.js";
|
|
|
3
3
|
/**
|
|
4
4
|
* The program in an LLM reply that was asked to contain nothing else: the last
|
|
5
5
|
* fenced block if there is one (models add explanations, or show a "before"
|
|
6
|
-
* first), otherwise the whole
|
|
6
|
+
* first), otherwise the whole text.
|
|
7
|
+
*
|
|
8
|
+
* A program may hold fences of its own, in a comment. So a reply in which
|
|
9
|
+
* every fence stands in a comment was not fenced at all; and a block ends at
|
|
10
|
+
* the first closing fence, of backticks enough, that does not stand in a
|
|
11
|
+
* comment of the block — or, if there is none such (the block is no program,
|
|
12
|
+
* its comment never ends, it was opened with more backticks than it is
|
|
13
|
+
* closed with), at the first closing fence there is.
|
|
14
|
+
*
|
|
15
|
+
* What this still takes wrongly, where the plain reading would not: a line
|
|
16
|
+
* that begins as a comment begins — among the words, or in another block:
|
|
17
|
+
* `/*.log` in a list of files to ignore, a snippet cut off inside a comment —
|
|
18
|
+
* when what ends a comment comes only further on, past a fence. Then the
|
|
19
|
+
* fences between are taken for a program's own, and the reply comes out
|
|
20
|
+
* whole, or as two blocks and the words between them. It is not a program,
|
|
21
|
+
* and the validation that follows says so.
|
|
7
22
|
*/
|
|
8
23
|
export declare function stripCodeFences(text: string): string;
|
|
9
24
|
/**
|
package/dist/agent.js
CHANGED
|
@@ -1,37 +1,120 @@
|
|
|
1
|
+
import { isJsonObject } from "./serializable.js";
|
|
2
|
+
const NAMED = /[\w.+#-]*\s*\n/y;
|
|
3
|
+
/** The fences of a text, in the order they stand in. */
|
|
4
|
+
function fencesOf(text) {
|
|
5
|
+
const fences = [];
|
|
6
|
+
for (const run of text.matchAll(/`{3,}/g)) {
|
|
7
|
+
const at = run.index, ticks = run[0].length;
|
|
8
|
+
const line = text.lastIndexOf("\n", at - 1) + 1;
|
|
9
|
+
const newline = text.indexOf("\n", at);
|
|
10
|
+
NAMED.lastIndex = at + ticks;
|
|
11
|
+
const opens = NAMED.test(text);
|
|
12
|
+
const closes = text.slice(line, at).trim() === "";
|
|
13
|
+
if (opens || closes)
|
|
14
|
+
fences.push({ at, line, next: newline === -1 ? text.length : newline + 1, ticks, opens, closes });
|
|
15
|
+
}
|
|
16
|
+
return fences;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* A reader of the comments of `text` from `from` on, to be asked of one
|
|
20
|
+
* fence after another, in order, whether it stands in one — and so is the
|
|
21
|
+
* program's own text: a program may show how it is used, between fences, in
|
|
22
|
+
* a comment.
|
|
23
|
+
*
|
|
24
|
+
* Only a comment that begins its line is one here (as a comment that holds
|
|
25
|
+
* lines of its own does): `src/*.ts` in a sentence, or in a command, opens
|
|
26
|
+
* nothing. Nothing else of the language is read — a string or a template
|
|
27
|
+
* literal cannot hold a line of backticks anyway.
|
|
28
|
+
*/
|
|
29
|
+
function commentsFrom(text, from) {
|
|
30
|
+
const marks = /^[ \t]*\/\*|\*\//gm;
|
|
31
|
+
let at = from, open = false;
|
|
32
|
+
const readTo = (end) => {
|
|
33
|
+
marks.lastIndex = at;
|
|
34
|
+
for (let mark; (mark = marks.exec(text)) !== null && mark.index < end;)
|
|
35
|
+
open = mark[0] !== "*/";
|
|
36
|
+
at = end;
|
|
37
|
+
return open;
|
|
38
|
+
};
|
|
39
|
+
return {
|
|
40
|
+
holds: (fence) => readTo(fence.at) || /^[ \t]*\/\//.test(text.slice(fence.line, fence.at)),
|
|
41
|
+
open: () => readTo(text.length),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
1
44
|
/**
|
|
2
45
|
* The program in an LLM reply that was asked to contain nothing else: the last
|
|
3
46
|
* fenced block if there is one (models add explanations, or show a "before"
|
|
4
|
-
* first), otherwise the whole
|
|
47
|
+
* first), otherwise the whole text.
|
|
48
|
+
*
|
|
49
|
+
* A program may hold fences of its own, in a comment. So a reply in which
|
|
50
|
+
* every fence stands in a comment was not fenced at all; and a block ends at
|
|
51
|
+
* the first closing fence, of backticks enough, that does not stand in a
|
|
52
|
+
* comment of the block — or, if there is none such (the block is no program,
|
|
53
|
+
* its comment never ends, it was opened with more backticks than it is
|
|
54
|
+
* closed with), at the first closing fence there is.
|
|
55
|
+
*
|
|
56
|
+
* What this still takes wrongly, where the plain reading would not: a line
|
|
57
|
+
* that begins as a comment begins — among the words, or in another block:
|
|
58
|
+
* `/*.log` in a list of files to ignore, a snippet cut off inside a comment —
|
|
59
|
+
* when what ends a comment comes only further on, past a fence. Then the
|
|
60
|
+
* fences between are taken for a program's own, and the reply comes out
|
|
61
|
+
* whole, or as two blocks and the words between them. It is not a program,
|
|
62
|
+
* and the validation that follows says so.
|
|
5
63
|
*/
|
|
6
64
|
export function stripCodeFences(text) {
|
|
7
|
-
const
|
|
8
|
-
const
|
|
9
|
-
|
|
10
|
-
|
|
65
|
+
const reply = text.trim();
|
|
66
|
+
const fences = fencesOf(reply);
|
|
67
|
+
const whole = commentsFrom(reply, 0);
|
|
68
|
+
if (fences.every((fence) => whole.holds(fence)) && !whole.open())
|
|
69
|
+
return reply;
|
|
70
|
+
let last;
|
|
71
|
+
for (let from = 0;;) {
|
|
72
|
+
const opener = fences.find((fence) => fence.opens && fence.at >= from);
|
|
73
|
+
if (!opener)
|
|
74
|
+
break;
|
|
75
|
+
const closers = fences.filter((fence) => fence.at >= opener.next && fence.closes);
|
|
76
|
+
const inBlock = commentsFrom(reply, opener.next);
|
|
77
|
+
const closer = closers.find((fence) => fence.ticks >= opener.ticks && !inBlock.holds(fence)) ?? closers[0];
|
|
78
|
+
if (closer)
|
|
79
|
+
last = reply.slice(opener.next, closer.line).trim();
|
|
80
|
+
from = (closer ?? opener).at + (closer ?? opener).ticks;
|
|
11
81
|
}
|
|
12
|
-
return
|
|
82
|
+
return last ?? reply;
|
|
13
83
|
}
|
|
84
|
+
const SUPPORTED_SCHEMA_TYPES = new Set(["string", "number", "boolean"]);
|
|
14
85
|
/**
|
|
15
|
-
*
|
|
16
|
-
* Checks all schema keys exist and values match declared primitive types.
|
|
86
|
+
* Parse and validate the caller's schema declaration up front.
|
|
17
87
|
* The part after ":" is a description and is ignored during validation.
|
|
18
88
|
*/
|
|
19
|
-
function
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
89
|
+
function parseSchema(schema) {
|
|
90
|
+
return Object.entries(schema).map(([key, typeDesc]) => {
|
|
91
|
+
// (What a field is to be is said in words: "number: how many". Anything else says nothing that is supported.)
|
|
92
|
+
const expectedType = typeof typeDesc === "string" ? typeDesc.split(":")[0].trim() : JSON.stringify(typeDesc);
|
|
93
|
+
if (typeof typeDesc !== "string" || !SUPPORTED_SCHEMA_TYPES.has(expectedType)) {
|
|
94
|
+
throw new Error(`Schema validation failed: unsupported schema type "${expectedType}" for key "${key}"`);
|
|
95
|
+
}
|
|
96
|
+
return [key, expectedType];
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Minimal shape validation + projection: verifies every schema key exists with
|
|
101
|
+
* its declared primitive type, and returns an object containing only those keys.
|
|
102
|
+
*/
|
|
103
|
+
function extractBySchema(result, entries) {
|
|
104
|
+
if (!isJsonObject(result))
|
|
105
|
+
throw new Error("Schema validation failed: response is not an object");
|
|
106
|
+
const picked = {};
|
|
107
|
+
for (const [key, expectedType] of entries) {
|
|
108
|
+
if (!(key in result))
|
|
109
|
+
throw new Error(`Schema validation failed: missing key: ${key}`);
|
|
110
|
+
const val = result[key];
|
|
111
|
+
const actual = typeof val;
|
|
112
|
+
if (actual !== expectedType || (expectedType === "number" && !Number.isFinite(val))) {
|
|
113
|
+
throw new Error(`Schema validation failed: ${key}: expected ${expectedType}, got ${actual === "number" ? String(val) : actual}`);
|
|
114
|
+
}
|
|
115
|
+
picked[key] = val;
|
|
33
116
|
}
|
|
34
|
-
return
|
|
117
|
+
return picked;
|
|
35
118
|
}
|
|
36
119
|
/**
|
|
37
120
|
* The `agent` a program talks to: its calls, served by `backend` working in
|
|
@@ -43,6 +126,7 @@ export function createAgent(backend, cwd, signal) {
|
|
|
43
126
|
return backend.ask(prompt, { cwd, system: options?.system, signal });
|
|
44
127
|
},
|
|
45
128
|
async generate(input) {
|
|
129
|
+
const schemaEntries = parseSchema(input.schema);
|
|
46
130
|
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.`;
|
|
47
131
|
const fullPrompt = `${input.prompt}\n\n${schemaInstruction}`;
|
|
48
132
|
const call = { cwd, system: input.system, signal };
|
|
@@ -58,10 +142,7 @@ export function createAgent(backend, cwd, signal) {
|
|
|
58
142
|
const fenceMatch = trimmed.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);
|
|
59
143
|
parsed = JSON.parse(fenceMatch ? fenceMatch[1].trim() : trimmed);
|
|
60
144
|
}
|
|
61
|
-
|
|
62
|
-
if (error)
|
|
63
|
-
throw new Error(`Schema validation failed: ${error}`);
|
|
64
|
-
return stripToSchema(parsed, input.schema);
|
|
145
|
+
return extractBySchema(parsed, schemaEntries);
|
|
65
146
|
};
|
|
66
147
|
// First attempt — backend errors (network/auth) propagate immediately.
|
|
67
148
|
// Only parse/validation failures trigger a retry.
|
|
@@ -77,11 +158,3 @@ export function createAgent(backend, cwd, signal) {
|
|
|
77
158
|
}
|
|
78
159
|
};
|
|
79
160
|
}
|
|
80
|
-
/** Return a new object containing only the keys declared in the schema. */
|
|
81
|
-
function stripToSchema(obj, schema) {
|
|
82
|
-
const result = {};
|
|
83
|
-
for (const key of Object.keys(schema)) {
|
|
84
|
-
result[key] = obj[key];
|
|
85
|
-
}
|
|
86
|
-
return result;
|
|
87
|
-
}
|
package/dist/bridge-client.js
CHANGED
|
@@ -2,17 +2,37 @@
|
|
|
2
2
|
// reaches the runner that started it (ipc-server.ts is the other end).
|
|
3
3
|
import { readFileSync } from "fs";
|
|
4
4
|
import { request } from "http";
|
|
5
|
+
import { messageOf } from "./errors.js";
|
|
6
|
+
let cached;
|
|
7
|
+
/**
|
|
8
|
+
* A call's body as it goes over the bridge. JSON has no way to say NaN or
|
|
9
|
+
* Infinity: it writes null for them, which the other end reads as a field
|
|
10
|
+
* that was left out. So a number it cannot carry is refused here — a call is
|
|
11
|
+
* carried out as it was made, or not at all.
|
|
12
|
+
*/
|
|
13
|
+
function encode(endpoint, body) {
|
|
14
|
+
return JSON.stringify(body, function (name, value) {
|
|
15
|
+
if (typeof value === "number" && !Number.isFinite(value)) {
|
|
16
|
+
const where = Array.isArray(this) ? `item ${name} of a list` : name;
|
|
17
|
+
throw new TypeError(`${where} is ${value}, which cannot be sent to the runner (${endpoint})`);
|
|
18
|
+
}
|
|
19
|
+
return value;
|
|
20
|
+
});
|
|
21
|
+
}
|
|
5
22
|
/**
|
|
6
23
|
* @param port - the runner's loopback port (TRAMA_PORT)
|
|
7
24
|
* @param initPath - the file the runner wrote for this program (TRAMA_INIT)
|
|
8
25
|
*/
|
|
9
26
|
export function openBridge(port, initPath) {
|
|
27
|
+
if (cached?.bridge && cached.port === port && cached.initPath === initPath) {
|
|
28
|
+
return cached.bridge;
|
|
29
|
+
}
|
|
10
30
|
const init = JSON.parse(readFileSync(initPath, "utf-8"));
|
|
11
31
|
// A call lasts as long as the work behind it — an agent run, or the whole
|
|
12
32
|
// run of another program — so this uses node:http, which sets no deadline
|
|
13
33
|
// for the response. (fetch gives up after five minutes without response headers.)
|
|
14
34
|
const call = (endpoint, body) => new Promise((resolve, reject) => {
|
|
15
|
-
const payload =
|
|
35
|
+
const payload = encode(endpoint, body);
|
|
16
36
|
const req = request({
|
|
17
37
|
host: "127.0.0.1",
|
|
18
38
|
port,
|
|
@@ -27,35 +47,45 @@ export function openBridge(port, initPath) {
|
|
|
27
47
|
const chunks = [];
|
|
28
48
|
res.on("data", (chunk) => chunks.push(chunk));
|
|
29
49
|
res.on("error", reject);
|
|
50
|
+
// (An answer that is cut off is an error of the response, above: it never comes to an end.)
|
|
30
51
|
res.on("end", () => {
|
|
31
52
|
const text = Buffer.concat(chunks).toString("utf-8");
|
|
32
53
|
if (res.statusCode !== 200)
|
|
33
|
-
reject(new Error(`trama runtime error: ${text}`));
|
|
34
|
-
|
|
54
|
+
return reject(new Error(`trama runtime error: ${text}`));
|
|
55
|
+
// Whatever is wrong with an answer is the call's to fail with — not thrown at whoever is on the stack.
|
|
56
|
+
try {
|
|
35
57
|
resolve(JSON.parse(text).result);
|
|
58
|
+
}
|
|
59
|
+
catch (err) {
|
|
60
|
+
reject(new Error(`trama runtime error: the runner's answer to ${endpoint} cannot be read: ${messageOf(err)}`));
|
|
61
|
+
}
|
|
36
62
|
});
|
|
37
63
|
});
|
|
38
64
|
req.on("error", reject);
|
|
39
65
|
req.end(payload);
|
|
40
66
|
});
|
|
41
|
-
|
|
67
|
+
const bridge = { init, call };
|
|
68
|
+
cached = { port, initPath, bridge };
|
|
69
|
+
return bridge;
|
|
42
70
|
}
|
|
43
|
-
let parent;
|
|
44
71
|
/**
|
|
45
72
|
* The bridge to the runner that started this process as a program — or null
|
|
46
73
|
* when this process is not a program, and so is itself where runs happen.
|
|
47
74
|
*/
|
|
48
75
|
export function parentBridge() {
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
76
|
+
const { TRAMA_PORT: port, TRAMA_INIT: initPath } = process.env;
|
|
77
|
+
if (!port || !initPath)
|
|
78
|
+
return null;
|
|
79
|
+
if (cached && cached.port === port && cached.initPath === initPath) {
|
|
80
|
+
return cached.bridge;
|
|
81
|
+
}
|
|
82
|
+
try {
|
|
83
|
+
return openBridge(port, initPath);
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
cached = { port, initPath, bridge: null }; // a stale environment: there is no runner to ask
|
|
87
|
+
return null;
|
|
57
88
|
}
|
|
58
|
-
return parent;
|
|
59
89
|
}
|
|
60
90
|
/**
|
|
61
91
|
* A workspace reached over a bridge: the directory `dir`, or — without one —
|
package/dist/child-process.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { StringDecoder } from "string_decoder";
|
|
2
|
+
import { onAbort } from "./abort.js";
|
|
2
3
|
import { stopGroups } from "./stopping.js";
|
|
3
4
|
const MAX_OUTPUT = 10 * 1024 * 1024; // 10 MB
|
|
4
5
|
/** How long a child's output is waited for once the child itself has exited. */
|
|
@@ -84,7 +85,6 @@ export function superviseChild(child, options) {
|
|
|
84
85
|
const errDecoder = new StringDecoder("utf-8");
|
|
85
86
|
let timedOut = false;
|
|
86
87
|
let stopped = false;
|
|
87
|
-
let exited = false;
|
|
88
88
|
const emitOut = (text) => { if (text) {
|
|
89
89
|
out.append(text);
|
|
90
90
|
sinks?.stdout?.(text);
|
|
@@ -97,16 +97,13 @@ export function superviseChild(child, options) {
|
|
|
97
97
|
// A child that failed to spawn has no pid, and nothing to stop.
|
|
98
98
|
const terminate = () => { if (child.pid)
|
|
99
99
|
void stopGroups([child.pid]); };
|
|
100
|
-
const
|
|
101
|
-
if (
|
|
100
|
+
const offStop = onAbort(stopSignal, () => {
|
|
101
|
+
if (timedOut)
|
|
102
102
|
return;
|
|
103
103
|
stopped = true;
|
|
104
104
|
terminate();
|
|
105
|
-
};
|
|
106
|
-
stopSignal?.addEventListener("abort", onStopRequest, { once: true });
|
|
105
|
+
});
|
|
107
106
|
allowance.start(() => {
|
|
108
|
-
if (exited)
|
|
109
|
-
return;
|
|
110
107
|
timedOut = true;
|
|
111
108
|
terminate();
|
|
112
109
|
});
|
|
@@ -114,7 +111,7 @@ export function superviseChild(child, options) {
|
|
|
114
111
|
allowance.cancel();
|
|
115
112
|
if (drainTimer)
|
|
116
113
|
clearTimeout(drainTimer);
|
|
117
|
-
|
|
114
|
+
offStop();
|
|
118
115
|
};
|
|
119
116
|
child.stdout?.on("data", (chunk) => emitOut(outDecoder.write(chunk)));
|
|
120
117
|
child.stderr?.on("data", (chunk) => emitErr(errDecoder.write(chunk)));
|
|
@@ -127,10 +124,13 @@ export function superviseChild(child, options) {
|
|
|
127
124
|
// and what that writes is not the child's output. Stop waiting for it:
|
|
128
125
|
// otherwise such a process keeps the run from ever ending, timeout or not.
|
|
129
126
|
child.on("exit", () => {
|
|
127
|
+
// From here on there is no child to stop, and none that could run out of time: what
|
|
128
|
+
// is still waited for is its output, for a moment (see below).
|
|
129
|
+
allowance.cancel();
|
|
130
|
+
offStop();
|
|
130
131
|
drainTimer = setTimeout(() => { child.stdout?.destroy(); child.stderr?.destroy(); }, DRAIN_MS);
|
|
131
132
|
});
|
|
132
133
|
child.on("close", (code, signal) => {
|
|
133
|
-
exited = true;
|
|
134
134
|
cleanup();
|
|
135
135
|
emitOut(outDecoder.end());
|
|
136
136
|
emitErr(errDecoder.end());
|
package/dist/client.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import type { Ctx, Agent, Tools, Workspace } from "./types.js";
|
|
1
|
+
import type { Ctx, Agent, ShellResult, Tools, ObserveResult, Workspace } from "./types.js";
|
|
2
|
+
export type { Ctx, Agent, ShellResult, Tools, ObserveResult, Workspace };
|
|
2
3
|
export declare const ctx: Ctx;
|
|
3
4
|
export declare const agent: Agent;
|
|
4
5
|
export declare const tools: Tools;
|
package/dist/client.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// A thin wrapper that forwards every call to the runner's IPC server
|
|
3
3
|
// (ipc-server.ts), which does the real work.
|
|
4
4
|
import { openBridge, remoteWorkspace } from "./bridge-client.js";
|
|
5
|
-
import { assertSerializable } from "./serializable.js";
|
|
5
|
+
import { assertSerializable, toLogData } from "./serializable.js";
|
|
6
6
|
const PORT = process.env.TRAMA_PORT;
|
|
7
7
|
if (!PORT) {
|
|
8
8
|
throw new Error("@trama-dev/runtime must be executed via `trama run`. " +
|
|
@@ -14,18 +14,8 @@ if (!INIT_PATH) {
|
|
|
14
14
|
"This program must be launched by the trama runner.");
|
|
15
15
|
}
|
|
16
16
|
const { init: initData, call } = openBridge(PORT, INIT_PATH);
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
try {
|
|
20
|
-
JSON.stringify(data);
|
|
21
|
-
return data;
|
|
22
|
-
}
|
|
23
|
-
catch {
|
|
24
|
-
return { __trama_unserializable: String(data) };
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
// The lifecycle rules (ready once, done once, done and yield mutually exclusive)
|
|
28
|
-
// are enforced by the runner. Here each call is checked for what only this
|
|
17
|
+
// The lifecycle rules (ready once; a run ends once, by done or by yield, and
|
|
18
|
+
// nothing is persisted after that) are enforced by the runner. Here each call is checked for what only this
|
|
29
19
|
// process can see — whether the values survive JSON — and then forwarded.
|
|
30
20
|
export const ctx = {
|
|
31
21
|
input: initData.input,
|
|
@@ -35,10 +25,10 @@ export const ctx = {
|
|
|
35
25
|
resumed: initData.resumed,
|
|
36
26
|
yieldReason: initData.yieldReason,
|
|
37
27
|
async log(msg, data) {
|
|
38
|
-
await call("/ctx/log", { message: msg, data:
|
|
28
|
+
await call("/ctx/log", { message: msg, data: toLogData(data) });
|
|
39
29
|
},
|
|
40
30
|
async ready(data) {
|
|
41
|
-
await call("/ctx/ready", { data:
|
|
31
|
+
await call("/ctx/ready", { data: toLogData(data) });
|
|
42
32
|
},
|
|
43
33
|
async checkpoint() {
|
|
44
34
|
assertSerializable(ctx.state, "ctx.state");
|
package/dist/context.d.ts
CHANGED
|
@@ -1,12 +1,41 @@
|
|
|
1
1
|
import type { Ctx } from "./types.js";
|
|
2
|
+
import type { ProgramResult } from "./runner-types.js";
|
|
3
|
+
/** Where a project's structured run log lives, relative to the project root. */
|
|
4
|
+
export declare const LATEST_LOG_PATH: string;
|
|
5
|
+
/** Append one structured JSONL entry to a run log file. `data` is what the program's side made of what it was given (see toLogData). */
|
|
6
|
+
export declare function appendLogEntry(logsPath: string, message: string, data?: unknown): void;
|
|
2
7
|
/**
|
|
3
|
-
* The runner
|
|
4
|
-
*
|
|
8
|
+
* The runner's side of a program's `ctx`: what the program is told when it
|
|
9
|
+
* starts, and where its state file and run log are written while it runs
|
|
10
|
+
* (once it is over, the runner settles both: see runProgramOnce). The
|
|
11
|
+
* program's own `ctx` (client.ts) forwards to this over IPC.
|
|
5
12
|
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
|
|
13
|
+
* The state is the program's. It is handed over with each call that persists
|
|
14
|
+
* it and is not kept here: there is one copy of it in the program, and one on
|
|
15
|
+
* disk.
|
|
16
|
+
*/
|
|
17
|
+
export interface RunContext {
|
|
18
|
+
readonly input: Ctx["input"];
|
|
19
|
+
readonly maxIterations: number;
|
|
20
|
+
/** Whether this run takes up from a yield, and the reason that yield gave. */
|
|
21
|
+
readonly resumed: boolean;
|
|
22
|
+
readonly yieldReason: string | null;
|
|
23
|
+
/** How many times the state has been persisted — in this run and the ones before it. */
|
|
24
|
+
readonly iteration: number;
|
|
25
|
+
/** How the program ended the run: null until it has called done() or yield(). */
|
|
26
|
+
readonly ended: ProgramResult | null;
|
|
27
|
+
log(message: string, data?: unknown): void;
|
|
28
|
+
/** The first call is logged and passed on to `onReady`; any other does nothing. */
|
|
29
|
+
ready(data?: Record<string, unknown>): void;
|
|
30
|
+
/** Persist the program's state as it is now. Returns the iteration that makes it. */
|
|
31
|
+
checkpoint(state: Record<string, unknown>): number;
|
|
32
|
+
/** Persist the state and end the run as done. Returns the iteration it ended on. */
|
|
33
|
+
done(state: Record<string, unknown>, result?: unknown): number;
|
|
34
|
+
/** Persist the state, with the mark the next run resumes from, and end the run as yielded. */
|
|
35
|
+
yield(state: Record<string, unknown>, reason: string): void;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Bookkeeping lives in the state file under reserved `__trama_*` keys:
|
|
10
39
|
* `__trama_iteration` (progress counter) and `__trama_yield` (set while the
|
|
11
40
|
* program is suspended, cleared when it next advances).
|
|
12
41
|
*/
|
|
@@ -16,4 +45,4 @@ export declare function createContext(projectDir: string, initialState: Record<s
|
|
|
16
45
|
onReady?: (data?: Record<string, unknown>) => void;
|
|
17
46
|
/** Where the run's log lines are shown as they are written. Defaults to the console. */
|
|
18
47
|
print?: (line: string) => void;
|
|
19
|
-
}):
|
|
48
|
+
}): RunContext;
|