@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.
@@ -0,0 +1,322 @@
1
+ // The journal: a record of what a run did.
2
+ //
3
+ // What a program does through the runtime goes through the bridge, so the
4
+ // bridge is where a run can be written down: each call as it arrives, and how
5
+ // it was answered. Around the calls go the things only the runner knows — which
6
+ // program was run, each attempt and how it exited, each fix that was asked for
7
+ // and what came back, and how the run as a whole ended. (What a program does on
8
+ // its own — it is a node process like any other — is not seen here.)
9
+ //
10
+ // One file per run, one JSON record per line, appended as things happen, so a
11
+ // journal says what had happened by the time of its last line: a run that died
12
+ // has no "end", and a call nobody was left to answer has no "result".
13
+ //
14
+ // It records. Nothing reads it back to change what a run does.
15
+ import { appendFileSync, closeSync, mkdirSync, openSync, readSync, readdirSync, realpathSync, rmSync } from "fs";
16
+ import { createHash, randomBytes } from "crypto";
17
+ import { join } from "path";
18
+ import { guardPath } from "./path-guard.js";
19
+ /** The format of the records. Bump it when a reader of older journals would be misled. */
20
+ export const JOURNAL_VERSION = 1;
21
+ /** Where a project keeps its journals, relative to the project — under logs/, which trama keeps out of version control. */
22
+ export const JOURNAL_DIR = join("logs", "journal");
23
+ /**
24
+ * A project's journal directory, by its one real name however the project was
25
+ * referred to: a journal is recognised as still being written by its path.
26
+ */
27
+ export function journalDirOf(projectDir) {
28
+ const dir = guardPath(projectDir, JOURNAL_DIR);
29
+ try {
30
+ return realpathSync(dir);
31
+ }
32
+ catch {
33
+ return dir; /* not there yet */
34
+ }
35
+ }
36
+ /** The ids of the runs that have a journal in `dir`, oldest first. (A run's id starts with when it started.) */
37
+ export function runsIn(dir) {
38
+ let names;
39
+ try {
40
+ names = readdirSync(dir);
41
+ }
42
+ catch (err) {
43
+ if (err.code === "ENOENT")
44
+ return []; // no run has been recorded
45
+ throw err;
46
+ }
47
+ return names.filter(name => name.endsWith(".jsonl")).sort().map(name => name.slice(0, -".jsonl".length));
48
+ }
49
+ /** The journal of a run, in a journal directory. */
50
+ export const journalIn = (dir, run) => join(dir, `${run}.jsonl`);
51
+ /** The longest text kept whole. */
52
+ const MAX_TEXT = 256 * 1024;
53
+ /** About how much one record may hold. It is spent in the order the record's fields come in. */
54
+ const MAX_RECORD = 1024 * 1024;
55
+ /** How far into nested values a record goes. */
56
+ const MAX_DEPTH = 12;
57
+ /** The longest name a field is recorded under. */
58
+ const MAX_NAME = 1024;
59
+ /** How large a journal grows before it stops taking down calls. */
60
+ const MAX_JOURNAL = 64 * 1024 * 1024;
61
+ /**
62
+ * A value as it is written down: whole if there is room, and otherwise cut
63
+ * short, with a note of it in `room.cuts`. Everything written is counted
64
+ * against `room.left` — the notes too — so a record holds about that many
65
+ * characters whatever shape its contents have. (Its line can be longer: JSON
66
+ * writes some characters as escapes of up to six.)
67
+ */
68
+ function clip(value, room, path = []) {
69
+ const cut = (about) => {
70
+ room.cuts.push({ path, ...about });
71
+ room.left -= 128 + path.reduce((size, step) => size + String(step).length + 3, 0);
72
+ };
73
+ if (typeof value === "string") {
74
+ const keep = Math.max(0, Math.min(MAX_TEXT, room.left));
75
+ room.left -= Math.min(value.length, keep) + 3;
76
+ if (value.length <= keep)
77
+ return value;
78
+ cut({ cut: "text", length: value.length, sha256: createHash("sha256").update(value).digest("hex") });
79
+ return value.slice(0, keep);
80
+ }
81
+ if (typeof value === "bigint")
82
+ value = value.toString();
83
+ if (value === null || typeof value !== "object") {
84
+ room.left -= typeof value === "number" ? String(value).length + 1 : 8;
85
+ return value;
86
+ }
87
+ // Binary data is recorded by its size: as text it would be a list of numbers.
88
+ if (ArrayBuffer.isView(value)) {
89
+ cut({ cut: "bytes", length: value.byteLength });
90
+ return null;
91
+ }
92
+ // Anything that knows how it wants to be written (a Date) is asked.
93
+ if (typeof value.toJSON === "function") {
94
+ return clip(value.toJSON(), room, path);
95
+ }
96
+ if (path.length >= MAX_DEPTH) {
97
+ cut({ cut: "depth" });
98
+ return null;
99
+ }
100
+ room.left -= 3; // an empty list or object takes room too
101
+ if (Array.isArray(value)) {
102
+ const items = [];
103
+ for (const item of value) {
104
+ if (room.left <= 0) {
105
+ cut({ cut: "list", length: value.length });
106
+ break;
107
+ }
108
+ items.push(clip(item, room, [...path, items.length]));
109
+ }
110
+ return items;
111
+ }
112
+ const fields = {};
113
+ let fieldsLeftOut = false;
114
+ for (const key in value) {
115
+ if (!Object.hasOwn(value, key))
116
+ continue;
117
+ // A field goes in with its name, or not at all. A name that is too long
118
+ // is passed over — it would be repeated in the path of everything cut
119
+ // beneath it — and one there is no room for ends the object.
120
+ const noRoom = room.left <= key.length;
121
+ if (noRoom || key.length > MAX_NAME) {
122
+ if (!fieldsLeftOut)
123
+ cut({ cut: "object" });
124
+ fieldsLeftOut = true;
125
+ if (noRoom)
126
+ break;
127
+ continue;
128
+ }
129
+ room.left -= key.length + 3;
130
+ fields[key] = clip(value[key], room, [...path, key]);
131
+ }
132
+ return fields;
133
+ }
134
+ /**
135
+ * Header names whose values are credentials more often than not. Wide on
136
+ * purpose: a header wrongly held back costs little, one wrongly kept is a leak.
137
+ * (Rate-limit headers count tokens, they do not carry one.)
138
+ */
139
+ const SECRET_HEADER = /auth|cookie|secret|passw|credential|session|jwt|csrf|xsrf|signature|token|key/i;
140
+ const isSecretHeader = (name) => SECRET_HEADER.test(name) && !/rate-?limit/i.test(name);
141
+ /** A copy of a set of HTTP headers — an object, or a list of pairs — with the secret-looking values left out. */
142
+ function redactHeaders(headers) {
143
+ if (Array.isArray(headers)) {
144
+ return headers.map(pair => Array.isArray(pair) && typeof pair[0] === "string" && isSecretHeader(pair[0]) ? [pair[0], "[redacted]"] : pair);
145
+ }
146
+ if (typeof headers !== "object" || headers === null)
147
+ return headers;
148
+ return Object.fromEntries(Object.entries(headers).map(([name, value]) => [name, isSecretHeader(name) ? "[redacted]" : value]));
149
+ }
150
+ /**
151
+ * What is written down of a call's request or result. The one thing known to
152
+ * carry secrets by design — the headers of a web request — is redacted. A
153
+ * secret a program puts anywhere else (a URL, a prompt, a command) is recorded
154
+ * like the rest: the journal cannot tell.
155
+ */
156
+ function recordable(endpoint, value) {
157
+ if (endpoint === "/tools/fetch" && typeof value === "object" && value !== null && "headers" in value) {
158
+ return { ...value, headers: redactHeaders(value.headers) };
159
+ }
160
+ return value;
161
+ }
162
+ /** A journal that records nothing. Calls are still numbered, so the rest of the runner need not care. */
163
+ function noJournal() {
164
+ let seq = 0;
165
+ return { run: "", path: "", note() { }, call: () => ({ seq: ++seq, end() { } }), close() { } };
166
+ }
167
+ /** Journals this process is writing. They are never the ones to make room. */
168
+ const beingWritten = new Set();
169
+ /** The process that started a journal — named at the start of its first record — or null if it cannot be told. */
170
+ function writerOf(path) {
171
+ let fd = null;
172
+ try {
173
+ fd = openSync(path, "r");
174
+ const start = Buffer.alloc(512);
175
+ const pid = /"pid":(\d+)/.exec(start.toString("utf-8", 0, readSync(fd, start, 0, start.length, 0)))?.[1];
176
+ return pid ? Number(pid) : null;
177
+ }
178
+ catch {
179
+ return null;
180
+ }
181
+ finally {
182
+ if (fd !== null)
183
+ closeSync(fd);
184
+ }
185
+ }
186
+ const isAlive = (pid) => { try {
187
+ process.kill(pid, 0);
188
+ return true;
189
+ }
190
+ catch {
191
+ return false;
192
+ } };
193
+ /**
194
+ * Whether a journal is still being written: by this process, or by another
195
+ * runner that is still there. (A journal this process started and has closed
196
+ * is finished, though the process lives on.)
197
+ */
198
+ export function stillBeingWritten(path) {
199
+ if (beingWritten.has(path))
200
+ return true;
201
+ const writer = writerOf(path);
202
+ return writer !== null && writer !== process.pid && isAlive(writer);
203
+ }
204
+ /**
205
+ * Remove the oldest journals of a project so that, with one more, at most
206
+ * `keep` remain — but never one that is still being written, by this process
207
+ * or by another runner: a run of the same project may be going on right now
208
+ * (two participants of a session, or a program that runs its own project).
209
+ * Such journals stay, and the project holds more than `keep` for a while.
210
+ */
211
+ function makeRoom(dir, keep) {
212
+ const runs = runsIn(dir);
213
+ for (const run of runs.slice(0, Math.max(0, runs.length - (keep - 1)))) {
214
+ const path = journalIn(dir, run);
215
+ if (!stillBeingWritten(path))
216
+ rmSync(path, { force: true });
217
+ }
218
+ }
219
+ /**
220
+ * Start the journal of a run of `projectDir`, keeping the journals of at most
221
+ * `keep` runs of it (0: record nothing). `about` is what is known at the start
222
+ * and goes into the first record.
223
+ *
224
+ * The journal belongs to the project, not to wherever the program happens to
225
+ * be executed: a fix tried on a copy, or a candidate validated in one, is
226
+ * still recorded here, where it will be looked for.
227
+ *
228
+ * Recording is best-effort. If the journal cannot be opened or written, the
229
+ * run goes on without one — a record must never change what it records.
230
+ */
231
+ export function openJournal(projectDir, keep, about) {
232
+ if (keep <= 0)
233
+ return noJournal();
234
+ const started = new Date();
235
+ const run = `${started.toISOString().replace(/[:.]/g, "-")}-${randomBytes(3).toString("hex")}`;
236
+ let fd;
237
+ let path;
238
+ try {
239
+ mkdirSync(guardPath(projectDir, JOURNAL_DIR), { recursive: true });
240
+ const dir = journalDirOf(projectDir);
241
+ makeRoom(dir, keep);
242
+ path = journalIn(dir, run);
243
+ // Readable by its owner only: it holds what the program read, wrote and was told.
244
+ fd = openSync(path, "a", 0o600);
245
+ beingWritten.add(path);
246
+ }
247
+ catch (err) {
248
+ console.warn(`[trama] this run is not being recorded: ${err instanceof Error ? err.message : err}`);
249
+ return noJournal();
250
+ }
251
+ const t0 = performance.now();
252
+ let written = 0;
253
+ let full = false;
254
+ const close = () => {
255
+ if (fd === null)
256
+ return;
257
+ try {
258
+ closeSync(fd);
259
+ }
260
+ catch { /* nothing more to do with it */ }
261
+ fd = null;
262
+ beingWritten.delete(path);
263
+ };
264
+ /** Write one record. `compose` builds it, and may fail: what cannot be written down is noted as such. */
265
+ const write = (kind, compose) => {
266
+ if (fd === null)
267
+ return;
268
+ const at = Math.round(performance.now() - t0);
269
+ let line;
270
+ try {
271
+ const room = { left: MAX_RECORD, cuts: [] };
272
+ const record = clip({ at, kind, ...compose() }, room);
273
+ if (room.cuts.length > 0)
274
+ record.cuts = room.cuts;
275
+ line = JSON.stringify(record);
276
+ }
277
+ catch (err) {
278
+ line = JSON.stringify({ at, kind, unrecordable: err instanceof Error ? err.message : String(err) });
279
+ }
280
+ try {
281
+ appendFileSync(fd, line + "\n");
282
+ written += line.length + 1;
283
+ }
284
+ catch (err) {
285
+ console.warn(`[trama] the journal could not be written, and stops here: ${err instanceof Error ? err.message : err}`);
286
+ close();
287
+ }
288
+ };
289
+ /** Past its size, a journal keeps the shape of the run — attempts, exits, the end — but no more of its calls. */
290
+ const roomForCalls = () => {
291
+ if (!full && written > MAX_JOURNAL) {
292
+ full = true;
293
+ write("full", () => ({ bytes: written, note: "calls after this point are not recorded" }));
294
+ }
295
+ return !full;
296
+ };
297
+ let seq = 0;
298
+ write("run", () => ({ v: JOURNAL_VERSION, run, pid: process.pid, started: started.toISOString(), project: projectDir, ...about }));
299
+ return {
300
+ run,
301
+ path,
302
+ note: (kind, fields = {}) => write(kind, () => fields),
303
+ call(endpoint, request) {
304
+ const position = ++seq;
305
+ if (!roomForCalls())
306
+ return { seq: position, end() { } };
307
+ const arrived = performance.now();
308
+ write("call", () => ({ seq: position, endpoint, request: recordable(endpoint, request) }));
309
+ return {
310
+ seq: position,
311
+ end(outcome) {
312
+ write("result", () => ({
313
+ seq: position,
314
+ ms: Math.round(performance.now() - arrived),
315
+ ...(outcome.ok ? { ok: true, result: recordable(endpoint, outcome.result) } : outcome),
316
+ }));
317
+ },
318
+ };
319
+ },
320
+ close,
321
+ };
322
+ }
@@ -1,7 +1,7 @@
1
- import type { AgentBackend, AgentCall } from "./agent-backend.js";
1
+ import { type AgentBackend, type AgentCall } from "./agent-backend.js";
2
2
  import type { ModelConfig } from "./runner-types.js";
