@trama-dev/runtime 0.6.1 → 0.7.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/dist/agent-backend.d.ts +51 -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.js +122 -56
  6. package/dist/agent.d.ts +16 -5
  7. package/dist/agent.js +22 -64
  8. package/dist/bridge-client.d.ts +6 -2
  9. package/dist/bridge-client.js +6 -1
  10. package/dist/client.d.ts +2 -2
  11. package/dist/client.js +126 -2
  12. package/dist/context.js +3 -2
  13. package/dist/history.d.ts +9 -0
  14. package/dist/history.js +98 -0
  15. package/dist/index.d.ts +1 -0
  16. package/dist/index.js +70 -41
  17. package/dist/ipc-server.d.ts +2 -3
  18. package/dist/ipc-server.js +93 -37
  19. package/dist/journal-view.js +19 -9
  20. package/dist/journal.d.ts +10 -4
  21. package/dist/journal.js +28 -6
  22. package/dist/merge-deeds.d.ts +22 -0
  23. package/dist/merge-deeds.js +201 -0
  24. package/dist/merge-doing.d.ts +9 -0
  25. package/dist/merge-doing.js +410 -0
  26. package/dist/merge-settle.d.ts +14 -0
  27. package/dist/merge-settle.js +166 -0
  28. package/dist/merge-shared.d.ts +64 -0
  29. package/dist/merge-shared.js +159 -0
  30. package/dist/merge.d.ts +150 -0
  31. package/dist/merge.js +209 -0
  32. package/dist/model-relay.js +35 -5
  33. package/dist/own-tools.d.ts +60 -0
  34. package/dist/own-tools.js +209 -0
  35. package/dist/path-guard.js +8 -6
  36. package/dist/pi-adapter.d.ts +22 -0
  37. package/dist/pi-adapter.js +147 -46
  38. package/dist/project.d.ts +31 -0
  39. package/dist/project.js +253 -0
  40. package/dist/replace-file.d.ts +13 -2
  41. package/dist/replace-file.js +23 -6
  42. package/dist/runner-backend.d.ts +43 -0
  43. package/dist/runner-backend.js +125 -0
  44. package/dist/runner-types.d.ts +8 -0
  45. package/dist/runner.d.ts +8 -123
  46. package/dist/runner.js +57 -453
  47. package/dist/schema.d.ts +38 -0
  48. package/dist/schema.js +104 -0
  49. package/dist/stopping.js +2 -3
  50. package/dist/tools.js +31 -7
  51. package/dist/tree.d.ts +33 -149
  52. package/dist/tree.js +43 -1077
  53. package/dist/types.d.ts +54 -2
  54. package/dist/workspace.d.ts +20 -0
  55. package/dist/workspace.js +76 -12
  56. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -9,12 +9,15 @@ import { onAbort, throwIfAborted } from "./abort.js";
9
9
  import { createMeter } from "./budget.js";
10
10
  import { LATEST_LOG_PATH } from "./context.js";
11
11
  import { readProjectMeta } from "./meta.js";
12
- import { loadConfig, loadProjectConfig, loadState, createBackend, validateProgram, installValidatedProgram, withTempDir, prepareProject, shownPaths, ensureProjectScaffold, RUNTIME_TYPES, runProgram as runHere, whyNotReplaceable, tagged, saysOnce, } from "./runner.js";
12
+ import { ensureProjectScaffold, loadConfig, loadProjectConfig, loadState } from "./project.js";
13
+ import { createBackend, saysOnce } from "./runner-backend.js";
14
+ import { validateProgram, installValidatedProgram, withTempDir, prepareProject, shownPaths, RUNTIME_TYPES, runProgram as runHere, whyNotReplaceable, tagged, } from "./runner.js";
13
15
  import { createWorkspace as workspaceHere, ensureWorkspaceDir } from "./workspace.js";
14
16
  import { parentBridge, remoteWorkspace, withOptions } from "./bridge-client.js";
15
17
  import { guardPath, identityOf, sameProjectAs } from "./path-guard.js";
16
18
  import { printJournals, spentIn } from "./journal-view.js";
17
19
  import { messageOf } from "./errors.js";
20
+ export { failureOf } from "./runner.js";
18
21
  // --- Running a project, making one, and reaching a workspace ---
19
22
  //
20
23
  // A program never runs another program, nor makes or changes a project: it
