@trama-dev/runtime 0.4.0 → 0.6.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 (56) 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 +127 -7
  5. package/dist/agent-backend.js +38 -19
  6. package/dist/agent-host.d.ts +50 -0
  7. package/dist/agent-host.js +97 -0
  8. package/dist/agent-hosts.d.ts +14 -0
  9. package/dist/agent-hosts.js +321 -0
  10. package/dist/agent.d.ts +26 -3
  11. package/dist/agent.js +165 -43
  12. package/dist/bridge-client.d.ts +6 -0
  13. package/dist/bridge-client.js +69 -16
  14. package/dist/budget.d.ts +52 -0
  15. package/dist/budget.js +118 -0
  16. package/dist/child-process.d.ts +18 -0
  17. package/dist/child-process.js +38 -9
  18. package/dist/client.d.ts +2 -1
  19. package/dist/client.js +9 -19
  20. package/dist/context.d.ts +36 -7
  21. package/dist/context.js +83 -92
  22. package/dist/errors.d.ts +2 -0
  23. package/dist/errors.js +2 -0
  24. package/dist/index.d.ts +7 -2
  25. package/dist/index.js +254 -88
  26. package/dist/ipc-server.d.ts +14 -5
  27. package/dist/ipc-server.js +174 -144
  28. package/dist/journal-view.d.ts +2 -0
  29. package/dist/journal-view.js +52 -7
  30. package/dist/journal.d.ts +27 -9
  31. package/dist/journal.js +216 -79
  32. package/dist/meta.d.ts +18 -0
  33. package/dist/meta.js +29 -0
  34. package/dist/model-relay.d.ts +130 -0
  35. package/dist/model-relay.js +339 -0
  36. package/dist/path-guard.d.ts +128 -19
  37. package/dist/path-guard.js +384 -68
  38. package/dist/pi-adapter.d.ts +35 -9
  39. package/dist/pi-adapter.js +865 -66
  40. package/dist/replace-file.d.ts +31 -0
  41. package/dist/replace-file.js +75 -0
  42. package/dist/runner-types.d.ts +35 -0
  43. package/dist/runner.d.ts +202 -30
  44. package/dist/runner.js +949 -273
  45. package/dist/serializable.d.ts +10 -4
  46. package/dist/serializable.js +56 -31
  47. package/dist/stopping.d.ts +37 -3
  48. package/dist/stopping.js +167 -21
  49. package/dist/tools.d.ts +2 -1
  50. package/dist/tools.js +90 -21
  51. package/dist/tree.d.ts +241 -0
  52. package/dist/tree.js +1431 -0
  53. package/dist/types.d.ts +106 -15
  54. package/dist/workspace.d.ts +7 -0
  55. package/dist/workspace.js +93 -104
  56. package/package.json +1 -1
package/dist/journal.js CHANGED
@@ -12,42 +12,153 @@
12
12
  // has no "end", and a call nobody was left to answer has no "result".
13
13
  //
14
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";
15
+ import { closeSync, constants, fstatSync, openSync, readSync, readdirSync, renameSync, rmSync, writeSync } from "fs";
16
16
  import { createHash, randomBytes } from "crypto";
17
17
  import { join } from "path";
18
- import { guardPath } from "./path-guard.js";
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
+ import { declaredUsage } from "./agent-backend.js";
19
23
  /** The format of the records. Bump it when a reader of older journals would be misled. */
20
24
  export const JOURNAL_VERSION = 1;
21
25
  /** Where a project keeps its journals, relative to the project — under logs/, which trama keeps out of version control. */
22
26
  export const JOURNAL_DIR = join("logs", "journal");
27
+ /** The shape of a run's id: ISO timestamp (with dashes) followed by 6 hex digits. */
28
+ const RUN_ID = /^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-[0-9a-f]{6}$/;
29
+ /** 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. */
30
+ const LONGEST_LINE = 8 * 1024 * 1024;
31
+ const SAFE_READ_FLAGS = constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW;
23
32
  /**
24
33
  * 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.
34
+ * referred to.
26
35
  */
