@trama-dev/runtime 0.3.0 → 0.4.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.
@@ -12,13 +12,17 @@ const isPlainObject = (v) => typeof v === "object" && v !== null && !Array.isArr
12
12
  function validate(body, fields) {
13
13
  for (const [name, type] of Object.entries(fields)) {
14
14
  const value = body[name];
15
- if (type === "optional object") {
16
- if (value !== undefined && !isPlainObject(value)) {
17
- throw new BadRequest(`Invalid field: ${name} (expected object or undefined)`);
18
- }
15
+ const optional = type.startsWith("optional ");
16
+ // 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];
19
+ continue;
19
20
  }
20
- else if (type === "object" ? !isPlainObject(value) : typeof value !== type) {
21
- throw new BadRequest(`Missing or invalid field: ${name} (expected ${type})`);
21
+ const expected = optional ? type.slice("optional ".length) : type;
22
+ if (expected === "object" ? !isPlainObject(value) : typeof value !== expected) {
23
+ throw new BadRequest(optional
24
+ ? `Invalid field: ${name} (expected ${expected} or undefined)`
25
+ : `Missing or invalid field: ${name} (expected ${expected})`);
22
26
  }
23
27
  }
24
28
  }
@@ -28,13 +32,23 @@ function isAuthorized(header, token) {
28
32
  const actual = Buffer.from(header ?? "");
29
33
  return actual.length === expected.length && timingSafeEqual(actual, expected);
30
34
  }
31
- function buildRoutes({ ctx, agent, tools, workspace, onTerminalSignal, holdClock }) {
35
+ function buildRoutes({ ctx, agent, tools, workspace, workspaceAt, run, onTerminalSignal }) {
32
36
  /** The program owns ctx.state; each persisting call hands over its current copy. */
33
37
  const adoptState = (state) => {
34
38
  assertSerializable(state, "ctx.state");
35
39
  ctx.state = state;
36
40
  };
37
- const inSession = () => {
41
+ /** Runs the program has asked for and that have not ended, by the id it gave each. */
42
+ const runsAskedFor = new Map();
43
+ /** Ids the program asked to stop before their run was seen here: such a run starts stopped. */
44
+ const stoppedAhead = new Set();
45
+ /** The workspace a call is about: the directory it names, or else the one this run was started with. */
46
+ const workspaceOf = (body) => {
47
+ if (body.dir !== undefined) {
48
+ if (typeof body.dir !== "string" || body.dir === "")
49
+ throw new BadRequest("Invalid field: dir (expected a directory path)");
50
+ return workspaceAt(body.dir);
51
+ }
38
52
  if (!workspace)
39
53
  throw new BadRequest("Workspace is only available when running in a session");
40
54
  return workspace;
@@ -86,27 +100,60 @@ function buildRoutes({ ctx, agent, tools, workspace, onTerminalSignal, holdClock
86
100
  onTerminalSignal({ status: "yielded", reason: b.reason });
87
101
  },
88
102
  },
89
- // A run the program starts — a session participant — is under a timeout
90
- // of its own, and the program's clock stops while it lasts (see
91
- // holdParentClock). The hold is the connection: it ends when the caller
92
- // closes it, and cannot outlast a caller that dies without doing so.
93
- "/clock/hold": {
94
- fields: {},
95
- handle: async (_body, connectionClosed) => {
96
- const release = holdClock();
97
- await connectionClosed;
98
- release();
103
+ // A program never runs another program: it asks its runner to. The call
104
+ // lasts as long as the run does, repairs included.
105
+ "/run/program": {
106
+ fields: {
107
+ projectDir: "string", args: "optional object",
108
+ id: "optional string", label: "optional string", workspaceDir: "optional string",
109
+ },
110
+ handle: async (b, connectionClosed, seq) => {
111
+ const stop = new AbortController();
112
+ // A caller that is gone — its process died, or it gave up — no longer wants the run.
113
+ void connectionClosed.then(() => stop.abort());
114
+ // The name the program gave the run, to stop it by.
115
+ const id = b.id;
116
+ if (id && stoppedAhead.delete(id))
117
+ stop.abort();
118
+ if (id)
119
+ runsAskedFor.set(id, stop);
120
+ try {
121
+ return await run({
122
+ projectDir: b.projectDir,
123
+ args: b.args,
124
+ timeout: b.timeout,
125
+ maxRepairAttempts: b.maxRepairAttempts,
126
+ workspaceDir: b.workspaceDir,
127
+ label: b.label,
128
+ }, stop.signal, seq);
129
+ }
130
+ finally {
131
+ if (id)
132
+ runsAskedFor.delete(id);
133
+ }
134
+ },
135
+ },
136
+ // Stop a run asked for above. The call that asked for it still gets its
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);
99
146
  },
100
147
  },
101
- "/workspace/read": { fields: { path: "string" }, handle: b => inSession().read(b.path) },
148
+ "/workspace/read": { fields: { path: "string" }, handle: b => workspaceOf(b).read(b.path) },
102
149
  "/workspace/write": {
103
150
  fields: { path: "string", content: "string" },
104
- handle: b => inSession().write(b.path, b.content),
151
+ handle: b => workspaceOf(b).write(b.path, b.content),
105
152
  },
106
- "/workspace/list": { fields: { pattern: "string" }, handle: b => inSession().list(b.pattern) },
153
+ "/workspace/list": { fields: { pattern: "string" }, handle: b => workspaceOf(b).list(b.pattern) },
107
154
  "/workspace/observe": {
108
155
  fields: { pattern: "string" },
109
- handle: b => inSession().observe(b.pattern, { expect: b.expect, timeout: b.timeout }),
156
+ handle: b => workspaceOf(b).observe(b.pattern, { expect: b.expect, timeout: b.timeout }),
110
157
  },
111
158
  };
112
159
  }
@@ -114,9 +161,11 @@ export function createIPCServer(backends) {
114
161
  const routes = buildRoutes(backends);
115
162
  return createServer((req, res) => {
116
163
  const connectionClosed = new Promise(resolve => res.once("close", resolve));
164
+ // An answer can be given once, and only while there is someone to give it to.
165
+ const answerable = () => !res.writableEnded && !res.destroyed;
117
166
  const reply = (status, body, json = false) => {
118
- if (res.writableEnded || res.destroyed)
119
- return; // answered already, or nobody left to answer
167
+ if (!answerable())
168
+ return;
120
169
  res.writeHead(status, json ? { "Content-Type": "application/json" } : undefined);
121
170
  res.end(body);
122
171
  };
@@ -146,17 +195,28 @@ export function createIPCServer(backends) {
146
195
  req.on("end", async () => {
147
196
  if (overflow)
148
197
  return;
198
+ // Written down as soon as it can be read, and again when it is answered.
199
+ // What comes back for a caller that is gone is not an answer, and is not
200
+ // recorded as one: a call nobody was left to answer has no result.
201
+ let call;
149
202
  try {
150
203
  const body = JSON.parse(Buffer.concat(chunks).toString("utf-8"));
151
204
  const route = req.url ? routes[req.url] : undefined;
152
205
  if (!route)
153
206
  return reply(404, "Not found");
207
+ call = backends.journal.call(req.url, body);
154
208
  validate(body, route.fields);
155
- const result = await route.handle(body, connectionClosed);
156
- reply(200, JSON.stringify({ result: result ?? null }), true);
209
+ const result = (await route.handle(body, connectionClosed, call.seq)) ?? null;
210
+ if (answerable())
211
+ call.end({ ok: true, result });
212
+ reply(200, JSON.stringify({ result }), true);
157
213
  }
158
214
  catch (err) {
159
- reply(err instanceof BadRequest ? 400 : 500, err instanceof BadRequest ? err.message : String(err));
215
+ const refused = err instanceof BadRequest;
216
+ const error = refused ? err.message : String(err);
217
+ if (answerable())
218
+ call?.end({ ok: false, error });
219
+ reply(refused ? 400 : 500, error);
160
220
  }
161
221
  });
162
222
  });
@@ -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,131 @@
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
+ /**
8
+ * The records of a journal file. A line that is not a whole record — the last
9
+ * one, if the runner died writing it — is left out, and so is a file that
10
+ * cannot be read at all.
11
+ */
12
+ function readJournal(path) {
13
+ const records = [];
14
+ let text = "";
15
+ try {
16
+ text = readFileSync(path, "utf-8");
17
+ }
18
+ catch { /* shown as a run with nothing on record */ }
19
+ for (const line of text.split("\n")) {
20
+ if (!line)
21
+ continue;
22
+ try {
23
+ const record = JSON.parse(line);
24
+ if (typeof record === "object" && record !== null)
25
+ records.push(record);
26
+ }
27
+ catch { /* not a whole record */ }
28
+ }
29
+ return records;
30
+ }
31
+ const oneLine = (value, max) => {
32
+ const text = (typeof value === "string" ? value : JSON.stringify(value) ?? "").replace(/\s+/g, " ").trim();
33
+ return text.length > max ? text.slice(0, max - 1) + "…" : text;
34
+ };
35
+ /** The one field of a request that says most about it. */
36
+ function gist(request) {
37
+ // A run that was asked for is best known by the name it was given.
38
+ if (typeof request?.label === "string")
39
+ return oneLine(`${request.label} (${request.projectDir})`, 60);
40
+ for (const field of ["prompt", "command", "path", "pattern", "url", "message", "projectDir", "reason"]) {
41
+ if (request?.[field] !== undefined)
42
+ return oneLine(request[field], 60);
43
+ }
44
+ return "";
45
+ }
46
+ /** How a run ended, in a word or two — or that it has not, or never will. */
47
+ function ending(path, records) {
48
+ const end = records.find(record => record.kind === "end");
49
+ if (!end)
50
+ return stillBeingWritten(path) ? "still running" : "did not finish";
51
+ return end.result ? end.result.status : `could not run: ${oneLine(end.error, 60)}`;
52
+ }
53
+ function printJournal(path, records) {
54
+ const head = records[0];
55
+ console.log(`${head?.run ?? "?"} ${head?.purpose ?? ""}${head?.label ? ` [${head.label}]` : ""} ${ending(path, records)}`);
56
+ if (head && head.v !== JOURNAL_VERSION) {
57
+ console.log(`(recorded in format ${head.v}; this trama reads format ${JOURNAL_VERSION}, and shows what it can make of it)`);
58
+ }
59
+ const results = new Map();
60
+ for (const record of records)
61
+ if (record.kind === "result")
62
+ results.set(record.seq, record);
63
+ for (const record of records) {
64
+ const at = `${(record.at / 1000).toFixed(3).padStart(9)}s`;
65
+ switch (record.kind) {
66
+ case "attempt":
67
+ console.log(`${at} attempt ${record.attempt} program ${record.program?.sha256?.slice(0, 8) ?? "missing"}`);
68
+ break;
69
+ case "call": {
70
+ const result = results.get(record.seq);
71
+ const how = !result ? "never answered"
72
+ : result.ok ? `ok ${result.ms}ms`
73
+ : `failed ${result.ms}ms ${oneLine(result.error, 60)}`;
74
+ console.log(`${at} #${String(record.seq).padEnd(3)} ${record.endpoint.slice(1).padEnd(18)} ${gist(record.request).padEnd(60)} ${how}`);
75
+ break;
76
+ }
77
+ case "child":
78
+ console.log(`${at} #${String(record.seq).padEnd(3)} started run ${record.run}`);
79
+ break;
80
+ case "fix-request":
81
+ console.log(`${at} fix asked for: ${oneLine(record.error, 80)}`);
82
+ break;
83
+ case "fix":
84
+ console.log(`${at} fix ${record.ok ? "returned" : `not returned: ${oneLine(record.error, 80)}`}`);
85
+ break;
86
+ case "exit": {
87
+ const how = record.timedOut ? "timed out"
88
+ : record.validated ? `stopped, validated (${record.validated})`
89
+ : record.stopped ? "stopped"
90
+ : record.signal ? `killed by ${record.signal}`
91
+ : `exit code ${record.code}`;
92
+ const verdict = record.error ? `unusable: ${oneLine(record.error, 60)}` : record.outcome ? record.outcome.status : "failed";
93
+ console.log(`${at} attempt ${record.attempt} over: ${how} → ${verdict}`);
94
+ break;
95
+ }
96
+ case "full":
97
+ console.log(`${at} the journal is full: calls from here on were not recorded`);
98
+ break;
99
+ case "end":
100
+ console.log(`${at} end: ${ending(path, records)}`);
101
+ break;
102
+ }
103
+ }
104
+ }
105
+ /**
106
+ * Print what a run of the project in `projectDir` did: the latest run, or the
107
+ * one named. With `list`, print which runs have a journal instead. `name` is
108
+ * what the project is called where the user asked.
109
+ */
110
+ export function printJournals(projectDir, name, options) {
111
+ const dir = journalDirOf(projectDir);
112
+ const runs = runsIn(dir);
113
+ if (runs.length === 0) {
114
+ console.log("No runs have been recorded.");
115
+ return;
116
+ }
117
+ if (options.list) {
118
+ for (const run of runs) {
119
+ const path = journalIn(dir, run);
120
+ const records = readJournal(path);
121
+ const calls = records.filter(record => record.kind === "call").length;
122
+ console.log(`${run} ${String(records[0]?.purpose ?? "").padEnd(8)} ${String(calls).padStart(4)} calls ${ending(path, records)}`);
123
+ }
124
+ return;
125
+ }
126
+ const run = options.run ?? runs[runs.length - 1];
127
+ if (!runs.includes(run)) {
128
+ throw new Error(`No journal for run "${run}". \`trama journal ${name} --list\` shows the runs that have one.`);
129
+ }
130
+ printJournal(journalIn(dir, run), readJournal(journalIn(dir, run)));
131
+ }
@@ -0,0 +1,60 @@
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: a journal is recognised as still being written by its path.
8
+ */
9
+ 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
+ /** The journal of a run, in a journal directory. */
13
+ export declare const journalIn: (dir: string, run: string) => string;
14
+ export type CallOutcome = {
15
+ ok: true;
16
+ result: unknown;
17
+ } | {
18
+ ok: false;
19
+ error: string;
20
+ };
21
+ export interface Journal {
22
+ /** The run's id — the name of its journal file, without the extension. Empty if nothing is being recorded. */
23
+ readonly run: string;
24
+ /** The journal file. Empty if nothing is being recorded. */
25
+ readonly path: string;
26
+ /**
27
+ * Append a record of the given kind. Put small fields first: a record's
28
+ * allowance is spent in order, and what comes last is what gets cut.
29
+ */
30
+ note(kind: string, fields?: Record<string, unknown>): void;
31
+ /**
32
+ * Record a bridge call as it arrives. Returns its position among the run's
33
+ * calls, and what records how it was answered.
34
+ */
35
+ call(endpoint: string, request: unknown): {
36
+ seq: number;
37
+ end(outcome: CallOutcome): void;
38
+ };
39
+ /** Stop recording. Anything noted after this is dropped. */
40
+ close(): void;
41
+ }
42
+ /**
43
+ * Whether a journal is still being written: by this process, or by another
44
+ * runner that is still there. (A journal this process started and has closed
45
+ * is finished, though the process lives on.)
46
+ */
47
+ export declare function stillBeingWritten(path: string): boolean;
48
+ /**
49
+ * Start the journal of a run of `projectDir`, keeping the journals of at most
50
+ * `keep` runs of it (0: record nothing). `about` is what is known at the start
51
+ * and goes into the first record.
52
+ *
53
+ * The journal belongs to the project, not to wherever the program happens to
54
+ * be executed: a fix tried on a copy, or a candidate validated in one, is
55
+ * still recorded here, where it will be looked for.
56
+ *
57
+ * Recording is best-effort. If the journal cannot be opened or written, the
58
+ * run goes on without one — a record must never change what it records.
59
+ */
60
+ export declare function openJournal(projectDir: string, keep: number, about: Record<string, unknown>): Journal;