@trama-dev/runtime 0.2.2 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-backend.d.ts +24 -0
- package/dist/agent-backend.js +29 -0
- package/dist/agent.d.ts +12 -2
- package/dist/agent.js +23 -6
- package/dist/bridge-client.d.ts +22 -0
- package/dist/bridge-client.js +71 -0
- package/dist/child-process.d.ts +39 -6
- package/dist/child-process.js +132 -25
- package/dist/client.d.ts +1 -0
- package/dist/client.js +5 -48
- package/dist/context.d.ts +2 -0
- package/dist/context.js +1 -1
- package/dist/index.d.ts +6 -2
- package/dist/index.js +61 -15
- package/dist/ipc-server.d.ts +6 -2
- package/dist/ipc-server.js +65 -8
- package/dist/pi-adapter.d.ts +7 -14
- package/dist/pi-adapter.js +20 -54
- package/dist/runner-types.d.ts +18 -7
- package/dist/runner.d.ts +22 -5
- package/dist/runner.js +251 -71
- package/dist/tools.d.ts +2 -2
- package/dist/tools.js +15 -12
- package/dist/watchdog.d.ts +19 -0
- package/dist/watchdog.js +167 -0
- package/package.json +1 -1
- package/dist/lifetime.d.ts +0 -8
- package/dist/lifetime.js +0 -70
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export interface AgentCall {
|
|
2
|
+
/** The directory the agent works in: what its tools read is here, and what they write lands here. */
|
|
3
|
+
cwd: string;
|
|
4
|
+
/** Instructions for this call, on top of the agent's own. */
|
|
5
|
+
system?: string;
|
|
6
|
+
/** Cancels the call. A cancelled call rejects; it never resolves with a partial answer. */
|
|
7
|
+
signal?: AbortSignal;
|
|
8
|
+
}
|
|
9
|
+
export interface AgentBackend {
|
|
10
|
+
/**
|
|
11
|
+
* Run one prompt to completion and return the agent's final text.
|
|
12
|
+
*
|
|
13
|
+
* Each call stands alone — nothing carries over from one to the next, and
|
|
14
|
+
* everything a call depends on is in its arguments. A backend that cannot
|
|
15
|
+
* honour something in `call` must reject, never silently ignore it.
|
|
16
|
+
*/
|
|
17
|
+
ask(prompt: string, call: AgentCall): Promise<string>;
|
|
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>;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// The one thing the runtime needs from whatever does the LLM work: hand it a
|
|
2
|
+
// prompt, get its final text back.
|
|
3
|
+
//
|
|
4
|
+
// Everything trama asks of an LLM goes through this — a program's agent calls,
|
|
5
|
+
// generating a program, repairing one. To a backend they are all the same
|
|
6
|
+
// request; what to ask for, and what to make of the reply, is decided by the
|
|
7
|
+
// caller. Nothing outside the backend's own file knows which agent, harness or
|
|
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
|
+
}
|
package/dist/agent.d.ts
CHANGED
|
@@ -1,3 +1,13 @@
|
|
|
1
1
|
import type { Agent } from "./types.js";
|
|
2
|
-
import type {
|
|
3
|
-
|
|
2
|
+
import type { AgentBackend } from "./agent-backend.js";
|
|
3
|
+
/**
|
|
4
|
+
* The program in an LLM reply that was asked to contain nothing else: the last
|
|
5
|
+
* fenced block if there is one (models add explanations, or show a "before"
|
|
6
|
+
* first), otherwise the whole reply.
|
|
7
|
+
*/
|
|
8
|
+
export declare function stripCodeFences(text: string): string;
|
|
9
|
+
/**
|
|
10
|
+
* The `agent` a program talks to: its calls, served by `backend` working in
|
|
11
|
+
* `cwd`, and cancelled together through `signal`.
|
|
12
|
+
*/
|
|
13
|
+
export declare function createAgent(backend: AgentBackend, cwd: string, signal?: AbortSignal): Agent;
|
package/dist/agent.js
CHANGED
|
@@ -1,3 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The program in an LLM reply that was asked to contain nothing else: the last
|
|
3
|
+
* fenced block if there is one (models add explanations, or show a "before"
|
|
4
|
+
* first), otherwise the whole reply.
|
|
5
|
+
*/
|
|
6
|
+
export function stripCodeFences(text) {
|
|
7
|
+
const trimmed = text.trim();
|
|
8
|
+
const matches = [...trimmed.matchAll(/```(?:\w*)\s*\n([\s\S]*?)\n\s*```/g)];
|
|
9
|
+
if (matches.length > 0) {
|
|
10
|
+
return matches[matches.length - 1][1].trim();
|
|
11
|
+
}
|
|
12
|
+
return trimmed;
|
|
13
|
+
}
|
|
1
14
|
/**
|
|
2
15
|
* Minimal shape validation.
|
|
3
16
|
* Checks all schema keys exist and values match declared primitive types.
|
|
@@ -20,15 +33,19 @@ function validateShape(result, schema) {
|
|
|
20
33
|
}
|
|
21
34
|
return null;
|
|
22
35
|
}
|
|
23
|
-
|
|
36
|
+
/**
|
|
37
|
+
* The `agent` a program talks to: its calls, served by `backend` working in
|
|
38
|
+
* `cwd`, and cancelled together through `signal`.
|
|
39
|
+
*/
|
|
40
|
+
export function createAgent(backend, cwd, signal) {
|
|
24
41
|
return {
|
|
25
42
|
async instruct(prompt, options) {
|
|
26
|
-
return
|
|
43
|
+
return backend.ask(prompt, { cwd, system: options?.system, signal });
|
|
27
44
|
},
|
|
28
45
|
async generate(input) {
|
|
29
46
|
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
47
|
const fullPrompt = `${input.prompt}\n\n${schemaInstruction}`;
|
|
31
|
-
const
|
|
48
|
+
const call = { cwd, system: input.system, signal };
|
|
32
49
|
const parseAndValidate = (response) => {
|
|
33
50
|
const trimmed = response.trim();
|
|
34
51
|
// Try raw parse first — avoids mangling valid JSON that contains
|
|
@@ -46,15 +63,15 @@ export function createAgent(adapter, signal) {
|
|
|
46
63
|
throw new Error(`Schema validation failed: ${error}`);
|
|
47
64
|
return stripToSchema(parsed, input.schema);
|
|
48
65
|
};
|
|
49
|
-
// First attempt —
|
|
66
|
+
// First attempt — backend errors (network/auth) propagate immediately.
|
|
50
67
|
// Only parse/validation failures trigger a retry.
|
|
51
|
-
const response = await
|
|
68
|
+
const response = await backend.ask(fullPrompt, call);
|
|
52
69
|
try {
|
|
53
70
|
return parseAndValidate(response);
|
|
54
71
|
}
|
|
55
72
|
catch (firstError) {
|
|
56
73
|
const retryPrompt = `Your previous response failed validation: ${firstError}.\nTry again.\n\n${fullPrompt}`;
|
|
57
|
-
const retryResponse = await
|
|
74
|
+
const retryResponse = await backend.ask(retryPrompt, call);
|
|
58
75
|
return parseAndValidate(retryResponse);
|
|
59
76
|
}
|
|
60
77
|
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { Workspace } from "./types.js";
|
|
2
|
+
export interface Bridge {
|
|
3
|
+
/** What the runner handed the program when it started it — the bridge secret among it. */
|
|
4
|
+
init: Record<string, any>;
|
|
5
|
+
/** POST one call to the runner and return its result. */
|
|
6
|
+
call(endpoint: string, body: unknown): Promise<any>;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* @param port - the runner's loopback port (TRAMA_PORT)
|
|
10
|
+
* @param initPath - the file the runner wrote for this program (TRAMA_INIT)
|
|
11
|
+
*/
|
|
12
|
+
export declare function openBridge(port: string, initPath: string): Bridge;
|
|
13
|
+
/**
|
|
14
|
+
* The bridge to the runner that started this process as a program — or null
|
|
15
|
+
* when this process is not a program, and so is itself where runs happen.
|
|
16
|
+
*/
|
|
17
|
+
export declare function parentBridge(): Bridge | null;
|
|
18
|
+
/**
|
|
19
|
+
* A workspace reached over a bridge: the directory `dir`, or — without one —
|
|
20
|
+
* the workspace of the session the calling program is running in.
|
|
21
|
+
*/
|
|
22
|
+
export declare function remoteWorkspace(call: Bridge["call"], dir?: string): Workspace;
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// The program's end of the IPC bridge: how code running inside a program
|
|
2
|
+
// reaches the runner that started it (ipc-server.ts is the other end).
|
|
3
|
+
import { readFileSync } from "fs";
|
|
4
|
+
import { request } from "http";
|
|
5
|
+
/**
|
|
6
|
+
* @param port - the runner's loopback port (TRAMA_PORT)
|
|
7
|
+
* @param initPath - the file the runner wrote for this program (TRAMA_INIT)
|
|
8
|
+
*/
|
|
9
|
+
export function openBridge(port, initPath) {
|
|
10
|
+
const init = JSON.parse(readFileSync(initPath, "utf-8"));
|
|
11
|
+
// A call lasts as long as the work behind it — an agent run, or the whole
|
|
12
|
+
// run of another program — so this uses node:http, which sets no deadline
|
|
13
|
+
// for the response. (fetch gives up after five minutes without response headers.)
|
|
14
|
+
const call = (endpoint, body) => new Promise((resolve, reject) => {
|
|
15
|
+
const payload = JSON.stringify(body);
|
|
16
|
+
const req = request({
|
|
17
|
+
host: "127.0.0.1",
|
|
18
|
+
port,
|
|
19
|
+
path: endpoint,
|
|
20
|
+
method: "POST",
|
|
21
|
+
headers: {
|
|
22
|
+
"Content-Type": "application/json",
|
|
23
|
+
"Content-Length": Buffer.byteLength(payload),
|
|
24
|
+
"Authorization": `Bearer ${init.token}`,
|
|
25
|
+
},
|
|
26
|
+
}, (res) => {
|
|
27
|
+
const chunks = [];
|
|
28
|
+
res.on("data", (chunk) => chunks.push(chunk));
|
|
29
|
+
res.on("error", reject);
|
|
30
|
+
res.on("end", () => {
|
|
31
|
+
const text = Buffer.concat(chunks).toString("utf-8");
|
|
32
|
+
if (res.statusCode !== 200)
|
|
33
|
+
reject(new Error(`trama runtime error: ${text}`));
|
|
34
|
+
else
|
|
35
|
+
resolve(JSON.parse(text).result);
|
|
36
|
+
});
|
|
37
|
+
});
|
|
38
|
+
req.on("error", reject);
|
|
39
|
+
req.end(payload);
|
|
40
|
+
});
|
|
41
|
+
return { init, call };
|
|
42
|
+
}
|
|
43
|
+
let parent;
|
|
44
|
+
/**
|
|
45
|
+
* The bridge to the runner that started this process as a program — or null
|
|
46
|
+
* when this process is not a program, and so is itself where runs happen.
|
|
47
|
+
*/
|
|
48
|
+
export function parentBridge() {
|
|
49
|
+
if (parent === undefined) {
|
|
50
|
+
const { TRAMA_PORT: port, TRAMA_INIT: initPath } = process.env;
|
|
51
|
+
try {
|
|
52
|
+
parent = port && initPath ? openBridge(port, initPath) : null;
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
parent = null; // a stale environment: there is no runner to ask
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return parent;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* A workspace reached over a bridge: the directory `dir`, or — without one —
|
|
62
|
+
* the workspace of the session the calling program is running in.
|
|
63
|
+
*/
|
|
64
|
+
export function remoteWorkspace(call, dir) {
|
|
65
|
+
return {
|
|
66
|
+
read: (path) => call("/workspace/read", { dir, path }),
|
|
67
|
+
write: (path, content) => call("/workspace/write", { dir, path, content }),
|
|
68
|
+
list: (pattern) => call("/workspace/list", { dir, pattern }),
|
|
69
|
+
observe: (pattern, options) => call("/workspace/observe", { dir, pattern, ...options }),
|
|
70
|
+
};
|
|
71
|
+
}
|
package/dist/child-process.d.ts
CHANGED
|
@@ -10,15 +10,48 @@ export declare function cappedBuffer(): {
|
|
|
10
10
|
* Signal 0 only probes. Returns false if the group no longer exists.
|
|
11
11
|
*/
|
|
12
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
|
+
/**
|
|
27
|
+
* A time limit that only runs down while nothing is holding it.
|
|
28
|
+
*
|
|
29
|
+
* A program's timeout is an allowance for its own work. While it waits for a
|
|
30
|
+
* run it started — one that is under a timeout of its own — the clock stops,
|
|
31
|
+
* so that every moment is charged to exactly one of them and a program is
|
|
32
|
+
* never killed for the time something else was entitled to take.
|
|
33
|
+
*/
|
|
34
|
+
export interface Allowance {
|
|
35
|
+
/** Start the clock. `onSpent` is called once, if the allowance runs out. */
|
|
36
|
+
start(onSpent: () => void): void;
|
|
37
|
+
/** Stop the clock until the returned function is called. Holds add up: the clock runs only when all are released. */
|
|
38
|
+
hold(): () => void;
|
|
39
|
+
/** Stop for good; `onSpent` will not be called. */
|
|
40
|
+
cancel(): void;
|
|
41
|
+
}
|
|
42
|
+
export declare function createAllowance(ms: number): Allowance;
|
|
13
43
|
export interface SuperviseOptions {
|
|
14
|
-
/**
|
|
15
|
-
|
|
44
|
+
/**
|
|
45
|
+
* Time limit: a number of ms of wall-clock time, or an allowance that its
|
|
46
|
+
* owner may put on hold. On expiry the child's process group is terminated.
|
|
47
|
+
*/
|
|
48
|
+
timeout: number | Allowance;
|
|
16
49
|
/** Receive output as it arrives, in addition to it being collected. */
|
|
17
50
|
sinks?: {
|
|
18
51
|
stdout?: (chunk: string) => void;
|
|
19
52
|
stderr?: (chunk: string) => void;
|
|
20
53
|
};
|
|
21
|
-
/** Aborting this asks the child to stop
|
|
54
|
+
/** Aborting this asks the child to stop, the same way a timeout does. */
|
|
22
55
|
stopSignal?: AbortSignal;
|
|
23
56
|
}
|
|
24
57
|
export interface ChildExit {
|
|
@@ -32,9 +65,9 @@ export interface ChildExit {
|
|
|
32
65
|
stopped: boolean;
|
|
33
66
|
}
|
|
34
67
|
/**
|
|
35
|
-
* Collect a child's output and wait for it to exit, enforcing a
|
|
36
|
-
*
|
|
37
|
-
*
|
|
68
|
+
* Collect a child's output and wait for it to exit, enforcing a time limit
|
|
69
|
+
* and an optional stop request. Either one stops the child's whole process
|
|
70
|
+
* group (see stopGroups).
|
|
38
71
|
* Resolves on exit however it happened; rejects only if the child failed to spawn.
|
|
39
72
|
*/
|
|
40
73
|
export declare function superviseChild(child: ChildProcess, options: SuperviseOptions): Promise<ChildExit>;
|
package/dist/child-process.js
CHANGED
|
@@ -1,7 +1,14 @@
|
|
|
1
1
|
import { StringDecoder } from "string_decoder";
|
|
2
2
|
const MAX_OUTPUT = 10 * 1024 * 1024; // 10 MB
|
|
3
|
-
/** How long a
|
|
3
|
+
/** How long a process group gets to exit after SIGTERM before it is sent SIGKILL. */
|
|
4
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
|
+
/** How long a child's output is waited for once the child itself has exited. */
|
|
9
|
+
const DRAIN_MS = 1000;
|
|
10
|
+
/** The longest delay a timer can be given; a longer one fires at once. */
|
|
11
|
+
const MAX_TIMER_MS = 2 ** 31 - 1;
|
|
5
12
|
/** A string accumulator that stops growing (and says so) once it passes 10MB. */
|
|
6
13
|
export function cappedBuffer() {
|
|
7
14
|
let buf = "";
|
|
@@ -33,14 +40,118 @@ export function signalGroup(pgid, signal) {
|
|
|
33
40
|
return false;
|
|
34
41
|
}
|
|
35
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
|
+
export function createAllowance(ms) {
|
|
101
|
+
let remaining = ms;
|
|
102
|
+
let holds = 0;
|
|
103
|
+
let onSpent = null;
|
|
104
|
+
// Set while the clock is running: the timer, and when it was started. Time
|
|
105
|
+
// is read from a clock that only moves forward — the wall clock can be set.
|
|
106
|
+
let running = null;
|
|
107
|
+
const pause = () => {
|
|
108
|
+
if (!running)
|
|
109
|
+
return;
|
|
110
|
+
clearTimeout(running.timer);
|
|
111
|
+
remaining = Math.max(0, remaining - (performance.now() - running.since));
|
|
112
|
+
running = null;
|
|
113
|
+
};
|
|
114
|
+
const run = () => {
|
|
115
|
+
if (!onSpent || holds > 0 || running)
|
|
116
|
+
return;
|
|
117
|
+
running = {
|
|
118
|
+
since: performance.now(),
|
|
119
|
+
timer: setTimeout(() => {
|
|
120
|
+
pause();
|
|
121
|
+
if (remaining > 0)
|
|
122
|
+
return run(); // an allowance longer than one timer can measure
|
|
123
|
+
const spent = onSpent;
|
|
124
|
+
onSpent = null;
|
|
125
|
+
spent?.();
|
|
126
|
+
}, Math.min(remaining, MAX_TIMER_MS)),
|
|
127
|
+
};
|
|
128
|
+
};
|
|
129
|
+
return {
|
|
130
|
+
start(fn) { onSpent = fn; run(); },
|
|
131
|
+
hold() {
|
|
132
|
+
holds += 1;
|
|
133
|
+
pause();
|
|
134
|
+
let released = false;
|
|
135
|
+
return () => {
|
|
136
|
+
if (released)
|
|
137
|
+
return;
|
|
138
|
+
released = true;
|
|
139
|
+
holds -= 1;
|
|
140
|
+
run();
|
|
141
|
+
};
|
|
142
|
+
},
|
|
143
|
+
cancel() { pause(); onSpent = null; },
|
|
144
|
+
};
|
|
145
|
+
}
|
|
36
146
|
/**
|
|
37
|
-
* Collect a child's output and wait for it to exit, enforcing a
|
|
38
|
-
*
|
|
39
|
-
*
|
|
147
|
+
* Collect a child's output and wait for it to exit, enforcing a time limit
|
|
148
|
+
* and an optional stop request. Either one stops the child's whole process
|
|
149
|
+
* group (see stopGroups).
|
|
40
150
|
* Resolves on exit however it happened; rejects only if the child failed to spawn.
|
|
41
151
|
*/
|
|
42
152
|
export function superviseChild(child, options) {
|
|
43
|
-
const {
|
|
153
|
+
const { sinks, stopSignal } = options;
|
|
154
|
+
const allowance = typeof options.timeout === "number" ? createAllowance(options.timeout) : options.timeout;
|
|
44
155
|
return new Promise((resolve, reject) => {
|
|
45
156
|
const out = cappedBuffer();
|
|
46
157
|
const err = cappedBuffer();
|
|
@@ -49,7 +160,6 @@ export function superviseChild(child, options) {
|
|
|
49
160
|
let timedOut = false;
|
|
50
161
|
let stopped = false;
|
|
51
162
|
let exited = false;
|
|
52
|
-
let killFallbackTimer = null;
|
|
53
163
|
const emitOut = (text) => { if (text) {
|
|
54
164
|
out.append(text);
|
|
55
165
|
sinks?.stdout?.(text);
|
|
@@ -58,20 +168,10 @@ export function superviseChild(child, options) {
|
|
|
58
168
|
err.append(text);
|
|
59
169
|
sinks?.stderr?.(text);
|
|
60
170
|
} };
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
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
|
-
};
|
|
171
|
+
let drainTimer = null;
|
|
172
|
+
// A child that failed to spawn has no pid, and nothing to stop.
|
|
173
|
+
const terminate = () => { if (child.pid)
|
|
174
|
+
void stopGroups([child.pid]); };
|
|
75
175
|
const onStopRequest = () => {
|
|
76
176
|
if (exited || stopped || timedOut)
|
|
77
177
|
return;
|
|
@@ -79,16 +179,16 @@ export function superviseChild(child, options) {
|
|
|
79
179
|
terminate();
|
|
80
180
|
};
|
|
81
181
|
stopSignal?.addEventListener("abort", onStopRequest, { once: true });
|
|
82
|
-
|
|
182
|
+
allowance.start(() => {
|
|
83
183
|
if (exited)
|
|
84
184
|
return;
|
|
85
185
|
timedOut = true;
|
|
86
186
|
terminate();
|
|
87
|
-
}
|
|
187
|
+
});
|
|
88
188
|
const cleanup = () => {
|
|
89
|
-
|
|
90
|
-
if (
|
|
91
|
-
clearTimeout(
|
|
189
|
+
allowance.cancel();
|
|
190
|
+
if (drainTimer)
|
|
191
|
+
clearTimeout(drainTimer);
|
|
92
192
|
stopSignal?.removeEventListener("abort", onStopRequest);
|
|
93
193
|
};
|
|
94
194
|
child.stdout?.on("data", (chunk) => emitOut(outDecoder.write(chunk)));
|
|
@@ -97,6 +197,13 @@ export function superviseChild(child, options) {
|
|
|
97
197
|
cleanup();
|
|
98
198
|
reject(spawnError);
|
|
99
199
|
});
|
|
200
|
+
// The output pipes normally close right behind the exit. They stay open
|
|
201
|
+
// only if something else inherited them — a process the child detached —
|
|
202
|
+
// and what that writes is not the child's output. Stop waiting for it:
|
|
203
|
+
// otherwise such a process keeps the run from ever ending, timeout or not.
|
|
204
|
+
child.on("exit", () => {
|
|
205
|
+
drainTimer = setTimeout(() => { child.stdout?.destroy(); child.stderr?.destroy(); }, DRAIN_MS);
|
|
206
|
+
});
|
|
100
207
|
child.on("close", (code, signal) => {
|
|
101
208
|
exited = true;
|
|
102
209
|
cleanup();
|
package/dist/client.d.ts
CHANGED
|
@@ -2,4 +2,5 @@ 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
|
+
/** workspace.* exists only inside a session — everywhere else it fails clearly, without a round trip. */
|
|
5
6
|
export declare const workspace: Workspace;
|
package/dist/client.js
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
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
3
|
// (ipc-server.ts), which does the real work.
|
|
4
|
-
import {
|
|
5
|
-
import { request } from "http";
|
|
4
|
+
import { openBridge, remoteWorkspace } from "./bridge-client.js";
|
|
6
5
|
import { assertSerializable } from "./serializable.js";
|
|
7
6
|
const PORT = process.env.TRAMA_PORT;
|
|
8
7
|
if (!PORT) {
|
|
@@ -14,43 +13,7 @@ if (!INIT_PATH) {
|
|
|
14
13
|
throw new Error("@trama-dev/runtime: TRAMA_INIT env var missing. " +
|
|
15
14
|
"This program must be launched by the trama runner.");
|
|
16
15
|
}
|
|
17
|
-
const initData =
|
|
18
|
-
/**
|
|
19
|
-
* POST one call to the runner and return its result.
|
|
20
|
-
*
|
|
21
|
-
* A call lasts as long as the work behind it — an agent run, or a wait for
|
|
22
|
-
* another program — so this uses node:http, which sets no deadline for the
|
|
23
|
-
* response. (fetch gives up after five minutes without response headers.)
|
|
24
|
-
*/
|
|
25
|
-
function call(endpoint, body) {
|
|
26
|
-
return new Promise((resolve, reject) => {
|
|
27
|
-
const payload = JSON.stringify(body);
|
|
28
|
-
const req = request({
|
|
29
|
-
host: "127.0.0.1",
|
|
30
|
-
port: PORT,
|
|
31
|
-
path: endpoint,
|
|
32
|
-
method: "POST",
|
|
33
|
-
headers: {
|
|
34
|
-
"Content-Type": "application/json",
|
|
35
|
-
"Content-Length": Buffer.byteLength(payload),
|
|
36
|
-
"Authorization": `Bearer ${initData.token}`,
|
|
37
|
-
},
|
|
38
|
-
}, (res) => {
|
|
39
|
-
const chunks = [];
|
|
40
|
-
res.on("data", (chunk) => chunks.push(chunk));
|
|
41
|
-
res.on("error", reject);
|
|
42
|
-
res.on("end", () => {
|
|
43
|
-
const text = Buffer.concat(chunks).toString("utf-8");
|
|
44
|
-
if (res.statusCode !== 200)
|
|
45
|
-
reject(new Error(`trama runtime error: ${text}`));
|
|
46
|
-
else
|
|
47
|
-
resolve(JSON.parse(text).result);
|
|
48
|
-
});
|
|
49
|
-
});
|
|
50
|
-
req.on("error", reject);
|
|
51
|
-
req.end(payload);
|
|
52
|
-
});
|
|
53
|
-
}
|
|
16
|
+
const { init: initData, call } = openBridge(PORT, INIT_PATH);
|
|
54
17
|
/** Log payloads are best-effort: anything that can't be sent as JSON is replaced by its string form. */
|
|
55
18
|
function sendable(data) {
|
|
56
19
|
try {
|
|
@@ -105,15 +68,9 @@ export const tools = {
|
|
|
105
68
|
fetch: (url, opts) => call("/tools/fetch", { url, ...opts }),
|
|
106
69
|
};
|
|
107
70
|
/** workspace.* exists only inside a session — everywhere else it fails clearly, without a round trip. */
|
|
108
|
-
|
|
71
|
+
export const workspace = remoteWorkspace((endpoint, body) => {
|
|
109
72
|
if (!initData.inSession) {
|
|
110
|
-
|
|
73
|
+
return Promise.reject(new Error("workspace is only available when running in a session"));
|
|
111
74
|
}
|
|
112
75
|
return call(endpoint, body);
|
|
113
|
-
}
|
|
114
|
-
export const workspace = {
|
|
115
|
-
read: (path) => workspaceCall("/workspace/read", { path }),
|
|
116
|
-
write: (path, content) => workspaceCall("/workspace/write", { path, content }),
|
|
117
|
-
list: (pattern) => workspaceCall("/workspace/list", { pattern }),
|
|
118
|
-
observe: (pattern, options) => workspaceCall("/workspace/observe", { pattern, ...options }),
|
|
119
|
-
};
|
|
76
|
+
});
|
package/dist/context.d.ts
CHANGED
|
@@ -14,4 +14,6 @@ export declare function createContext(projectDir: string, initialState: Record<s
|
|
|
14
14
|
maxIterations?: number;
|
|
15
15
|
argsOverride?: Record<string, unknown>;
|
|
16
16
|
onReady?: (data?: Record<string, unknown>) => void;
|
|
17
|
+
/** Where the run's log lines are shown as they are written. Defaults to the console. */
|
|
18
|
+
print?: (line: string) => void;
|
|
17
19
|
}): Ctx;
|
package/dist/context.js
CHANGED
|
@@ -51,7 +51,7 @@ export function createContext(projectDir, initialState, options) {
|
|
|
51
51
|
}
|
|
52
52
|
const entry = { ts: Date.now(), message, data: safeData };
|
|
53
53
|
appendFileSync(logsPath, JSON.stringify(entry) + "\n");
|
|
54
|
-
console.log(`[trama] ${message}`);
|
|
54
|
+
(options?.print ?? console.log)(`[trama] ${message}`);
|
|
55
55
|
},
|
|
56
56
|
async ready(data) {
|
|
57
57
|
if (readyCalled)
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
|
-
export { runProgram } from "./runner.js";
|
|
2
|
-
export { createWorkspace } from "./workspace.js";
|
|
3
1
|
export type { ProgramResult, RunOptions } from "./runner-types.js";
|
|
2
|
+
import type { ProgramResult, RunOptions } from "./runner-types.js";
|
|
4
3
|
export type { Workspace, ObserveResult } from "./types.js";
|
|
4
|
+
import type { Workspace } from "./types.js";
|
|
5
|
+
/** Run a project to an outcome: done, yielded, or failed. */
|
|
6
|
+
export declare function runProgram(options: RunOptions): Promise<ProgramResult>;
|
|
7
|
+
/** The shared workspace in a directory, created if it does not exist: read, write, list, observe. */
|
|
8
|
+
export declare function createWorkspace(dir: string): Workspace;
|
|
5
9
|
export declare function validateProjectName(name: string): void;
|
|
6
10
|
export declare function resolveProject(name: string): string;
|
|
7
11
|
export declare function createProject(name: string, prompt: string, options?: {
|