27
36
  export function journalDirOf(projectDir) {
28
- const dir = guardPath(projectDir, JOURNAL_DIR);
37
+ // Where the path leads, by the guard's own reckoning — the same before the
38
+ // directory exists as after, and never a place the guard did not check.
39
+ return guardPath(projectDir, JOURNAL_DIR);
40
+ }
41
+ /** The journal of a run, in a journal directory. */
42
+ export const journalIn = (dir, run) => join(dir, `${run}.jsonl`);
43
+ /** How a journal begins: the record of its run, which names the run and the process that writes it. */
44
+ const FIRST_RECORD = /^\{"at":\d+,"kind":"run","v":\d+,"run":"([^"]+)","pid":(\d+)[,}]/;
45
+ /**
46
+ * Look into what may be a journal — the file of `run`, if one is named —
47
+ * without waiting on a pipe or following a link there: `look` is given what
48
+ * to read it with. Undefined if it is no journal: not a file, or one that
49
+ * does not begin as a journal does. (Any `.jsonl` file can be put where the
50
+ * journals are; only what trama wrote is listed, read, or removed in its turn.)
51
+ * Throws where it cannot be opened at all, which is the caller's to judge.
52
+ */
53
+ function inJournal(path, run, look) {
54
+ const fd = openSync(path, SAFE_READ_FLAGS);
29
55
  try {
30
- return realpathSync(dir);
56
+ const file = fd, stat = fstatSync(fd), size = stat.size;
57
+ if (!stat.isFile())
58
+ return undefined;
59
+ const read = (from, length) => {
60
+ const buffer = Buffer.allocUnsafe(length);
61
+ return buffer.toString("utf-8", 0, readSync(file, buffer, 0, length, from));
62
+ };
63
+ // The start of the first record is always written the same way, however long the record is.
64
+ const first = FIRST_RECORD.exec(read(0, Math.min(size, 512)));
65
+ if (!first || !RUN_ID.test(first[1]) || (run !== undefined && first[1] !== run))
66
+ return undefined;
67
+ const pid = Number(first[2]);
68
+ /** The last line, if it begins within the last `length` bytes. */
69
+ const lastLine = (length) => {
70
+ const from = Math.max(0, size - length);
71
+ const text = read(from, size - from).trimEnd();
72
+ const line = text.lastIndexOf("\n");
73
+ return line === -1 && from > 0 ? undefined : text.slice(line + 1);
74
+ };
75
+ return look({
76
+ writer: Number.isSafeInteger(pid) && pid > 0 ? pid : null,
77
+ // A record's line is rarely longer than a page, and never than LONGEST_LINE.
78
+ ended() {
79
+ try {
80
+ const last = JSON.parse(lastLine(4096) ?? lastLine(LONGEST_LINE) ?? "");
81
+ return isJsonObject(last) && last.kind === "end";
82
+ }
83
+ catch {
84
+ return false; // cut off in the middle of a record
85
+ }
86
+ },
87
+ });
31
88
  }
32
89
  catch {
33
- return dir; /* not there yet */
90
+ return undefined;
91
+ }
92
+ finally {
93
+ try {
94
+ closeSync(fd);
95
+ }
96
+ catch { /* nothing more to do with it */ }
97
+ }
98
+ }
99
+ /**
100
+ * Whether the file `name` of a journal directory is a journal: named for a
101
+ * run, and beginning as that run's journal does. One that is named for a run
102
+ * and may not be read — another user's run of the project wrote it — is taken
103
+ * at its name: it can be listed and removed in its turn, and cannot be copied.
104
+ */
105
+ function isJournal(dir, name) {
106
+ const run = name.endsWith(".jsonl") ? name.slice(0, -".jsonl".length) : "";
107
+ if (!RUN_ID.test(run))
108
+ return false;
109
+ try {
110
+ return inJournal(join(dir, name), run, () => true) === true;
111
+ }
112
+ catch (err) {
113
+ const code = err.code;
114
+ return code === "EACCES" || code === "EPERM";
34
115
  }
35
116
  }
36
117
  /** The ids of the runs that have a journal in `dir`, oldest first. (A run's id starts with when it started.) */
