@trama-dev/runtime 0.3.1 → 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.
@@ -4,25 +4,6 @@ export declare function cappedBuffer(): {
4
4
  append(text: string): void;
5
5
  readonly value: string;
6
6
  };
7
- /**
8
- * Send a signal to a whole process group. Children spawned with `detached: true`
9
- * lead their own group, so this also reaches whatever they started in the background.
10
- * Signal 0 only probes. Returns false if the group no longer exists.
11
- */
12
- export declare function signalGroup(pgid: number, signal: NodeJS.Signals | 0): boolean;
13
- /** The timing of a stop, shared with the watchdog. */
14
- export declare const STOP_TIMINGS: {
15
- grace: number;
16
- settle: number;
17
- poll: number;
18
- };
19
- export declare function onGroupAskedToStop(listener: (pgid: number) => void): void;
20
- /**
21
- * Stop process groups for good: SIGTERM now, SIGKILL after the grace period to
22
- * whichever are still there. Resolves when none is left — so that what follows
23
- * (merging a directory they were writing to, deleting it) finds them gone.
24
- */
25
- export declare function stopGroups(pgids: number[]): Promise<void>;
26
7
  /**
27
8
  * A time limit that only runs down while nothing is holding it.
28
9
  *
@@ -67,7 +48,7 @@ export interface ChildExit {
67
48
  /**
68
49
  * Collect a child's output and wait for it to exit, enforcing a time limit
69
50
  * and an optional stop request. Either one stops the child's whole process
70
- * group (see stopGroups).
51
+ * group (see stopping.ts).
71
52
  * Resolves on exit however it happened; rejects only if the child failed to spawn.
72
53
  */
73
54
  export declare function superviseChild(child: ChildProcess, options: SuperviseOptions): Promise<ChildExit>;
@@ -1,10 +1,6 @@
1
1
  import { StringDecoder } from "string_decoder";
2
+ import { stopGroups } from "./stopping.js";
2
3
  const MAX_OUTPUT = 10 * 1024 * 1024; // 10 MB
3
- /** How long a process group gets to exit after SIGTERM before it is sent SIGKILL. */
4
- const KILL_GRACE_MS = 5000;
5
- const STOP_POLL_MS = 25;
6
- /** How long a group is waited for after SIGKILL before it is given up on. */
7
- const KILL_SETTLE_MS = 1000;
8
4
  /** How long a child's output is waited for once the child itself has exited. */
9
5
  const DRAIN_MS = 1000;
10
6
  /** The longest delay a timer can be given; a longer one fires at once. */
@@ -26,77 +22,6 @@ export function cappedBuffer() {
26
22
  get value() { return buf; },
27
23
  };
28
24
  }
