@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.
Files changed (47) hide show
  1. package/README.md +4 -3
  2. package/dist/abort.d.ts +12 -0
  3. package/dist/abort.js +31 -0
  4. package/dist/agent-backend.d.ts +0 -6
  5. package/dist/agent-backend.js +1 -21
  6. package/dist/agent.d.ts +16 -1
  7. package/dist/agent.js +108 -35
  8. package/dist/bridge-client.js +44 -14
  9. package/dist/child-process.d.ts +1 -20
  10. package/dist/child-process.js +11 -86
  11. package/dist/client.d.ts +2 -1
  12. package/dist/client.js +5 -15
  13. package/dist/context.d.ts +36 -7
  14. package/dist/context.js +83 -92
  15. package/dist/errors.d.ts +2 -0
  16. package/dist/errors.js +2 -0
  17. package/dist/index.d.ts +12 -1
  18. package/dist/index.js +93 -53
  19. package/dist/ipc-server.d.ts +12 -6
  20. package/dist/ipc-server.js +124 -136
  21. package/dist/journal-view.d.ts +9 -0
  22. package/dist/journal-view.js +139 -0
  23. package/dist/journal.d.ts +70 -0
  24. package/dist/journal.js +454 -0
  25. package/dist/meta.d.ts +18 -0
  26. package/dist/meta.js +29 -0
  27. package/dist/path-guard.d.ts +128 -19
  28. package/dist/path-guard.js +384 -68
  29. package/dist/pi-adapter.d.ts +7 -6
  30. package/dist/pi-adapter.js +15 -26
  31. package/dist/replace-file.d.ts +31 -0
  32. package/dist/replace-file.js +75 -0
  33. package/dist/runner-types.d.ts +2 -0
  34. package/dist/runner.d.ts +37 -37
  35. package/dist/runner.js +565 -239
  36. package/dist/serializable.d.ts +10 -4
  37. package/dist/serializable.js +56 -31
  38. package/dist/{watchdog.d.ts → stopping.d.ts} +15 -0
  39. package/dist/stopping.js +268 -0
  40. package/dist/tools.js +44 -13
  41. package/dist/tree.d.ts +234 -0
  42. package/dist/tree.js +1409 -0
  43. package/dist/types.d.ts +6 -3
  44. package/dist/workspace.d.ts +7 -0
  45. package/dist/workspace.js +93 -104
  46. package/package.json +2 -2
  47. package/dist/watchdog.js +0 -167