37
118
  export function runsIn(dir) {
38
- let names;
119
+ let entries;
39
120
  try {
40
- names = readdirSync(dir);
121
+ entries = readdirSync(dir, { withFileTypes: true });
41
122
  }
42
123
  catch (err) {
43
124
  if (err.code === "ENOENT")
44
125
  return []; // no run has been recorded
45
126
  throw err;
46
127
  }
47
- return names.filter(name => name.endsWith(".jsonl")).sort().map(name => name.slice(0, -".jsonl".length));
128
+ // A journal is a file. Anything else that bears a journal's name — a directory, a link, a pipe,
129
+ // which would hold up whoever opened it — is not one; nor is a file somebody else put there.
130
+ return entries.filter((entry) => entry.isFile() && isJournal(dir, entry.name))
131
+ .map((entry) => entry.name.slice(0, -".jsonl".length)).sort();
132
+ }
133
+ /**
134
+ * What a copy of `projectDir` is to leave out so as not to carry the project's
135
+ * journals, each by what it is (its `identityOf`): the directory they are in,
136
+ * if nothing else is in it or it may not be read or searched — and otherwise every
137
+ * journal in it. Somebody's own file among the journals is the project's
138
+ * like any other, and is copied.
139
+ */
140
+ export function journalEntriesOf(projectDir) {
141
+ const only = (...ids) => new Set(ids.filter((id) => id !== undefined));
142
+ let dir;
143
+ /** The directory itself — which is not left out where it is the project (by links that lead back to it). */
144
+ const whole = () => {
145
+ const id = dir === undefined ? undefined : identityOf(dir);
146
+ return id === identityOf(realRootOf(projectDir)) ? undefined : id;
147
+ };
148
+ try {
149
+ const journalDir = dir = journalDirOf(projectDir);
150
+ const entries = readdirSync(journalDir, { withFileTypes: true });
151
+ const journals = entries.filter((entry) => entry.isFile() && isJournal(journalDir, entry.name));
152
+ const all = journals.length === entries.length ? whole() : undefined;
153
+ return all !== undefined ? only(all) : only(...journals.map((entry) => identityOf(join(journalDir, entry.name))));
154
+ }
155
+ catch (err) {
156
+ // Where the journals would be, the project has none: the way leads out of it, or to nothing, or to a file.
157
+ // And a directory that may not be read, or looked into, is left out whole: no part of it can be told from another.
158
+ const code = err.code;
159
+ return code === "EACCES" || code === "EPERM" ? only(whole()) : only();
160
+ }
48
161
  }
49
- /** The journal of a run, in a journal directory. */
50
- export const journalIn = (dir, run) => join(dir, `${run}.jsonl`);
51
162
  /** The longest text kept whole. */
52
163
  const MAX_TEXT = 256 * 1024;
53
164
  /** About how much one record may hold. It is spent in the order the record's fields come in. */
@@ -65,11 +176,13 @@ const MAX_JOURNAL = 64 * 1024 * 1024;
65
176
  * characters whatever shape its contents have. (Its line can be longer: JSON
66
177
  * writes some characters as escapes of up to six.)
67
178
  */