@@ -165,14 +168,17 @@ function projectsDir() {
165
168
  return join(homedir(), ".trama", "projects");
166
169
  }
167
170
  export function validateProjectName(name) {
168
- if (!name || /[\/\\]/.test(name) || name === "." || name === "..") {
169
- throw new Error(`Invalid project name: "${name}". Must be a simple directory name without path separators.`);
171
+ // (One line of text, too: a name is shown, in a line of its own making, wherever its project is spoken of.)
172
+ if (!name || /[\/\\\x00-\x1f\x7f]/.test(name) || name === "." || name === "..") {
173
+ throw new Error(`Invalid project name: ${JSON.stringify(name)}. Must be a simple directory name without path separators.`);
170
174
  }
171
175
  }
176
+ /** Whether a project is at a path: a directory, reached however the path reaches it. */
177
+ const isProject = (dir) => statSync(dir, { throwIfNoEntry: false })?.isDirectory() === true;
172
178
  export function resolveProject(name) {
173
179
  validateProjectName(name);
174
180
  const dir = join(projectsDir(), name);
175
- if (!existsSync(dir)) {
181
+ if (!isProject(dir)) {
176
182
  throw new Error(`Project "${name}" not found. Run \`trama list\` to see available projects.`);
177
183
  }
178
184
  return dir;
@@ -222,24 +228,24 @@ function backendFor(config, asked) {
222
228
  }
223
229
  /** Carry what the agent made beside a program into the project the program is now in, and say what that was. */
224
230
  function keepPrepared(prepared, label) {
225
- const console = shownUnder(label);
231
+ const say = shownUnder(label);
226
232
  let kept;
227
233
  try {
228
234
  kept = prepared.keep();
229
235
  }
230
236
  catch (err) {
231
237
  // The program is in the project. That what was made beside it cannot be carried over is said, and does not undo that.
232
- console.warn(`[trama] what was made beside the program, while it was written, could not be carried into the project: ${messageOf(err)}`);
238
+ say.warn(`[trama] what was made beside the program, while it was written, could not be carried into the project: ${messageOf(err)}`);
233
239
  return;
234
240
  }
235
241
  const { changed, unmerged } = kept;
236
242
  if (changed.length > 0) {
237
- console.log(`[trama] ${changed.length} path(s) made or changed beside the program, while it was written: ${shownPaths(changed)}`);
243
+ say.log(`[trama] ${changed.length} path(s) made or changed beside the program, while it was written: ${shownPaths(changed)}`);
238
244
  }
239
245
  if (unmerged.length > 0) {
240
- console.warn(`[trama] ${unmerged.length} thing(s) done while the program was written did not reach the project:`);
246
+ say.warn(`[trama] ${unmerged.length} thing(s) done while the program was written did not reach the project:`);
241
247
  for (const { path, why } of unmerged)
242
- console.warn(`[trama] ${path} — ${why}`);
248
+ say.warn(`[trama] ${path} — ${why}`);
243
249
  }
244
250
  }
245
251
  /**
@@ -283,6 +289,30 @@ const shownUnder = (label) => ({
283
289
  log: (line) => console.log(tagged(label, line)),
284
290
  warn: (line) => console.warn(tagged(label, line)),
285
291
  });
292
+ /**
293
+ * How a project comes by a program that was asked for — a new project's
294
+ * first, or one in the place of another: written off to the side, in a copy
295
+ * of the project; validated; and only then made the project's, with what
296
+ * the agent made beside it where that is kept. The project is written to
297
+ * once there is a program that works. (`written`: told of the candidate
298
+ * before it is validated, for whoever has a use for one that may yet fail.)
299
+ */
300
+ async function writeValidateInstall(projectDir, how) {
301
+ const { config, backend, stillTheProject, signal, asked } = how;
302
+ const wrote = [];
303
+ await withTempDir("trama-gen-", async (privateDir) => {
304
+ const prepared = prepareProject(projectDir, privateDir);
305
+ const candidate = await generateProgram(backend, prepared, how.ask, how.system, wrote, signal, asked.label);
306
+ stillTheProject();
307
+ how.written?.(candidate);
308
+ shownUnder(asked.label).log(how.validating);
309
+ const { validated, kept } = await validateCandidate(projectDir, backend, candidate, config, prepared, wrote, signal, asked);
310
+ stillTheProject();
311
+ installValidatedProgram(projectDir, validated, how.reason, how.prompt);
312
+ if (kept)
313
+ keepPrepared(prepared, asked.label);
314
+ });
315
+ }
286
316
  // --- Public API ---
287
317
  /** Generate a program for a new project from a prompt, validate it, and make it the project's. */
288
318
  export async function createProject(name, prompt, options) {
@@ -301,8 +331,12 @@ export async function updateProject(name, prompt, options) {
301
331
  await overBridge(bridge, "/project/update", withOptions({ name, prompt }, asked), signal);
302
332
  }
303
333
  async function createHere(name, prompt, options, asked = {}) {
304
- const console = shownUnder(asked.label);
334
+ const say = shownUnder(asked.label);
305
335
  validateProjectName(name);
336
+ // (Asked before a project is made: what is no name of a model would be written down as the project's, and no run of it could read that.)
337
+ if (options?.model !== undefined && typeof options.model !== "string") {
338
+ throw new Error(`Invalid model: ${JSON.stringify(options.model)}. A model is named in text.`);
339
+ }
306
340
  throwIfAborted(options?.signal);
307
341
  const projectDir = join(projectsDir(), name);
308
342
  let keepProjectOnFailure = false;
@@ -331,28 +365,26 @@ async function createHere(name, prompt, options, asked = {}) {
331
365
  model: config.model,
332
366
  provider: config.provider,
333
367
  };
334
- writeFileSync(join(projectDir, "meta.json"), JSON.stringify(meta, null, 2));
368
+ writeFileSync(guardPath(projectDir, "meta.json"), JSON.stringify(meta, null, 2));
335
369
  const backend = backendFor(config, asked);
336
- const wrote = [];
337
- console.log(`Generating program for "${name}"...`);
370
+ say.log(`Generating program for "${name}"...`);
338
371
  // (What the agent is given to look at is the project made here, and no other directory that is at its path by now.)
339
372
  stillTheProject();
340
- await withTempDir("trama-gen-", async (privateDir) => {
341
- const prepared = prepareProject(projectDir, privateDir);
342
- const candidate = await generateProgram(backend, prepared, `${prompt}\n\nOutput ONLY the TypeScript program. No markdown fences. No explanation.`, getSystemPrompt(config.agentChanges === "keep"), wrote, options?.signal, asked.label);
343
- stillTheProject();
373
+ await writeValidateInstall(projectDir, {
374
+ reason: "create",
375
+ prompt,
376
+ ask: `${prompt}\n\nOutput ONLY the TypeScript program. No markdown fences. No explanation.`,
377
+ system: getSystemPrompt(config.agentChanges === "keep"),
378
+ validating: "Validating program...",
379
+ config, backend, stillTheProject, signal: options?.signal, asked,
344
380
  // From here on the project is kept even if validation fails, so the
345
381
  // generated program can be inspected and fixed by hand.
346
- writeFileSync(guardPath(projectDir, "program.ts"), candidate);
347
- keepProjectOnFailure = true;
348
- console.log("Validating program...");
349
- const { validated, kept } = await validateCandidate(projectDir, backend, candidate, config, prepared, wrote, options?.signal, asked);
350
- stillTheProject();
351
- installValidatedProgram(projectDir, validated, "create", prompt);
352
- if (kept)
353
- keepPrepared(prepared, asked.label);
382
+ written: (candidate) => {
383
+ writeFileSync(guardPath(projectDir, "program.ts"), candidate);
384
+ keepProjectOnFailure = true;
385
+ },
354
386
  });
355
- console.log(`Created ${name}. Run with: trama run ${name}`);
387
+ say.log(`Created ${name}. Run with: trama run ${name}`);
356
388
  }
357
389
  catch (err) {
358
390
  if (!keepProjectOnFailure && identityOf(projectDir) === made) {
@@ -362,7 +394,7 @@ async function createHere(name, prompt, options, asked = {}) {
362
394
  }
363
395
  }
364
396
  async function updateHere(name, prompt, options, asked = {}) {
365
- const console = shownUnder(asked.label);
397
+ const say = shownUnder(asked.label);
366
398
  const projectDir = resolveProject(name);
367
399
  const unchanged = (why) => new Error(`Update failed — the program is unchanged.\n${messageOf(why)}`);
368
400
  const stillTheProject = sameProjectAs(projectDir);
@@ -383,28 +415,24 @@ async function updateHere(name, prompt, options, asked = {}) {
383
415
  const meta = readProjectMeta(projectDir);
384
416
  const config = loadProjectConfig(projectDir, meta);
385
417
  const backend = backendFor(config, asked);
386
- const wrote = [];
387
418
  const systemPrompt = getSystemPrompt(config.agentChanges === "keep") +
388
419
  `\n\nOriginal prompt: ${meta.input.prompt}` +
389
420
  `\n\nCurrent program.ts:\n${originalSource}` +
390
421
  (Object.keys(state).length > 0 ? `\n\nCurrent state:\n${JSON.stringify(state, null, 2)}` : "");
391
- console.log(`Updating "${name}"...`);
392
- await withTempDir("trama-gen-", async (privateDir) => {
393
- const prepared = prepareProject(projectDir, privateDir);
394
- const candidate = await generateProgram(backend, prepared, `${prompt}\n\nOutput the complete updated program.ts. No partial patches. No markdown fences. No explanation.`, systemPrompt, wrote, options?.signal, asked.label);
395
- stillTheProject();
396
- console.log("Validating updated program...");
397
- const { validated, kept } = await validateCandidate(projectDir, backend, candidate, config, prepared, wrote, options?.signal, asked);
398
- stillTheProject();
399
- installValidatedProgram(projectDir, validated, "update", prompt);
400
- if (kept)
401
- keepPrepared(prepared, asked.label);
422
+ say.log(`Updating "${name}"...`);
423
+ await writeValidateInstall(projectDir, {
424
+ reason: "update",
425
+ prompt,
426
+ ask: `${prompt}\n\nOutput the complete updated program.ts. No partial patches. No markdown fences. No explanation.`,
427
+ system: systemPrompt,
428
+ validating: "Validating updated program...",
429
+ config, backend, stillTheProject, signal: options?.signal, asked,
402
430
  });
403
431
  }
404
432
  catch (err) {
405
433
  throw unchanged(err);
406
434
  }
407
- console.log(`Updated ${name}. Run with: trama run ${name}`);
435
+ say.log(`Updated ${name}. Run with: trama run ${name}`);
408
436
  }
409
437
  export async function listProjects() {
410
438
  const dir = projectsDir();
@@ -412,8 +440,9 @@ export async function listProjects() {
412
440
  console.log("No projects found.");
413
441
  return;
414
442
  }
443
+ // (What can be run by its name is listed by it: a project reached through a link among them.)
415
444
  const entries = readdirSync(dir, { withFileTypes: true })
416
- .filter(e => e.isDirectory());
445
+ .filter(e => isProject(join(dir, e.name)));
417
446
  if (entries.length === 0) {
418
447
  console.log("No projects found.");
419
448
  return;
@@ -2,9 +2,8 @@ import { type Server } from "http";
2
2
  import type { Tools, Workspace } from "./types.js";
3
3
  import type { RunnerAgent } from "./agent.js";
4
4
  import type { RunContext } from "./context.js";
5
- import type { ProgramResult, RunRequest } from "./runner-types.js";
6
- import type { MakeRequest } from "./runner.js";
7
- import type { Journal } from "./journal.js";
5
+ import type { MakeRequest, ProgramResult, RunRequest } from "./runner-types.js";
6
+ import { type Journal } from "./journal.js";
8
7
  export interface IpcBackends {
9
8
  /**
10
9
  * The secret only this run's program knows. Every request must present it:
@@ -3,19 +3,24 @@
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";
6
8
  import { describeJson, isJsonObject } from "./serializable.js";
7
9
  import { checkedEnv, variableName } from "./child-process.js";
8
10
  import { checkedBudget } from "./budget.js";
11
+ import { checkedRepairAttempts, checkedTimeout } from "./project.js";
9
12
  import { messageOf } from "./errors.js";
10
13
  const MAX_IPC_BODY = 50 * 1024 * 1024; // 50 MB
11
14
  const MAX_STOPPED_AHEAD = 1024;
12
15
  /** A request the program got wrong — answered with 400 rather than 500. */
13
16
  class BadRequest extends Error {
14
17
  }
18
+ /** 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. */
19
+ const CARRIES = new Set(["toolsId"]);
15
20
  const isStrings = (value) => Array.isArray(value) && value.every(item => typeof item === "string");
16
21
  const isOfKind = (value, kind) => kind === "any" ? value !== undefined
17
22
  : kind === "object" ? isJsonObject(value)
18
- : kind === "strings" ? isStrings(value)
23
+ : kind === "strings or tools" ? Array.isArray(value) && value.every(item => typeof item === "string" || isJsonObject(item))
19
24
  : kind === "boolean or strings" ? typeof value === "boolean" || isStrings(value)
20
25
  : kind === "boolean or string" ? typeof value === "boolean" || typeof value === "string"
21
26
  : typeof value === kind;
@@ -40,8 +45,9 @@ function read(body, fields) {
40
45
  }
41
46
  // 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
47
  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(", ")})`);
48
+ if (unknown !== undefined) {
49
+ throw new BadRequest(`Unknown field: ${unknown} (this call takes: ${Object.keys(fields).filter(name => !CARRIES.has(name)).join(", ")})`);
50
+ }
45
51
  return args;
46
52
  }
47
53
  /**
@@ -50,30 +56,43 @@ function read(body, fields) {
50
56
  * is refused, and one that is arrives as the kind it says.
51
57
  * (What is inside an object is the business of whoever it is handed to.)
52
58
  */
53
- function route(fields, handle) {
54
- return { handle: (body, connectionClosed, call) => handle(read(body, fields), connectionClosed, call) };
59
+ function route(fields, handle, how = {}) {
60
+ return { ...how, handle: (body, connectionClosed, call) => handle(read(body, fields), connectionClosed, call) };
55
61
  }
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;
62
+ /**
63
+ * Read what a request gave by whoever knows what it is to be: what that
64
+ * finds wrong with it is the request's fault, said in its words (`as` has
65
+ * them say which field it was).
66
+ */
67
+ function asGiven(read, as = why => why) {
60
68
  try {
61
- return checkedEnv(env);
69
+ return read();
62
70
  }
63
71
  catch (err) {
64
- throw new BadRequest(`Invalid field: ${messageOf(err)}`);
72
+ throw new BadRequest(as(messageOf(err)));
65
73
  }
66
74
  }
75
+ /** A field that names itself in what is wrong with it. */
76
+ const ofAField = (why) => `Invalid field: ${why}`;
77
+ /** The variables a call gives, held to what variables are (see checkedEnv). */
78
+ const envOf = (env) => env === undefined ? undefined : asGiven(() => checkedEnv(env), ofAField);
67
79
  /** 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
- }
80
+ const budgetOf = (budget) => budget === undefined ? undefined : asGiven(() => checkedBudget(budget), ofAField);
81
+ /** 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. */
82
+ const timeoutOf = (timeout) => (timeout === undefined ? undefined : asGiven(() => checkedTimeout(timeout)));
83
+ const attemptsOf = (attempts) => (attempts === undefined ? undefined : asGiven(() => checkedRepairAttempts(attempts)));
84
+ /** The headers a request is to go with: names and their text. */
85
+ function headersOf(headers) {
86
+ const [name, value] = Object.entries(headers ?? {}).find(([, value]) => typeof value !== "string") ?? [];
87
+ if (name !== undefined)
88
+ throw new BadRequest(`Invalid field: headers (${name}: expected string, got ${describeJson(value)})`);
89
+ return headers;
90
+ }
91
+ /** The id a program gives to what it may want stopped: a name, so not an empty one. */
92
+ function namedBy(id) {
93
+ if (id === "")
94
+ throw new BadRequest("Invalid field: id (expected a non-empty string)");
95
+ return id;
77
96
  }
78
97
  /**
79
98
  * A request as it is written down: all of it, but for what it gives as
@@ -88,8 +107,10 @@ const asRecorded = (body) => !isJsonObject(body) || body.env == null ? body
88
107
  * not, for what says how to answer follows it.)
89
108
  */
90
109
  const HOW_SERVED = {
91
- system: "optional string", model: "optional string", thinking: "optional string", tools: "optional strings",
110
+ system: "optional string", model: "optional string", thinking: "optional string", tools: "optional strings or tools",
92
111
  skills: "optional boolean or strings", extensions: "optional boolean or string", cutOff: "optional string",
112
+ // Where the program waits to be asked for the tools of its own that the call has (see own-tools.ts).
113
+ toolsId: "optional string",
93
114
  };
94
115
  /** Whether a request carries `Authorization: Bearer <token>`, compared in constant time. */
95
116
  function isAuthorized(header, token) {
@@ -108,12 +129,8 @@ function buildRoutes({ ctx, agent, tools, workspace, workspaceAt, run, make }) {
108
129
  * or is gone — its process died, or it gave up — and no longer wants it.
109
130
  */
110
131
  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
- }
132
+ if (id !== undefined && runsAskedFor.has(namedBy(id)))
133
+ throw new BadRequest(`Duplicate run id: ${id}`);
117
134
  const stop = new AbortController();
118
135
  void connectionClosed.then(() => stop.abort());
119
136
  if (id !== undefined) {
@@ -129,6 +146,33 @@ function buildRoutes({ ctx, agent, tools, workspace, workspaceAt, run, make }) {
129
146
  runsAskedFor.delete(id);
130
147
  }
131
148
  };
149
+ /** The tools of the program's own that its agent calls have, and how the program is asked for each. */
150
+ const asks = createToolAsks();
151
+ /**
152
+ * Have an agent call served with the tools it named: the agent's by name,
153
+ * and the program's own — each made a way to ask the program, open for as
154
+ * long as the call lasts. (A list of names and nothing else is the
155
+ * backend's to read, as it always was.)
156
+ */
157
+ const withTools = async (tools, toolsId, call, serve) => {
158
+ const ofTheProgram = tools?.some(tool => typeof tool !== "string") ?? false;
159
+ if (!ofTheProgram) {
160
+ if (toolsId !== undefined)
161
+ throw new BadRequest("Invalid field: toolsId (the call has no tools of the program's own)");
162
+ return serve(tools, undefined);
163
+ }
164
+ if (toolsId === undefined)
165
+ throw new BadRequest("Missing field: toolsId (expected string, for a call with tools of the program's own)");
166
+ // (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.)
167
+ const read = asGiven(() => toolsOf(tools), why => `Invalid field: tools (${why})`);
168
+ const way = asGiven(() => asks.open(toolsId, read.declared, call.tool));
169
+ try {
170
+ return await serve(read.names, way.tools);
171
+ }
172
+ finally {
173
+ way.close();
174
+ }
175
+ };
132
176
  /** The workspace a call is about: the directory it names, or else the one this run was started with. */
133
177
  const workspaceOf = (dir) => {
134
178
  if (dir !== undefined) {
@@ -141,12 +185,24 @@ function buildRoutes({ ctx, agent, tools, workspace, workspaceAt, run, make }) {
141
185
  return workspace;
142
186
  };
143
187
  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)),
188
+ "/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))),
189
+ "/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))),
190
+ // How a program's own tools are asked (see own-tools.ts): its client waits here to be told that one is
191
+ // called, or is to stop — held until there is something to tell, or the agent call is over — and says
192
+ // here what one answered.
193
+ "/agent/tool/asked": route({ of: "string" }, (b, closed) => asks.next(b.of, closed), { offTheRecord: true }),
194
+ "/agent/tool/answered": route({ of: "string", key: "string", text: "optional string", images: "optional any", error: "optional string" }, (b) => {
195
+ if ((b.text === undefined) === (b.error === undefined))
196
+ throw new BadRequest("A tool's answer is its text, or the error it failed with: one of the two");
197
+ const images = asGiven(() => imagesOf(b.images));
198
+ if (images && b.error !== undefined)
199
+ throw new BadRequest("Invalid field: images (a tool that failed has its error, and no images)");
200
+ asks.answered(b.of, b.key, b.error !== undefined ? { text: b.error, failed: true } : { text: b.text, ...(images && { images }) });
201
+ }, { offTheRecord: true }),
146
202
  "/tools/read": route({ path: "string" }, b => tools.read(b.path)),
147
203
  "/tools/write": route({ path: "string", content: "string" }, b => tools.write(b.path, b.content)),
148
204
  "/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 })),
205
+ "/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
206
  "/ctx/log": route({ message: "string", data: "optional any" }, b => ctx.log(b.message, b.data)),
151
207
  "/ctx/ready": route({ data: "optional object" }, b => ctx.ready(b.data)),
152
208
  // The state is the program's: each call that persists it hands over its current copy.
@@ -161,8 +217,8 @@ function buildRoutes({ ctx, agent, tools, workspace, workspaceAt, run, make }) {
161
217
  timeout: "optional number", maxRepairAttempts: "optional number",
162
218
  id: "optional string", label: "optional string", workspaceDir: "optional string", env: "optional object",
163
219
  budget: "optional object",
164
- }, async ({ id, env, budget, ...asked }, connectionClosed, { seq }) => {
165
- const request = { ...asked, env: envOf(env), budget: budgetOf(budget) };
220
+ }, async ({ id, env, budget, timeout, maxRepairAttempts, ...asked }, connectionClosed, { seq }) => {
221
+ const request = { ...asked, timeout: timeoutOf(timeout), maxRepairAttempts: attemptsOf(maxRepairAttempts), env: envOf(env), budget: budgetOf(budget) };
166
222
  return lasting(id, connectionClosed, stop => run(request, stop, seq));
167
223
  }),
168
224
  // Nor does a program make a project, or change one: its runner does, as it runs one — under the
@@ -172,9 +228,7 @@ function buildRoutes({ ctx, agent, tools, workspace, workspaceAt, run, make }) {
172
228
  // Stop a run asked for above, or a project being made. The call that asked
173
229
  // for it still gets its answer — a failed run, an error — once it is over.
174
230
  "/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);
231
+ const asked = runsAskedFor.get(namedBy(b.id));
178
232
  if (asked)
179
233
  asked.abort();
180
234
  else {
@@ -202,8 +256,10 @@ export function createIPCServer(backends) {
202
256
  res.writeHead(status, json ? { "Content-Type": "application/json" } : undefined);
203
257
  res.end(body);
204
258
  };
205
- if (req.method !== "POST")
259
+ if (req.method !== "POST") {
260
+ req.resume(); // discard the body
206
261
  return reply(405, "Method not allowed");
262
+ }
207
263
  if (!isAuthorized(req.headers.authorization, backends.token)) {
208
264
  req.resume(); // discard the body
209
265
  return reply(401, "Missing or invalid IPC token");
@@ -243,7 +299,7 @@ export function createIPCServer(backends) {
243
299
  const route = req.url && Object.hasOwn(routes, req.url) ? routes[req.url] : undefined;
244
300
  if (!route)
245
301
  return reply(404, "Not found");
246
- call = backends.journal.call(req.url, asRecorded(body));
302
+ call = route.offTheRecord ? OFF_THE_RECORD : backends.journal.call(req.url, asRecorded(body));
247
303
  const result = (await route.handle(body, connectionClosed, call)) ?? null;
248
304
  const payload = JSON.stringify({ result });
249
305
  if (answerable())
@@ -54,7 +54,10 @@ export function spentIn(usage) {
54
54
  const sum = (field) => usage.reduce((total, record) => total + (Number(record[field]) || 0), 0);
55
55
  return `${sum("input") + sum("output") + sum("cacheRead") + sum("cacheWrite")} tokens $${sum("cost").toFixed(4)}`;
56
56
  }
57
- const spent = spentIn;
57
+ /** How a call, or a use of a tool, was answered — as its record of that says, where it has one. */
58
+ const howAnswered = (answer) => !answer ? "never answered"
59
+ : answer.ok ? `ok ${answer.ms}ms`
60
+ : `failed ${answer.ms}ms ${oneLine(answer.error, 60)}`;
58
61
  const usageIn = (records) => records.filter(record => record.kind === "usage");
59
62
  /**
60
63
  * What a run used, as far as its journal says. That is all of it (`inAll`
@@ -62,7 +65,7 @@ const usageIn = (records) => records.filter(record => record.kind === "usage");
62
65
  * that nothing, and is said to be.
63
66
  */
64
67
  function spentInAll(records, inAll = "") {
65
- const counted = spent(usageIn(records));
68
+ const counted = spentIn(usageIn(records));
66
69
  if (!records.some(record => record.kind === "full"))
67
70
  return counted && counted + inAll;
68
71
  return `${counted || "no usage"} on record — the journal was full`;
@@ -85,6 +88,11 @@ function printJournal(path, records) {
85
88
  for (const record of records)
86
89
  if (record.kind === "result")
87
90
  results.set(record.seq, record);
91
+ // What a tool of the program's answered, by the call it was used for and which use of a tool that was.
92
+ const answers = new Map();
93
+ for (const record of records)
94
+ if (record.kind === "tool-result")
95
+ answers.set(`${record.seq}/${record.tool}`, record);
88
96
  const usage = usageIn(records);
89
97
  const total = spentInAll(records, " in all");
90
98
  for (const record of records) {
@@ -94,20 +102,22 @@ function printJournal(path, records) {
94
102
  console.log(`${at} attempt ${record.attempt} program ${record.program?.sha256?.slice(0, 8) ?? "missing"}`);
95
103
  break;
96
104
  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));
105
+ const how = howAnswered(results.get(record.seq));
106
+ const used = spentIn(usage.filter(item => item.seq === record.seq));
102
107
  console.log(`${at} #${String(record.seq).padEnd(3)} ${record.endpoint.slice(1).padEnd(18)} ${gist(record.request).padEnd(60)} ${how}${used && ` ${used}`}`);
103
108
  break;
104
109
  }
110
+ case "tool-call": {
111
+ const how = howAnswered(answers.get(`${record.seq}/${record.tool}`));
112
+ console.log(`${at} #${String(record.seq).padEnd(3)} ${` tool ${record.name}`.padEnd(18)} ${oneLine(record.args, 60).padEnd(60)} ${how}`);
113
+ break;
114
+ }
105
115
  case "usage":
106
116
  // (What a call used is shown with the call.)
107
117
  if (record.for === "fix")
108
- console.log(`${at} asking for the fix used ${spent([record])}`);
118
+ console.log(`${at} asking for the fix used ${spentIn([record])}`);
109
119
  if (record.for === "generate")
110
- console.log(`${at} writing the program used ${spent([record])}`);
120
+ console.log(`${at} writing the program used ${spentIn([record])}`);
111
121
  break;
112
122
  case "budget":
113
123
  console.log(`${at} ${oneLine(record.spent, 100)}`);
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,14 @@ function recordable(endpoint, value) {
275
278
  }
276
279
  return value;
277
280
  }
281
+ /** What is written down of a call that is not on record: nothing. */
282
+ const UNRECORDED = { end() { }, used() { }, tool: () => () => { } };
283
+ /** A call that is nobody's to look up: what carries other calls rather than being one (see ipc-server). */
284
+ export const OFF_THE_RECORD = { seq: 0, ...UNRECORDED };
278
285
  /** A journal that records nothing. Calls are still numbered, so the rest of the runner need not care. */
279
286
  function noJournal() {
280
287
  let seq = 0;
281
- return { run: "", path: "", note() { }, used() { }, call: () => ({ seq: ++seq, end() { }, used() { } }), close() { } };
288
+ return { run: "", path: "", note() { }, used() { }, call: () => ({ seq: ++seq, ...UNRECORDED }), close() { } };
282
289
  }
283
290
  /**
284
291
  * Journals this process is writing, each by what it is (see identityOf): a
@@ -437,8 +444,10 @@ export function openJournal(projectDir, keep, about) {
437
444
  call(endpoint, request) {
438
445
  const position = ++seq;
439
446
  if (!roomForCalls())
440
- return { seq: position, end() { }, used() { } };
447
+ return { seq: position, ...UNRECORDED };
441
448
  const arrived = performance.now();
449
+ // How many times the agent behind it has called a tool of the program's.
450
+ let uses = 0;
442
451
  write("call", () => ({ seq: position, endpoint, request: recordable(endpoint, request) }));
443
452
  return {
444
453
  seq: position,
@@ -452,6 +461,19 @@ export function openJournal(projectDir, keep, about) {
452
461
  used(usage) {
453
462
  write("usage", () => ({ seq: position, ...declaredUsage(usage) }));
454
463
  },
464
+ tool(id, name, args) {
465
+ const use = ++uses;
466
+ const asked = performance.now();
467
+ write("tool-call", () => ({ seq: position, tool: use, id, name, args }));
468
+ return (answer) => write("tool-result", () => ({
469
+ seq: position,
470
+ tool: use,
471
+ ms: Math.round(performance.now() - asked),
472
+ ...(answer.failed ? { ok: false, error: answer.text } : { ok: true, result: answer.text }),
473
+ // (Of an image: what kind it is and how large — it is the model's to see, and no record's to keep.)
474
+ ...(answer.images && { images: answer.images.map(({ mimeType, data }) => ({ mimeType, bytes: Buffer.byteLength(data, "base64") })) }),
475
+ }));
476
+ },
455
477
  };
456
478
  },
457
479
  close,