@trama-dev/runtime 0.6.1 → 0.8.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 (64) hide show
  1. package/dist/agent-backend.d.ts +100 -0
  2. package/dist/agent-backend.js +4 -0
  3. package/dist/agent-host.d.ts +46 -7
  4. package/dist/agent-host.js +59 -19
  5. package/dist/agent-hosts.d.ts +8 -0
  6. package/dist/agent-hosts.js +123 -56
  7. package/dist/agent.d.ts +18 -5
  8. package/dist/agent.js +23 -64
  9. package/dist/bridge-client.d.ts +6 -2
  10. package/dist/bridge-client.js +7 -1
  11. package/dist/budget.d.ts +6 -0
  12. package/dist/budget.js +1 -0
  13. package/dist/client.d.ts +3 -2
  14. package/dist/client.js +146 -2
  15. package/dist/context.js +3 -2
  16. package/dist/history.d.ts +9 -0
  17. package/dist/history.js +98 -0
  18. package/dist/index.d.ts +2 -0
  19. package/dist/index.js +73 -41
  20. package/dist/ipc-server.d.ts +2 -3
  21. package/dist/ipc-server.js +99 -38
  22. package/dist/journal-view.d.ts +8 -0
  23. package/dist/journal-view.js +63 -11
  24. package/dist/journal.d.ts +10 -4
  25. package/dist/journal.js +73 -7
  26. package/dist/merge-deeds.d.ts +22 -0
  27. package/dist/merge-deeds.js +201 -0
  28. package/dist/merge-doing.d.ts +9 -0
  29. package/dist/merge-doing.js +410 -0
  30. package/dist/merge-settle.d.ts +14 -0
  31. package/dist/merge-settle.js +166 -0
  32. package/dist/merge-shared.d.ts +64 -0
  33. package/dist/merge-shared.js +159 -0
  34. package/dist/merge.d.ts +150 -0
  35. package/dist/merge.js +209 -0
  36. package/dist/model-relay.d.ts +19 -0
  37. package/dist/model-relay.js +91 -9
  38. package/dist/model-request.d.ts +9 -0
  39. package/dist/model-request.js +185 -0
  40. package/dist/own-tools.d.ts +60 -0
  41. package/dist/own-tools.js +209 -0
  42. package/dist/path-guard.js +8 -6
  43. package/dist/pi-adapter.d.ts +32 -9
  44. package/dist/pi-adapter.js +198 -51
  45. package/dist/project.d.ts +39 -0
  46. package/dist/project.js +270 -0
  47. package/dist/replace-file.d.ts +13 -2
  48. package/dist/replace-file.js +23 -6
  49. package/dist/runner-backend.d.ts +43 -0
  50. package/dist/runner-backend.js +149 -0
  51. package/dist/runner-types.d.ts +26 -0
  52. package/dist/runner.d.ts +10 -125
  53. package/dist/runner.js +148 -461
  54. package/dist/schema.d.ts +45 -0
  55. package/dist/schema.js +113 -0
  56. package/dist/stopping.js +2 -3
  57. package/dist/tools.d.ts +8 -1
  58. package/dist/tools.js +36 -10
  59. package/dist/tree.d.ts +33 -149
  60. package/dist/tree.js +43 -1077
  61. package/dist/types.d.ts +182 -2
  62. package/dist/workspace.d.ts +28 -1
  63. package/dist/workspace.js +88 -13
  64. package/package.json +2 -2
@@ -3,19 +3,25 @@
3
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 { OFF_THE_RECORD } from "./journal.js";
7
+ import { createToolAsks, imagesOf, toolsOf } from "./own-tools.js";
8
+ import { REQUEST_FIELDS, requestOf } from "./model-request.js";
6
9
  import { describeJson, isJsonObject } from "./serializable.js";
7
10
  import { checkedEnv, variableName } from "./child-process.js";
8
11
  import { checkedBudget } from "./budget.js";
12
+ import { checkedRepairAttempts, checkedTimeout } from "./project.js";
9
13
  import { messageOf } from "./errors.js";
10
14
  const MAX_IPC_BODY = 50 * 1024 * 1024; // 50 MB
11
15
  const MAX_STOPPED_AHEAD = 1024;
12
16
  /** A request the program got wrong — answered with 400 rather than 500. */
13
17
  class BadRequest extends Error {
14
18
  }
19
+ /** Fields that are the client's own way of carrying a call, and nothing a program says: not among what a call is said to take. */
20
+ const CARRIES = new Set(["toolsId"]);
15
21
  const isStrings = (value) => Array.isArray(value) && value.every(item => typeof item === "string");
16
22
  const isOfKind = (value, kind) => kind === "any" ? value !== undefined
17
23
  : kind === "object" ? isJsonObject(value)
18
- : kind === "strings" ? isStrings(value)
24
+ : kind === "strings or tools" ? Array.isArray(value) && value.every(item => typeof item === "string" || isJsonObject(item))
19
25
  : kind === "boolean or strings" ? typeof value === "boolean" || isStrings(value)
20
26
  : kind === "boolean or string" ? typeof value === "boolean" || typeof value === "string"
