@trama-dev/runtime 0.3.1 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -3
- package/dist/abort.d.ts +12 -0
- package/dist/abort.js +31 -0
- package/dist/agent-backend.d.ts +0 -6
- package/dist/agent-backend.js +1 -21
- package/dist/agent.d.ts +16 -1
- package/dist/agent.js +108 -35
- package/dist/bridge-client.js +44 -14
- package/dist/child-process.d.ts +1 -20
- package/dist/child-process.js +11 -86
- package/dist/client.d.ts +2 -1
- package/dist/client.js +5 -15
- package/dist/context.d.ts +36 -7
- package/dist/context.js +83 -92
- package/dist/errors.d.ts +2 -0
- package/dist/errors.js +2 -0
- package/dist/index.d.ts +12 -1
- package/dist/index.js +93 -53
- package/dist/ipc-server.d.ts +12 -6
- package/dist/ipc-server.js +124 -136
- package/dist/journal-view.d.ts +9 -0
- package/dist/journal-view.js +139 -0
- package/dist/journal.d.ts +70 -0
- package/dist/journal.js +454 -0
- package/dist/meta.d.ts +18 -0
- package/dist/meta.js +29 -0
- package/dist/path-guard.d.ts +128 -19
- package/dist/path-guard.js +384 -68
- package/dist/pi-adapter.d.ts +7 -6
- package/dist/pi-adapter.js +15 -26
- package/dist/replace-file.d.ts +31 -0
- package/dist/replace-file.js +75 -0
- package/dist/runner-types.d.ts +2 -0
- package/dist/runner.d.ts +37 -37
- package/dist/runner.js +565 -239
- package/dist/serializable.d.ts +10 -4
- package/dist/serializable.js +56 -31
- package/dist/{watchdog.d.ts → stopping.d.ts} +15 -0
- package/dist/stopping.js +268 -0
- package/dist/tools.js +44 -13
- package/dist/tree.d.ts +234 -0
- package/dist/tree.js +1409 -0
- package/dist/types.d.ts +6 -3
- package/dist/workspace.d.ts +7 -0
- package/dist/workspace.js +93 -104
- package/package.json +2 -2
- package/dist/watchdog.js +0 -167
package/dist/ipc-server.js
CHANGED
|
@@ -1,26 +1,44 @@
|
|
|
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 { isJsonObject } from "./serializable.js";
|
|
7
7
|
const MAX_IPC_BODY = 50 * 1024 * 1024; // 50 MB
|
|
8
|
+
const MAX_STOPPED_AHEAD = 1024;
|
|
8
9
|
/** A request the program got wrong — answered with 400 rather than 500. */
|
|
9
10
|
class BadRequest extends Error {
|
|
10
11
|
}
|
|
11
|
-
const
|
|
12
|
-
|
|
13
|
-
|
|
12
|
+
const isOfKind = (value, kind) => kind === "any" ? value !== undefined : kind === "object" ? isJsonObject(value) : typeof value === kind;
|
|
13
|
+
/** Read a call's declared fields out of a request body — refusing a body that does not hold them as declared. */
|
|
14
|
+
function read(body, fields) {
|
|
15
|
+
if (!isJsonObject(body))
|
|
16
|
+
throw new BadRequest("The request body must be a JSON object");
|
|
17
|
+
const args = {};
|
|
18
|
+
for (const [name, field] of Object.entries(fields)) {
|
|
19
|
+
const optional = field.startsWith("optional ");
|
|
20
|
+
const kind = (optional ? field.slice("optional ".length) : field);
|
|
14
21
|
const value = body[name];
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
+
// null is how JSON says a field is not there: an optional one given as null was left out.
|
|
23
|
+
if (optional && value == null)
|
|
24
|
+
continue;
|
|
25
|
+
if (!isOfKind(value, kind)) {
|
|
26
|
+
throw new BadRequest(optional
|
|
27
|
+
? `Invalid field: ${name} (expected ${kind} or undefined)`
|
|
28
|
+
: `Missing or invalid field: ${name} (expected ${kind})`);
|
|
22
29
|
}
|
|
30
|
+
args[name] = value;
|
|
23
31
|
}
|
|
32
|
+
return args;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* A call: every field it takes, and what is done with them. The declaration
|
|
36
|
+
* is the whole of what a handler sees of a request — a field that is not
|
|
37
|
+
* declared does not reach it, and one that is arrives as the kind it says.
|
|
38
|
+
* (What is inside an object is the business of whoever it is handed to.)
|
|
39
|
+
*/
|
|
40
|
+
function route(fields, handle) {
|
|
41
|
+
return { handle: (body, connectionClosed, seq) => handle(read(body, fields), connectionClosed, seq) };
|
|
24
42
|
}
|
|
25
43
|
/** Whether a request carries `Authorization: Bearer <token>`, compared in constant time. */
|
|
26
44
|
function isAuthorized(header, token) {
|
|
@@ -28,134 +46,96 @@ function isAuthorized(header, token) {
|
|
|
28
46
|
const actual = Buffer.from(header ?? "");
|
|
29
47
|
return actual.length === expected.length && timingSafeEqual(actual, expected);
|
|
30
48
|
}
|
|
31
|
-
function buildRoutes({ ctx, agent, tools, workspace, workspaceAt, run
|
|
32
|
-
/** The program owns ctx.state; each persisting call hands over its current copy. */
|
|
33
|
-
const adoptState = (state) => {
|
|
34
|
-
assertSerializable(state, "ctx.state");
|
|
35
|
-
ctx.state = state;
|
|
36
|
-
};
|
|
49
|
+
function buildRoutes({ ctx, agent, tools, workspace, workspaceAt, run }) {
|
|
37
50
|
/** Runs the program has asked for and that have not ended, by the id it gave each. */
|
|
38
51
|
const runsAskedFor = new Map();
|
|
39
52
|
/** Ids the program asked to stop before their run was seen here: such a run starts stopped. */
|
|
40
53
|
const stoppedAhead = new Set();
|
|
41
54
|
/** The workspace a call is about: the directory it names, or else the one this run was started with. */
|
|
42
|
-
const workspaceOf = (
|
|
43
|
-
if (
|
|
44
|
-
if (
|
|
55
|
+
const workspaceOf = (dir) => {
|
|
56
|
+
if (dir !== undefined) {
|
|
57
|
+
if (dir === "")
|
|
45
58
|
throw new BadRequest("Invalid field: dir (expected a directory path)");
|
|
46
|
-
return workspaceAt(
|
|
59
|
+
return workspaceAt(dir);
|
|
47
60
|
}
|
|
48
61
|
if (!workspace)
|
|
49
62
|
throw new BadRequest("Workspace is only available when running in a session");
|
|
50
63
|
return workspace;
|
|
51
64
|
};
|
|
52
65
|
return {
|
|
53
|
-
"/agent/instruct": {
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
},
|
|
57
|
-
"/
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
},
|
|
61
|
-
|
|
62
|
-
"/
|
|
63
|
-
"/
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
},
|
|
67
|
-
"/tools/fetch": {
|
|
68
|
-
fields: { url: "string" },
|
|
69
|
-
handle: b => tools.fetch(b.url, { method: b.method, headers: b.headers, body: b.body }),
|
|
70
|
-
},
|
|
71
|
-
"/ctx/log": { fields: { message: "string" }, handle: b => ctx.log(b.message, b.data) },
|
|
72
|
-
"/ctx/ready": { fields: { data: "optional object" }, handle: b => ctx.ready(b.data) },
|
|
73
|
-
"/ctx/checkpoint": {
|
|
74
|
-
fields: { state: "object" },
|
|
75
|
-
handle: async (b) => {
|
|
76
|
-
adoptState(b.state);
|
|
77
|
-
await ctx.checkpoint();
|
|
78
|
-
return ctx.iteration;
|
|
79
|
-
},
|
|
80
|
-
},
|
|
81
|
-
"/ctx/done": {
|
|
82
|
-
fields: { state: "object" },
|
|
83
|
-
handle: async (b) => {
|
|
84
|
-
adoptState(b.state);
|
|
85
|
-
await ctx.done(b.result);
|
|
86
|
-
onTerminalSignal({ status: "done", result: b.result ?? undefined });
|
|
87
|
-
return ctx.iteration;
|
|
88
|
-
},
|
|
89
|
-
},
|
|
90
|
-
"/ctx/yield": {
|
|
91
|
-
fields: { state: "object", reason: "string" },
|
|
92
|
-
handle: async (b) => {
|
|
93
|
-
adoptState(b.state);
|
|
94
|
-
// Persists the yield marker and returns; the program exits itself once we answer.
|
|
95
|
-
await ctx.yield(b.reason);
|
|
96
|
-
onTerminalSignal({ status: "yielded", reason: b.reason });
|
|
97
|
-
},
|
|
98
|
-
},
|
|
66
|
+
"/agent/instruct": route({ prompt: "string", system: "optional string" }, b => agent.instruct(b.prompt, { system: b.system })),
|
|
67
|
+
"/agent/generate": route({ prompt: "string", schema: "object", system: "optional string" }, b => agent.generate({ prompt: b.prompt, schema: b.schema, system: b.system })),
|
|
68
|
+
"/tools/read": route({ path: "string" }, b => tools.read(b.path)),
|
|
69
|
+
"/tools/write": route({ path: "string", content: "string" }, b => tools.write(b.path, b.content)),
|
|
70
|
+
"/tools/shell": route({ command: "string", cwd: "optional string", timeout: "optional number" }, b => tools.shell(b.command, { cwd: b.cwd, timeout: b.timeout })),
|
|
71
|
+
"/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 })),
|
|
72
|
+
"/ctx/log": route({ message: "string", data: "optional any" }, b => ctx.log(b.message, b.data)),
|
|
73
|
+
"/ctx/ready": route({ data: "optional object" }, b => ctx.ready(b.data)),
|
|
74
|
+
// The state is the program's: each call that persists it hands over its current copy.
|
|
75
|
+
"/ctx/checkpoint": route({ state: "object" }, b => ctx.checkpoint(b.state)),
|
|
76
|
+
"/ctx/done": route({ state: "object", result: "optional any" }, b => ctx.done(b.state, b.result)),
|
|
77
|
+
// Persists the yield marker and returns; the program exits itself once it is answered.
|
|
78
|
+
"/ctx/yield": route({ state: "object", reason: "string" }, b => ctx.yield(b.state, b.reason)),
|
|
99
79
|
// A program never runs another program: it asks its runner to. The call
|
|
100
80
|
// lasts as long as the run does, repairs included.
|
|
101
|
-
"/run/program": {
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
81
|
+
"/run/program": route({
|
|
82
|
+
projectDir: "string", args: "optional object",
|
|
83
|
+
timeout: "optional number", maxRepairAttempts: "optional number",
|
|
84
|
+
id: "optional string", label: "optional string", workspaceDir: "optional string",
|
|
85
|
+
}, async ({ id, ...request }, connectionClosed, seq) => {
|
|
86
|
+
if (id !== undefined) {
|
|
87
|
+
if (id === "")
|
|
88
|
+
throw new BadRequest("Invalid field: id (expected a non-empty string)");
|
|
89
|
+
if (runsAskedFor.has(id))
|
|
90
|
+
throw new BadRequest(`Duplicate run id: ${id}`);
|
|
91
|
+
}
|
|
92
|
+
const stop = new AbortController();
|
|
93
|
+
// A caller that is gone — its process died, or it gave up — no longer wants the run.
|
|
94
|
+
void connectionClosed.then(() => stop.abort());
|
|
95
|
+
// `id` is the name the program gave the run, to stop it by.
|
|
96
|
+
if (id !== undefined) {
|
|
97
|
+
if (stoppedAhead.delete(id))
|
|
109
98
|
stop.abort();
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
}, stop.signal);
|
|
121
|
-
}
|
|
122
|
-
finally {
|
|
123
|
-
if (id)
|
|
124
|
-
runsAskedFor.delete(id);
|
|
125
|
-
}
|
|
126
|
-
},
|
|
127
|
-
},
|
|
99
|
+
runsAskedFor.set(id, stop);
|
|
100
|
+
}
|
|
101
|
+
try {
|
|
102
|
+
return await run(request, stop.signal, seq);
|
|
103
|
+
}
|
|
104
|
+
finally {
|
|
105
|
+
if (id !== undefined)
|
|
106
|
+
runsAskedFor.delete(id);
|
|
107
|
+
}
|
|
108
|
+
}),
|
|
128
109
|
// Stop a run asked for above. The call that asked for it still gets its
|
|
129
110
|
// answer — a failed run — once the run is over.
|
|
130
|
-
"/run/stop": {
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
},
|
|
145
|
-
"/workspace/list": {
|
|
146
|
-
"/workspace/observe": {
|
|
147
|
-
fields: { pattern: "string" },
|
|
148
|
-
handle: b => workspaceOf(b).observe(b.pattern, { expect: b.expect, timeout: b.timeout }),
|
|
149
|
-
},
|
|
111
|
+
"/run/stop": route({ id: "string" }, b => {
|
|
112
|
+
if (b.id === "")
|
|
113
|
+
throw new BadRequest("Invalid field: id (expected a non-empty string)");
|
|
114
|
+
const asked = runsAskedFor.get(b.id);
|
|
115
|
+
if (asked)
|
|
116
|
+
asked.abort();
|
|
117
|
+
else {
|
|
118
|
+
if (stoppedAhead.size >= MAX_STOPPED_AHEAD && !stoppedAhead.has(b.id)) {
|
|
119
|
+
stoppedAhead.delete(stoppedAhead.values().next().value);
|
|
120
|
+
}
|
|
121
|
+
stoppedAhead.add(b.id);
|
|
122
|
+
}
|
|
123
|
+
}),
|
|
124
|
+
"/workspace/read": route({ path: "string", dir: "optional string" }, b => workspaceOf(b.dir).read(b.path)),
|
|
125
|
+
"/workspace/write": route({ path: "string", content: "string", dir: "optional string" }, b => workspaceOf(b.dir).write(b.path, b.content)),
|
|
126
|
+
"/workspace/list": route({ pattern: "string", dir: "optional string" }, b => workspaceOf(b.dir).list(b.pattern)),
|
|
127
|
+
"/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 })),
|
|
150
128
|
};
|
|
151
129
|
}
|
|
152
130
|
export function createIPCServer(backends) {
|
|
153
131
|
const routes = buildRoutes(backends);
|
|
154
132
|
return createServer((req, res) => {
|
|
155
133
|
const connectionClosed = new Promise(resolve => res.once("close", resolve));
|
|
134
|
+
// An answer can be given once, and only while there is someone to give it to.
|
|
135
|
+
const answerable = () => !res.writableEnded && !res.destroyed;
|
|
156
136
|
const reply = (status, body, json = false) => {
|
|
157
|
-
if (
|
|
158
|
-
return;
|
|
137
|
+
if (!answerable())
|
|
138
|
+
return;
|
|
159
139
|
res.writeHead(status, json ? { "Content-Type": "application/json" } : undefined);
|
|
160
140
|
res.end(body);
|
|
161
141
|
};
|
|
@@ -185,17 +165,34 @@ export function createIPCServer(backends) {
|
|
|
185
165
|
req.on("end", async () => {
|
|
186
166
|
if (overflow)
|
|
187
167
|
return;
|
|
168
|
+
// Written down as soon as it can be read, and again when it is answered.
|
|
169
|
+
// What comes back for a caller that is gone is not an answer, and is not
|
|
170
|
+
// recorded as one: a call nobody was left to answer has no result.
|
|
171
|
+
let call;
|
|
188
172
|
try {
|
|
189
|
-
|
|
190
|
-
|
|
173
|
+
let body;
|
|
174
|
+
try {
|
|
175
|
+
body = JSON.parse(Buffer.concat(chunks).toString("utf-8"));
|
|
176
|
+
}
|
|
177
|
+
catch {
|
|
178
|
+
return reply(400, "The request body is not valid JSON");
|
|
179
|
+
}
|
|
180
|
+
const route = req.url && Object.hasOwn(routes, req.url) ? routes[req.url] : undefined;
|
|
191
181
|
if (!route)
|
|
192
182
|
return reply(404, "Not found");
|
|
193
|
-
|
|
194
|
-
const result = await route.handle(body, connectionClosed);
|
|
195
|
-
|
|
183
|
+
call = backends.journal.call(req.url, body);
|
|
184
|
+
const result = (await route.handle(body, connectionClosed, call.seq)) ?? null;
|
|
185
|
+
const payload = JSON.stringify({ result });
|
|
186
|
+
if (answerable())
|
|
187
|
+
call.end({ ok: true, result });
|
|
188
|
+
reply(200, payload, true);
|
|
196
189
|
}
|
|
197
190
|
catch (err) {
|
|
198
|
-
|
|
191
|
+
const refused = err instanceof BadRequest;
|
|
192
|
+
const error = refused ? err.message : String(err);
|
|
193
|
+
if (answerable())
|
|
194
|
+
call?.end({ ok: false, error });
|
|
195
|
+
reply(refused ? 400 : 500, error);
|
|
199
196
|
}
|
|
200
197
|
});
|
|
201
198
|
});
|
|
@@ -205,21 +202,12 @@ export function listen(server) {
|
|
|
205
202
|
return new Promise((resolve, reject) => {
|
|
206
203
|
server.once("error", reject);
|
|
207
204
|
server.listen(0, "127.0.0.1", () => {
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
resolve(addr.port);
|
|
211
|
-
else
|
|
212
|
-
reject(new Error("Failed to get server port"));
|
|
205
|
+
server.removeListener("error", reject);
|
|
206
|
+
resolve(server.address().port);
|
|
213
207
|
});
|
|
214
208
|
});
|
|
215
209
|
}
|
|
210
|
+
/** Stop listening, and wait until it has. (The one thing a server can say against it is that it was not listening.) */
|
|
216
211
|
export function closeServer(server) {
|
|
217
|
-
return new Promise((resolve
|
|
218
|
-
server.close(err => {
|
|
219
|
-
if (!err || err.code === "ERR_SERVER_NOT_RUNNING")
|
|
220
|
-
resolve();
|
|
221
|
-
else
|
|
222
|
-
reject(err);
|
|
223
|
-
});
|
|
224
|
-
});
|
|
212
|
+
return new Promise((resolve) => { server.close(() => resolve()); });
|
|
225
213
|
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Print what a run of the project in `projectDir` did: the latest run, or the
|
|
3
|
+
* one named. With `list`, print which runs have a journal instead. `name` is
|
|
4
|
+
* what the project is called where the user asked.
|
|
5
|
+
*/
|
|
6
|
+
export declare function printJournals(projectDir: string, name: string, options: {
|
|
7
|
+
run?: string;
|
|
8
|
+
list?: boolean;
|
|
9
|
+
}): void;
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
// Showing a journal: what `trama journal` prints.
|
|
2
|
+
//
|
|
3
|
+
// This reads what journal.ts writes, and only to show it. A journal is read
|
|
4
|
+
// as far as it goes — a run may still be writing it, or have died doing so.
|
|
5
|
+
import { readFileSync } from "fs";
|
|
6
|
+
import { JOURNAL_VERSION, journalDirOf, journalIn, runsIn, stillBeingWritten } from "./journal.js";
|
|
7
|
+
import { isJsonObject } from "./serializable.js";
|
|
8
|
+
/**
|
|
9
|
+
* The records of a journal file. A line that is not a whole record — the last
|
|
10
|
+
* one, if the runner died writing it — is left out, and so is a file that
|
|
11
|
+
* cannot be read at all.
|
|
12
|
+
*/
|
|
13
|
+
function readJournal(path) {
|
|
14
|
+
const records = [];
|
|
15
|
+
let text = "";
|
|
16
|
+
try {
|
|
17
|
+
text = readFileSync(path, "utf-8");
|
|
18
|
+
}
|
|
19
|
+
catch { /* shown as a run with nothing on record */ }
|
|
20
|
+
for (const line of text.split("\n")) {
|
|
21
|
+
if (!line)
|
|
22
|
+
continue;
|
|
23
|
+
try {
|
|
24
|
+
const record = JSON.parse(line);
|
|
25
|
+
if (isJsonObject(record))
|
|
26
|
+
records.push(record);
|
|
27
|
+
}
|
|
28
|
+
catch { /* not a whole record */ }
|
|
29
|
+
}
|
|
30
|
+
return records;
|
|
31
|
+
}
|
|
32
|
+
const oneLine = (value, max) => {
|
|
33
|
+
const text = (typeof value === "string" ? value : JSON.stringify(value) ?? "").replace(/\s+/g, " ").trim();
|
|
34
|
+
return text.length > max ? text.slice(0, max - 1) + "…" : text;
|
|
35
|
+
};
|
|
36
|
+
/** The one field of a request that says most about it. */
|
|
37
|
+
function gist(request) {
|
|
38
|
+
// A run that was asked for is best known by the name it was given.
|
|
39
|
+
if (typeof request?.label === "string")
|
|
40
|
+
return oneLine(`${request.label} (${request.projectDir})`, 60);
|
|
41
|
+
for (const field of ["prompt", "command", "path", "pattern", "url", "message", "projectDir", "reason"]) {
|
|
42
|
+
if (request?.[field] !== undefined)
|
|
43
|
+
return oneLine(request[field], 60);
|
|
44
|
+
}
|
|
45
|
+
return "";
|
|
46
|
+
}
|
|
47
|
+
/** How a run ended, in a word or two — or that it has not, or never will. */
|
|
48
|
+
function ending(path, records) {
|
|
49
|
+
const end = records.find(record => record.kind === "end");
|
|
50
|
+
if (!end)
|
|
51
|
+
return stillBeingWritten(path) ? "still running" : "did not finish";
|
|
52
|
+
return end.result ? end.result.status : `could not run: ${oneLine(end.error, 60)}`;
|
|
53
|
+
}
|
|
54
|
+
function printJournal(path, records) {
|
|
55
|
+
const head = records[0];
|
|
56
|
+
const howEnded = ending(path, records);
|
|
57
|
+
console.log(`${head?.run ?? "?"} ${head?.purpose ?? ""}${head?.label ? ` [${head.label}]` : ""} ${howEnded}`);
|
|
58
|
+
if (head && head.v !== JOURNAL_VERSION) {
|
|
59
|
+
console.log(`(recorded in format ${head.v}; this trama reads format ${JOURNAL_VERSION}, and shows what it can make of it)`);
|
|
60
|
+
}
|
|
61
|
+
const results = new Map();
|
|
62
|
+
for (const record of records)
|
|
63
|
+
if (record.kind === "result")
|
|
64
|
+
results.set(record.seq, record);
|
|
65
|
+
for (const record of records) {
|
|
66
|
+
const at = `${(record.at / 1000).toFixed(3).padStart(9)}s`;
|
|
67
|
+
switch (record.kind) {
|
|
68
|
+
case "attempt":
|
|
69
|
+
console.log(`${at} attempt ${record.attempt} program ${record.program?.sha256?.slice(0, 8) ?? "missing"}`);
|
|
70
|
+
break;
|
|
71
|
+
case "call": {
|
|
72
|
+
const result = results.get(record.seq);
|
|
73
|
+
const how = !result ? "never answered"
|
|
74
|
+
: result.ok ? `ok ${result.ms}ms`
|
|
75
|
+
: `failed ${result.ms}ms ${oneLine(result.error, 60)}`;
|
|
76
|
+
console.log(`${at} #${String(record.seq).padEnd(3)} ${record.endpoint.slice(1).padEnd(18)} ${gist(record.request).padEnd(60)} ${how}`);
|
|
77
|
+
break;
|
|
78
|
+
}
|
|
79
|
+
case "child":
|
|
80
|
+
console.log(`${at} #${String(record.seq).padEnd(3)} started run ${record.run}`);
|
|
81
|
+
break;
|
|
82
|
+
case "fix-request":
|
|
83
|
+
console.log(`${at} fix asked for: ${oneLine(record.error, 80)}`);
|
|
84
|
+
break;
|
|
85
|
+
case "fix":
|
|
86
|
+
console.log(`${at} fix ${record.ok ? "returned" : `not returned: ${oneLine(record.error, 80)}`}`);
|
|
87
|
+
break;
|
|
88
|
+
case "exit": {
|
|
89
|
+
const how = record.timedOut ? "timed out"
|
|
90
|
+
: record.validated ? `stopped, validated (${record.validated})`
|
|
91
|
+
: record.stopped ? "stopped"
|
|
92
|
+
: record.signal ? `killed by ${record.signal}`
|
|
93
|
+
: `exit code ${record.code}`;
|
|
94
|
+
const verdict = record.error ? `unusable: ${oneLine(record.error, 60)}` : record.outcome ? record.outcome.status : "failed";
|
|
95
|
+
console.log(`${at} attempt ${record.attempt} over: ${how} → ${verdict}`);
|
|
96
|
+
break;
|
|
97
|
+
}
|
|
98
|
+
case "unmerged":
|
|
99
|
+
console.log(`${at} attempt ${record.attempt}: ${record.files?.length ?? 0} change(s) it made did not reach the project`);
|
|
100
|
+
for (const file of record.files ?? [])
|
|
101
|
+
console.log(`${" ".repeat(at.length)} ${file.path} — ${oneLine(file.why, 80)}`);
|
|
102
|
+
break;
|
|
103
|
+
case "full":
|
|
104
|
+
console.log(`${at} the journal is full: calls from here on were not recorded`);
|
|
105
|
+
break;
|
|
106
|
+
case "end":
|
|
107
|
+
console.log(`${at} end: ${howEnded}`);
|
|
108
|
+
break;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Print what a run of the project in `projectDir` did: the latest run, or the
|
|
114
|
+
* one named. With `list`, print which runs have a journal instead. `name` is
|
|
115
|
+
* what the project is called where the user asked.
|
|
116
|
+
*/
|
|
117
|
+
export function printJournals(projectDir, name, options) {
|
|
118
|
+
const dir = journalDirOf(projectDir);
|
|
119
|
+
const runs = runsIn(dir);
|
|
120
|
+
if (runs.length === 0) {
|
|
121
|
+
console.log("No runs have been recorded.");
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
if (options.list) {
|
|
125
|
+
for (const run of runs) {
|
|
126
|
+
const path = journalIn(dir, run);
|
|
127
|
+
const records = readJournal(path);
|
|
128
|
+
const calls = records.filter(record => record.kind === "call").length;
|
|
129
|
+
console.log(`${run} ${String(records[0]?.purpose ?? "").padEnd(8)} ${String(calls).padStart(4)} calls ${ending(path, records)}`);
|
|
130
|
+
}
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
const run = options.run ?? runs[runs.length - 1];
|
|
134
|
+
if (!runs.includes(run)) {
|
|
135
|
+
throw new Error(`No journal for run "${run}". \`trama journal ${name} --list\` shows the runs that have one.`);
|
|
136
|
+
}
|
|
137
|
+
const path = journalIn(dir, run);
|
|
138
|
+
printJournal(path, readJournal(path));
|
|
139
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/** The format of the records. Bump it when a reader of older journals would be misled. */
|
|
2
|
+
export declare const JOURNAL_VERSION = 1;
|
|
3
|
+
/** Where a project keeps its journals, relative to the project — under logs/, which trama keeps out of version control. */
|
|
4
|
+
export declare const JOURNAL_DIR: string;
|
|
5
|
+
/**
|
|
6
|
+
* A project's journal directory, by its one real name however the project was
|
|
7
|
+
* referred to.
|
|
8
|
+
*/
|
|
9
|
+
export declare function journalDirOf(projectDir: string): string;
|
|
10
|
+
/** The journal of a run, in a journal directory. */
|
|
11
|
+
export declare const journalIn: (dir: string, run: string) => string;
|
|
12
|
+
/** The ids of the runs that have a journal in `dir`, oldest first. (A run's id starts with when it started.) */
|
|
13
|
+
export declare function runsIn(dir: string): string[];
|
|
14
|
+
/**
|
|
15
|
+
* What a copy of `projectDir` is to leave out so as not to carry the project's
|
|
16
|
+
* journals, each by what it is (its `identityOf`): the directory they are in,
|
|
17
|
+
* if nothing else is in it or it may not be read or searched — and otherwise every
|
|
18
|
+
* journal in it. Somebody's own file among the journals is the project's
|
|
19
|
+
* like any other, and is copied.
|
|
20
|
+
*/
|
|
21
|
+
export declare function journalEntriesOf(projectDir: string): Set<string>;
|
|
22
|
+
export type CallOutcome = {
|
|
23
|
+
ok: true;
|
|
24
|
+
result: unknown;
|
|
25
|
+
} | {
|
|
26
|
+
ok: false;
|
|
27
|
+
error: string;
|
|
28
|
+
};
|
|
29
|
+
export interface Journal {
|
|
30
|
+
/** The run's id — the name of its journal file, without the extension. Empty if nothing is being recorded. */
|
|
31
|
+
readonly run: string;
|
|
32
|
+
/** The journal file. Empty if nothing is being recorded. */
|
|
33
|
+
readonly path: string;
|
|
34
|
+
/**
|
|
35
|
+
* Append a record of the given kind. Put small fields first: a record's
|
|
36
|
+
* allowance is spent in order, and what comes last is what gets cut.
|
|
37
|
+
*/
|
|
38
|
+
note(kind: string, fields?: Record<string, unknown>): void;
|
|
39
|
+
/**
|
|
40
|
+
* Record a bridge call as it arrives. Returns its position among the run's
|
|
41
|
+
* calls, and what records how it was answered.
|
|
42
|
+
*/
|
|
43
|
+
call(endpoint: string, request: unknown): {
|
|
44
|
+
seq: number;
|
|
45
|
+
end(outcome: CallOutcome): void;
|
|
46
|
+
};
|
|
47
|
+
/** Stop recording. Anything noted after this is dropped. */
|
|
48
|
+
close(): void;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Whether a journal is still being written: by this process, or by another
|
|
52
|
+
* runner that is still there and has not yet written its ending. (A journal
|
|
53
|
+
* this process started and has closed is finished, though the process lives
|
|
54
|
+
* on. And a process that may not be signalled is not the writer of a journal
|
|
55
|
+
* that can be read: its number has been given to somebody else's since.)
|
|
56
|
+
*/
|
|
57
|
+
export declare function stillBeingWritten(path: string): boolean;
|
|
58
|
+
/**
|
|
59
|
+
* Start the journal of a run of `projectDir`, keeping the journals of at most
|
|
60
|
+
* `keep` runs of it (0: record nothing). `about` is what is known at the start
|
|
61
|
+
* and goes into the first record.
|
|
62
|
+
*
|
|
63
|
+
* The journal belongs to the project, not to wherever the program happens to
|
|
64
|
+
* be executed: a fix tried on a copy, or a candidate validated in one, is
|
|
65
|
+
* still recorded here, where it will be looked for.
|
|
66
|
+
*
|
|
67
|
+
* Recording is best-effort. If the journal cannot be opened or written, the
|
|
68
|
+
* run goes on without one — a record must never change what it records.
|
|
69
|
+
*/
|
|
70
|
+
export declare function openJournal(projectDir: string, keep: number, about: Record<string, unknown>): Journal;
|