@trama-dev/runtime 0.3.1 → 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.d.ts +1 -20
- package/dist/child-process.js +11 -86
- 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 +12 -1
- package/dist/index.js +93 -53
- package/dist/ipc-server.d.ts +12 -6
- package/dist/ipc-server.js +124 -136
- package/dist/journal-view.d.ts +9 -0
- package/dist/journal-view.js +139 -0
- package/dist/journal.d.ts +70 -0
- package/dist/journal.js +454 -0
- 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-types.d.ts +2 -0
- package/dist/runner.d.ts +37 -37
- package/dist/runner.js +565 -239
- package/dist/serializable.d.ts +10 -4
- package/dist/serializable.js +56 -31
- package/dist/{watchdog.d.ts → stopping.d.ts} +15 -0
- package/dist/stopping.js +268 -0
- package/dist/tools.js +44 -13
- 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 +2 -2
- package/dist/watchdog.js +0 -167
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.d.ts
CHANGED
|
@@ -4,25 +4,6 @@ export declare function cappedBuffer(): {
|
|
|
4
4
|
append(text: string): void;
|
|
5
5
|
readonly value: string;
|
|
6
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
|
-
/** The timing of a stop, shared with the watchdog. */
|
|
14
|
-
export declare const STOP_TIMINGS: {
|
|
15
|
-
grace: number;
|
|
16
|
-
settle: number;
|
|
17
|
-
poll: number;
|
|
18
|
-
};
|
|
19
|
-
export declare function onGroupAskedToStop(listener: (pgid: number) => void): void;
|
|
20
|
-
/**
|
|
21
|
-
* Stop process groups for good: SIGTERM now, SIGKILL after the grace period to
|
|
22
|
-
* whichever are still there. Resolves when none is left — so that what follows
|
|
23
|
-
* (merging a directory they were writing to, deleting it) finds them gone.
|
|
24
|
-
*/
|
|
25
|
-
export declare function stopGroups(pgids: number[]): Promise<void>;
|
|
26
7
|
/**
|
|
27
8
|
* A time limit that only runs down while nothing is holding it.
|
|
28
9
|
*
|
|
@@ -67,7 +48,7 @@ export interface ChildExit {
|
|
|
67
48
|
/**
|
|
68
49
|
* Collect a child's output and wait for it to exit, enforcing a time limit
|
|
69
50
|
* and an optional stop request. Either one stops the child's whole process
|
|
70
|
-
* group (see
|
|
51
|
+
* group (see stopping.ts).
|
|
71
52
|
* Resolves on exit however it happened; rejects only if the child failed to spawn.
|
|
72
53
|
*/
|
|
73
54
|
export declare function superviseChild(child: ChildProcess, options: SuperviseOptions): Promise<ChildExit>;
|
package/dist/child-process.js
CHANGED
|
@@ -1,10 +1,7 @@
|
|
|
1
1
|
import { StringDecoder } from "string_decoder";
|
|
2
|
+
import { onAbort } from "./abort.js";
|
|
3
|
+
import { stopGroups } from "./stopping.js";
|
|
2
4
|
const MAX_OUTPUT = 10 * 1024 * 1024; // 10 MB
|
|
3
|
-
/** How long a process group gets to exit after SIGTERM before it is sent SIGKILL. */
|
|
4
|
-
const KILL_GRACE_MS = 5000;
|
|
5
|
-
const STOP_POLL_MS = 25;
|
|
6
|
-
/** How long a group is waited for after SIGKILL before it is given up on. */
|
|
7
|
-
const KILL_SETTLE_MS = 1000;
|
|
8
5
|
/** How long a child's output is waited for once the child itself has exited. */
|
|
9
6
|
const DRAIN_MS = 1000;
|
|
10
7
|
/** The longest delay a timer can be given; a longer one fires at once. */
|
|
@@ -26,77 +23,6 @@ export function cappedBuffer() {
|
|
|
26
23
|
get value() { return buf; },
|
|
27
24
|
};
|
|
28
25
|
}
|
|
29
|
-
/**
|
|
30
|
-
* Send a signal to a whole process group. Children spawned with `detached: true`
|
|
31
|
-
* lead their own group, so this also reaches whatever they started in the background.
|
|
32
|
-
* Signal 0 only probes. Returns false if the group no longer exists.
|
|
33
|
-
*/
|
|
34
|
-
export function signalGroup(pgid, signal) {
|
|
35
|
-
try {
|
|
36
|
-
process.kill(-pgid, signal);
|
|
37
|
-
return true;
|
|
38
|
-
}
|
|
39
|
-
catch {
|
|
40
|
-
return false;
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
// --- Stopping ---
|
|
44
|
-
//
|
|
45
|
-
// Never SIGKILL first. A group gets the chance to end properly — a program to
|
|
46
|
-
// close what it opened, a `trama` command to stop its own run and report it.
|
|
47
|
-
// Killed outright, nothing in it gets to finish anything. So a group is asked
|
|
48
|
-
// to stop, and killed only if it is still there when the grace period is over.
|
|
49
|
-
//
|
|
50
|
-
// stopGroups does that for a runner that is there to see it through. When the
|
|
51
|
-
// runner itself is gone, its watchdog does the same (see watchdog.ts).
|
|
52
|
-
/** The timing of a stop, shared with the watchdog. */
|
|
53
|
-
export const STOP_TIMINGS = { grace: KILL_GRACE_MS, settle: KILL_SETTLE_MS, poll: STOP_POLL_MS };
|
|
54
|
-
/** Groups this process has asked to stop and is still watching. */
|
|
55
|
-
const stopping = new Map();
|
|
56
|
-
/** Called with each group as it is asked to stop — for the watchdog, which must not ask it again. */
|
|
57
|
-
let onAsked = () => { };
|
|
58
|
-
export function onGroupAskedToStop(listener) {
|
|
59
|
-
onAsked = listener;
|
|
60
|
-
}
|
|
61
|
-
function stopGroup(pgid) {
|
|
62
|
-
// Asked once is enough: to some programs a second SIGTERM means "now".
|
|
63
|
-
const watched = stopping.get(pgid);
|
|
64
|
-
if (watched)
|
|
65
|
-
return watched;
|
|
66
|
-
if (!signalGroup(pgid, "SIGTERM"))
|
|
67
|
-
return Promise.resolve();
|
|
68
|
-
onAsked(pgid);
|
|
69
|
-
const gone = new Promise((resolve) => {
|
|
70
|
-
let deadline = performance.now() + KILL_GRACE_MS;
|
|
71
|
-
let killed = false;
|
|
72
|
-
const poll = setInterval(() => {
|
|
73
|
-
const alive = signalGroup(pgid, 0);
|
|
74
|
-
if (alive && performance.now() < deadline)
|
|
75
|
-
return;
|
|
76
|
-
if (alive && !killed) {
|
|
77
|
-
// Out of patience. A killed group is gone in a moment; allow it that
|
|
78
|
-
// moment, but do not wait on one that for some reason never goes.
|
|
79
|
-
signalGroup(pgid, "SIGKILL");
|
|
80
|
-
killed = true;
|
|
81
|
-
deadline = performance.now() + KILL_SETTLE_MS;
|
|
82
|
-
return;
|
|
83
|
-
}
|
|
84
|
-
clearInterval(poll);
|
|
85
|
-
stopping.delete(pgid);
|
|
86
|
-
resolve();
|
|
87
|
-
}, STOP_POLL_MS);
|
|
88
|
-
});
|
|
89
|
-
stopping.set(pgid, gone);
|
|
90
|
-
return gone;
|
|
91
|
-
}
|
|
92
|
-
/**
|
|
93
|
-
* Stop process groups for good: SIGTERM now, SIGKILL after the grace period to
|
|
94
|
-
* whichever are still there. Resolves when none is left — so that what follows
|
|
95
|
-
* (merging a directory they were writing to, deleting it) finds them gone.
|
|
96
|
-
*/
|
|
97
|
-
export async function stopGroups(pgids) {
|
|
98
|
-
await Promise.all(pgids.map(stopGroup));
|
|
99
|
-
}
|
|
100
26
|
export function createAllowance(ms) {
|
|
101
27
|
let remaining = ms;
|
|
102
28
|
let holds = 0;
|
|
@@ -146,7 +72,7 @@ export function createAllowance(ms) {
|
|
|
146
72
|
/**
|
|
147
73
|
* Collect a child's output and wait for it to exit, enforcing a time limit
|
|
148
74
|
* and an optional stop request. Either one stops the child's whole process
|
|
149
|
-
* group (see
|
|
75
|
+
* group (see stopping.ts).
|
|
150
76
|
* Resolves on exit however it happened; rejects only if the child failed to spawn.
|
|
151
77
|
*/
|
|
152
78
|
export function superviseChild(child, options) {
|
|
@@ -159,7 +85,6 @@ export function superviseChild(child, options) {
|
|
|
159
85
|
const errDecoder = new StringDecoder("utf-8");
|
|
160
86
|
let timedOut = false;
|
|
161
87
|
let stopped = false;
|
|
162
|
-
let exited = false;
|
|
163
88
|
const emitOut = (text) => { if (text) {
|
|
164
89
|
out.append(text);
|
|
165
90
|
sinks?.stdout?.(text);
|
|
@@ -172,16 +97,13 @@ export function superviseChild(child, options) {
|
|
|
172
97
|
// A child that failed to spawn has no pid, and nothing to stop.
|
|
173
98
|
const terminate = () => { if (child.pid)
|
|
174
99
|
void stopGroups([child.pid]); };
|
|
175
|
-
const
|
|
176
|
-
if (
|
|
100
|
+
const offStop = onAbort(stopSignal, () => {
|
|
101
|
+
if (timedOut)
|
|
177
102
|
return;
|
|
178
103
|
stopped = true;
|
|
179
104
|
terminate();
|
|
180
|
-
};
|
|
181
|
-
stopSignal?.addEventListener("abort", onStopRequest, { once: true });
|
|
105
|
+
});
|
|
182
106
|
allowance.start(() => {
|
|
183
|
-
if (exited)
|
|
184
|
-
return;
|
|
185
107
|
timedOut = true;
|
|
186
108
|
terminate();
|
|
187
109
|
});
|
|
@@ -189,7 +111,7 @@ export function superviseChild(child, options) {
|
|
|
189
111
|
allowance.cancel();
|
|
190
112
|
if (drainTimer)
|
|
191
113
|
clearTimeout(drainTimer);
|
|
192
|
-
|
|
114
|
+
offStop();
|
|
193
115
|
};
|
|
194
116
|
child.stdout?.on("data", (chunk) => emitOut(outDecoder.write(chunk)));
|
|
195
117
|
child.stderr?.on("data", (chunk) => emitErr(errDecoder.write(chunk)));
|
|
@@ -202,10 +124,13 @@ export function superviseChild(child, options) {
|
|
|
202
124
|
// and what that writes is not the child's output. Stop waiting for it:
|
|
203
125
|
// otherwise such a process keeps the run from ever ending, timeout or not.
|
|
204
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();
|
|
205
131
|
drainTimer = setTimeout(() => { child.stdout?.destroy(); child.stderr?.destroy(); }, DRAIN_MS);
|
|
206
132
|
});
|
|
207
133
|
child.on("close", (code, signal) => {
|
|
208
|
-
exited = true;
|
|
209
134
|
cleanup();
|
|
210
135
|
emitOut(outDecoder.end());
|
|
211
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");
|