21
27
  : typeof value === kind;
@@ -40,8 +46,9 @@ function read(body, fields) {
40
46
  }
41
47
  // What a call does not declare it cannot do anything with: to pass it over would be to let its sender think it had.
42
48
  const unknown = Object.keys(body).find(name => !Object.hasOwn(fields, name));
43
- if (unknown !== undefined)
44
- throw new BadRequest(`Unknown field: ${unknown} (this call takes: ${Object.keys(fields).join(", ")})`);
49
+ if (unknown !== undefined) {
50
+ throw new BadRequest(`Unknown field: ${unknown} (this call takes: ${Object.keys(fields).filter(name => !CARRIES.has(name)).join(", ")})`);
51
+ }
45
52
  return args;
46
53
  }
47
54
  /**
@@ -50,30 +57,43 @@ function read(body, fields) {
50
57
  * is refused, and one that is arrives as the kind it says.
51
58
  * (What is inside an object is the business of whoever it is handed to.)
52
59
  */
53
- function route(fields, handle) {
54
- return { handle: (body, connectionClosed, call) => handle(read(body, fields), connectionClosed, call) };
60
+ function route(fields, handle, how = {}) {
61
+ return { ...how, handle: (body, connectionClosed, call) => handle(read(body, fields), connectionClosed, call) };
55
62
  }
56
- /** The variables a call gives, held to what variables are (see checkedEnv): what is none is the request's fault. */
57
- function envOf(env) {
58
- if (env === undefined)
59
- return undefined;
63
+ /**
64
+ * Read what a request gave by whoever knows what it is to be: what that
65
+ * finds wrong with it is the request's fault, said in its words (`as` has
66
+ * them say which field it was).
67
+ */
68
+ function asGiven(read, as = why => why) {
60
69
  try {
61
- return checkedEnv(env);
70
+ return read();
62
71
  }
63
72
  catch (err) {
64
- throw new BadRequest(`Invalid field: ${messageOf(err)}`);
73
+ throw new BadRequest(as(messageOf(err)));
65
74
  }
66
75
  }
76
+ /** A field that names itself in what is wrong with it. */
77
+ const ofAField = (why) => `Invalid field: ${why}`;
78
+ /** The variables a call gives, held to what variables are (see checkedEnv). */
79
+ const envOf = (env) => env === undefined ? undefined : asGiven(() => checkedEnv(env), ofAField);
67
80
  /** The budget a call gives a run, held to what a budget is (see checkedBudget). */
68
- function budgetOf(budget) {
69
- if (budget === undefined)
70
- return undefined;
71
- try {
72
- return checkedBudget(budget);
73
- }
74
- catch (err) {
75
- throw new BadRequest(`Invalid field: ${messageOf(err)}`);
76
- }
81
+ const budgetOf = (budget) => budget === undefined ? undefined : asGiven(() => checkedBudget(budget), ofAField);
82
+ /** A run's time and its count of attempts, where a call gives them: held to what each is before the run is looked for. */
83
+ const timeoutOf = (timeout) => (timeout === undefined ? undefined : asGiven(() => checkedTimeout(timeout)));
84
+ const attemptsOf = (attempts) => (attempts === undefined ? undefined : asGiven(() => checkedRepairAttempts(attempts)));
85
+ /** The headers a request is to go with: names and their text. */
86
+ function headersOf(headers) {
87
+ const [name, value] = Object.entries(headers ?? {}).find(([, value]) => typeof value !== "string") ?? [];
88
+ if (name !== undefined)
89
+ throw new BadRequest(`Invalid field: headers (${name}: expected string, got ${describeJson(value)})`);
90
+ return headers;
91
+ }
92
+ /** The id a program gives to what it may want stopped: a name, so not an empty one. */
93
+ function namedBy(id) {
94
+ if (id === "")
95
+ throw new BadRequest("Invalid field: id (expected a non-empty string)");
96
+ return id;
77
97
  }
78
98
  /**
79
99
  * A request as it is written down: all of it, but for what it gives as
@@ -88,8 +108,10 @@ const asRecorded = (body) => !isJsonObject(body) || body.env == null ? body
88
108
  * not, for what says how to answer follows it.)
89
109
  */
90
110
  const HOW_SERVED = {
91
- system: "optional string", model: "optional string", thinking: "optional string", tools: "optional strings",
111
+ system: "optional string", model: "optional string", thinking: "optional string", tools: "optional strings or tools",
92
112
  skills: "optional boolean or strings", extensions: "optional boolean or string", cutOff: "optional string",
113
+ // Where the program waits to be asked for the tools of its own that the call has (see own-tools.ts).
114
+ toolsId: "optional string",
93
115
  };
94
116
  /** Whether a request carries `Authorization: Bearer <token>`, compared in constant time. */
95
117
  function isAuthorized(header, token) {
@@ -108,12 +130,8 @@ function buildRoutes({ ctx, agent, tools, workspace, workspaceAt, run, make }) {
108
130
  * or is gone — its process died, or it gave up — and no longer wants it.
109
131
  */
110
132
  const lasting = async (id, connectionClosed, work) => {
111
- if (id !== undefined) {
112
- if (id === "")
113
- throw new BadRequest("Invalid field: id (expected a non-empty string)");
114
- if (runsAskedFor.has(id))
115
- throw new BadRequest(`Duplicate run id: ${id}`);
116
- }
133
+ if (id !== undefined && runsAskedFor.has(namedBy(id)))
134
+ throw new BadRequest(`Duplicate run id: ${id}`);
117
135
  const stop = new AbortController();
118
136
  void connectionClosed.then(() => stop.abort());
119
137
  if (id !== undefined) {
@@ -129,6 +147,33 @@ function buildRoutes({ ctx, agent, tools, workspace, workspaceAt, run, make }) {
129
147
  runsAskedFor.delete(id);
130
148
  }
131
149
  };
150
+ /** The tools of the program's own that its agent calls have, and how the program is asked for each. */
151
+ const asks = createToolAsks();
152
+ /**
153
+ * Have an agent call served with the tools it named: the agent's by name,
154
+ * and the program's own — each made a way to ask the program, open for as
155
+ * long as the call lasts. (A list of names and nothing else is the
156
+ * backend's to read, as it always was.)
157
+ */
158
+ const withTools = async (tools, toolsId, call, serve) => {
159
+ const ofTheProgram = tools?.some(tool => typeof tool !== "string") ?? false;
160
+ if (!ofTheProgram) {
161
+ if (toolsId !== undefined)
162
+ throw new BadRequest("Invalid field: toolsId (the call has no tools of the program's own)");
163
+ return serve(tools, undefined);
164
+ }
165
+ if (toolsId === undefined)
166
+ throw new BadRequest("Missing field: toolsId (expected string, for a call with tools of the program's own)");
167
+ // (What is wrong with a tool as it was written, or with where its program waits, is the request's fault: found before anything is asked.)
168
+ const read = asGiven(() => toolsOf(tools), why => `Invalid field: tools (${why})`);
169
+ const way = asGiven(() => asks.open(toolsId, read.declared, call.tool));
170
+ try {
171
+ return await serve(read.names, way.tools);
172
+ }
173
+ finally {
174
+ way.close();
175
+ }
176
+ };
132
177
  /** The workspace a call is about: the directory it names, or else the one this run was started with. */
133
178
  const workspaceOf = (dir) => {
134
179
  if (dir !== undefined) {
@@ -141,12 +186,27 @@ function buildRoutes({ ctx, agent, tools, workspace, workspaceAt, run, make }) {
141
186
  return workspace;
142
187
  };
143
188
  return {
144
- "/agent/instruct": route({ prompt: "string", ...HOW_SERVED, templates: "optional boolean or strings" }, ({ prompt, ...options }, _closed, call) => agent.instruct(prompt, options, call.used)),
145
- "/agent/generate": route({ prompt: "string", schema: "object", ...HOW_SERVED }, (input, _closed, call) => agent.generate(input, call.used)),
189
+ "/agent/instruct": route({ prompt: "string", ...HOW_SERVED, templates: "optional boolean or strings" }, ({ prompt, tools, toolsId, ...options }, _closed, call) => withTools(tools, toolsId, call, (names, own) => agent.instruct(prompt, { ...options, tools: names }, call.used, own))),
190
+ "/agent/generate": route({ prompt: "string", schema: "object", ...HOW_SERVED }, ({ tools, toolsId, ...input }, _closed, call) => withTools(tools, toolsId, call, (names, own) => agent.generate({ ...input, tools: names }, call.used, own))),
191
+ // One request to a model (see model-request.ts): what it holds is read there, all of it, before anything is
192
+ // asked or counted — a conversation is no list of fields, and what is wrong with one is said by where it is.
193
+ "/agent/complete": route(Object.fromEntries(REQUEST_FIELDS.map(field => [field, "optional any"])), (request, _closed, call) => agent.complete(asGiven(() => requestOf(request), ofAField), call.used)),
194
+ // How a program's own tools are asked (see own-tools.ts): its client waits here to be told that one is
195
+ // called, or is to stop — held until there is something to tell, or the agent call is over — and says
196
+ // here what one answered.
197
+ "/agent/tool/asked": route({ of: "string" }, (b, closed) => asks.next(b.of, closed), { offTheRecord: true }),
198
+ "/agent/tool/answered": route({ of: "string", key: "string", text: "optional string", images: "optional any", error: "optional string" }, (b) => {
199
+ if ((b.text === undefined) === (b.error === undefined))
200
+ throw new BadRequest("A tool's answer is its text, or the error it failed with: one of the two");
201
+ const images = asGiven(() => imagesOf(b.images));
202
+ if (images && b.error !== undefined)
203
+ throw new BadRequest("Invalid field: images (a tool that failed has its error, and no images)");
204
+ asks.answered(b.of, b.key, b.error !== undefined ? { text: b.error, failed: true } : { text: b.text, ...(images && { images }) });
205
+ }, { offTheRecord: true }),
146
206
  "/tools/read": route({ path: "string" }, b => tools.read(b.path)),
147
207
  "/tools/write": route({ path: "string", content: "string" }, b => tools.write(b.path, b.content)),
148
208
  "/tools/shell": route({ command: "string", cwd: "optional string", timeout: "optional number", env: "optional object" }, b => tools.shell(b.command, { cwd: b.cwd, timeout: b.timeout, env: envOf(b.env) })),
149
- "/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 })),
209
+ "/tools/fetch": route({ url: "string", method: "optional string", headers: "optional object", body: "optional string" }, b => tools.fetch(b.url, { method: b.method, headers: headersOf(b.headers), body: b.body })),
150
210
  "/ctx/log": route({ message: "string", data: "optional any" }, b => ctx.log(b.message, b.data)),
151
211
  "/ctx/ready": route({ data: "optional object" }, b => ctx.ready(b.data)),
152
212
  // The state is the program's: each call that persists it hands over its current copy.
@@ -160,9 +220,9 @@ function buildRoutes({ ctx, agent, tools, workspace, workspaceAt, run, make }) {
160
220
  projectDir: "string", args: "optional object",
161
221
  timeout: "optional number", maxRepairAttempts: "optional number",
162
222
  id: "optional string", label: "optional string", workspaceDir: "optional string", env: "optional object",
163
- budget: "optional object",
164
- }, async ({ id, env, budget, ...asked }, connectionClosed, { seq }) => {
165
- const request = { ...asked, env: envOf(env), budget: budgetOf(budget) };
223
+ budget: "optional object", repairWith: "optional string",
224
+ }, async ({ id, env, budget, timeout, maxRepairAttempts, ...asked }, connectionClosed, { seq }) => {
225
+ const request = { ...asked, timeout: timeoutOf(timeout), maxRepairAttempts: attemptsOf(maxRepairAttempts), env: envOf(env), budget: budgetOf(budget) };
166
226
  return lasting(id, connectionClosed, stop => run(request, stop, seq));
167
227
  }),
168
228
  // Nor does a program make a project, or change one: its runner does, as it runs one — under the
@@ -172,9 +232,7 @@ function buildRoutes({ ctx, agent, tools, workspace, workspaceAt, run, make }) {
172
232
  // Stop a run asked for above, or a project being made. The call that asked
173
233
  // for it still gets its answer — a failed run, an error — once it is over.
174
234
  "/run/stop": route({ id: "string" }, b => {
175
- if (b.id === "")
176
- throw new BadRequest("Invalid field: id (expected a non-empty string)");
177
- const asked = runsAskedFor.get(b.id);
235
+ const asked = runsAskedFor.get(namedBy(b.id));
178
236
  if (asked)
179
237
  asked.abort();
180
238
  else {
@@ -187,6 +245,7 @@ function buildRoutes({ ctx, agent, tools, workspace, workspaceAt, run, make }) {
187
245
  "/workspace/read": route({ path: "string", dir: "optional string" }, b => workspaceOf(b.dir).read(b.path)),
188
246
  "/workspace/write": route({ path: "string", content: "string", dir: "optional string" }, b => workspaceOf(b.dir).write(b.path, b.content)),
189
247
  "/workspace/list": route({ pattern: "string", dir: "optional string" }, b => workspaceOf(b.dir).list(b.pattern)),
248
+ "/workspace/shell": route({ command: "string", dir: "optional string", cwd: "optional string", timeout: "optional number", env: "optional object" }, b => workspaceOf(b.dir).shell(b.command, { cwd: b.cwd, timeout: b.timeout, env: envOf(b.env) })),
190
249
  "/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 })),
191
250
  };
192
251
  }
@@ -202,8 +261,10 @@ export function createIPCServer(backends) {
202
261
  res.writeHead(status, json ? { "Content-Type": "application/json" } : undefined);
203
262
  res.end(body);
204
263
  };
205
- if (req.method !== "POST")
264
+ if (req.method !== "POST") {
265
+ req.resume(); // discard the body
206
266
  return reply(405, "Method not allowed");
267
+ }
207
268
  if (!isAuthorized(req.headers.authorization, backends.token)) {
208
269
  req.resume(); // discard the body
209
270
  return reply(401, "Missing or invalid IPC token");
@@ -243,7 +304,7 @@ export function createIPCServer(backends) {
243
304
  const route = req.url && Object.hasOwn(routes, req.url) ? routes[req.url] : undefined;
244
305
  if (!route)
245
306
  return reply(404, "Not found");
246
- call = backends.journal.call(req.url, asRecorded(body));
307
+ call = route.offTheRecord ? OFF_THE_RECORD : backends.journal.call(req.url, asRecorded(body));
247
308
  const result = (await route.handle(body, connectionClosed, call)) ?? null;
248
309
  const payload = JSON.stringify({ result });
249
310
  if (answerable())
@@ -1,3 +1,11 @@
1
+ /** The one field of a request that says most about it. */
2
+ /**
3
+ * The requests to a model on a record, each whole, by the position of its
4
+ * call: a journal has of each what it adds to the one before (see
5
+ * `besideTheLast` in journal.ts), and this puts them together again. (As far
6
+ * as the record has them: what was cut from a record for its size is cut.)
7
+ */
8
+ export declare function requestsWhole(records: Array<Record<string, any>>): Map<number, Record<string, unknown>>;
1
9
  /** What reports of usage — `usage` records, or what a backend said — add up to, in a few words: and nothing where there are none. */
2
10
  export declare function spentIn(usage: object[]): string;
3
11
  /**
@@ -34,6 +34,38 @@ const oneLine = (value, max) => {
34
34
  return text.length > max ? text.slice(0, max - 1) + "…" : text;
35
35
  };
36
36
  /** The one field of a request that says most about it. */
37
+ /**
38
+ * The requests to a model on a record, each whole, by the position of its
39
+ * call: a journal has of each what it adds to the one before (see
40
+ * `besideTheLast` in journal.ts), and this puts them together again. (As far
41
+ * as the record has them: what was cut from a record for its size is cut.)
42
+ */
43
+ export function requestsWhole(records) {
44
+ const whole = new Map();
45
+ let last;
46
+ for (const record of records) {
47
+ if (record.kind !== "call" || record.endpoint !== "/agent/complete" || !Array.isArray(record.request?.messages))
48
+ continue;
49
+ const { messagesBefore = 0, unchanged = [], messages, ...others } = record.request;
50
+ const request = { ...others };
51
+ for (const name of unchanged)
52
+ if (last?.[name] !== undefined)
53
+ request[name] = last[name];
54
+ request.messages = [...(last?.messages ?? []).slice(0, messagesBefore), ...messages];
55
+ whole.set(record.seq, request);
56
+ last = request;
57
+ }
58
+ return whole;
59
+ }
60
+ /** The words of a conversation's last message — or, where it has none, what it has instead. */
61
+ function lastSaid(messages) {
62
+ const content = messages.at(-1)?.content;
63
+ if (typeof content === "string")
64
+ return content;
65
+ const parts = Array.isArray(content) ? content : [];
66
+ const text = parts.find(part => typeof part?.text === "string");
67
+ return text ? String(text.text) : parts.length > 0 ? `(${String(parts[0]?.type)})` : "";
68
+ }
37
69
  function gist(request) {
38
70
  // A run that was asked for is best known by the name it was given.
39
71
  if (typeof request?.label === "string")
@@ -41,6 +73,9 @@ function gist(request) {
41
73
  // ...and a project that was asked for by its own.
42
74
  if (typeof request?.name === "string")
43
75
  return oneLine(`${request.name}: ${typeof request.prompt === "string" ? request.prompt : ""}`, 60);
76
+ // ...and a request to a model by the last that was said in the conversation it carries.
77
+ if (Array.isArray(request?.messages))
78
+ return oneLine(request.messages.length === 0 && request.messagesBefore ? "(asked again, as before)" : lastSaid(request.messages), 60);
44
79
  for (const field of ["prompt", "command", "path", "pattern", "url", "message", "projectDir", "reason"]) {
45
80
  if (request?.[field] !== undefined)
46
81
  return oneLine(request[field], 60);
@@ -54,15 +89,21 @@ export function spentIn(usage) {
54
89
  const sum = (field) => usage.reduce((total, record) => total + (Number(record[field]) || 0), 0);
55
90
  return `${sum("input") + sum("output") + sum("cacheRead") + sum("cacheWrite")} tokens $${sum("cost").toFixed(4)}`;
56
91
  }
57
- const spent = spentIn;
92
+ /** How a call, or a use of a tool, was answered — as its record of that says, where it has one. */
93
+ const howAnswered = (answer) => !answer ? "never answered"
94
+ : answer.ok ? `ok ${answer.ms}ms`
95
+ : `failed ${answer.ms}ms ${oneLine(answer.error, 60)}`;
58
96
  const usageIn = (records) => records.filter(record => record.kind === "usage");
59
97
  /**
60
98
  * What a run used, as far as its journal says. That is all of it (`inAll`
61
99
  * says so) unless the journal filled up: then it is what is on record, be
62
100
  * that nothing, and is said to be.
63
101
  */
102
+ /** What a project asked for a fix used (see the `fix` record), as a report of usage is added up: its tokens are not told apart there. */
103
+ const asUsage = (used) => ({ input: used.tokens ?? 0, cost: used.cost ?? 0 });
64
104
  function spentInAll(records, inAll = "") {
65
- const counted = spent(usageIn(records));
105
+ // (A fix is part of the run it is for, whoever made it: what a project used for one is counted with the rest.)
106
+ const counted = spentIn([...usageIn(records), ...records.filter(record => record.kind === "fix" && record.used).map(record => asUsage(record.used))]);
66
107
  if (!records.some(record => record.kind === "full"))
67
108
  return counted && counted + inAll;
68
109
  return `${counted || "no usage"} on record — the journal was full`;
@@ -85,6 +126,11 @@ function printJournal(path, records) {
85
126
  for (const record of records)
86
127
  if (record.kind === "result")
87
128
  results.set(record.seq, record);
129
+ // What a tool of the program's answered, by the call it was used for and which use of a tool that was.
130
+ const answers = new Map();
131
+ for (const record of records)
132
+ if (record.kind === "tool-result")
133
+ answers.set(`${record.seq}/${record.tool}`, record);
88
134
  const usage = usageIn(records);
89
135
  const total = spentInAll(records, " in all");
90
136
  for (const record of records) {
@@ -94,32 +140,38 @@ function printJournal(path, records) {
94
140
  console.log(`${at} attempt ${record.attempt} program ${record.program?.sha256?.slice(0, 8) ?? "missing"}`);
95
141
  break;
96
142
  case "call": {
97
- const result = results.get(record.seq);
98
- const how = !result ? "never answered"
99
- : result.ok ? `ok ${result.ms}ms`
100
- : `failed ${result.ms}ms ${oneLine(result.error, 60)}`;
101
- const used = spent(usage.filter(item => item.seq === record.seq));
143
+ const how = howAnswered(results.get(record.seq));
144
+ const used = spentIn(usage.filter(item => item.seq === record.seq));
102
145
  console.log(`${at} #${String(record.seq).padEnd(3)} ${record.endpoint.slice(1).padEnd(18)} ${gist(record.request).padEnd(60)} ${how}${used && ` ${used}`}`);
103
146
  break;
104
147
  }
148
+ case "tool-call": {
149
+ const how = howAnswered(answers.get(`${record.seq}/${record.tool}`));
150
+ console.log(`${at} #${String(record.seq).padEnd(3)} ${` tool ${record.name}`.padEnd(18)} ${oneLine(record.args, 60).padEnd(60)} ${how}`);
151
+ break;
152
+ }
105
153
  case "usage":
106
154
  // (What a call used is shown with the call.)
107
155
  if (record.for === "fix")
108
- console.log(`${at} asking for the fix used ${spent([record])}`);
156
+ console.log(`${at} asking for the fix used ${spentIn([record])}`);
109
157
  if (record.for === "generate")
110
- console.log(`${at} writing the program used ${spent([record])}`);
158
+ console.log(`${at} writing the program used ${spentIn([record])}`);
111
159
  break;
112
160
  case "budget":
113
161
  console.log(`${at} ${oneLine(record.spent, 100)}`);
114
162
  break;
115
163
  case "child":
116
- console.log(`${at} #${String(record.seq).padEnd(3)} started ${record.purpose === "validate" ? "validation" : "run"} ${record.run}`);
164
+ // (A run a call of the program's started — or, for a fix, one the run itself started.)
165
+ console.log(record.purpose === "fix"
166
+ ? `${at} the fix is asked of a project: run ${record.run}`
167
+ : `${at} #${String(record.seq).padEnd(3)} started ${record.purpose === "validate" ? "validation" : "run"} ${record.run}`);
117
168
  break;
118
169
  case "fix-request":
119
170
  console.log(`${at} fix asked for: ${oneLine(record.error, 80)}`);
120
171
  break;
121
172
  case "fix":
122
- console.log(`${at} fix ${record.ok ? "returned" : `not returned: ${oneLine(record.error, 80)}`}`);
173
+ // (What a project that was asked for it used is said with it: what pi's agent used is in the lines of `usage`.)
174
+ console.log(`${at} fix ${record.ok ? "returned" : `not returned: ${oneLine(record.error, 80)}`}${record.used ? ` ${spentIn([asUsage(record.used)])}` : ""}`);
123
175
  break;
124
176
  case "exit": {
125
177
  const how = record.timedOut ? "timed out"
package/dist/journal.d.ts CHANGED
@@ -1,14 +1,11 @@
1
- import { type AgentUsage } from "./agent-backend.js";
1
+ import { type AgentUsage, type ToolAnswer } from "./agent-backend.js";
2
2
  /** The format of the records. Bump it when a reader of older journals would be misled. */
3
3
  export declare const JOURNAL_VERSION = 1;
4
- /** Where a project keeps its journals, relative to the project — under logs/, which trama keeps out of version control. */
5
- export declare const JOURNAL_DIR: string;
6
4
  /**
7
5
  * A project's journal directory, by its one real name however the project was
8
6
  * referred to.
9
7
  */
10
8
  export declare function journalDirOf(projectDir: string): string;
11
- /** The journal of a run, in a journal directory. */
12
9
  export declare const journalIn: (dir: string, run: string) => string;
13
10
  /** The ids of the runs that have a journal in `dir`, oldest first. (A run's id starts with when it started.) */
14
11
  export declare function runsIn(dir: string): string[];
@@ -34,6 +31,13 @@ export interface RecordedCall {
34
31
  end(outcome: CallOutcome): void;
35
32
  /** What the agent behind it used — each time it was asked, and whether or not the call is answered. */
36
33
  used(usage: AgentUsage): void;
34
+ /**
35
+ * That the agent behind it called a tool of the program's (`id`: as the
36
+ * model called it) — what the program was asked. Returns what writes down
37
+ * what the program answered: a use of a tool that was not waited for has
38
+ * no answer on record, as a call nobody was left to answer has no result.
39
+ */
40
+ tool(id: string, name: string, args: unknown): (answer: ToolAnswer) => void;
37
41
  }
38
42
  export interface Journal {
39
43
  /** The run's id — the name of its journal file, without the extension. Empty if nothing is being recorded. */
@@ -55,6 +59,8 @@ export interface Journal {
55
59
  /** Stop recording. Anything noted after this is dropped. */
56
60
  close(): void;
57
61
  }
62
+ /** A call that is nobody's to look up: what carries other calls rather than being one (see ipc-server). */
63
+ export declare const OFF_THE_RECORD: RecordedCall;
58
64
  /**
59
65
  * Whether a journal is still being written: by this process, or by another
60
66
  * runner that is still there and has not yet written its ending. (A journal
package/dist/journal.js CHANGED
@@ -23,7 +23,7 @@ import { declaredUsage } from "./agent-backend.js";
23
23
  /** The format of the records. Bump it when a reader of older journals would be misled. */
24
24
  export const JOURNAL_VERSION = 1;
25
25
  /** Where a project keeps its journals, relative to the project — under logs/, which trama keeps out of version control. */
26
- export const JOURNAL_DIR = join("logs", "journal");
26
+ const JOURNAL_DIR = join("logs", "journal");
27
27
  /** The shape of a run's id: ISO timestamp (with dashes) followed by 6 hex digits. */
28
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
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. */
@@ -39,7 +39,10 @@ export function journalDirOf(projectDir) {
39
39
  return guardPath(projectDir, JOURNAL_DIR);
40
40
  }
41
41
  /** The journal of a run, in a journal directory. */
42
- export const journalIn = (dir, run) => join(dir, `${run}.jsonl`);
42
+ const EXT = ".jsonl";
43
+ export const journalIn = (dir, run) => join(dir, `${run}${EXT}`);
44
+ /** The run a file of a journal directory is named for: none, where it is not named as a journal is. */
45
+ const runNamed = (name) => (name.endsWith(EXT) ? name.slice(0, -EXT.length) : "");
43
46
  /** How a journal begins: the record of its run, which names the run and the process that writes it. */
44
47
  const FIRST_RECORD = /^\{"at":\d+,"kind":"run","v":\d+,"run":"([^"]+)","pid":(\d+)[,}]/;
45
48
  /**
@@ -103,7 +106,7 @@ function inJournal(path, run, look) {
103
106
  * at its name: it can be listed and removed in its turn, and cannot be copied.
104
107
  */
105
108
  function isJournal(dir, name) {
106
- const run = name.endsWith(".jsonl") ? name.slice(0, -".jsonl".length) : "";
109
+ const run = runNamed(name);
107
110
  if (!RUN_ID.test(run))
108
111
  return false;
109
112
  try {
@@ -128,7 +131,7 @@ export function runsIn(dir) {
128
131
  // A journal is a file. Anything else that bears a journal's name — a directory, a link, a pipe,
129
132
  // which would hold up whoever opened it — is not one; nor is a file somebody else put there.
130
133
  return entries.filter((entry) => entry.isFile() && isJournal(dir, entry.name))
131
- .map((entry) => entry.name.slice(0, -".jsonl".length)).sort();
134
+ .map((entry) => runNamed(entry.name)).sort();
132
135
  }
133
136
  /**
134
137
  * What a copy of `projectDir` is to leave out so as not to carry the project's
@@ -275,10 +278,50 @@ function recordable(endpoint, value) {
275
278
  }
276
279
  return value;
277
280
  }
281
+ /** What a request to a model may have again that it had before, beside its conversation: left out of its record where it is the same (see `besideTheLast`). */
282
+ const SAID_ONCE = ["system", "tools"];
283
+ const markOf = (value) => createHash("sha1").update(JSON.stringify(value) ?? "").digest("base64");
284
+ /**
285
+ * A request to a model, as it is written down beside the one before it on
286
+ * the same record. A program that is its own harness sends the whole
287
+ * conversation with every request: written down whole each time, a record
288
+ * grows with the square of the turns. So of a conversation that begins as
289
+ * the last one did, what is written is what it adds: `messagesBefore` says
290
+ * how many of its messages are those the request before it began with, and
291
+ * `messages` has the rest. And `unchanged` names what else it has as that
292
+ * request had it (what the model is told to be, its tools), which is then
293
+ * left out. A request that shares nothing with the one before is written
294
+ * whole, as the first is. (Read back whole by `requestsWhole`.)
295
+ */
296
+ function besideTheLast(request, last) {
297
+ if (!isJsonObject(request) || !Array.isArray(request.messages))
298
+ return { recorded: request };
299
+ const asked = {
300
+ messages: request.messages.map(markOf),
301
+ rest: Object.fromEntries(SAID_ONCE.filter(name => request[name] !== undefined).map(name => [name, markOf(request[name])])),
302
+ };
303
+ if (!last)
304
+ return { recorded: request, asked };
305
+ let same = 0;
306
+ while (same < asked.messages.length && same < last.messages.length && asked.messages[same] === last.messages[same])
307
+ same += 1;
308
+ const unchanged = SAID_ONCE.filter(name => asked.rest[name] !== undefined && asked.rest[name] === last.rest[name]);
309
+ if (same === 0 && unchanged.length === 0)
310
+ return { recorded: request, asked };
311
+ const { messages, ...others } = request;
312
+ for (const name of unchanged)
313
+ delete others[name];
314
+ // (The small fields first: a record's allowance is spent in order.)
315
+ return { recorded: { ...(same > 0 && { messagesBefore: same }), ...(unchanged.length > 0 && { unchanged }), ...others, messages: messages.slice(same) }, asked };
316
+ }
317
+ /** What is written down of a call that is not on record: nothing. */
318
+ const UNRECORDED = { end() { }, used() { }, tool: () => () => { } };
319
+ /** A call that is nobody's to look up: what carries other calls rather than being one (see ipc-server). */
320
+ export const OFF_THE_RECORD = { seq: 0, ...UNRECORDED };
278
321
  /** A journal that records nothing. Calls are still numbered, so the rest of the runner need not care. */
279
322
  function noJournal() {
280
323
  let seq = 0;
281
- return { run: "", path: "", note() { }, used() { }, call: () => ({ seq: ++seq, end() { }, used() { } }), close() { } };
324
+ return { run: "", path: "", note() { }, used() { }, call: () => ({ seq: ++seq, ...UNRECORDED }), close() { } };
282
325
  }
283
326
  /**
284
327
  * Journals this process is writing, each by what it is (see identityOf): a
@@ -429,6 +472,8 @@ export function openJournal(projectDir, keep, about) {
429
472
  return !full;
430
473
  };
431
474
  let seq = 0;
475
+ // The last request to a model that was written down: the next is written beside it.
476
+ let lastAsked;
432
477
  return {
433
478
  run,
434
479
  path,
@@ -437,9 +482,17 @@ export function openJournal(projectDir, keep, about) {
437
482
  call(endpoint, request) {
438
483
  const position = ++seq;
439
484
  if (!roomForCalls())
440
- return { seq: position, end() { }, used() { } };
485
+ return { seq: position, ...UNRECORDED };
441
486
  const arrived = performance.now();
442
- write("call", () => ({ seq: position, endpoint, request: recordable(endpoint, request) }));
487
+ // How many times the agent behind it has called a tool of the program's.
488
+ let uses = 0;
489
+ let recorded = recordable(endpoint, request);
490
+ if (endpoint === "/agent/complete") {
491
+ const beside = besideTheLast(request, lastAsked);
492
+ recorded = beside.recorded;
493
+ lastAsked = beside.asked ?? lastAsked;
494
+ }
495
+ write("call", () => ({ seq: position, endpoint, request: recorded }));
443
496
  return {
444
497
  seq: position,
445
498
  end(outcome) {
@@ -452,6 +505,19 @@ export function openJournal(projectDir, keep, about) {
452
505
  used(usage) {
453
506
  write("usage", () => ({ seq: position, ...declaredUsage(usage) }));
454
507
  },
508
+ tool(id, name, args) {
509
+ const use = ++uses;
510
+ const asked = performance.now();
511
+ write("tool-call", () => ({ seq: position, tool: use, id, name, args }));
512
+ return (answer) => write("tool-result", () => ({
513
+ seq: position,
514
+ tool: use,
515
+ ms: Math.round(performance.now() - asked),
516
+ ...(answer.failed ? { ok: false, error: answer.text } : { ok: true, result: answer.text }),
517
+ // (Of an image: what kind it is and how large — it is the model's to see, and no record's to keep.)
518
+ ...(answer.images && { images: answer.images.map(({ mimeType, data }) => ({ mimeType, bytes: Buffer.byteLength(data, "base64") })) }),
519
+ }));
520
+ },
455
521
  };
456
522
  },
457
523
  close,
@@ -0,0 +1,22 @@
1
+ import { type Entry } from "./tree.js";
2
+ import type { Changes, Given, Left, Opened, Told } from "./merge-shared.js";
3
+ /** One thing to do: at a place holding `there`, to have `want` (nothing, for what the run removed). */
4
+ export interface Deed {
5
+ path: string;
6
+ place: string;
7
+ want: Entry | undefined;
8
+ there: Entry | undefined;
9
+ }
10
+ /** Whether a deed is at a directory that is to be a directory: what it allows is all that changes there. */
11
+ export declare const staysADirectory: ({ want, there }: Pick<Deed, "want" | "there">) => boolean;
12
+ /** Whether a deed is at a directory that is to go — removed, or with something else in its place. */
13
+ export declare const goesAsADirectory: ({ want, there }: Pick<Deed, "want" | "there">) => boolean;
14
+ /**
15
+ * The deeds of a merge, a path before every path under it — and, of the parts
16
+ * of things the run left as they were, those that are not so in the project
17
+ * (`amiss`: by the path, why). What cannot be done is told as refused.
18
+ */
19
+ export declare function deedsOf({ real, before, after, seed }: Pick<Given, "real" | "before" | "after" | "seed">, { changed, isChanged, parts }: Pick<Changes, "changed" | "isChanged" | "parts">, { refused, leftAlone }: Pick<Told, "refused" | "leftAlone">, { wanted, holds }: Pick<Left, "wanted" | "holds">, { open }: Pick<Opened, "open">): {
20
+ deeds: Deed[];
21
+ amiss: Map<string, string>;
22
+ };