@@ -0,0 +1,454 @@
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 { closeSync, constants, fstatSync, openSync, readSync, readdirSync, renameSync, rmSync, writeSync } from "fs";
16
+ import { createHash, randomBytes } from "crypto";
17
+ import { join } from "path";
18
+ import { guardPath, identityIn, identityOf, makeDirsIn, realRootOf } from "./path-guard.js";
19
+ import { stagedNameFor } from "./replace-file.js";
20
+ import { isJsonObject } from "./serializable.js";
21
+ import { messageOf } from "./errors.js";
22
+ /** The format of the records. Bump it when a reader of older journals would be misled. */
23
+ export const JOURNAL_VERSION = 1;
24
+ /** Where a project keeps its journals, relative to the project — under logs/, which trama keeps out of version control. */
25
+ export const JOURNAL_DIR = join("logs", "journal");
26
+ /** The shape of a run's id: ISO timestamp (with dashes) followed by 6 hex digits. */
27
+ const RUN_ID = /^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-[0-9a-f]{6}$/;
28
+ /** A record's line is never longer than this: a megabyte of characters, each written as an escape of six at most, and its cuts. */
29
+ const LONGEST_LINE = 8 * 1024 * 1024;
30
+ const SAFE_READ_FLAGS = constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW;
31
+ /**
32
+ * A project's journal directory, by its one real name however the project was
33
+ * referred to.
34
+ */
35
+ export function journalDirOf(projectDir) {
36
+ // Where the path leads, by the guard's own reckoning — the same before the
37
+ // directory exists as after, and never a place the guard did not check.
38
+ return guardPath(projectDir, JOURNAL_DIR);
39
+ }
40
+ /** The journal of a run, in a journal directory. */
41
+ export const journalIn = (dir, run) => join(dir, `${run}.jsonl`);
42
+ /** How a journal begins: the record of its run, which names the run and the process that writes it. */
43
+ const FIRST_RECORD = /^\{"at":\d+,"kind":"run","v":\d+,"run":"([^"]+)","pid":(\d+)[,}]/;
44
+ /**
45
+ * Look into what may be a journal — the file of `run`, if one is named —
46
+ * without waiting on a pipe or following a link there: `look` is given what
47
+ * to read it with. Undefined if it is no journal: not a file, or one that
48
+ * does not begin as a journal does. (Any `.jsonl` file can be put where the
49
+ * journals are; only what trama wrote is listed, read, or removed in its turn.)
50
+ * Throws where it cannot be opened at all, which is the caller's to judge.
51
+ */
52
+ function inJournal(path, run, look) {
53
+ const fd = openSync(path, SAFE_READ_FLAGS);
54
+ try {
55
+ const file = fd, stat = fstatSync(fd), size = stat.size;
56
+ if (!stat.isFile())
57
+ return undefined;
58
+ const read = (from, length) => {
59
+ const buffer = Buffer.allocUnsafe(length);
60
+ return buffer.toString("utf-8", 0, readSync(file, buffer, 0, length, from));
61
+ };
62
+ // The start of the first record is always written the same way, however long the record is.
63
+ const first = FIRST_RECORD.exec(read(0, Math.min(size, 512)));
64
+ if (!first || !RUN_ID.test(first[1]) || (run !== undefined && first[1] !== run))
65
+ return undefined;
66
+ const pid = Number(first[2]);
67
+ /** The last line, if it begins within the last `length` bytes. */
68
+ const lastLine = (length) => {
69
+ const from = Math.max(0, size - length);
70
+ const text = read(from, size - from).trimEnd();
71
+ const line = text.lastIndexOf("\n");
72
+ return line === -1 && from > 0 ? undefined : text.slice(line + 1);
73
+ };
74
+ return look({
75
+ writer: Number.isSafeInteger(pid) && pid > 0 ? pid : null,
76
+ // A record's line is rarely longer than a page, and never than LONGEST_LINE.
77
+ ended() {
78
+ try {
79
+ const last = JSON.parse(lastLine(4096) ?? lastLine(LONGEST_LINE) ?? "");
80
+ return isJsonObject(last) && last.kind === "end";
81
+ }
82
+ catch {
83
+ return false; // cut off in the middle of a record
84
+ }
85
+ },
86
+ });
87
+ }
88
+ catch {
89
+ return undefined;
90
+ }
91
+ finally {
92
+ try {
93
+ closeSync(fd);
94
+ }
95
+ catch { /* nothing more to do with it */ }
96
+ }
97
+ }
98
+ /**
99
+ * Whether the file `name` of a journal directory is a journal: named for a
100
+ * run, and beginning as that run's journal does. One that is named for a run
101
+ * and may not be read — another user's run of the project wrote it — is taken
102
+ * at its name: it can be listed and removed in its turn, and cannot be copied.
103
+ */
104
+ function isJournal(dir, name) {
105
+ const run = name.endsWith(".jsonl") ? name.slice(0, -".jsonl".length) : "";
106
+ if (!RUN_ID.test(run))
107
+ return false;
108
+ try {
109
+ return inJournal(join(dir, name), run, () => true) === true;
110
+ }
111
+ catch (err) {
112
+ const code = err.code;
113
+ return code === "EACCES" || code === "EPERM";
114
+ }
115
+ }
116
+ /** The ids of the runs that have a journal in `dir`, oldest first. (A run's id starts with when it started.) */
117
+ export function runsIn(dir) {
118
+ let entries;
119
+ try {
120
+ entries = readdirSync(dir, { withFileTypes: true });
121
+ }
122
+ catch (err) {
123
+ if (err.code === "ENOENT")
124
+ return []; // no run has been recorded
125
+ throw err;
126
+ }
127
+ // A journal is a file. Anything else that bears a journal's name — a directory, a link, a pipe,
128
+ // which would hold up whoever opened it — is not one; nor is a file somebody else put there.
129
+ return entries.filter((entry) => entry.isFile() && isJournal(dir, entry.name))
130
+ .map((entry) => entry.name.slice(0, -".jsonl".length)).sort();
131
+ }
132
+ /**
133
+ * What a copy of `projectDir` is to leave out so as not to carry the project's
134
+ * journals, each by what it is (its `identityOf`): the directory they are in,
135
+ * if nothing else is in it or it may not be read or searched — and otherwise every
136
+ * journal in it. Somebody's own file among the journals is the project's
137
+ * like any other, and is copied.
138
+ */
139
+ export function journalEntriesOf(projectDir) {
140
+ const only = (...ids) => new Set(ids.filter((id) => id !== undefined));
141
+ let dir;
142
+ /** The directory itself — which is not left out where it is the project (by links that lead back to it). */
143
+ const whole = () => {
144
+ const id = dir === undefined ? undefined : identityOf(dir);
145
+ return id === identityOf(realRootOf(projectDir)) ? undefined : id;
146
+ };
147
+ try {
148
+ const journalDir = dir = journalDirOf(projectDir);
149
+ const entries = readdirSync(journalDir, { withFileTypes: true });
150
+ const journals = entries.filter((entry) => entry.isFile() && isJournal(journalDir, entry.name));
151
+ const all = journals.length === entries.length ? whole() : undefined;
152
+ return all !== undefined ? only(all) : only(...journals.map((entry) => identityOf(join(journalDir, entry.name))));
153
+ }
154
+ catch (err) {
155
+ // Where the journals would be, the project has none: the way leads out of it, or to nothing, or to a file.
156
+ // And a directory that may not be read, or looked into, is left out whole: no part of it can be told from another.
157
+ const code = err.code;
158
+ return code === "EACCES" || code === "EPERM" ? only(whole()) : only();
159
+ }
160
+ }
161
+ /** The longest text kept whole. */
162
+ const MAX_TEXT = 256 * 1024;
163
+ /** About how much one record may hold. It is spent in the order the record's fields come in. */
164
+ const MAX_RECORD = 1024 * 1024;
165
+ /** How far into nested values a record goes. */
166
+ const MAX_DEPTH = 12;
167
+ /** The longest name a field is recorded under. */
168
+ const MAX_NAME = 1024;
169
+ /** How large a journal grows before it stops taking down calls. */
170
+ const MAX_JOURNAL = 64 * 1024 * 1024;
171
+ /**
172
+ * A value as it is written down: whole if there is room, and otherwise cut
173
+ * short, with a note of it in `room.cuts`. Everything written is counted
174
+ * against `room.left` — the notes too — so a record holds about that many
175
+ * characters whatever shape its contents have. (Its line can be longer: JSON
176
+ * writes some characters as escapes of up to six.)
177
+ */
178
+ function clip(value, room, path = [], expanded = false) {
179
+ const cut = (about) => {
180
+ room.cuts.push({ path, ...about });
181
+ room.left -= 128 + path.reduce((size, step) => size + String(step).length + 3, 0);
182
+ };
183
+ if (typeof value === "bigint")
184
+ value = value.toString();
185
+ if (typeof value === "string") {
186
+ const keep = Math.max(0, Math.min(MAX_TEXT, room.left));
187
+ room.left -= Math.min(value.length, keep) + 3;
188
+ if (value.length <= keep)
189
+ return value;
190
+ cut({ cut: "text", length: value.length, sha256: createHash("sha256").update(value).digest("hex") });
191
+ return value.slice(0, keep);
192
+ }
193
+ if (value === null || typeof value !== "object") {
194
+ room.left -= typeof value === "number" ? String(value).length + 1 : 8;
195
+ return value;
196
+ }
197
+ // Binary data is recorded by its size: as text it would be a list of numbers.
198
+ if (ArrayBuffer.isView(value)) {
199
+ cut({ cut: "bytes", length: value.byteLength });
200
+ return null;
201
+ }
202
+ // Anything that knows how it wants to be written (a Date) is asked — once per slot, like JSON.stringify.
203
+ if (!expanded && typeof value.toJSON === "function") {
204
+ return clip(value.toJSON(), room, path, true);
205
+ }
206
+ if (path.length >= MAX_DEPTH) {
207
+ cut({ cut: "depth" });
208
+ return null;
209
+ }
210
+ room.left -= 3; // an empty list or object takes room too
211
+ if (Array.isArray(value)) {
212
+ const items = [];
213
+ for (const item of value) {
214
+ if (room.left <= 0) {
215
+ cut({ cut: "list", length: value.length });
216
+ break;
217
+ }
218
+ items.push(clip(item, room, [...path, items.length]));
219
+ }
220
+ return items;
221
+ }
222
+ const fields = {};
223
+ let fieldsLeftOut = false;
224
+ for (const key in value) {
225
+ if (!Object.hasOwn(value, key))
226
+ continue;
227
+ // What cannot be written down is no field, as it is none to JSON — and so nothing the record
228
+ // is made of says how it wants to be written: each thing was asked that once, above.
229
+ const field = value[key];
230
+ if (typeof field === "function")
231
+ continue;
232
+ // A field goes in with its name, or not at all. A name that is too long
233
+ // is passed over — it would be repeated in the path of everything cut
234
+ // beneath it — and one there is no room for ends the object.
235
+ const noRoom = room.left <= key.length;
236
+ if (noRoom || key.length > MAX_NAME) {
237
+ if (!fieldsLeftOut)
238
+ cut({ cut: "object" });
239
+ fieldsLeftOut = true;
240
+ if (noRoom)
241
+ break;
242
+ continue;
243
+ }
244
+ room.left -= key.length + 3;
245
+ fields[key] = clip(field, room, [...path, key]);
246
+ }
247
+ return fields;
248
+ }
249
+ /**
250
+ * Header names whose values are credentials more often than not. Wide on
251
+ * purpose: a header wrongly held back costs little, one wrongly kept is a leak.
252
+ * (Rate-limit headers count tokens, they do not carry one.)
253
+ */
254
+ const SECRET_HEADER = /auth|cookie|secret|passw|credential|session|jwt|csrf|xsrf|signature|token|key/i;
255
+ const isSecretHeader = (name) => SECRET_HEADER.test(name) && !/rate-?limit/i.test(name);
256
+ /** A copy of a set of HTTP headers — an object, or a list of pairs — with the secret-looking values left out. */
257
+ function redactHeaders(headers) {
258
+ if (Array.isArray(headers)) {
259
+ return headers.map(pair => Array.isArray(pair) && typeof pair[0] === "string" && isSecretHeader(pair[0]) ? [pair[0], "[redacted]"] : pair);
260
+ }
261
+ if (!isJsonObject(headers))
262
+ return headers;
263
+ return Object.fromEntries(Object.entries(headers).map(([name, value]) => [name, isSecretHeader(name) ? "[redacted]" : value]));
264
+ }
265
+ /**
266
+ * What is written down of a call's request or result. The one thing known to
267
+ * carry secrets by design — the headers of a web request — is redacted. A
268
+ * secret a program puts anywhere else (a URL, a prompt, a command) is recorded
269
+ * like the rest: the journal cannot tell.
270
+ */
271
+ function recordable(endpoint, value) {
272
+ if (endpoint === "/tools/fetch" && isJsonObject(value) && "headers" in value) {
273
+ return { ...value, headers: redactHeaders(value.headers) };
274
+ }
275
+ return value;
276
+ }
277
+ /** A journal that records nothing. Calls are still numbered, so the rest of the runner need not care. */
278
+ function noJournal() {
279
+ let seq = 0;
280
+ return { run: "", path: "", note() { }, call: () => ({ seq: ++seq, end() { } }), close() { } };
281
+ }
282
+ /**
283
+ * Journals this process is writing, each by what it is (see identityOf): a
284
+ * project may be named in more ways than one, and its journals with it. They
285
+ * are never the ones to make room.
286
+ */
287
+ const beingWritten = new Set();
288
+ /**
289
+ * Whether a journal is still being written: by this process, or by another
290
+ * runner that is still there and has not yet written its ending. (A journal
291
+ * this process started and has closed is finished, though the process lives
292
+ * on. And a process that may not be signalled is not the writer of a journal
293
+ * that can be read: its number has been given to somebody else's since.)
294
+ */
295
+ export function stillBeingWritten(path) {
296
+ const journal = identityOf(path);
297
+ if (journal !== undefined && beingWritten.has(journal))
298
+ return true;
299
+ const isAlive = (pid) => { try {
300
+ process.kill(pid, 0);
301
+ return true;
302
+ }
303
+ catch {
304
+ return false;
305
+ } };
306
+ try {
307
+ return inJournal(path, undefined, ({ writer, ended }) => writer !== null && writer !== process.pid && isAlive(writer) && !ended()) === true;
308
+ }
309
+ catch {
310
+ return false; // (nothing to be read there, so nothing that says who writes it)
311
+ }
312
+ }
313
+ /**
314
+ * Remove the oldest journals of a project so that, with one more, at most
315
+ * `keep` remain — but never one that is still being written, by this process
316
+ * or by another runner: a run of the same project may be going on right now
317
+ * (two participants of a session, or a program that runs its own project).
318
+ * Such journals stay, and the project holds more than `keep` for a while.
319
+ */
320
+ function makeRoom(dir, keep) {
321
+ const runs = runsIn(dir);
322
+ for (const run of runs.slice(0, Math.max(0, runs.length - (keep - 1)))) {
323
+ const path = journalIn(dir, run);
324
+ if (!stillBeingWritten(path))
325
+ rmSync(path, { force: true });
326
+ }
327
+ }
328
+ /**
329
+ * Start the journal of a run of `projectDir`, keeping the journals of at most
330
+ * `keep` runs of it (0: record nothing). `about` is what is known at the start
331
+ * and goes into the first record.
332
+ *
333
+ * The journal belongs to the project, not to wherever the program happens to
334
+ * be executed: a fix tried on a copy, or a candidate validated in one, is
335
+ * still recorded here, where it will be looked for.
336
+ *
337
+ * Recording is best-effort. If the journal cannot be opened or written, the
338
+ * run goes on without one — a record must never change what it records.
339
+ */
340
+ export function openJournal(projectDir, keep, about) {
341
+ if (keep <= 0)
342
+ return noJournal();
343
+ const started = new Date();
344
+ const run = `${started.toISOString().replace(/[:.]/g, "-")}-${randomBytes(3).toString("hex")}`;
345
+ const t0 = performance.now();
346
+ let fd = null;
347
+ let path = "";
348
+ let staged = "";
349
+ let identity;
350
+ let written = 0;
351
+ let full = false;
352
+ const formatLine = (at, kind, compose) => {
353
+ try {
354
+ const room = { left: MAX_RECORD, cuts: [] };
355
+ const record = clip({ at, kind, ...compose() }, room);
356
+ if (room.cuts.length > 0)
357
+ record.cuts = room.cuts;
358
+ return JSON.stringify(record);
359
+ }
360
+ catch (err) {
361
+ return JSON.stringify({ at, kind, unrecordable: messageOf(err) });
362
+ }
363
+ };
364
+ try {
365
+ const dir = journalDirOf(projectDir);
366
+ // (In the project, which is there: a journal is not what makes a directory where a project was.)
367
+ makeDirsIn(projectDir, dir);
368
+ makeRoom(dir, keep);
369
+ path = journalIn(dir, run);
370
+ staged = stagedNameFor(path);
371
+ const firstLine = formatLine(0, "run", () => ({
372
+ v: JOURNAL_VERSION, run, pid: process.pid, started: started.toISOString(), project: projectDir, ...about,
373
+ }));
374
+ // Readable by its owner only, and whole from the moment its name appears in the directory.
375
+ fd = openSync(staged, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_APPEND, 0o600);
376
+ written = writeSync(fd, firstLine + "\n");
377
+ identity = identityIn(fstatSync(fd, { bigint: true }));
378
+ beingWritten.add(identity);
379
+ renameSync(staged, path);
380
+ staged = "";
381
+ }
382
+ catch (err) {
383
+ if (fd !== null)
384
+ try {
385
+ closeSync(fd);
386
+ }
387
+ catch { /* ignore */ }
388
+ if (identity !== undefined)
389
+ beingWritten.delete(identity);
390
+ if (staged)
391
+ try {
392
+ rmSync(staged, { force: true });
393
+ }
394
+ catch { /* ignore */ }
395
+ console.warn(`[trama] this run is not being recorded: ${messageOf(err)}`);
396
+ return noJournal();
397
+ }
398
+ const close = () => {
399
+ if (fd === null)
400
+ return;
401
+ try {
402
+ closeSync(fd);
403
+ }
404
+ catch { /* nothing more to do with it */ }
405
+ fd = null;
406
+ if (identity !== undefined)
407
+ beingWritten.delete(identity);
408
+ };
409
+ /** Write one record. `compose` builds it, and may fail: what cannot be written down is noted as such. */
410
+ const write = (kind, compose) => {
411
+ if (fd === null)
412
+ return;
413
+ const line = formatLine(Math.round(performance.now() - t0), kind, compose);
414
+ try {
415
+ written += writeSync(fd, line + "\n");
416
+ }
417
+ catch (err) {
418
+ console.warn(`[trama] the journal could not be written, and stops here: ${messageOf(err)}`);
419
+ close();
420
+ }
421
+ };
422
+ /** Past its size, a journal keeps the shape of the run — attempts, exits, the end — but no more of its calls. */
423
+ const roomForCalls = () => {
424
+ if (!full && written > MAX_JOURNAL) {
425
+ full = true;
426
+ write("full", () => ({ bytes: written, note: "calls after this point are not recorded" }));
427
+ }
428
+ return !full;
429
+ };
430
+ let seq = 0;
431
+ return {
432
+ run,
433
+ path,
434
+ note: (kind, fields = {}) => write(kind, () => fields),
435
+ call(endpoint, request) {
436
+ const position = ++seq;
437
+ if (!roomForCalls())
438
+ return { seq: position, end() { } };
439
+ const arrived = performance.now();
440
+ write("call", () => ({ seq: position, endpoint, request: recordable(endpoint, request) }));
441
+ return {
442
+ seq: position,
443
+ end(outcome) {
444
+ write("result", () => ({
445
+ seq: position,
446
+ ms: Math.round(performance.now() - arrived),
447
+ ...(outcome.ok ? { ok: true, result: recordable(endpoint, outcome.result) } : outcome),
448
+ }));
449
+ },
450
+ };
451
+ },
452
+ close,
453
+ };
454
+ }
package/dist/meta.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ export interface ProjectMeta {
2
+ /** What the program is given as ctx.input. */
3
+ input: {
4
+ prompt?: string;
5
+ args?: Record<string, unknown>;
6
+ } & Record<string, unknown>;
7
+ createdAt?: string;
8
+ piVersion?: string;
9
+ /** The model and provider the project was created with; they take precedence over the global config. */
10
+ model?: string;
11
+ provider?: string;
12
+ }
13
+ /**
14
+ * Read a project's meta.json. A file that is not what a run needs — not JSON,
15
+ * or without an `input` object — is refused here, by name, rather than left to
16
+ * fail wherever its contents are first used.
17
+ */
18
+ export declare function readProjectMeta(projectDir: string): ProjectMeta;
package/dist/meta.js ADDED
@@ -0,0 +1,29 @@
1
+ // meta.json: what a project was created with. Written once, by `create` (or
2
+ // by hand, for a hand-written project), and read by every run.
3
+ import { readFileSync } from "fs";
4
+ import { guardPath } from "./path-guard.js";
5
+ import { describeJson, isJsonObject } from "./serializable.js";
6
+ import { messageOf } from "./errors.js";
7
+ /**
8
+ * Read a project's meta.json. A file that is not what a run needs — not JSON,
9
+ * or without an `input` object — is refused here, by name, rather than left to
10
+ * fail wherever its contents are first used.
11
+ */
12
+ export function readProjectMeta(projectDir) {
13
+ const raw = readFileSync(guardPath(projectDir, "meta.json"), "utf-8");
14
+ const fail = (reason) => new Error(`Malformed meta.json in ${projectDir} — ${reason}\n` +
15
+ `It needs to be a JSON object with an "input" object, like {"input": {"prompt": "...", "args": {}}}.`);
16
+ let parsed;
17
+ try {
18
+ parsed = JSON.parse(raw);
19
+ }
20
+ catch (err) {
21
+ throw fail(`Parse error: ${messageOf(err)}`);
22
+ }
23
+ if (!isJsonObject(parsed)) {
24
+ throw fail(`expected a JSON object but got ${describeJson(parsed)}.`);
25
+ }
26
+ if (!isJsonObject(parsed.input))
27
+ throw fail(`"input" is ${parsed.input === undefined ? "missing" : "not an object"}.`);
28
+ return parsed;
29
+ }
@@ -1,27 +1,136 @@
1
+ import { type BigIntStats } from "fs";
1
2
  /**
2
- * Keep file access inside a bounded root directory (a project directory or a
3
- * session workspace) — rejecting escapes via ".." segments or symlinks.
4
- *
5
- * Not a security sandbox — just a footgun guard against malicious shared
6
- * projects where files like state.json or .gitignore are symlinks pointing
7
- * outside the project directory.
3
+ * A byte buffer as UTF-8 text — undefined if its bytes are not valid UTF-8.
4
+ * Leading BOM bytes are preserved as text rather than stripped.
5
+ */
6
+ export declare function utf8Text(raw: Buffer): string | undefined;
7
+ /**
8
+ * What a link says, as text — undefined if it says nothing a path can be made
9
+ * of: a name that is not valid UTF-8, or nothing at all (macOS lets a link to
10
+ * nothing be made, and then refuses every use of it).
8
11
  */