68
- function clip(value, room, path = []) {
179
+ function clip(value, room, path = [], expanded = false) {
69
180
  const cut = (about) => {
70
181
  room.cuts.push({ path, ...about });
71
182
  room.left -= 128 + path.reduce((size, step) => size + String(step).length + 3, 0);
72
183
  };
184
+ if (typeof value === "bigint")
185
+ value = value.toString();
73
186
  if (typeof value === "string") {
74
187
  const keep = Math.max(0, Math.min(MAX_TEXT, room.left));
75
188
  room.left -= Math.min(value.length, keep) + 3;
@@ -78,8 +191,6 @@ function clip(value, room, path = []) {
78
191
  cut({ cut: "text", length: value.length, sha256: createHash("sha256").update(value).digest("hex") });
79
192
  return value.slice(0, keep);
80
193
  }
81
- if (typeof value === "bigint")
82
- value = value.toString();
83
194
  if (value === null || typeof value !== "object") {
84
195
  room.left -= typeof value === "number" ? String(value).length + 1 : 8;
85
196
  return value;
@@ -89,9 +200,9 @@ function clip(value, room, path = []) {
89
200
  cut({ cut: "bytes", length: value.byteLength });
90
201
  return null;
91
202
  }
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);
203
+ // Anything that knows how it wants to be written (a Date) is asked — once per slot, like JSON.stringify.
204
+ if (!expanded && typeof value.toJSON === "function") {
205
+ return clip(value.toJSON(), room, path, true);
95
206
  }
96
207
  if (path.length >= MAX_DEPTH) {
97
208
  cut({ cut: "depth" });
@@ -114,6 +225,11 @@ function clip(value, room, path = []) {
114
225
  for (const key in value) {
115
226
  if (!Object.hasOwn(value, key))
116
227
  continue;
228
+ // What cannot be written down is no field, as it is none to JSON — and so nothing the record
229
+ // is made of says how it wants to be written: each thing was asked that once, above.
230
+ const field = value[key];
231
+ if (typeof field === "function")
232
+ continue;
117
233
  // A field goes in with its name, or not at all. A name that is too long
118
234
  // is passed over — it would be repeated in the path of everything cut
119
235
  // beneath it — and one there is no room for ends the object.
@@ -127,7 +243,7 @@ function clip(value, room, path = []) {
127
243
  continue;
128
244
  }
129
245
  room.left -= key.length + 3;
130
- fields[key] = clip(value[key], room, [...path, key]);
246
+ fields[key] = clip(field, room, [...path, key]);
131
247
  }
132
248
  return fields;
133
249
  }
@@ -143,7 +259,7 @@ function redactHeaders(headers) {
143
259
  if (Array.isArray(headers)) {
144
260
  return headers.map(pair => Array.isArray(pair) && typeof pair[0] === "string" && isSecretHeader(pair[0]) ? [pair[0], "[redacted]"] : pair);
145
261
  }
146
- if (typeof headers !== "object" || headers === null)
262
+ if (!isJsonObject(headers))
147
263
  return headers;
148
264
  return Object.fromEntries(Object.entries(headers).map(([name, value]) => [name, isSecretHeader(name) ? "[redacted]" : value]));
149
265
  }
@@ -154,7 +270,7 @@ function redactHeaders(headers) {
154
270
  * like the rest: the journal cannot tell.
155
271
  */
156
272
  function recordable(endpoint, value) {
157
- if (endpoint === "/tools/fetch" && typeof value === "object" && value !== null && "headers" in value) {
273
+ if (endpoint === "/tools/fetch" && isJsonObject(value) && "headers" in value) {
158
274
  return { ...value, headers: redactHeaders(value.headers) };
159
275
  }
160
276
  return value;
@@ -162,44 +278,38 @@ function recordable(endpoint, value) {
162
278
  /** A journal that records nothing. Calls are still numbered, so the rest of the runner need not care. */
163
279
  function noJournal() {
164
280
  let seq = 0;
165
- return { run: "", path: "", note() { }, call: () => ({ seq: ++seq, end() { } }), close() { } };
281
+ return { run: "", path: "", note() { }, used() { }, call: () => ({ seq: ++seq, end() { }, used() { } }), close() { } };
166
282
  }
167
- /** Journals this process is writing. They are never the ones to make room. */
283
+ /**
284
+ * Journals this process is writing, each by what it is (see identityOf): a
285
+ * project may be named in more ways than one, and its journals with it. They
286
+ * are never the ones to make room.
287
+ */
168
288
  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
289
  /**
194
290
  * 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.)
291
+ * runner that is still there and has not yet written its ending. (A journal
292
+ * this process started and has closed is finished, though the process lives
293
+ * on. And a process that may not be signalled is not the writer of a journal
294
+ * that can be read: its number has been given to somebody else's since.)
197
295
  */
198
296
  export function stillBeingWritten(path) {
199
- if (beingWritten.has(path))
297
+ const journal = identityOf(path);
298
+ if (journal !== undefined && beingWritten.has(journal))
200
299
  return true;
201
- const writer = writerOf(path);
202
- return writer !== null && writer !== process.pid && isAlive(writer);
300
+ const isAlive = (pid) => { try {
301
+ process.kill(pid, 0);
302
+ return true;
303
+ }
304
+ catch {
305
+ return false;
306
+ } };
307
+ try {
308
+ return inJournal(path, undefined, ({ writer, ended }) => writer !== null && writer !== process.pid && isAlive(writer) && !ended()) === true;
309
+ }
310
+ catch {
311
+ return false; // (nothing to be read there, so nothing that says who writes it)
312
+ }
203
313
  }
204
314
  /**
205
315
  * Remove the oldest journals of a project so that, with one more, at most
@@ -233,24 +343,59 @@ export function openJournal(projectDir, keep, about) {
233
343
  return noJournal();
234
344
  const started = new Date();
235
345
  const run = `${started.toISOString().replace(/[:.]/g, "-")}-${randomBytes(3).toString("hex")}`;
236
- let fd;
237
- let path;
346
+ const t0 = performance.now();
347
+ let fd = null;
348
+ let path = "";
349
+ let staged = "";
350
+ let identity;
351
+ let written = 0;
352
+ let full = false;
353
+ const formatLine = (at, kind, compose) => {
354
+ try {
355
+ const room = { left: MAX_RECORD, cuts: [] };
356
+ const record = clip({ at, kind, ...compose() }, room);
357
+ if (room.cuts.length > 0)
358
+ record.cuts = room.cuts;
359
+ return JSON.stringify(record);
360
+ }
361
+ catch (err) {
362
+ return JSON.stringify({ at, kind, unrecordable: messageOf(err) });
363
+ }
364
+ };
238
365
  try {
239
- mkdirSync(guardPath(projectDir, JOURNAL_DIR), { recursive: true });
240
366
  const dir = journalDirOf(projectDir);
367
+ // (In the project, which is there: a journal is not what makes a directory where a project was.)
368
+ makeDirsIn(projectDir, dir);
241
369
  makeRoom(dir, keep);
242
370
  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);
371
+ staged = stagedNameFor(path);
372
+ const firstLine = formatLine(0, "run", () => ({
373
+ v: JOURNAL_VERSION, run, pid: process.pid, started: started.toISOString(), project: projectDir, ...about,
374
+ }));
375
+ // Readable by its owner only, and whole from the moment its name appears in the directory.
376
+ fd = openSync(staged, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_APPEND, 0o600);
377
+ written = writeSync(fd, firstLine + "\n");
378
+ identity = identityIn(fstatSync(fd, { bigint: true }));
379
+ beingWritten.add(identity);
380
+ renameSync(staged, path);
381
+ staged = "";
246
382
  }
247
383
  catch (err) {
248
- console.warn(`[trama] this run is not being recorded: ${err instanceof Error ? err.message : err}`);
384
+ if (fd !== null)
385
+ try {
386
+ closeSync(fd);
387
+ }
388
+ catch { /* ignore */ }
389
+ if (identity !== undefined)
390
+ beingWritten.delete(identity);
391
+ if (staged)
392
+ try {
393
+ rmSync(staged, { force: true });
394
+ }
395
+ catch { /* ignore */ }
396
+ console.warn(`[trama] this run is not being recorded: ${messageOf(err)}`);
249
397
  return noJournal();
250
398
  }
251
- const t0 = performance.now();
252
- let written = 0;
253
- let full = false;
254
399
  const close = () => {
255
400
  if (fd === null)
256
401
  return;
@@ -259,30 +404,19 @@ export function openJournal(projectDir, keep, about) {
259
404
  }
260
405
  catch { /* nothing more to do with it */ }
261
406
  fd = null;
262
- beingWritten.delete(path);
407
+ if (identity !== undefined)
408
+ beingWritten.delete(identity);
263
409
  };
264
410
  /** Write one record. `compose` builds it, and may fail: what cannot be written down is noted as such. */
265
411
  const write = (kind, compose) => {
266
412
  if (fd === null)
267
413
  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
- }
414
+ const line = formatLine(Math.round(performance.now() - t0), kind, compose);
280
415
  try {
281
- appendFileSync(fd, line + "\n");
282
- written += line.length + 1;
416
+ written += writeSync(fd, line + "\n");
283
417
  }
284
418
  catch (err) {
285
- console.warn(`[trama] the journal could not be written, and stops here: ${err instanceof Error ? err.message : err}`);
419
+ console.warn(`[trama] the journal could not be written, and stops here: ${messageOf(err)}`);
286
420
  close();
287
421
  }
288
422
  };
@@ -295,15 +429,15 @@ export function openJournal(projectDir, keep, about) {
295
429
  return !full;
296
430
  };
297
431
  let seq = 0;
298
- write("run", () => ({ v: JOURNAL_VERSION, run, pid: process.pid, started: started.toISOString(), project: projectDir, ...about }));
299
432
  return {
300
433
  run,
301
434
  path,
302
435
  note: (kind, fields = {}) => write(kind, () => fields),
436
+ used: (what, usage) => write("usage", () => ({ for: what, ...declaredUsage(usage) })),
303
437
  call(endpoint, request) {
304
438
  const position = ++seq;
305
439
  if (!roomForCalls())
306
- return { seq: position, end() { } };
440
+ return { seq: position, end() { }, used() { } };
307
441
  const arrived = performance.now();
308
442
  write("call", () => ({ seq: position, endpoint, request: recordable(endpoint, request) }));
309
443
  return {
@@ -315,6 +449,9 @@ export function openJournal(projectDir, keep, about) {
315
449
  ...(outcome.ok ? { ok: true, result: recordable(endpoint, outcome.result) } : outcome),
316
450
  }));
317
451
  },
452
+ used(usage) {
453
+ write("usage", () => ({ seq: position, ...declaredUsage(usage) }));
454
+ },
318
455
  };
319
456
  },
320
457
  close,
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
+ }
@@ -0,0 +1,130 @@
1
+ /** A model as pi has it in its catalog: plain data. */
2
+ export type RelayModel = {
3
+ provider: string;
4
+ id: string;
5
+ api?: string;
6
+ } & Record<string, unknown>;
7
+ /** A request of a model: plain data, all of it. */
8
+ export interface RelayRequest {
9
+ /** The model, as the session that asks has it. */
10
+ model: RelayModel;
11
+ /** What the model is to be sent: as pi hands it to a provider. */
12
+ context: unknown;
13
+ /** The options of the request that are data (see `dataOf`). */
14
+ options: Record<string, unknown>;
15
+ /** Whether it is asked beside a call that is over — one that has its answer, or has failed (see AgentCall.sofar). */
16
+ answered?: true;
17
+ }
18
+ /** An event of a reply, as pi's stream of it has them. The last is of type "done" or "error", and has the reply whole. */
19
+ export type RelayEvent = {
20
+ type: string;
21
+ } & Record<string, unknown>;
22
+ export interface ModelRelay {
23
+ /**
24
+ * Ask the model. Resolves to the events of the reply, to the last — or to
25
+ * undefined where the model is not one this relay can ask as the session
26
+ * that asks would: that session then asks it itself. It does not reject.
27
+ */
28
+ ask(request: RelayRequest, signal?: AbortSignal): Promise<AsyncIterable<RelayEvent> | undefined>;
29
+ }
30
+ /**
31
+ * Of the options a session asks with, those that go with a relayed request —
32
+ * or undefined where one is there that cannot go, and would be missed: a key
33
+ * of the asker's own, a way of its own to reach the provider, a reply that is
34
+ * to be fetched later.
35
+ */
36
+ export declare function dataOf(options?: Record<string, unknown>): Record<string, unknown> | undefined;
37
+ /** What a reply used, as pi has it on the reply. */
38
+ export interface ReplyUsage {
39
+ input: number;
40
+ output: number;
41
+ cacheRead: number;
42
+ cacheWrite: number;
43
+ cost: {
44
+ total: number;
45
+ };
46
+ }
47
+ /** What the reply an event is the last of used — undefined of any other event. */
48
+ export declare function usageAtEnd(event: RelayEvent): ReplyUsage | undefined;
49
+ /**
50
+ * The event that ends a reply the model was not asked for: as pi makes the
51
+ * reply of a request that was cancelled before it was sent. (Said as one that
52
+ * was cancelled, whyever it was: pi reads the words of a reply that failed —
53
+ * for a number that looks like a server's, to try again; for a limit, to sum
54
+ * the conversation up — and a request that is not to be made is neither.)
55
+ */
56
+ export declare function notAsked(model: RelayModel, why: string, as?: "aborted" | "error"): RelayEvent;
57
+ /**
58
+ * Makes of a reply's events the events as they are sent: without the reply
59
+ * so far. (One for each reply: it keeps how much of each tool call has been
60
+ * sent.) What an event adds is sent with it — but a tool call's arguments,
61
+ * which pi puts together from their pieces in its own way for each kind of
62
+ * provider, can only be sent whole: so they are, with every piece while they
63
+ * are short, and after that each time they have grown by half — and whole at
64
+ * their end. Whoever is shown a long tool call as it comes is shown its
65
+ * arguments as they were a little while before.
66
+ */
67
+ export declare function leaner(): (event: RelayEvent) => RelayEvent;
68
+ /** The reply so far, kept where events that were sent without it are given it again. */
69
+ export interface SoFar {
70
+ partial?: {
71
+ content: Record<string, unknown>[];
72
+ } & Record<string, unknown>;
73
+ }
74
+ /** An event that was sent without the reply so far (see `leaner`), with it. */
75
+ export declare function whole(event: RelayEvent, state: SoFar): RelayEvent;
76
+ /**
77
+ * A relay that asks with this process's own pi: the models it finds, and the
78
+ * keys it has for their providers. Its events are sent ones (see `leaner`).
79
+ * `close` when whoever it asks for is done: what is still being asked is
80
+ * asked no further, and what was kept for it is let go of.
81
+ */
82
+ export declare function createModelRelay(): ModelRelay & {
83
+ close(): Promise<void>;
84
+ };
85
+ /** What the end that asks sends: a request, or that one it sent is cancelled. */
86
+ export type RelayAsked = {
87
+ relay: {
88
+ id: number;
89
+ request: RelayRequest;
90
+ };
91
+ } | {
92
+ relayAbort: number;
93
+ };
94
+ /** What the end that answers sends: an event of the reply to a request, or that the request is not one it can serve. */
95
+ export type RelayAnswered = {
96
+ relayed: {
97
+ id: number;
98
+ event: RelayEvent;
99
+ } | {
100
+ id: number;
101
+ not: true;
102
+ };
103
+ };
104
+ /**
105
+ * The asking end: a relay that is reached by messages. `heard` is to be told
106
+ * what the other end answers; `close` when the other end is gone — whatever
107
+ * is still waited for then ends as a request that failed, saying so (nobody
108
+ * cancelled it), and nothing more is asked by it.
109
+ */
110
+ export declare function relayClient(send: (message: RelayAsked) => void): {
111
+ relay: ModelRelay;
112
+ heard(answer: RelayAnswered["relayed"]): void;
113
+ close(): void;
114
+ };
115
+ /**
116
+ * The answering end: serves, by `relay`, the requests that `heard` is told
117
+ * of. `refuse`: whether a request is not to be made at all (it then ends as
118
+ * one that was cancelled) — asked before each, and waited for; `replied`:
119
+ * told what each reply used, as its last event passes. `close`: what is
120
+ * still being asked is asked no further.
121
+ */
122
+ export declare function relayServer(relay: ModelRelay, send: (message: RelayAnswered) => void, on?: {
123
+ refuse?: (request: RelayRequest) => boolean | Promise<boolean>;
124
+ replied?: (usage: ReplyUsage) => void;
125
+ }): {
126
+ heard(message: RelayAsked): void;
127
+ close(): void;
128
+ };
129
+ /** A relay whose events are sent ones, as one whose events are pi's own: each with the reply so far. */
130
+ export declare function withRepliesWhole(relay: ModelRelay): ModelRelay;