3
3
  /** The pi version this runtime is built against (recorded in each project's meta.json). */
4
- export { VERSION as PI_VERSION } from "@earendil-works/pi-coding-agent";
4
+ export declare const piVersion: () => Promise<string>;
5
5
  /** The pi coding agent, run in-process: a fresh in-memory session for every call. */
6
6
  export declare class PiAdapter implements AgentBackend {
7
7
  private config;
@@ -1,6 +1,12 @@
1
- import { createAgentSession, SessionManager, DefaultResourceLoader, ModelRuntime, getAgentDir, } from "@earendil-works/pi-coding-agent";
1
+ import { rejectOnAbort } from "./agent-backend.js";
2
+ /**
3
+ * pi is loaded when it is first needed, not when this file is: it is most of
4
+ * what the runtime weighs, and listing projects, reading logs, or running a
5
+ * program that never calls the agent does not need it.
6
+ */
7
+ const loadPi = () => import("@earendil-works/pi-coding-agent");
2
8
  /** The pi version this runtime is built against (recorded in each project's meta.json). */
3
- export { VERSION as PI_VERSION } from "@earendil-works/pi-coding-agent";
9
+ export const piVersion = async () => (await loadPi()).VERSION;
4
10
  /** provider/model pairs already warned about, so a loop of agent calls warns once per process. */
5
11
  const warnedUnknownModels = new Set();
6
12
  /** The pi coding agent, run in-process: a fresh in-memory session for every call. */
@@ -12,6 +18,9 @@ export class PiAdapter {
12
18
  async createSession(cwd, systemPrompt, signal) {
13
19
  if (signal?.aborted)
14
20
  throw new Error("Aborted");
21
+ // Each step below is given up on the moment the call is cancelled.
22
+ const raceAbort = (step) => rejectOnAbort(step, signal);
23
+ const { createAgentSession, SessionManager, DefaultResourceLoader, ModelRuntime, getAgentDir } = await raceAbort(loadPi());
15
24
  const agentDir = getAgentDir();
16
25
  const resourceLoader = new DefaultResourceLoader({
17
26
  cwd,
@@ -20,26 +29,6 @@ export class PiAdapter {
20
29
  noSkills: true,
21
30
  ...(systemPrompt && { appendSystemPrompt: [systemPrompt] }),
22
31
  });
23
- // Race an async step against the abort signal.
24
- // Returns the result on success, or rejects with "Aborted" on abort.
25
- const raceAbort = (promise) => {
26
- if (!signal)
27
- return promise;
28
- let onAbort = null;
29
- const cleanup = () => {
30
- if (onAbort) {
31
- signal.removeEventListener("abort", onAbort);
32
- onAbort = null;
33
- }
34
- };
35
- return Promise.race([
36
- promise.finally(cleanup),
37
- new Promise((_resolve, reject) => {
38
- onAbort = () => reject(new Error("Aborted"));
39
- signal.addEventListener("abort", onAbort, { once: true });
40
- }),
41
- ]);
42
- };
43
32
  await raceAbort(resourceLoader.reload());
44
33
  if (signal?.aborted)
45
34
  throw new Error("Aborted");
@@ -23,9 +23,20 @@ export interface RunOptions {
23
23
  args?: Record<string, unknown>;
24
24
  /** Shared workspace directory. When set, workspace.* API is enabled for the program. */
25
25
  workspaceDir?: string;
26
+ /** A name for this run — a participant's, say. Its output is shown under it. */
27
+ label?: string;
28
+ /**
29
+ * Stops the run: its program is stopped, no repair is attempted, and the
30
+ * run ends as failed. A fix that was being tried leaves no trace.
31
+ */
32
+ signal?: AbortSignal;
26
33
  }
34
+ /** A run as one program asks its runner for it: everything in RunOptions that can cross the bridge. */
35
+ export type RunRequest = Omit<RunOptions, "signal">;
27
36
  export interface TramaConfig extends ModelConfig {
28
37
  maxRepairAttempts: number;
29
38
  defaultTimeout: number;
30
39
  defaultMaxIterations: number;
40
+ /** How many runs of a project keep their journal. 0 records nothing. */
41
+ journalRuns: number;
31
42
  }
package/dist/runner.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { RunOptions, TramaConfig, ProgramResult } from "./runner-types.js";
2
- import type { AgentBackend } from "./agent-backend.js";
2
+ import { type AgentBackend } from "./agent-backend.js";
3
3
  /**
4
4
  * Everything a project directory needs around program.ts before it can run:
5
5
  * history/ and logs/, an ESM package.json, .gitignore entries, and links to the
@@ -57,18 +57,22 @@ export declare function withTempDir<T>(prefix: string, fn: (dir: string) => Prom
57
57
  /** The instructions a request for a fix is made under. (Exported so the tests' stand-in LLM can tell one from any other call.) */
58
58
  export declare const REPAIR_SYSTEM_PROMPT = "You are a TypeScript repair tool.";
59
59
  /**
60
- * Validate a candidate program.ts for a project without touching the project:
61
- * run it (with repair) in a throwaway copy. Returns the program that worked —
60
+ * Validate a candidate program.ts for a project without touching what the
61
+ * project holds: run it (with repair) in a throwaway copy. The one thing left
62
+ * in the project is the journal of the validation. Returns the program that worked —
62
63
  * the candidate itself, or a repaired version of it, with the failure that was
63
64
  * repaired. Throws if it cannot be made to run.
64
65
  *
65
66
  * Only the project's own files are shielded. What the program does beyond
66
- * them — network calls, shell commands, other projects it runs — is real.
67
+ * them — network calls, shell commands, agent calls — is real. A run it asks
68
+ * its runner for is not started: the validation ends where it asks for the
69
+ * first.
67
70
  */
68
71
  export declare function validateProgram(projectDir: string, backend: AgentBackend, candidate: string, options: {
69
72
  timeout: number;
70
73
  maxRepairAttempts: number;
71
74
  maxIterations: number;
75
+ journalRuns?: number;
72
76
  }): Promise<{
73
77
  source: string;
74
78
  repairedError?: string;
@@ -82,5 +86,25 @@ export declare function installValidatedProgram(projectDir: string, validated: {
82
86
  source: string;
83
87
  repairedError?: string;
84
88
  }, reason: "create" | "update", prompt: string): void;
85
- export declare function runProgram(options: RunOptions): Promise<ProgramResult>;
89
+ /** What a run is told when a program asked for it, rather than a person or a host. */
90
+ interface AskedFor {
91
+ /** How many runs deep it is: one more than the run that asked. */
92
+ depth: number;
93
+ /** The call that asked for it: which run's, and which of that run's calls. */
94
+ parent: {
95
+ run: string;
96
+ journal: string;
97
+ seq: number;
98
+ };
99
+ /** Called once this run has a journal of its own. */
100
+ started(run: string, journal: string): void;
101
+ }
102
+ /**
103
+ * Run a project, in this process: this is what a runner does.
104
+ *
105
+ * `askedFor` is set when a program asked for the run (see the "/run/program"
106
+ * call). One runner carries the whole tree of runs, so it is also where the
107
+ * tree is kept from growing without bound.
108
+ */
109
+ export declare function runProgram(options: RunOptions, askedFor?: AskedFor): Promise<ProgramResult>;
86
110
  export {};