@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/ipc-server.js
CHANGED
|
@@ -1,160 +1,193 @@
|
|
|
1
1
|
// The runner side of the IPC bridge. A running program.ts reaches ctx, agent,
|
|
2
|
-
// tools and workspace by POSTing JSON to this local HTTP server (see
|
|
3
|
-
// for the other end).
|
|
2
|
+
// tools and workspace by POSTing JSON to this local HTTP server (see
|
|
3
|
+
// bridge-client.ts for the other end, and client.ts for what is made of it).
|
|
4
4
|
import { createServer } from "http";
|
|
5
5
|
import { timingSafeEqual } from "crypto";
|
|
6
|
-
import {
|
|
6
|
+
import { describeJson, isJsonObject } from "./serializable.js";
|
|
7
|
+
import { checkedEnv, variableName } from "./child-process.js";
|
|
8
|
+
import { checkedBudget } from "./budget.js";
|
|
9
|
+
import { messageOf } from "./errors.js";
|
|
7
10
|
const MAX_IPC_BODY = 50 * 1024 * 1024; // 50 MB
|
|
11
|
+
const MAX_STOPPED_AHEAD = 1024;
|
|
8
12
|
/** A request the program got wrong — answered with 400 rather than 500. */
|
|
9
13
|
class BadRequest extends Error {
|
|
10
14
|
}
|
|
11
|
-
const
|
|
12
|
-
|
|
13
|
-
|
|
15
|
+
const isStrings = (value) => Array.isArray(value) && value.every(item => typeof item === "string");
|
|
16
|
+
const isOfKind = (value, kind) => kind === "any" ? value !== undefined
|
|
17
|
+
: kind === "object" ? isJsonObject(value)
|
|
18
|
+
: kind === "strings" ? isStrings(value)
|
|
19
|
+
: kind === "boolean or strings" ? typeof value === "boolean" || isStrings(value)
|
|
20
|
+
: kind === "boolean or string" ? typeof value === "boolean" || typeof value === "string"
|
|
21
|
+
: typeof value === kind;
|
|
22
|
+
/** Read a call's declared fields out of a request body — refusing a body that does not hold them as declared, or holds any other. */
|
|
23
|
+
function read(body, fields) {
|
|
24
|
+
if (!isJsonObject(body))
|
|
25
|
+
throw new BadRequest("The request body must be a JSON object");
|
|
26
|
+
const args = {};
|
|
27
|
+
for (const [name, field] of Object.entries(fields)) {
|
|
28
|
+
const optional = field.startsWith("optional ");
|
|
29
|
+
const kind = (optional ? field.slice("optional ".length) : field);
|
|
14
30
|
const value = body[name];
|
|
15
|
-
const optional = type.startsWith("optional ");
|
|
16
31
|
// null is how JSON says a field is not there: an optional one given as null was left out.
|
|
17
|
-
if (optional && value == null)
|
|
18
|
-
delete body[name];
|
|
32
|
+
if (optional && value == null)
|
|
19
33
|
continue;
|
|
20
|
-
|
|
21
|
-
const expected = optional ? type.slice("optional ".length) : type;
|
|
22
|
-
if (expected === "object" ? !isPlainObject(value) : typeof value !== expected) {
|
|
34
|
+
if (!isOfKind(value, kind)) {
|
|
23
35
|
throw new BadRequest(optional
|
|
24
|
-
? `Invalid field: ${name} (expected ${
|
|
25
|
-
: `Missing or invalid field: ${name} (expected ${
|
|
36
|
+
? `Invalid field: ${name} (expected ${kind} or undefined)`
|
|
37
|
+
: `Missing or invalid field: ${name} (expected ${kind})`);
|
|
26
38
|
}
|
|
39
|
+
args[name] = value;
|
|
40
|
+
}
|
|
41
|
+
// What a call does not declare it cannot do anything with: to pass it over would be to let its sender think it had.
|
|
42
|
+
const unknown = Object.keys(body).find(name => !Object.hasOwn(fields, name));
|
|
43
|
+
if (unknown !== undefined)
|
|
44
|
+
throw new BadRequest(`Unknown field: ${unknown} (this call takes: ${Object.keys(fields).join(", ")})`);
|
|
45
|
+
return args;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* A call: every field it takes, and what is done with them. The declaration
|
|
49
|
+
* is the whole of what a request may hold — a field that is not declared
|
|
50
|
+
* is refused, and one that is arrives as the kind it says.
|
|
51
|
+
* (What is inside an object is the business of whoever it is handed to.)
|
|
52
|
+
*/
|
|
53
|
+
function route(fields, handle) {
|
|
54
|
+
return { handle: (body, connectionClosed, call) => handle(read(body, fields), connectionClosed, call) };
|
|
55
|
+
}
|
|
56
|
+
/** The variables a call gives, held to what variables are (see checkedEnv): what is none is the request's fault. */
|
|
57
|
+
function envOf(env) {
|
|
58
|
+
if (env === undefined)
|
|
59
|
+
return undefined;
|
|
60
|
+
try {
|
|
61
|
+
return checkedEnv(env);
|
|
62
|
+
}
|
|
63
|
+
catch (err) {
|
|
64
|
+
throw new BadRequest(`Invalid field: ${messageOf(err)}`);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/** The budget a call gives a run, held to what a budget is (see checkedBudget). */
|
|
68
|
+
function budgetOf(budget) {
|
|
69
|
+
if (budget === undefined)
|
|
70
|
+
return undefined;
|
|
71
|
+
try {
|
|
72
|
+
return checkedBudget(budget);
|
|
73
|
+
}
|
|
74
|
+
catch (err) {
|
|
75
|
+
throw new BadRequest(`Invalid field: ${messageOf(err)}`);
|
|
27
76
|
}
|
|
28
77
|
}
|
|
78
|
+
/**
|
|
79
|
+
* A request as it is written down: all of it, but for what it gives as
|
|
80
|
+
* variables — a journal is no place for a key. Of variables the names are
|
|
81
|
+
* kept; of what is given in their place and is none, what kind of thing it is.
|
|
82
|
+
*/
|
|
83
|
+
const asRecorded = (body) => !isJsonObject(body) || body.env == null ? body
|
|
84
|
+
: { ...body, env: isJsonObject(body.env) ? Object.keys(body.env).map(variableName) : `(${describeJson(body.env)})` };
|
|
85
|
+
/**
|
|
86
|
+
* What an agent call may say about how it is served (see AgentOptions). (A
|
|
87
|
+
* prompt of `instruct` may be read as a template besides: a typed answer's is
|
|
88
|
+
* not, for what says how to answer follows it.)
|
|
89
|
+
*/
|
|
90
|
+
const HOW_SERVED = {
|
|
91
|
+
system: "optional string", model: "optional string", thinking: "optional string", tools: "optional strings",
|
|
92
|
+
skills: "optional boolean or strings", extensions: "optional boolean or string", cutOff: "optional string",
|
|
93
|
+
};
|
|
29
94
|
/** Whether a request carries `Authorization: Bearer <token>`, compared in constant time. */
|
|
30
95
|
function isAuthorized(header, token) {
|
|
31
96
|
const expected = Buffer.from(`Bearer ${token}`);
|
|
32
97
|
const actual = Buffer.from(header ?? "");
|
|
33
98
|
return actual.length === expected.length && timingSafeEqual(actual, expected);
|
|
34
99
|
}
|
|
35
|
-
function buildRoutes({ ctx, agent, tools, workspace, workspaceAt, run,
|
|
36
|
-
/**
|
|
37
|
-
const adoptState = (state) => {
|
|
38
|
-
assertSerializable(state, "ctx.state");
|
|
39
|
-
ctx.state = state;
|
|
40
|
-
};
|
|
41
|
-
/** Runs the program has asked for and that have not ended, by the id it gave each. */
|
|
100
|
+
function buildRoutes({ ctx, agent, tools, workspace, workspaceAt, run, make }) {
|
|
101
|
+
/** What the program has asked for that lasts — a run, a project made — and has not ended, by the id it gave each. */
|
|
42
102
|
const runsAskedFor = new Map();
|
|
43
|
-
/** Ids the program asked to stop before
|
|
103
|
+
/** Ids the program asked to stop before what bears them was seen here: such a thing starts stopped. */
|
|
44
104
|
const stoppedAhead = new Set();
|
|
105
|
+
/**
|
|
106
|
+
* Carry out what a call asks for and that lasts as long as the call does,
|
|
107
|
+
* until it ends or is to stop: the program says so by the id it gave it,
|
|
108
|
+
* or is gone — its process died, or it gave up — and no longer wants it.
|
|
109
|
+
*/
|
|
110
|
+
const lasting = async (id, connectionClosed, work) => {
|
|
111
|
+
if (id !== undefined) {
|
|
112
|
+
if (id === "")
|
|
113
|
+
throw new BadRequest("Invalid field: id (expected a non-empty string)");
|
|
114
|
+
if (runsAskedFor.has(id))
|
|
115
|
+
throw new BadRequest(`Duplicate run id: ${id}`);
|
|
116
|
+
}
|
|
117
|
+
const stop = new AbortController();
|
|
118
|
+
void connectionClosed.then(() => stop.abort());
|
|
119
|
+
if (id !== undefined) {
|
|
120
|
+
if (stoppedAhead.delete(id))
|
|
121
|
+
stop.abort();
|
|
122
|
+
runsAskedFor.set(id, stop);
|
|
123
|
+
}
|
|
124
|
+
try {
|
|
125
|
+
return await work(stop.signal);
|
|
126
|
+
}
|
|
127
|
+
finally {
|
|
128
|
+
if (id !== undefined)
|
|
129
|
+
runsAskedFor.delete(id);
|
|
130
|
+
}
|
|
131
|
+
};
|
|
45
132
|
/** The workspace a call is about: the directory it names, or else the one this run was started with. */
|
|
46
|
-
const workspaceOf = (
|
|
47
|
-
if (
|
|
48
|
-
if (
|
|
133
|
+
const workspaceOf = (dir) => {
|
|
134
|
+
if (dir !== undefined) {
|
|
135
|
+
if (dir === "")
|
|
49
136
|
throw new BadRequest("Invalid field: dir (expected a directory path)");
|
|
50
|
-
return workspaceAt(
|
|
137
|
+
return workspaceAt(dir);
|
|
51
138
|
}
|
|
52
139
|
if (!workspace)
|
|
53
140
|
throw new BadRequest("Workspace is only available when running in a session");
|
|
54
141
|
return workspace;
|
|
55
142
|
};
|
|
56
143
|
return {
|
|
57
|
-
"/agent/instruct": {
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
},
|
|
61
|
-
"/
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
},
|
|
65
|
-
|
|
66
|
-
"/
|
|
67
|
-
"/
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
},
|
|
71
|
-
"/tools/fetch": {
|
|
72
|
-
fields: { url: "string" },
|
|
73
|
-
handle: b => tools.fetch(b.url, { method: b.method, headers: b.headers, body: b.body }),
|
|
74
|
-
},
|
|
75
|
-
"/ctx/log": { fields: { message: "string" }, handle: b => ctx.log(b.message, b.data) },
|
|
76
|
-
"/ctx/ready": { fields: { data: "optional object" }, handle: b => ctx.ready(b.data) },
|
|
77
|
-
"/ctx/checkpoint": {
|
|
78
|
-
fields: { state: "object" },
|
|
79
|
-
handle: async (b) => {
|
|
80
|
-
adoptState(b.state);
|
|
81
|
-
await ctx.checkpoint();
|
|
82
|
-
return ctx.iteration;
|
|
83
|
-
},
|
|
84
|
-
},
|
|
85
|
-
"/ctx/done": {
|
|
86
|
-
fields: { state: "object" },
|
|
87
|
-
handle: async (b) => {
|
|
88
|
-
adoptState(b.state);
|
|
89
|
-
await ctx.done(b.result);
|
|
90
|
-
onTerminalSignal({ status: "done", result: b.result ?? undefined });
|
|
91
|
-
return ctx.iteration;
|
|
92
|
-
},
|
|
93
|
-
},
|
|
94
|
-
"/ctx/yield": {
|
|
95
|
-
fields: { state: "object", reason: "string" },
|
|
96
|
-
handle: async (b) => {
|
|
97
|
-
adoptState(b.state);
|
|
98
|
-
// Persists the yield marker and returns; the program exits itself once we answer.
|
|
99
|
-
await ctx.yield(b.reason);
|
|
100
|
-
onTerminalSignal({ status: "yielded", reason: b.reason });
|
|
101
|
-
},
|
|
102
|
-
},
|
|
144
|
+
"/agent/instruct": route({ prompt: "string", ...HOW_SERVED, templates: "optional boolean or strings" }, ({ prompt, ...options }, _closed, call) => agent.instruct(prompt, options, call.used)),
|
|
145
|
+
"/agent/generate": route({ prompt: "string", schema: "object", ...HOW_SERVED }, (input, _closed, call) => agent.generate(input, call.used)),
|
|
146
|
+
"/tools/read": route({ path: "string" }, b => tools.read(b.path)),
|
|
147
|
+
"/tools/write": route({ path: "string", content: "string" }, b => tools.write(b.path, b.content)),
|
|
148
|
+
"/tools/shell": route({ command: "string", cwd: "optional string", timeout: "optional number", env: "optional object" }, b => tools.shell(b.command, { cwd: b.cwd, timeout: b.timeout, env: envOf(b.env) })),
|
|
149
|
+
"/tools/fetch": route({ url: "string", method: "optional string", headers: "optional object", body: "optional string" }, b => tools.fetch(b.url, { method: b.method, headers: b.headers, body: b.body })),
|
|
150
|
+
"/ctx/log": route({ message: "string", data: "optional any" }, b => ctx.log(b.message, b.data)),
|
|
151
|
+
"/ctx/ready": route({ data: "optional object" }, b => ctx.ready(b.data)),
|
|
152
|
+
// The state is the program's: each call that persists it hands over its current copy.
|
|
153
|
+
"/ctx/checkpoint": route({ state: "object" }, b => ctx.checkpoint(b.state)),
|
|
154
|
+
"/ctx/done": route({ state: "object", result: "optional any" }, b => ctx.done(b.state, b.result)),
|
|
155
|
+
// Persists the yield marker and returns; the program exits itself once it is answered.
|
|
156
|
+
"/ctx/yield": route({ state: "object", reason: "string" }, b => ctx.yield(b.state, b.reason)),
|
|
103
157
|
// A program never runs another program: it asks its runner to. The call
|
|
104
158
|
// lasts as long as the run does, repairs included.
|
|
105
|
-
"/run/program": {
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
159
|
+
"/run/program": route({
|
|
160
|
+
projectDir: "string", args: "optional object",
|
|
161
|
+
timeout: "optional number", maxRepairAttempts: "optional number",
|
|
162
|
+
id: "optional string", label: "optional string", workspaceDir: "optional string", env: "optional object",
|
|
163
|
+
budget: "optional object",
|
|
164
|
+
}, async ({ id, env, budget, ...asked }, connectionClosed, { seq }) => {
|
|
165
|
+
const request = { ...asked, env: envOf(env), budget: budgetOf(budget) };
|
|
166
|
+
return lasting(id, connectionClosed, stop => run(request, stop, seq));
|
|
167
|
+
}),
|
|
168
|
+
// Nor does a program make a project, or change one: its runner does, as it runs one — under the
|
|
169
|
+
// run's budget, on its record, and stopped with it.
|
|
170
|
+
"/project/create": route({ name: "string", prompt: "string", model: "optional string", args: "optional object", id: "optional string" }, ({ id, ...asked }, connectionClosed, { seq }) => lasting(id, connectionClosed, stop => make({ kind: "create", ...asked }, stop, seq))),
|
|
171
|
+
"/project/update": route({ name: "string", prompt: "string", id: "optional string" }, ({ id, ...asked }, connectionClosed, { seq }) => lasting(id, connectionClosed, stop => make({ kind: "update", ...asked }, stop, seq))),
|
|
172
|
+
// Stop a run asked for above, or a project being made. The call that asked
|
|
173
|
+
// for it still gets its answer — a failed run, an error — once it is over.
|
|
174
|
+
"/run/stop": route({ id: "string" }, b => {
|
|
175
|
+
if (b.id === "")
|
|
176
|
+
throw new BadRequest("Invalid field: id (expected a non-empty string)");
|
|
177
|
+
const asked = runsAskedFor.get(b.id);
|
|
178
|
+
if (asked)
|
|
179
|
+
asked.abort();
|
|
180
|
+
else {
|
|
181
|
+
if (stoppedAhead.size >= MAX_STOPPED_AHEAD && !stoppedAhead.has(b.id)) {
|
|
182
|
+
stoppedAhead.delete(stoppedAhead.values().next().value);
|
|
129
183
|
}
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
},
|
|
136
|
-
|
|
137
|
-
// answer — a failed run — once the run is over.
|
|
138
|
-
"/run/stop": {
|
|
139
|
-
fields: { id: "string" },
|
|
140
|
-
handle: b => {
|
|
141
|
-
const asked = runsAskedFor.get(b.id);
|
|
142
|
-
if (asked)
|
|
143
|
-
asked.abort();
|
|
144
|
-
else
|
|
145
|
-
stoppedAhead.add(b.id);
|
|
146
|
-
},
|
|
147
|
-
},
|
|
148
|
-
"/workspace/read": { fields: { path: "string" }, handle: b => workspaceOf(b).read(b.path) },
|
|
149
|
-
"/workspace/write": {
|
|
150
|
-
fields: { path: "string", content: "string" },
|
|
151
|
-
handle: b => workspaceOf(b).write(b.path, b.content),
|
|
152
|
-
},
|
|
153
|
-
"/workspace/list": { fields: { pattern: "string" }, handle: b => workspaceOf(b).list(b.pattern) },
|
|
154
|
-
"/workspace/observe": {
|
|
155
|
-
fields: { pattern: "string" },
|
|
156
|
-
handle: b => workspaceOf(b).observe(b.pattern, { expect: b.expect, timeout: b.timeout }),
|
|
157
|
-
},
|
|
184
|
+
stoppedAhead.add(b.id);
|
|
185
|
+
}
|
|
186
|
+
}),
|
|
187
|
+
"/workspace/read": route({ path: "string", dir: "optional string" }, b => workspaceOf(b.dir).read(b.path)),
|
|
188
|
+
"/workspace/write": route({ path: "string", content: "string", dir: "optional string" }, b => workspaceOf(b.dir).write(b.path, b.content)),
|
|
189
|
+
"/workspace/list": route({ pattern: "string", dir: "optional string" }, b => workspaceOf(b.dir).list(b.pattern)),
|
|
190
|
+
"/workspace/observe": route({ pattern: "string", dir: "optional string", expect: "optional number", timeout: "optional number" }, b => workspaceOf(b.dir).observe(b.pattern, { expect: b.expect, timeout: b.timeout })),
|
|
158
191
|
};
|
|
159
192
|
}
|
|
160
193
|
export function createIPCServer(backends) {
|
|
@@ -162,7 +195,7 @@ export function createIPCServer(backends) {
|
|
|
162
195
|
return createServer((req, res) => {
|
|
163
196
|
const connectionClosed = new Promise(resolve => res.once("close", resolve));
|
|
164
197
|
// An answer can be given once, and only while there is someone to give it to.
|
|
165
|
-
const answerable = () => !res.writableEnded && !res.destroyed;
|
|
198
|
+
const answerable = () => !backends.programOver() && !res.writableEnded && !res.destroyed;
|
|
166
199
|
const reply = (status, body, json = false) => {
|
|
167
200
|
if (!answerable())
|
|
168
201
|
return;
|
|
@@ -200,16 +233,22 @@ export function createIPCServer(backends) {
|
|
|
200
233
|
// recorded as one: a call nobody was left to answer has no result.
|
|
201
234
|
let call;
|
|
202
235
|
try {
|
|
203
|
-
|
|
204
|
-
|
|
236
|
+
let body;
|
|
237
|
+
try {
|
|
238
|
+
body = JSON.parse(Buffer.concat(chunks).toString("utf-8"));
|
|
239
|
+
}
|
|
240
|
+
catch {
|
|
241
|
+
return reply(400, "The request body is not valid JSON");
|
|
242
|
+
}
|
|
243
|
+
const route = req.url && Object.hasOwn(routes, req.url) ? routes[req.url] : undefined;
|
|
205
244
|
if (!route)
|
|
206
245
|
return reply(404, "Not found");
|
|
207
|
-
call = backends.journal.call(req.url, body);
|
|
208
|
-
|
|
209
|
-
const
|
|
246
|
+
call = backends.journal.call(req.url, asRecorded(body));
|
|
247
|
+
const result = (await route.handle(body, connectionClosed, call)) ?? null;
|
|
248
|
+
const payload = JSON.stringify({ result });
|
|
210
249
|
if (answerable())
|
|
211
250
|
call.end({ ok: true, result });
|
|
212
|
-
reply(200,
|
|
251
|
+
reply(200, payload, true);
|
|
213
252
|
}
|
|
214
253
|
catch (err) {
|
|
215
254
|
const refused = err instanceof BadRequest;
|
|
@@ -226,21 +265,12 @@ export function listen(server) {
|
|
|
226
265
|
return new Promise((resolve, reject) => {
|
|
227
266
|
server.once("error", reject);
|
|
228
267
|
server.listen(0, "127.0.0.1", () => {
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
resolve(addr.port);
|
|
232
|
-
else
|
|
233
|
-
reject(new Error("Failed to get server port"));
|
|
268
|
+
server.removeListener("error", reject);
|
|
269
|
+
resolve(server.address().port);
|
|
234
270
|
});
|
|
235
271
|
});
|
|
236
272
|
}
|
|
273
|
+
/** Stop listening, and wait until it has. (The one thing a server can say against it is that it was not listening.) */
|
|
237
274
|
export function closeServer(server) {
|
|
238
|
-
return new Promise((resolve
|
|
239
|
-
server.close(err => {
|
|
240
|
-
if (!err || err.code === "ERR_SERVER_NOT_RUNNING")
|
|
241
|
-
resolve();
|
|
242
|
-
else
|
|
243
|
-
reject(err);
|
|
244
|
-
});
|
|
245
|
-
});
|
|
275
|
+
return new Promise((resolve) => { server.close(() => resolve()); });
|
|
246
276
|
}
|
package/dist/journal-view.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
/** What reports of usage — `usage` records, or what a backend said — add up to, in a few words: and nothing where there are none. */
|
|
2
|
+
export declare function spentIn(usage: object[]): string;
|
|
1
3
|
/**
|
|
2
4
|
* Print what a run of the project in `projectDir` did: the latest run, or the
|
|
3
5
|
* one named. With `list`, print which runs have a journal instead. `name` is
|
package/dist/journal-view.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
// as far as it goes — a run may still be writing it, or have died doing so.
|
|
5
5
|
import { readFileSync } from "fs";
|
|
6
6
|
import { JOURNAL_VERSION, journalDirOf, journalIn, runsIn, stillBeingWritten } from "./journal.js";
|
|
7
|
+
import { isJsonObject } from "./serializable.js";
|
|
7
8
|
/**
|
|
8
9
|
* The records of a journal file. A line that is not a whole record — the last
|
|
9
10
|
* one, if the runner died writing it — is left out, and so is a file that
|
|
@@ -21,7 +22,7 @@ function readJournal(path) {
|
|
|
21
22
|
continue;
|
|
22
23
|
try {
|
|
23
24
|
const record = JSON.parse(line);
|
|
24
|
-
if (
|
|
25
|
+
if (isJsonObject(record))
|
|
25
26
|
records.push(record);
|
|
26
27
|
}
|
|
27
28
|
catch { /* not a whole record */ }
|
|
@@ -37,12 +38,35 @@ function gist(request) {
|
|
|
37
38
|
// A run that was asked for is best known by the name it was given.
|
|
38
39
|
if (typeof request?.label === "string")
|
|
39
40
|
return oneLine(`${request.label} (${request.projectDir})`, 60);
|
|
41
|
+
// ...and a project that was asked for by its own.
|
|
42
|
+
if (typeof request?.name === "string")
|
|
43
|
+
return oneLine(`${request.name}: ${typeof request.prompt === "string" ? request.prompt : ""}`, 60);
|
|
40
44
|
for (const field of ["prompt", "command", "path", "pattern", "url", "message", "projectDir", "reason"]) {
|
|
41
45
|
if (request?.[field] !== undefined)
|
|
42
46
|
return oneLine(request[field], 60);
|
|
43
47
|
}
|
|
44
48
|
return "";
|
|
45
49
|
}
|
|
50
|
+
/** What reports of usage — `usage` records, or what a backend said — add up to, in a few words: and nothing where there are none. */
|
|
51
|
+
export function spentIn(usage) {
|
|
52
|
+
if (usage.length === 0)
|
|
53
|
+
return "";
|
|
54
|
+
const sum = (field) => usage.reduce((total, record) => total + (Number(record[field]) || 0), 0);
|
|
55
|
+
return `${sum("input") + sum("output") + sum("cacheRead") + sum("cacheWrite")} tokens $${sum("cost").toFixed(4)}`;
|
|
56
|
+
}
|
|
57
|
+
const spent = spentIn;
|
|
58
|
+
const usageIn = (records) => records.filter(record => record.kind === "usage");
|
|
59
|
+
/**
|
|
60
|
+
* What a run used, as far as its journal says. That is all of it (`inAll`
|
|
61
|
+
* says so) unless the journal filled up: then it is what is on record, be
|
|
62
|
+
* that nothing, and is said to be.
|
|
63
|
+
*/
|
|
64
|
+
function spentInAll(records, inAll = "") {
|
|
65
|
+
const counted = spent(usageIn(records));
|
|
66
|
+
if (!records.some(record => record.kind === "full"))
|
|
67
|
+
return counted && counted + inAll;
|
|
68
|
+
return `${counted || "no usage"} on record — the journal was full`;
|
|
69
|
+
}
|
|
46
70
|
/** How a run ended, in a word or two — or that it has not, or never will. */
|
|
47
71
|
function ending(path, records) {
|
|
48
72
|
const end = records.find(record => record.kind === "end");
|
|
@@ -52,7 +76,8 @@ function ending(path, records) {
|
|
|
52
76
|
}
|
|
53
77
|
function printJournal(path, records) {
|
|
54
78
|
const head = records[0];
|
|
55
|
-
|
|
79
|
+
const howEnded = ending(path, records);
|
|
80
|
+
console.log(`${head?.run ?? "?"} ${head?.purpose ?? ""}${head?.label ? ` [${head.label}]` : ""} ${howEnded}`);
|
|
56
81
|
if (head && head.v !== JOURNAL_VERSION) {
|
|
57
82
|
console.log(`(recorded in format ${head.v}; this trama reads format ${JOURNAL_VERSION}, and shows what it can make of it)`);
|
|
58
83
|
}
|
|
@@ -60,6 +85,8 @@ function printJournal(path, records) {
|
|
|
60
85
|
for (const record of records)
|
|
61
86
|
if (record.kind === "result")
|
|
62
87
|
results.set(record.seq, record);
|
|
88
|
+
const usage = usageIn(records);
|
|
89
|
+
const total = spentInAll(records, " in all");
|
|
63
90
|
for (const record of records) {
|
|
64
91
|
const at = `${(record.at / 1000).toFixed(3).padStart(9)}s`;
|
|
65
92
|
switch (record.kind) {
|
|
@@ -71,11 +98,22 @@ function printJournal(path, records) {
|
|
|
71
98
|
const how = !result ? "never answered"
|
|
72
99
|
: result.ok ? `ok ${result.ms}ms`
|
|
73
100
|
: `failed ${result.ms}ms ${oneLine(result.error, 60)}`;
|
|
74
|
-
|
|
101
|
+
const used = spent(usage.filter(item => item.seq === record.seq));
|
|
102
|
+
console.log(`${at} #${String(record.seq).padEnd(3)} ${record.endpoint.slice(1).padEnd(18)} ${gist(record.request).padEnd(60)} ${how}${used && ` ${used}`}`);
|
|
75
103
|
break;
|
|
76
104
|
}
|
|
105
|
+
case "usage":
|
|
106
|
+
// (What a call used is shown with the call.)
|
|
107
|
+
if (record.for === "fix")
|
|
108
|
+
console.log(`${at} asking for the fix used ${spent([record])}`);
|
|
109
|
+
if (record.for === "generate")
|
|
110
|
+
console.log(`${at} writing the program used ${spent([record])}`);
|
|
111
|
+
break;
|
|
112
|
+
case "budget":
|
|
113
|
+
console.log(`${at} ${oneLine(record.spent, 100)}`);
|
|
114
|
+
break;
|
|
77
115
|
case "child":
|
|
78
|
-
console.log(`${at} #${String(record.seq).padEnd(3)} started run ${record.run}`);
|
|
116
|
+
console.log(`${at} #${String(record.seq).padEnd(3)} started ${record.purpose === "validate" ? "validation" : "run"} ${record.run}`);
|
|
79
117
|
break;
|
|
80
118
|
case "fix-request":
|
|
81
119
|
console.log(`${at} fix asked for: ${oneLine(record.error, 80)}`);
|
|
@@ -93,11 +131,16 @@ function printJournal(path, records) {
|
|
|
93
131
|
console.log(`${at} attempt ${record.attempt} over: ${how} → ${verdict}`);
|
|
94
132
|
break;
|
|
95
133
|
}
|
|
134
|
+
case "unmerged":
|
|
135
|
+
console.log(`${at} attempt ${record.attempt}: ${record.files?.length ?? 0} change(s) it made did not reach the project`);
|
|
136
|
+
for (const file of record.files ?? [])
|
|
137
|
+
console.log(`${" ".repeat(at.length)} ${file.path} — ${oneLine(file.why, 80)}`);
|
|
138
|
+
break;
|
|
96
139
|
case "full":
|
|
97
140
|
console.log(`${at} the journal is full: calls from here on were not recorded`);
|
|
98
141
|
break;
|
|
99
142
|
case "end":
|
|
100
|
-
console.log(`${at} end: ${
|
|
143
|
+
console.log(`${at} end: ${howEnded}${total && ` (${total})`}`);
|
|
101
144
|
break;
|
|
102
145
|
}
|
|
103
146
|
}
|
|
@@ -119,7 +162,8 @@ export function printJournals(projectDir, name, options) {
|
|
|
119
162
|
const path = journalIn(dir, run);
|
|
120
163
|
const records = readJournal(path);
|
|
121
164
|
const calls = records.filter(record => record.kind === "call").length;
|
|
122
|
-
|
|
165
|
+
const used = spentInAll(records);
|
|
166
|
+
console.log(`${run} ${String(records[0]?.purpose ?? "").padEnd(8)} ${String(calls).padStart(4)} calls ${ending(path, records)}${used && ` ${used}`}`);
|
|
123
167
|
}
|
|
124
168
|
return;
|
|
125
169
|
}
|
|
@@ -127,5 +171,6 @@ export function printJournals(projectDir, name, options) {
|
|
|
127
171
|
if (!runs.includes(run)) {
|
|
128
172
|
throw new Error(`No journal for run "${run}". \`trama journal ${name} --list\` shows the runs that have one.`);
|
|
129
173
|
}
|
|
130
|
-
|
|
174
|
+
const path = journalIn(dir, run);
|
|
175
|
+
printJournal(path, readJournal(path));
|
|
131
176
|
}
|
package/dist/journal.d.ts
CHANGED
|
@@ -1,16 +1,25 @@
|
|
|
1
|
+
import { type AgentUsage } from "./agent-backend.js";
|
|
1
2
|
/** The format of the records. Bump it when a reader of older journals would be misled. */
|
|
2
3
|
export declare const JOURNAL_VERSION = 1;
|
|
3
4
|
/** Where a project keeps its journals, relative to the project — under logs/, which trama keeps out of version control. */
|
|
4
5
|
export declare const JOURNAL_DIR: string;
|
|
5
6
|
/**
|
|
6
7
|
* A project's journal directory, by its one real name however the project was
|
|
7
|
-
* referred to
|
|
8
|
+
* referred to.
|
|
8
9
|
*/
|
|
9
10
|
export declare function journalDirOf(projectDir: string): string;
|
|
10
|
-
/** The ids of the runs that have a journal in `dir`, oldest first. (A run's id starts with when it started.) */
|
|
11
|
-
export declare function runsIn(dir: string): string[];
|
|
12
11
|
/** The journal of a run, in a journal directory. */
|
|
13
12
|
export declare const journalIn: (dir: string, run: string) => string;
|
|
13
|
+
/** The ids of the runs that have a journal in `dir`, oldest first. (A run's id starts with when it started.) */
|
|
14
|
+
export declare function runsIn(dir: string): string[];
|
|
15
|
+
/**
|
|
16
|
+
* What a copy of `projectDir` is to leave out so as not to carry the project's
|
|
17
|
+
* journals, each by what it is (its `identityOf`): the directory they are in,
|
|
18
|
+
* if nothing else is in it or it may not be read or searched — and otherwise every
|
|
19
|
+
* journal in it. Somebody's own file among the journals is the project's
|
|
20
|
+
* like any other, and is copied.
|
|
21
|
+
*/
|
|
22
|
+
export declare function journalEntriesOf(projectDir: string): Set<string>;
|
|
14
23
|
export type CallOutcome = {
|
|
15
24
|
ok: true;
|
|
16
25
|
result: unknown;
|
|
@@ -18,6 +27,14 @@ export type CallOutcome = {
|
|
|
18
27
|
ok: false;
|
|
19
28
|
error: string;
|
|
20
29
|
};
|
|
30
|
+
/** A bridge call on record: its position among the run's calls, and what is written down of it later. */
|
|
31
|
+
export interface RecordedCall {
|
|
32
|
+
seq: number;
|
|
33
|
+
/** How it was answered. */
|
|
34
|
+
end(outcome: CallOutcome): void;
|
|
35
|
+
/** What the agent behind it used — each time it was asked, and whether or not the call is answered. */
|
|
36
|
+
used(usage: AgentUsage): void;
|
|
37
|
+
}
|
|
21
38
|
export interface Journal {
|
|
22
39
|
/** The run's id — the name of its journal file, without the extension. Empty if nothing is being recorded. */
|
|
23
40
|
readonly run: string;
|
|
@@ -28,21 +45,22 @@ export interface Journal {
|
|
|
28
45
|
* allowance is spent in order, and what comes last is what gets cut.
|
|
29
46
|
*/
|
|
30
47
|
note(kind: string, fields?: Record<string, unknown>): void;
|
|
48
|
+
/** Record what the agent used on the runner's own account — asking for a fix, say (`what`: "fix"). */
|
|
49
|
+
used(what: string, usage: AgentUsage): void;
|
|
31
50
|
/**
|
|
32
51
|
* Record a bridge call as it arrives. Returns its position among the run's
|
|
33
52
|
* calls, and what records how it was answered.
|
|
34
53
|
*/
|
|
35
|
-
call(endpoint: string, request: unknown):
|
|
36
|
-
seq: number;
|
|
37
|
-
end(outcome: CallOutcome): void;
|
|
38
|
-
};
|
|
54
|
+
call(endpoint: string, request: unknown): RecordedCall;
|
|
39
55
|
/** Stop recording. Anything noted after this is dropped. */
|
|
40
56
|
close(): void;
|
|
41
57
|
}
|
|
42
58
|
/**
|
|
43
59
|
* Whether a journal is still being written: by this process, or by another
|
|
44
|
-
* runner that is still there
|
|
45
|
-
* is finished, though the process lives
|
|
60
|
+
* runner that is still there and has not yet written its ending. (A journal
|
|
61
|
+
* this process started and has closed is finished, though the process lives
|
|
62
|
+
* on. And a process that may not be signalled is not the writer of a journal
|
|
63
|
+
* that can be read: its number has been given to somebody else's since.)
|
|
46
64
|
*/
|
|
47
65
|
export declare function stillBeingWritten(path: string): boolean;
|
|
48
66
|
/**
|