@trama-dev/runtime 0.4.0 → 0.6.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 +127 -7
- package/dist/agent-backend.js +38 -19
- package/dist/agent-host.d.ts +50 -0
- package/dist/agent-host.js +97 -0
- package/dist/agent-hosts.d.ts +14 -0
- package/dist/agent-hosts.js +321 -0
- package/dist/agent.d.ts +26 -3
- package/dist/agent.js +165 -43
- package/dist/bridge-client.d.ts +6 -0
- package/dist/bridge-client.js +69 -16
- package/dist/budget.d.ts +52 -0
- package/dist/budget.js +118 -0
- package/dist/child-process.d.ts +18 -0
- package/dist/child-process.js +38 -9
- package/dist/client.d.ts +2 -1
- package/dist/client.js +9 -19
- 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 +7 -2
- package/dist/index.js +254 -88
- package/dist/ipc-server.d.ts +14 -5
- package/dist/ipc-server.js +174 -144
- package/dist/journal-view.d.ts +2 -0
- package/dist/journal-view.js +52 -7
- package/dist/journal.d.ts +27 -9
- package/dist/journal.js +216 -79
- package/dist/meta.d.ts +18 -0
- package/dist/meta.js +29 -0
- package/dist/model-relay.d.ts +130 -0
- package/dist/model-relay.js +339 -0
- package/dist/path-guard.d.ts +128 -19
- package/dist/path-guard.js +384 -68
- package/dist/pi-adapter.d.ts +35 -9
- package/dist/pi-adapter.js +865 -66
- package/dist/replace-file.d.ts +31 -0
- package/dist/replace-file.js +75 -0
- package/dist/runner-types.d.ts +35 -0
- package/dist/runner.d.ts +202 -30
- package/dist/runner.js +949 -273
- package/dist/serializable.d.ts +10 -4
- package/dist/serializable.js +56 -31
- package/dist/stopping.d.ts +37 -3
- package/dist/stopping.js +167 -21
- package/dist/tools.d.ts +2 -1
- package/dist/tools.js +90 -21
- package/dist/tree.d.ts +241 -0
- package/dist/tree.js +1431 -0
- package/dist/types.d.ts +106 -15
- package/dist/workspace.d.ts +7 -0
- package/dist/workspace.js +93 -104
- package/package.json +1 -1
package/dist/bridge-client.js
CHANGED
|
@@ -1,23 +1,66 @@
|
|
|
1
1
|
// The program's end of the IPC bridge: how code running inside a program
|
|
2
2
|
// reaches the runner that started it (ipc-server.ts is the other end).
|
|
3
3
|
import { readFileSync } from "fs";
|
|
4
|
-
import { request } from "http";
|
|
4
|
+
import { Agent, request } from "http";
|
|
5
|
+
import { messageOf } from "./errors.js";
|
|
6
|
+
let cached;
|
|
7
|
+
/**
|
|
8
|
+
* How calls reach the runner: straight to it. Not by way of a proxy that the
|
|
9
|
+
* program's environment names for its HTTP — which node's own agent would
|
|
10
|
+
* take, and hand the call, with the bridge's secret, to. (Otherwise as node's
|
|
11
|
+
* own agent is.)
|
|
12
|
+
*/
|
|
13
|
+
const direct = new Agent({ keepAlive: true, scheduling: "lifo", timeout: 5000 });
|
|
14
|
+
/**
|
|
15
|
+
* A call's body as it goes over the bridge. JSON has no way to say NaN or
|
|
16
|
+
* Infinity, a function or a symbol: it writes null for them or leaves them
|
|
17
|
+
* out, which the other end reads as a field that was not given. So what it
|
|
18
|
+
* cannot carry is refused here — a call is carried out as it was made, or not
|
|
19
|
+
* at all.
|
|
20
|
+
*/
|
|
21
|
+
function encode(endpoint, body) {
|
|
22
|
+
return JSON.stringify(body, function (name, value) {
|
|
23
|
+
const lost = typeof value === "number" && !Number.isFinite(value) ? String(value)
|
|
24
|
+
: typeof value === "function" || typeof value === "symbol" ? `a ${typeof value}`
|
|
25
|
+
: undefined;
|
|
26
|
+
if (lost !== undefined) {
|
|
27
|
+
const where = Array.isArray(this) ? `item ${name} of a list` : name || "what the call is made with";
|
|
28
|
+
throw new TypeError(`${where} is ${lost}, which cannot be sent to the runner (${endpoint})`);
|
|
29
|
+
}
|
|
30
|
+
return value;
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* The body of a call that takes options: what the call is made with, and the
|
|
35
|
+
* options beside it. An option that bears the name of one of those is not an
|
|
36
|
+
* option — and would otherwise take its place.
|
|
37
|
+
*/
|
|
38
|
+
export function withOptions(madeWith, options) {
|
|
39
|
+
const taken = Object.keys(options ?? {}).find(name => Object.hasOwn(madeWith, name));
|
|
40
|
+
if (taken !== undefined)
|
|
41
|
+
throw new TypeError(`${taken} is what the call is made with, and cannot be given as an option`);
|
|
42
|
+
return { ...madeWith, ...options };
|
|
43
|
+
}
|
|
5
44
|
/**
|
|
6
45
|
* @param port - the runner's loopback port (TRAMA_PORT)
|
|
7
46
|
* @param initPath - the file the runner wrote for this program (TRAMA_INIT)
|
|
8
47
|
*/
|
|
9
48
|
export function openBridge(port, initPath) {
|
|
49
|
+
if (cached?.bridge && cached.port === port && cached.initPath === initPath) {
|
|
50
|
+
return cached.bridge;
|
|
51
|
+
}
|
|
10
52
|
const init = JSON.parse(readFileSync(initPath, "utf-8"));
|
|
11
53
|
// A call lasts as long as the work behind it — an agent run, or the whole
|
|
12
54
|
// run of another program — so this uses node:http, which sets no deadline
|
|
13
55
|
// for the response. (fetch gives up after five minutes without response headers.)
|
|
14
56
|
const call = (endpoint, body) => new Promise((resolve, reject) => {
|
|
15
|
-
const payload =
|
|
57
|
+
const payload = encode(endpoint, body);
|
|
16
58
|
const req = request({
|
|
17
59
|
host: "127.0.0.1",
|
|
18
60
|
port,
|
|
19
61
|
path: endpoint,
|
|
20
62
|
method: "POST",
|
|
63
|
+
agent: direct,
|
|
21
64
|
headers: {
|
|
22
65
|
"Content-Type": "application/json",
|
|
23
66
|
"Content-Length": Buffer.byteLength(payload),
|
|
@@ -27,35 +70,45 @@ export function openBridge(port, initPath) {
|
|
|
27
70
|
const chunks = [];
|
|
28
71
|
res.on("data", (chunk) => chunks.push(chunk));
|
|
29
72
|
res.on("error", reject);
|
|
73
|
+
// (An answer that is cut off is an error of the response, above: it never comes to an end.)
|
|
30
74
|
res.on("end", () => {
|
|
31
75
|
const text = Buffer.concat(chunks).toString("utf-8");
|
|
32
76
|
if (res.statusCode !== 200)
|
|
33
|
-
reject(new Error(`trama runtime error: ${text}`));
|
|
34
|
-
|
|
77
|
+
return reject(new Error(`trama runtime error: ${text}`));
|
|
78
|
+
// Whatever is wrong with an answer is the call's to fail with — not thrown at whoever is on the stack.
|
|
79
|
+
try {
|
|
35
80
|
resolve(JSON.parse(text).result);
|
|
81
|
+
}
|
|
82
|
+
catch (err) {
|
|
83
|
+
reject(new Error(`trama runtime error: the runner's answer to ${endpoint} cannot be read: ${messageOf(err)}`));
|
|
84
|
+
}
|
|
36
85
|
});
|
|
37
86
|
});
|
|
38
87
|
req.on("error", reject);
|
|
39
88
|
req.end(payload);
|
|
40
89
|
});
|
|
41
|
-
|
|
90
|
+
const bridge = { init, call };
|
|
91
|
+
cached = { port, initPath, bridge };
|
|
92
|
+
return bridge;
|
|
42
93
|
}
|
|
43
|
-
let parent;
|
|
44
94
|
/**
|
|
45
95
|
* The bridge to the runner that started this process as a program — or null
|
|
46
96
|
* when this process is not a program, and so is itself where runs happen.
|
|
47
97
|
*/
|
|
48
98
|
export function parentBridge() {
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
99
|
+
const { TRAMA_PORT: port, TRAMA_INIT: initPath } = process.env;
|
|
100
|
+
if (!port || !initPath)
|
|
101
|
+
return null;
|
|
102
|
+
if (cached && cached.port === port && cached.initPath === initPath) {
|
|
103
|
+
return cached.bridge;
|
|
104
|
+
}
|
|
105
|
+
try {
|
|
106
|
+
return openBridge(port, initPath);
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
cached = { port, initPath, bridge: null }; // a stale environment: there is no runner to ask
|
|
110
|
+
return null;
|
|
57
111
|
}
|
|
58
|
-
return parent;
|
|
59
112
|
}
|
|
60
113
|
/**
|
|
61
114
|
* A workspace reached over a bridge: the directory `dir`, or — without one —
|
|
@@ -66,6 +119,6 @@ export function remoteWorkspace(call, dir) {
|
|
|
66
119
|
read: (path) => call("/workspace/read", { dir, path }),
|
|
67
120
|
write: (path, content) => call("/workspace/write", { dir, path, content }),
|
|
68
121
|
list: (pattern) => call("/workspace/list", { dir, pattern }),
|
|
69
|
-
observe: (pattern, options) => call("/workspace/observe", { dir, pattern,
|
|
122
|
+
observe: async (pattern, options) => call("/workspace/observe", withOptions({ dir, pattern }, options)),
|
|
70
123
|
};
|
|
71
124
|
}
|
package/dist/budget.d.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { AgentUsage } from "./agent-backend.js";
|
|
2
|
+
/** A cap on what is asked of a model. What is not named is not capped. */
|
|
3
|
+
export interface Budget {
|
|
4
|
+
/** US dollars, as the backend's price list counts what was used. */
|
|
5
|
+
cost?: number;
|
|
6
|
+
/** Tokens: all the model read and wrote, from a cache or not. */
|
|
7
|
+
tokens?: number;
|
|
8
|
+
/**
|
|
9
|
+
* How many calls to a model's agent may be taken on: an agent call is one,
|
|
10
|
+
* a `generate` that had to ask again two, a request for a fix one. (A call
|
|
11
|
+
* counts when it is taken on, whatever then becomes of it.)
|
|
12
|
+
*/
|
|
13
|
+
calls?: number;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* A budget as it was given — in a config, to a run, over the bridge — held to
|
|
17
|
+
* what one is: a plain object of caps, each a number that is not negative,
|
|
18
|
+
* and `calls` a whole one. Returns a copy. Throws with what is wrong, as said
|
|
19
|
+
* of `what` it was given as.
|
|
20
|
+
*/
|
|
21
|
+
export declare function checkedBudget(given: unknown, what?: string): Budget;
|
|
22
|
+
/** What is counted of one call to a backend, while it lasts. */
|
|
23
|
+
export interface Account {
|
|
24
|
+
/**
|
|
25
|
+
* What the call has used by now, in all. Returns why the call is to go no
|
|
26
|
+
* further — a budget it counts in has been reached — or nothing.
|
|
27
|
+
*/
|
|
28
|
+
sofar(usage: AgentUsage): string | undefined;
|
|
29
|
+
/** The call is over: what it used is what was last said of it, and what is said of it from here on is counted nowhere. */
|
|
30
|
+
close(): void;
|
|
31
|
+
}
|
|
32
|
+
export interface Meter {
|
|
33
|
+
/** The caps it holds a run to, as they were given. */
|
|
34
|
+
readonly limit: Budget;
|
|
35
|
+
/** Whether it holds what it counts to anything: a cap of its own, or of a meter above. */
|
|
36
|
+
capped(): boolean;
|
|
37
|
+
/** Why nothing more may be asked of a model under it — or nothing, while something may. */
|
|
38
|
+
spent(): string | undefined;
|
|
39
|
+
/** Take on a call to a backend. Throws, with why, where nothing more may be asked. */
|
|
40
|
+
admit(): Account;
|
|
41
|
+
/** Why what is under way is to go no further: a cap on what calls use has been reached, here or above. */
|
|
42
|
+
reached(): string | undefined;
|
|
43
|
+
/** Add to the count, here and above: calls taken on, and what calls used — more than was said of them before, or less. */
|
|
44
|
+
count(calls: number, cost: number, tokens: number): void;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The count of what a run uses, held to `limit`. What it counts is counted
|
|
48
|
+
* under `above` too — the meter of the run that asked for this one — and is
|
|
49
|
+
* refused where that has no room: a run cannot use what the run it is part of
|
|
50
|
+
* may not.
|
|
51
|
+
*/
|
|
52
|
+
export declare function createMeter(limit?: Budget, above?: Meter): Meter;
|
package/dist/budget.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// What a run may use of a model, and the count of what it has.
|
|
2
|
+
//
|
|
3
|
+
// A budget is kept by the runner, where every question a run puts to a model
|
|
4
|
+
// passes (see createBackend): its program's agent calls, the requests for a
|
|
5
|
+
// fix, and — counted in the budget of each run above it too — all that the
|
|
6
|
+
// runs it asks for put to theirs. Nothing a program is given raises it.
|
|
7
|
+
// It is a guard and no wall: a program is not confined, and one that set out
|
|
8
|
+
// to could find other ways to a model.
|
|
9
|
+
import { describeJson, isJsonObject } from "./serializable.js";
|
|
10
|
+
const CAPS = ["cost", "tokens", "calls"];
|
|
11
|
+
/** A value as it is said back to whoever gave it. */
|
|
12
|
+
function shown(value) {
|
|
13
|
+
try {
|
|
14
|
+
return typeof value === "number" ? String(value) : JSON.stringify(value) ?? String(value);
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return String(value);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* A budget as it was given — in a config, to a run, over the bridge — held to
|
|
22
|
+
* what one is: a plain object of caps, each a number that is not negative,
|
|
23
|
+
* and `calls` a whole one. Returns a copy. Throws with what is wrong, as said
|
|
24
|
+
* of `what` it was given as.
|
|
25
|
+
*/
|
|
26
|
+
export function checkedBudget(given, what = "budget") {
|
|
27
|
+
// (A plain object: what holds its caps some other way — a Map, an object that has them from another — would be read as holding none.)
|
|
28
|
+
if (!isJsonObject(given) || ![Object.prototype, null].includes(Object.getPrototypeOf(given))) {
|
|
29
|
+
throw new Error(`${what} is an object of caps (${CAPS.join(", ")}): got ${isJsonObject(given) ? "an object that is not a plain one" : describeJson(given)}`);
|
|
30
|
+
}
|
|
31
|
+
const budget = {};
|
|
32
|
+
for (const [name, cap] of Object.entries(given)) {
|
|
33
|
+
if (!CAPS.includes(name))
|
|
34
|
+
throw new Error(`${what} has no cap "${name}": its caps are ${CAPS.join(", ")}`);
|
|
35
|
+
// (One given as undefined, or as null where it came as JSON, is one not given.)
|
|
36
|
+
if (cap == null)
|
|
37
|
+
continue;
|
|
38
|
+
if (typeof cap !== "number" || !Number.isFinite(cap) || cap < 0 || (name === "calls" && !Number.isInteger(cap))) {
|
|
39
|
+
throw new Error(`${what}.${name} must be ${name === "calls" ? "a whole number" : "a number"} that is not negative (got ${shown(cap)})`);
|
|
40
|
+
}
|
|
41
|
+
budget[name] = cap;
|
|
42
|
+
}
|
|
43
|
+
return budget;
|
|
44
|
+
}
|
|
45
|
+
/** More than this no one call has used of anything: what a report says beyond it is counted as this. */
|
|
46
|
+
const MOST = 1e15;
|
|
47
|
+
/**
|
|
48
|
+
* A count as it can be added up: what a backend did not say, or said as no
|
|
49
|
+
* number or as less than nothing, is nothing — it is not for a count to fail
|
|
50
|
+
* a call, nor for a report to make room — and what it said as more than any
|
|
51
|
+
* call uses is as much as a call can use: a sum that numbers cannot hold is
|
|
52
|
+
* no sum, and no cap would be reached by it again.
|
|
53
|
+
*/
|
|
54
|
+
const counted = (value) => (typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.min(value, MOST) : 0);
|
|
55
|
+
/** All the tokens of a report: read and written, from a cache or not. */
|
|
56
|
+
const tokensOf = (usage) => counted(usage?.input) + counted(usage?.output) + counted(usage?.cacheRead) + counted(usage?.cacheWrite);
|
|
57
|
+
/**
|
|
58
|
+
* How near a cap on cost counts as reached. A cost is a sum of fractions, and
|
|
59
|
+
* ten tenths of a dollar do not add up to one: a billionth of a dollar short
|
|
60
|
+
* is there.
|
|
61
|
+
*/
|
|
62
|
+
const NEAR = 1e-9;
|
|
63
|
+
/**
|
|
64
|
+
* The count of what a run uses, held to `limit`. What it counts is counted
|
|
65
|
+
* under `above` too — the meter of the run that asked for this one — and is
|
|
66
|
+
* refused where that has no room: a run cannot use what the run it is part of
|
|
67
|
+
* may not.
|
|
68
|
+
*/
|
|
69
|
+
export function createMeter(limit = {}, above) {
|
|
70
|
+
// What the calls taken on have used, as far as each has said, and how many they are.
|
|
71
|
+
let cost = 0, tokens = 0, calls = 0;
|
|
72
|
+
/** A cap on what calls use that has been reached. */
|
|
73
|
+
const used = () => {
|
|
74
|
+
if (limit.cost !== undefined && cost + NEAR >= limit.cost)
|
|
75
|
+
return `$${cost.toFixed(4)} used of $${limit.cost}`;
|
|
76
|
+
if (limit.tokens !== undefined && tokens >= limit.tokens)
|
|
77
|
+
return `${tokens} tokens used of ${limit.tokens}`;
|
|
78
|
+
return undefined;
|
|
79
|
+
};
|
|
80
|
+
/** ...or the cap on how many are made: that stops none that is under way, and admits no more. */
|
|
81
|
+
const made = () => limit.calls !== undefined && calls >= limit.calls ? `${calls} of ${limit.calls} calls to a model made` : undefined;
|
|
82
|
+
const said = (why, inherited) => why !== undefined ? `The budget is spent: ${why}.`
|
|
83
|
+
: inherited?.replace(/^The budget is/, "The budget of a run this one is part of is");
|
|
84
|
+
const meter = {
|
|
85
|
+
limit,
|
|
86
|
+
capped: () => Object.keys(limit).length > 0 || above?.capped() === true,
|
|
87
|
+
spent: () => said(used() ?? made(), above?.spent()),
|
|
88
|
+
reached: () => said(used(), above?.reached()),
|
|
89
|
+
count(more, dollars, read) {
|
|
90
|
+
calls += more;
|
|
91
|
+
cost += dollars;
|
|
92
|
+
tokens += read;
|
|
93
|
+
above?.count(more, dollars, read);
|
|
94
|
+
},
|
|
95
|
+
admit() {
|
|
96
|
+
const refusal = meter.spent();
|
|
97
|
+
if (refusal !== undefined)
|
|
98
|
+
throw new Error(refusal);
|
|
99
|
+
meter.count(1, 0, 0);
|
|
100
|
+
// What the call has said it used, in all: each word of it replaces the last.
|
|
101
|
+
let had = { cost: 0, tokens: 0 }, over = false;
|
|
102
|
+
return {
|
|
103
|
+
sofar(usage) {
|
|
104
|
+
if (!over) {
|
|
105
|
+
const now = { cost: counted(usage?.cost), tokens: tokensOf(usage) };
|
|
106
|
+
meter.count(0, now.cost - had.cost, now.tokens - had.tokens);
|
|
107
|
+
had = now;
|
|
108
|
+
}
|
|
109
|
+
return meter.reached();
|
|
110
|
+
},
|
|
111
|
+
close() {
|
|
112
|
+
over = true;
|
|
113
|
+
},
|
|
114
|
+
};
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
return meter;
|
|
118
|
+
}
|
package/dist/child-process.d.ts
CHANGED
|
@@ -35,6 +35,24 @@ export interface SuperviseOptions {
|
|
|
35
35
|
/** Aborting this asks the child to stop, the same way a timeout does. */
|
|
36
36
|
stopSignal?: AbortSignal;
|
|
37
37
|
}
|
|
38
|
+
/**
|
|
39
|
+
* A variable's name as it is shown, and written down. What follows a "=" in
|
|
40
|
+
* one is left out: a name cannot have one, and whoever wrote "KEY=value" for
|
|
41
|
+
* a name wrote a value there.
|
|
42
|
+
*/
|
|
43
|
+
export declare const variableName: (name: string) => string;
|
|
44
|
+
/**
|
|
45
|
+
* Variables a caller gives for what it starts, over those it would have
|
|
46
|
+
* anyway: each a name and its text. Returns them as they were when asked —
|
|
47
|
+
* the caller's object is its own, to change afterwards — or throws, saying
|
|
48
|
+
* which, for what is none.
|
|
49
|
+
*
|
|
50
|
+
* Two things given are not taken. One given as undefined is one not given.
|
|
51
|
+
* And the two names by which a program finds its runner are the runner's to
|
|
52
|
+
* give, to each program its own: they are passed over — so that a program
|
|
53
|
+
* can hand on its whole environment (`env: process.env`), which holds them.
|
|
54
|
+
*/
|
|
55
|
+
export declare function checkedEnv(env: unknown): Record<string, string>;
|
|
38
56
|
export interface ChildExit {
|
|
39
57
|
code: number | null;
|
|
40
58
|
signal: NodeJS.Signals | null;
|
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. */
|
|
@@ -68,6 +69,35 @@ export function createAllowance(ms) {
|
|
|
68
69
|
cancel() { pause(); onSpent = null; },
|
|
69
70
|
};
|
|
70
71
|
}
|
|
72
|
+
/**
|
|
73
|
+
* A variable's name as it is shown, and written down. What follows a "=" in
|
|
74
|
+
* one is left out: a name cannot have one, and whoever wrote "KEY=value" for
|
|
75
|
+
* a name wrote a value there.
|
|
76
|
+
*/
|
|
77
|
+
export const variableName = (name) => (name.includes("=") ? `${name.slice(0, name.indexOf("="))}=…` : name);
|
|
78
|
+
/**
|
|
79
|
+
* Variables a caller gives for what it starts, over those it would have
|
|
80
|
+
* anyway: each a name and its text. Returns them as they were when asked —
|
|
81
|
+
* the caller's object is its own, to change afterwards — or throws, saying
|
|
82
|
+
* which, for what is none.
|
|
83
|
+
*
|
|
84
|
+
* Two things given are not taken. One given as undefined is one not given.
|
|
85
|
+
* And the two names by which a program finds its runner are the runner's to
|
|
86
|
+
* give, to each program its own: they are passed over — so that a program
|
|
87
|
+
* can hand on its whole environment (`env: process.env`), which holds them.
|
|
88
|
+
*/
|
|
89
|
+
export function checkedEnv(env) {
|
|
90
|
+
if (typeof env !== "object" || env === null || Array.isArray(env))
|
|
91
|
+
throw new TypeError("env is an object of variables: each a name, and its text");
|
|
92
|
+
const given = Object.entries(env).filter(([name, value]) => value !== undefined && name !== "TRAMA_PORT" && name !== "TRAMA_INIT");
|
|
93
|
+
for (const [name, value] of given) {
|
|
94
|
+
if (name === "" || /[=\0]/.test(name))
|
|
95
|
+
throw new TypeError(`env has a name no variable can have: ${JSON.stringify(variableName(name))}`);
|
|
96
|
+
if (typeof value !== "string" || value.includes("\0"))
|
|
97
|
+
throw new TypeError(`env gives ${JSON.stringify(name)} what is not text a variable can hold`);
|
|
98
|
+
}
|
|
99
|
+
return Object.fromEntries(given);
|
|
100
|
+
}
|
|
71
101
|
/**
|
|
72
102
|
* Collect a child's output and wait for it to exit, enforcing a time limit
|
|
73
103
|
* and an optional stop request. Either one stops the child's whole process
|
|
@@ -84,7 +114,6 @@ export function superviseChild(child, options) {
|
|
|
84
114
|
const errDecoder = new StringDecoder("utf-8");
|
|
85
115
|
let timedOut = false;
|
|
86
116
|
let stopped = false;
|
|
87
|
-
let exited = false;
|
|
88
117
|
const emitOut = (text) => { if (text) {
|
|
89
118
|
out.append(text);
|
|
90
119
|
sinks?.stdout?.(text);
|
|
@@ -97,16 +126,13 @@ export function superviseChild(child, options) {
|
|
|
97
126
|
// A child that failed to spawn has no pid, and nothing to stop.
|
|
98
127
|
const terminate = () => { if (child.pid)
|
|
99
128
|
void stopGroups([child.pid]); };
|
|
100
|
-
const
|
|
101
|
-
if (
|
|
129
|
+
const offStop = onAbort(stopSignal, () => {
|
|
130
|
+
if (timedOut)
|
|
102
131
|
return;
|
|
103
132
|
stopped = true;
|
|
104
133
|
terminate();
|
|
105
|
-
};
|
|
106
|
-
stopSignal?.addEventListener("abort", onStopRequest, { once: true });
|
|
134
|
+
});
|
|
107
135
|
allowance.start(() => {
|
|
108
|
-
if (exited)
|
|
109
|
-
return;
|
|
110
136
|
timedOut = true;
|
|
111
137
|
terminate();
|
|
112
138
|
});
|
|
@@ -114,7 +140,7 @@ export function superviseChild(child, options) {
|
|
|
114
140
|
allowance.cancel();
|
|
115
141
|
if (drainTimer)
|
|
116
142
|
clearTimeout(drainTimer);
|
|
117
|
-
|
|
143
|
+
offStop();
|
|
118
144
|
};
|
|
119
145
|
child.stdout?.on("data", (chunk) => emitOut(outDecoder.write(chunk)));
|
|
120
146
|
child.stderr?.on("data", (chunk) => emitErr(errDecoder.write(chunk)));
|
|
@@ -127,10 +153,13 @@ export function superviseChild(child, options) {
|
|
|
127
153
|
// and what that writes is not the child's output. Stop waiting for it:
|
|
128
154
|
// otherwise such a process keeps the run from ever ending, timeout or not.
|
|
129
155
|
child.on("exit", () => {
|
|
156
|
+
// From here on there is no child to stop, and none that could run out of time: what
|
|
157
|
+
// is still waited for is its output, for a moment (see below).
|
|
158
|
+
allowance.cancel();
|
|
159
|
+
offStop();
|
|
130
160
|
drainTimer = setTimeout(() => { child.stdout?.destroy(); child.stderr?.destroy(); }, DRAIN_MS);
|
|
131
161
|
});
|
|
132
162
|
child.on("close", (code, signal) => {
|
|
133
|
-
exited = true;
|
|
134
163
|
cleanup();
|
|
135
164
|
emitOut(outDecoder.end());
|
|
136
165
|
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, AgentOptions, Thinking, Schema, SchemaField, ShellResult, Tools, ObserveResult, Workspace } from "./types.js";
|
|
2
|
+
export type { Ctx, Agent, AgentOptions, Thinking, Schema, SchemaField, 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
|
@@ -1,8 +1,8 @@
|
|
|
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 { openBridge, remoteWorkspace } from "./bridge-client.js";
|
|
5
|
-
import { assertSerializable } from "./serializable.js";
|
|
4
|
+
import { openBridge, remoteWorkspace, withOptions } from "./bridge-client.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");
|
|
@@ -58,14 +48,14 @@ export const ctx = {
|
|
|
58
48
|
},
|
|
59
49
|
};
|
|
60
50
|
export const agent = {
|
|
61
|
-
instruct: (prompt, opts) => call("/agent/instruct", { prompt,
|
|
51
|
+
instruct: async (prompt, opts) => call("/agent/instruct", withOptions({ prompt }, opts)),
|
|
62
52
|
generate: (input) => call("/agent/generate", input),
|
|
63
53
|
};
|
|
64
54
|
export const tools = {
|
|
65
55
|
read: (path) => call("/tools/read", { path }),
|
|
66
56
|
write: (path, content) => call("/tools/write", { path, content }),
|
|
67
|
-
shell: (cmd, opts) => call("/tools/shell", { command: cmd,
|
|
68
|
-
fetch: (url, opts) => call("/tools/fetch", { url,
|
|
57
|
+
shell: async (cmd, opts) => call("/tools/shell", withOptions({ command: cmd }, opts)),
|
|
58
|
+
fetch: async (url, opts) => call("/tools/fetch", withOptions({ url }, opts)),
|
|
69
59
|
};
|
|
70
60
|
/** workspace.* exists only inside a session — everywhere else it fails clearly, without a round trip. */
|
|
71
61
|
export const workspace = remoteWorkspace((endpoint, body) => {
|
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;
|