29
- /**
30
- * Send a signal to a whole process group. Children spawned with `detached: true`
31
- * lead their own group, so this also reaches whatever they started in the background.
32
- * Signal 0 only probes. Returns false if the group no longer exists.
33
- */
34
- export function signalGroup(pgid, signal) {
35
- try {
36
- process.kill(-pgid, signal);
37
- return true;
38
- }
39
- catch {
40
- return false;
41
- }
42
- }
43
- // --- Stopping ---
44
- //
45
- // Never SIGKILL first. A group gets the chance to end properly — a program to
46
- // close what it opened, a `trama` command to stop its own run and report it.
47
- // Killed outright, nothing in it gets to finish anything. So a group is asked
48
- // to stop, and killed only if it is still there when the grace period is over.
49
- //
50
- // stopGroups does that for a runner that is there to see it through. When the
51
- // runner itself is gone, its watchdog does the same (see watchdog.ts).
52
- /** The timing of a stop, shared with the watchdog. */
53
- export const STOP_TIMINGS = { grace: KILL_GRACE_MS, settle: KILL_SETTLE_MS, poll: STOP_POLL_MS };
54
- /** Groups this process has asked to stop and is still watching. */
55
- const stopping = new Map();
56
- /** Called with each group as it is asked to stop — for the watchdog, which must not ask it again. */
57
- let onAsked = () => { };
58
- export function onGroupAskedToStop(listener) {
59
- onAsked = listener;
60
- }
61
- function stopGroup(pgid) {
62
- // Asked once is enough: to some programs a second SIGTERM means "now".
63
- const watched = stopping.get(pgid);
64
- if (watched)
65
- return watched;
66
- if (!signalGroup(pgid, "SIGTERM"))
67
- return Promise.resolve();
68
- onAsked(pgid);
69
- const gone = new Promise((resolve) => {
70
- let deadline = performance.now() + KILL_GRACE_MS;
71
- let killed = false;
72
- const poll = setInterval(() => {
73
- const alive = signalGroup(pgid, 0);
74
- if (alive && performance.now() < deadline)
75
- return;
76
- if (alive && !killed) {
77
- // Out of patience. A killed group is gone in a moment; allow it that
78
- // moment, but do not wait on one that for some reason never goes.
79
- signalGroup(pgid, "SIGKILL");
80
- killed = true;
81
- deadline = performance.now() + KILL_SETTLE_MS;
82
- return;
83
- }
84
- clearInterval(poll);
85
- stopping.delete(pgid);
86
- resolve();
87
- }, STOP_POLL_MS);
88
- });
89
- stopping.set(pgid, gone);
90
- return gone;
91
- }
92
- /**
93
- * Stop process groups for good: SIGTERM now, SIGKILL after the grace period to
94
- * whichever are still there. Resolves when none is left — so that what follows
95
- * (merging a directory they were writing to, deleting it) finds them gone.
96
- */
97
- export async function stopGroups(pgids) {
98
- await Promise.all(pgids.map(stopGroup));
99
- }
100
25
  export function createAllowance(ms) {
101
26
  let remaining = ms;
102
27
  let holds = 0;
@@ -146,7 +71,7 @@ export function createAllowance(ms) {
146
71
  /**
147
72
  * Collect a child's output and wait for it to exit, enforcing a time limit
148
73
  * and an optional stop request. Either one stops the child's whole process
149
- * group (see stopGroups).
74
+ * group (see stopping.ts).
150
75
  * Resolves on exit however it happened; rejects only if the child failed to spawn.
151
76
  */
152
77
  export function superviseChild(child, options) {
package/dist/index.d.ts CHANGED
@@ -15,3 +15,11 @@ export declare function createProject(name: string, prompt: string, options?: {
15
15
  export declare function updateProject(name: string, prompt: string): Promise<void>;
16
16
  export declare function listProjects(): Promise<void>;
17
17
  export declare function showLogs(name: string): Promise<void>;
18
+ /**
19
+ * Show what a run of a project did, from its journal: the latest run, or the
20
+ * one named. With `list`, show which runs have a journal instead.
21
+ */
22
+ export declare function showJournal(name: string, options?: {
23
+ run?: string;
24
+ list?: boolean;
25
+ }): Promise<void>;
package/dist/index.js CHANGED
@@ -9,6 +9,7 @@ import { loadConfig, loadProjectConfig, loadState, createBackend, validateProgra
9
9
  import { createWorkspace as workspaceHere } from "./workspace.js";
10
10
  import { parentBridge, remoteWorkspace } from "./bridge-client.js";
11
11
  import { guardPath } from "./path-guard.js";
12
+ import { printJournals } from "./journal-view.js";
12
13
  // --- Running a project, and reaching a workspace ---
13
14
  //
14
15
  // A program never runs another program: it asks its runner to. So these two do
@@ -167,6 +168,7 @@ const validationOptions = (config) => ({
167
168
  timeout: config.defaultTimeout,
168
169
  maxRepairAttempts: config.maxRepairAttempts,
169
170
  maxIterations: config.defaultMaxIterations,
171
+ journalRuns: config.journalRuns,
170
172
  });
171
173
  // --- Public API ---
172
174
  export async function createProject(name, prompt, options) {
@@ -300,3 +302,10 @@ export async function showLogs(name) {
300
302
  }
301
303
  }
302
304
  }
305
+ /**
306
+ * Show what a run of a project did, from its journal: the latest run, or the
307
+ * one named. With `list`, show which runs have a journal instead.
308
+ */
309
+ export async function showJournal(name, options = {}) {
310
+ printJournals(resolveProject(name), name, options);
311
+ }
@@ -1,6 +1,7 @@
1
1
  import { type Server } from "http";
2
2
  import type { Ctx, Agent, Tools, Workspace } from "./types.js";
3
3
  import type { ProgramResult, RunRequest } from "./runner-types.js";
4
+ import type { Journal } from "./journal.js";
4
5
  export interface IpcBackends {
5
6
  /**
6
7
  * The secret only this run's program knows. Every request must present it:
@@ -15,8 +16,13 @@ export interface IpcBackends {
15
16
  workspace: Workspace | null;
16
17
  /** A workspace by directory, for a program that created a session rather than joined one. */
17
18
  workspaceAt(dir: string): Workspace;
18
- /** Run another project on the program's behalf, until it ends or `stop` says to stop it. */
19
- run(request: RunRequest, stop: AbortSignal): Promise<ProgramResult>;
19
+ /**
20
+ * Run another project on the program's behalf, until it ends or `stop` says
21
+ * to stop it. `seq` is the position of the call that asked for it.
22
+ */
23
+ run(request: RunRequest, stop: AbortSignal, seq: number): Promise<ProgramResult>;
24
+ /** Where every call, and how it ended, is written down. */
25
+ journal: Journal;
20
26
  /** Called once ctx.done() or ctx.yield() has been persisted for this run. */
21
27
  onTerminalSignal(result: ProgramResult): void;
22
28
  }
@@ -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
  }
@@ -99,12 +103,16 @@ function buildRoutes({ ctx, agent, tools, workspace, workspaceAt, run, onTermina
99
103
  // A program never runs another program: it asks its runner to. The call
100
104
  // lasts as long as the run does, repairs included.
101
105
  "/run/program": {
102
- fields: { projectDir: "string", args: "optional object" },
103
- handle: async (b, connectionClosed) => {
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) => {
104
111
  const stop = new AbortController();
105
112
  // A caller that is gone — its process died, or it gave up — no longer wants the run.
106
113
  void connectionClosed.then(() => stop.abort());
107
- const id = typeof b.id === "string" ? b.id : undefined;
114
+ // The name the program gave the run, to stop it by.
115
+ const id = b.id;
108
116
  if (id && stoppedAhead.delete(id))
109
117
  stop.abort();
110
118
  if (id)
@@ -117,7 +125,7 @@ function buildRoutes({ ctx, agent, tools, workspace, workspaceAt, run, onTermina
117
125
  maxRepairAttempts: b.maxRepairAttempts,
118
126
  workspaceDir: b.workspaceDir,
119
127
  label: b.label,
120
- }, stop.signal);
128
+ }, stop.signal, seq);
121
129
  }
122
130
  finally {
123
131
  if (id)
@@ -153,9 +161,11 @@ export function createIPCServer(backends) {
153
161
  const routes = buildRoutes(backends);
154
162
  return createServer((req, res) => {
155
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;
156
166
  const reply = (status, body, json = false) => {
157
- if (res.writableEnded || res.destroyed)
158
- return; // answered already, or nobody left to answer
167
+ if (!answerable())
168
+ return;
159
169
  res.writeHead(status, json ? { "Content-Type": "application/json" } : undefined);
160
170
  res.end(body);
161
171
  };
@@ -185,17 +195,28 @@ export function createIPCServer(backends) {
185
195
  req.on("end", async () => {
186
196
  if (overflow)
187
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;
188
202
  try {
189
203
  const body = JSON.parse(Buffer.concat(chunks).toString("utf-8"));
190
204
  const route = req.url ? routes[req.url] : undefined;
191
205
  if (!route)
192
206
  return reply(404, "Not found");
207
+ call = backends.journal.call(req.url, body);
193
208
  validate(body, route.fields);
194
- const result = await route.handle(body, connectionClosed);
195
- 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);
196
213
  }
197
214
  catch (err) {
198
- 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);
199
220
  }
200
221
  });
201
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;