9
- /** True if `path` is `root` itself or lies underneath it. Both must already be normalized. */
10
- export declare function isInside(path: string, root: string): boolean;
12
+ export declare function linkText(link: string): string | undefined;
11
13
  /**
12
- * Resolve `relativePath` against `rootDir` and verify the logical path
13
- * stays within the root. Returns the resolved absolute path.
14
- * Catches ".." traversal only — use guardPath to also catch symlink escapes.
14
+ * The real (symlink-resolved) location of a root directory, whether or not it
15
+ * exists yet. A root is named by whoever runs the program, not by the
16
+ * program, and is read as the rest of Node reads a directory it is given.
15
17
  */
16
- export declare function resolveBounded(rootDir: string, relativePath: string): string;
17
- /** The real (symlink-resolved) location of a root directory, or its normalized path if it doesn't exist yet. */
18
18
  export declare function realRootOf(rootDir: string): string;
19
+ export declare const identityIn: (stat: BigIntStats) => string;
20
+ /**
21
+ * What tells one file or directory from every other — undefined if nothing is
22
+ * there to be told apart. Two paths with one identity are one place, however
23
+ * each is spelled; a link is itself, not what it points at.
24
+ *
25
+ * This is how the runtime asks whether two paths are the same. Their text
26
+ * cannot say: a file system that takes "Data" and "data" for one name has
27
+ * many names for every directory.
28
+ *
29
+ * Undefined says that nothing is there, and only that. What is there and may
30
+ * not be looked at is not nothing: it throws.
31
+ */
32
+ export declare function identityOf(path: string): string | undefined;
33
+ /** What the words of a link come to, read by one who means to keep a copy of the root they are in. */
34
+ export interface Lead {
35
+ /** The place they name. A link of the root that they end at is the place: what it names in turn is its own affair. */
36
+ to: string;
37
+ /**
38
+ * Whether the way there is in the root at one point and out of it at
39
+ * another: it steps out over the root's top, or into it from outside. If it
40
+ * does neither, the same words name the same place in any copy of the
41
+ * root, wherever the copy is.
42
+ */
43
+ strays: boolean;
44
+ /**
45
+ * What the words go on to say once they have come to the root from outside
46
+ * it (see `sinceRoot`) — provided they have not stepped out of it over its
47
+ * top again since. That much is said of the root, and says the same of a
48
+ * copy of it, wherever its links lead. Undefined if they never come to the
49
+ * root so, or step out of it afterwards: such a way, if it strays, ends
50
+ * outside the root.
51
+ */
52
+ home: string | undefined;
53
+ }
54
+ /**
55
+ * A reader of the links in `root` (named without links), for one who means
56
+ * to keep a copy of the root.
57
+ *
58
+ * It reads as a copy of the root would have to be read. A link of the root
59
+ * that a way passes through is not followed step by step but taken for the
60
+ * place it names: a copy has that link too, saying whatever it must to name
61
+ * the same place there, and how it says so is no part of the way. A link
62
+ * outside the root is nobody's copy, and is followed like any other step —
63
+ * to the end, also where the words end at it: what matters of it is where it
64
+ * leads.
65
+ *
66
+ * Whether a place is in the root is asked of the place (see underRoot), not
67
+ * read off its name: a way that has left the root may come back to it by any
68
+ * of the names the file system has for it.
69
+ */
70
+ export declare function linksOf(root: string): {
71
+ /**
72
+ * Where words lead, for a link that is in `dir`. Throws if the way cannot
73
+ * be followed: then what they name cannot be told, which is not the same
74
+ * as its being outside.
75
+ */
76
+ names(dir: string, text: string): Lead;
77
+ /**
78
+ * What the same words go on to say once they have come to the root from
79
+ * outside it — a slash first, if any more is said — or undefined if they
80
+ * never do. Where they come to it more than once, it is the last time that
81
+ * counts. (Coming to it is a step into it from outside. A link of the root
82
+ * that names the root is a step within it.) Whatever they say from there
83
+ * on, and wherever that leads, it is said of the root: to one who takes a
84
+ * copy for the root itself, it is the copy's name that the words before it
85
+ * come to. Told as far as the way can be followed: one that cannot be
86
+ * followed to its end has still come as far as it has.
87
+ */
88
+ sinceRoot(dir: string, text: string): string | undefined;
89
+ };
90
+ /**
91
+ * The places under a root that make a path lead where it does: every place
92
+ * the way comes to there — each name it steps to, each link it follows, each
93
+ * directory it goes through (also one it leaves again with ".."), and the
94
+ * place it ends at. With any of them another thing, or gone, the path leads
95
+ * somewhere else, or nowhere. Told as far as the way can be followed, each
96
+ * as the way names it — which need not be how its directory lists it.
97
+ */
98
+ export declare function wayTo(rootDir: string, path: string): string[];
99
+ /**
100
+ * Where a project is — which is a directory that is there. Nothing in the
101
+ * runtime makes one for a project that is gone: what it makes for a project,
102
+ * it makes in it. (Making the directories on the way to a file would make a
103
+ * project of that file, at the path of one that somebody has moved away.)
104
+ */
105
+ export declare function projectAt(projectDir: string): string;
106
+ /**
107
+ * A question to ask later: whether what is at a project's path is still the
108
+ * directory that is there now. A project is known by what it is, and what is
109
+ * done over some time — generate a program, ask for a fix, try it, install it,
110
+ * write it down — is done to the project it was started on: not to another
111
+ * directory that somebody has put at the path meanwhile. (Gone is not another:
112
+ * what is to be done where no project is, each step says for itself.)
113
+ */
114
+ export declare function sameProjectAs(projectDir: string): () => void;
115
+ /**
116
+ * Make a directory under a root, with those on the way to it — in the root,
117
+ * which must be there: no root is made for the sake of what goes into it.
118
+ * This is for a root that is something in itself — a project, which
119
+ * somebody may have moved away since it was named: making the directory
120
+ * anew at its path would make another, and put into it what was meant for
121
+ * the first. (A workspace is nothing but its path, and is made as needed,
122
+ * with the way to it.)
123
+ * `dir` is a place the guard has passed.
124
+ */
125
+ export declare function makeDirsIn(rootDir: string, dir: string): void;
19
126
  /**
20
- * The guard for reading or writing a path under a bounded root.
21
- * Checks both the logical path (".." segments) and symlink resolution,
22
- * and returns the resolved absolute path.
127
+ * The guard for reading or writing a path under a bounded root: where the
128
+ * path leads, every link on the way followed — refused unless that is inside
129
+ * the root, and a file, a directory, or nothing yet. What comes back has no
130
+ * link left in it, so using it goes where this looked.
23
131
  *
24
- * For paths that don't exist yet, checks the nearest existing ancestor —
25
- * so a caller can safely mkdir and write afterwards.
132
+ * A path that does not exist yet is followed as far as it does, so a caller
133
+ * can safely mkdir and write afterwards: a write lands on what a link points
134
+ * at, not on a link on the way.
26
135
  */
27
- export declare function guardPath(rootDir: string, relativePath: string): string;
136
+ export declare function guardPath(rootDir: string, path: string): string;