@trama-dev/runtime 0.4.0 → 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.
@@ -1,30 +1,44 @@
1
1
  // The runner side of the IPC bridge. A running program.ts reaches ctx, agent,
2
- // tools and workspace by POSTing JSON to this local HTTP server (see client.ts
3
- // for the other end).
2
+ // tools and workspace by POSTing JSON to this local HTTP server (see
3
+ // bridge-client.ts for the other end, and client.ts for what is made of it).
4
4
  import { createServer } from "http";
5
5
  import { timingSafeEqual } from "crypto";
6
- import { assertSerializable } from "./serializable.js";
6
+ import { isJsonObject } from "./serializable.js";
7
7
  const MAX_IPC_BODY = 50 * 1024 * 1024; // 50 MB
8
+ const MAX_STOPPED_AHEAD = 1024;
8
9
  /** A request the program got wrong — answered with 400 rather than 500. */
9
10
  class BadRequest extends Error {
10
11
  }
11
- const isPlainObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
12
- function validate(body, fields) {
13
- for (const [name, type] of Object.entries(fields)) {
12
+ const isOfKind = (value, kind) => kind === "any" ? value !== undefined : kind === "object" ? isJsonObject(value) : typeof value === kind;
13
+ /** Read a call's declared fields out of a request body — refusing a body that does not hold them as declared. */
14
+ function read(body, fields) {
15
+ if (!isJsonObject(body))
16
+ throw new BadRequest("The request body must be a JSON object");
17
+ const args = {};
18
+ for (const [name, field] of Object.entries(fields)) {
19
+ const optional = field.startsWith("optional ");
20
+ const kind = (optional ? field.slice("optional ".length) : field);
14
21
  const value = body[name];
15
- const optional = type.startsWith("optional ");
16
22
  // 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];
23
+ if (optional && value == null)
19
24
  continue;
20
- }
21
- const expected = optional ? type.slice("optional ".length) : type;
22
- if (expected === "object" ? !isPlainObject(value) : typeof value !== expected) {
25
+ if (!isOfKind(value, kind)) {
23
26
  throw new BadRequest(optional
24
- ? `Invalid field: ${name} (expected ${expected} or undefined)`
25
- : `Missing or invalid field: ${name} (expected ${expected})`);
27
+ ? `Invalid field: ${name} (expected ${kind} or undefined)`
28
+ : `Missing or invalid field: ${name} (expected ${kind})`);
26
29
  }
30
+ args[name] = value;
27
31
  }
32
+ return args;
33
+ }
34
+ /**
35
+ * A call: every field it takes, and what is done with them. The declaration
36
+ * is the whole of what a handler sees of a request — a field that is not
37
+ * declared does not reach it, and one that is arrives as the kind it says.
38
+ * (What is inside an object is the business of whoever it is handed to.)
39
+ */
40
+ function route(fields, handle) {
41
+ return { handle: (body, connectionClosed, seq) => handle(read(body, fields), connectionClosed, seq) };
28
42
  }
29
43
  /** Whether a request carries `Authorization: Bearer <token>`, compared in constant time. */
30
44
  function isAuthorized(header, token) {
@@ -32,129 +46,85 @@ function isAuthorized(header, token) {
32
46
  const actual = Buffer.from(header ?? "");
33
47
  return actual.length === expected.length && timingSafeEqual(actual, expected);
34
48
  }
35
- function buildRoutes({ ctx, agent, tools, workspace, workspaceAt, run, onTerminalSignal }) {
36
- /** The program owns ctx.state; each persisting call hands over its current copy. */
37
- const adoptState = (state) => {
38
- assertSerializable(state, "ctx.state");
39
- ctx.state = state;
40
- };
49
+ function buildRoutes({ ctx, agent, tools, workspace, workspaceAt, run }) {
41
50
  /** Runs the program has asked for and that have not ended, by the id it gave each. */
42
51
  const runsAskedFor = new Map();
43
52
  /** Ids the program asked to stop before their run was seen here: such a run starts stopped. */
44
53
  const stoppedAhead = new Set();
45
54
  /** The workspace a call is about: the directory it names, or else the one this run was started with. */
46
- const workspaceOf = (body) => {
47
- if (body.dir !== undefined) {
48
- if (typeof body.dir !== "string" || body.dir === "")
55
+ const workspaceOf = (dir) => {
56
+ if (dir !== undefined) {
57
+ if (dir === "")
49
58
  throw new BadRequest("Invalid field: dir (expected a directory path)");
50
- return workspaceAt(body.dir);
59
+ return workspaceAt(dir);
51
60
  }
52
61
  if (!workspace)
53
62
  throw new BadRequest("Workspace is only available when running in a session");
54
63
  return workspace;
55
64
  };
56
65
  return {
57
- "/agent/instruct": {
58
- fields: { prompt: "string" },
59
- handle: b => agent.instruct(b.prompt, { system: b.system }),
60
- },
61
- "/agent/generate": {
62
- fields: { prompt: "string", schema: "object" },
63
- handle: b => agent.generate(b),
64
- },
65
- "/tools/read": { fields: { path: "string" }, handle: b => tools.read(b.path) },
66
- "/tools/write": { fields: { path: "string", content: "string" }, handle: b => tools.write(b.path, b.content) },
67
- "/tools/shell": {
68
- fields: { command: "string" },
69
- handle: b => tools.shell(b.command, { cwd: b.cwd, timeout: b.timeout }),
70
- },
71
- "/tools/fetch": {
72
- fields: { url: "string" },
73
- handle: b => tools.fetch(b.url, { method: b.method, headers: b.headers, body: b.body }),
74
- },
75
- "/ctx/log": { fields: { message: "string" }, handle: b => ctx.log(b.message, b.data) },
76
- "/ctx/ready": { fields: { data: "optional object" }, handle: b => ctx.ready(b.data) },
77
- "/ctx/checkpoint": {
78
- fields: { state: "object" },
79
- handle: async (b) => {
80
- adoptState(b.state);
81
- await ctx.checkpoint();
82
- return ctx.iteration;
83
- },
84
- },
85
- "/ctx/done": {
86
- fields: { state: "object" },
87
- handle: async (b) => {
88
- adoptState(b.state);
89
- await ctx.done(b.result);
90
- onTerminalSignal({ status: "done", result: b.result ?? undefined });
91
- return ctx.iteration;
92
- },
93
- },
94
- "/ctx/yield": {
95
- fields: { state: "object", reason: "string" },
96
- handle: async (b) => {
97
- adoptState(b.state);
98
- // Persists the yield marker and returns; the program exits itself once we answer.
99
- await ctx.yield(b.reason);
100
- onTerminalSignal({ status: "yielded", reason: b.reason });
101
- },
102
- },
66
+ "/agent/instruct": route({ prompt: "string", system: "optional string" }, b => agent.instruct(b.prompt, { system: b.system })),
67
+ "/agent/generate": route({ prompt: "string", schema: "object", system: "optional string" }, b => agent.generate({ prompt: b.prompt, schema: b.schema, system: b.system })),
68
+ "/tools/read": route({ path: "string" }, b => tools.read(b.path)),
69
+ "/tools/write": route({ path: "string", content: "string" }, b => tools.write(b.path, b.content)),
70
+ "/tools/shell": route({ command: "string", cwd: "optional string", timeout: "optional number" }, b => tools.shell(b.command, { cwd: b.cwd, timeout: b.timeout })),
71
+ "/tools/fetch": route({ url: "string", method: "optional string", headers: "optional object", body: "optional string" }, b => tools.fetch(b.url, { method: b.method, headers: b.headers, body: b.body })),
72
+ "/ctx/log": route({ message: "string", data: "optional any" }, b => ctx.log(b.message, b.data)),
73
+ "/ctx/ready": route({ data: "optional object" }, b => ctx.ready(b.data)),
74
+ // The state is the program's: each call that persists it hands over its current copy.
75
+ "/ctx/checkpoint": route({ state: "object" }, b => ctx.checkpoint(b.state)),
76
+ "/ctx/done": route({ state: "object", result: "optional any" }, b => ctx.done(b.state, b.result)),
77
+ // Persists the yield marker and returns; the program exits itself once it is answered.
78
+ "/ctx/yield": route({ state: "object", reason: "string" }, b => ctx.yield(b.state, b.reason)),
103
79
  // A program never runs another program: it asks its runner to. The call
104
80
  // lasts as long as the run does, repairs included.
105
- "/run/program": {
106
- fields: {
107
- projectDir: "string", args: "optional object",
108
- id: "optional string", label: "optional string", workspaceDir: "optional string",
109
- },
110
- handle: async (b, connectionClosed, seq) => {
111
- const stop = new AbortController();
112
- // A caller that is gone — its process died, or it gave up — no longer wants the run.
113
- void connectionClosed.then(() => stop.abort());
114
- // The name the program gave the run, to stop it by.
115
- const id = b.id;
116
- if (id && stoppedAhead.delete(id))
81
+ "/run/program": route({
82
+ projectDir: "string", args: "optional object",
83
+ timeout: "optional number", maxRepairAttempts: "optional number",
84
+ id: "optional string", label: "optional string", workspaceDir: "optional string",
85
+ }, async ({ id, ...request }, connectionClosed, seq) => {
86
+ if (id !== undefined) {
87
+ if (id === "")
88
+ throw new BadRequest("Invalid field: id (expected a non-empty string)");
89
+ if (runsAskedFor.has(id))
90
+ throw new BadRequest(`Duplicate run id: ${id}`);
91
+ }
92
+ const stop = new AbortController();
93
+ // A caller that is gone — its process died, or it gave up — no longer wants the run.
94
+ void connectionClosed.then(() => stop.abort());
95
+ // `id` is the name the program gave the run, to stop it by.
96
+ if (id !== undefined) {
97
+ if (stoppedAhead.delete(id))
117
98
  stop.abort();
118
- if (id)
119
- runsAskedFor.set(id, stop);
120
- try {
121
- return await run({
122
- projectDir: b.projectDir,
123
- args: b.args,
124
- timeout: b.timeout,
125
- maxRepairAttempts: b.maxRepairAttempts,
126
- workspaceDir: b.workspaceDir,
127
- label: b.label,
128
- }, stop.signal, seq);
129
- }
130
- finally {
131
- if (id)
132
- runsAskedFor.delete(id);
133
- }
134
- },
135
- },
99
+ runsAskedFor.set(id, stop);
100
+ }
101
+ try {
102
+ return await run(request, stop.signal, seq);
103
+ }
104
+ finally {
105
+ if (id !== undefined)
106
+ runsAskedFor.delete(id);
107
+ }
108
+ }),
136
109
  // Stop a run asked for above. The call that asked for it still gets its
137
110
  // answer — a failed run — once the run is over.
138
- "/run/stop": {
139
- fields: { id: "string" },
140
- handle: b => {
141
- const asked = runsAskedFor.get(b.id);
142
- if (asked)
143
- asked.abort();
144
- else
145
- stoppedAhead.add(b.id);
146
- },
147
- },
148
- "/workspace/read": { fields: { path: "string" }, handle: b => workspaceOf(b).read(b.path) },
149
- "/workspace/write": {
150
- fields: { path: "string", content: "string" },
151
- handle: b => workspaceOf(b).write(b.path, b.content),
152
- },
153
- "/workspace/list": { fields: { pattern: "string" }, handle: b => workspaceOf(b).list(b.pattern) },
154
- "/workspace/observe": {
155
- fields: { pattern: "string" },
156
- handle: b => workspaceOf(b).observe(b.pattern, { expect: b.expect, timeout: b.timeout }),
157
- },
111
+ "/run/stop": route({ id: "string" }, b => {
112
+ if (b.id === "")
113
+ throw new BadRequest("Invalid field: id (expected a non-empty string)");
114
+ const asked = runsAskedFor.get(b.id);
115
+ if (asked)
116
+ asked.abort();
117
+ else {
118
+ if (stoppedAhead.size >= MAX_STOPPED_AHEAD && !stoppedAhead.has(b.id)) {
119
+ stoppedAhead.delete(stoppedAhead.values().next().value);
120
+ }
121
+ stoppedAhead.add(b.id);
122
+ }
123
+ }),
124
+ "/workspace/read": route({ path: "string", dir: "optional string" }, b => workspaceOf(b.dir).read(b.path)),
125
+ "/workspace/write": route({ path: "string", content: "string", dir: "optional string" }, b => workspaceOf(b.dir).write(b.path, b.content)),
126
+ "/workspace/list": route({ pattern: "string", dir: "optional string" }, b => workspaceOf(b.dir).list(b.pattern)),
127
+ "/workspace/observe": route({ pattern: "string", dir: "optional string", expect: "optional number", timeout: "optional number" }, b => workspaceOf(b.dir).observe(b.pattern, { expect: b.expect, timeout: b.timeout })),
158
128
  };
159
129
  }
160
130
  export function createIPCServer(backends) {
@@ -200,16 +170,22 @@ export function createIPCServer(backends) {
200
170
  // recorded as one: a call nobody was left to answer has no result.
201
171
  let call;
202
172
  try {
203
- const body = JSON.parse(Buffer.concat(chunks).toString("utf-8"));
204
- const route = req.url ? routes[req.url] : undefined;
173
+ let body;
174
+ try {
175
+ body = JSON.parse(Buffer.concat(chunks).toString("utf-8"));
176
+ }
177
+ catch {
178
+ return reply(400, "The request body is not valid JSON");
179
+ }
180
+ const route = req.url && Object.hasOwn(routes, req.url) ? routes[req.url] : undefined;
205
181
  if (!route)
206
182
  return reply(404, "Not found");
207
183
  call = backends.journal.call(req.url, body);
208
- validate(body, route.fields);
209
184
  const result = (await route.handle(body, connectionClosed, call.seq)) ?? null;
185
+ const payload = JSON.stringify({ result });
210
186
  if (answerable())
211
187
  call.end({ ok: true, result });
212
- reply(200, JSON.stringify({ result }), true);
188
+ reply(200, payload, true);
213
189
  }
214
190
  catch (err) {
215
191
  const refused = err instanceof BadRequest;
@@ -226,21 +202,12 @@ export function listen(server) {
226
202
  return new Promise((resolve, reject) => {
227
203
  server.once("error", reject);
228
204
  server.listen(0, "127.0.0.1", () => {
229
- const addr = server.address();
230
- if (addr && typeof addr === "object")
231
- resolve(addr.port);
232
- else
233
- reject(new Error("Failed to get server port"));
205
+ server.removeListener("error", reject);
206
+ resolve(server.address().port);
234
207
  });
235
208
  });
236
209
  }
210
+ /** Stop listening, and wait until it has. (The one thing a server can say against it is that it was not listening.) */
237
211
  export function closeServer(server) {
238
- return new Promise((resolve, reject) => {
239
- server.close(err => {
240
- if (!err || err.code === "ERR_SERVER_NOT_RUNNING")
241
- resolve();
242
- else
243
- reject(err);
244
- });
245
- });
212
+ return new Promise((resolve) => { server.close(() => resolve()); });
246
213
  }
@@ -4,6 +4,7 @@
4
4
  // as far as it goes — a run may still be writing it, or have died doing so.
5
5
  import { readFileSync } from "fs";
6
6
  import { JOURNAL_VERSION, journalDirOf, journalIn, runsIn, stillBeingWritten } from "./journal.js";
7
+ import { isJsonObject } from "./serializable.js";
7
8
  /**
8
9
  * The records of a journal file. A line that is not a whole record — the last
9
10
  * one, if the runner died writing it — is left out, and so is a file that
@@ -21,7 +22,7 @@ function readJournal(path) {
21
22
  continue;
22
23
  try {
23
24
  const record = JSON.parse(line);
24
- if (typeof record === "object" && record !== null)
25
+ if (isJsonObject(record))
25
26
  records.push(record);
26
27
  }
27
28
  catch { /* not a whole record */ }
@@ -52,7 +53,8 @@ function ending(path, records) {
52
53
  }
53
54
  function printJournal(path, records) {
54
55
  const head = records[0];
55
- console.log(`${head?.run ?? "?"} ${head?.purpose ?? ""}${head?.label ? ` [${head.label}]` : ""} ${ending(path, records)}`);
56
+ const howEnded = ending(path, records);
57
+ console.log(`${head?.run ?? "?"} ${head?.purpose ?? ""}${head?.label ? ` [${head.label}]` : ""} ${howEnded}`);
56
58
  if (head && head.v !== JOURNAL_VERSION) {
57
59
  console.log(`(recorded in format ${head.v}; this trama reads format ${JOURNAL_VERSION}, and shows what it can make of it)`);
58
60
  }
@@ -93,11 +95,16 @@ function printJournal(path, records) {
93
95
  console.log(`${at} attempt ${record.attempt} over: ${how} → ${verdict}`);
94
96
  break;
95
97
  }
98
+ case "unmerged":
99
+ console.log(`${at} attempt ${record.attempt}: ${record.files?.length ?? 0} change(s) it made did not reach the project`);
100
+ for (const file of record.files ?? [])
101
+ console.log(`${" ".repeat(at.length)} ${file.path} — ${oneLine(file.why, 80)}`);
102
+ break;
96
103
  case "full":
97
104
  console.log(`${at} the journal is full: calls from here on were not recorded`);
98
105
  break;
99
106
  case "end":
100
- console.log(`${at} end: ${ending(path, records)}`);
107
+ console.log(`${at} end: ${howEnded}`);
101
108
  break;
102
109
  }
103
110
  }
@@ -127,5 +134,6 @@ export function printJournals(projectDir, name, options) {
127
134
  if (!runs.includes(run)) {
128
135
  throw new Error(`No journal for run "${run}". \`trama journal ${name} --list\` shows the runs that have one.`);
129
136
  }
130
- printJournal(journalIn(dir, run), readJournal(journalIn(dir, run)));
137
+ const path = journalIn(dir, run);
138
+ printJournal(path, readJournal(path));
131
139
  }
package/dist/journal.d.ts CHANGED
@@ -4,13 +4,21 @@ export declare const JOURNAL_VERSION = 1;
4
4
  export declare const JOURNAL_DIR: string;
5
5
  /**
6
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.
7
+ * referred to.
8
8
  */
9
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
10
  /** The journal of a run, in a journal directory. */
13
11
  export declare const journalIn: (dir: string, run: string) => string;
12
+ /** The ids of the runs that have a journal in `dir`, oldest first. (A run's id starts with when it started.) */
13
+ export declare function runsIn(dir: string): string[];
14
+ /**
15
+ * What a copy of `projectDir` is to leave out so as not to carry the project's
16
+ * journals, each by what it is (its `identityOf`): the directory they are in,
17
+ * if nothing else is in it or it may not be read or searched — and otherwise every
18
+ * journal in it. Somebody's own file among the journals is the project's
19
+ * like any other, and is copied.
20
+ */
21
+ export declare function journalEntriesOf(projectDir: string): Set<string>;
14
22
  export type CallOutcome = {
15
23
  ok: true;
16
24
  result: unknown;
@@ -41,8 +49,10 @@ export interface Journal {
41
49
  }
42
50
  /**
43
51
  * 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.)
52
+ * runner that is still there and has not yet written its ending. (A journal
53
+ * this process started and has closed is finished, though the process lives
54
+ * on. And a process that may not be signalled is not the writer of a journal
55
+ * that can be read: its number has been given to somebody else's since.)
46
56
  */
47
57
  export declare function stillBeingWritten(path: string): boolean;
48
58
  /**