@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
package/dist/types.d.ts CHANGED
@@ -54,6 +54,55 @@ export interface Ctx {
54
54
  }
55
55
  /** How much a model is to think before it answers. */
56
56
  export type Thinking = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
57
+ /**
58
+ * A tool of the program's own, for the agent of one call: a function of the
59
+ * program's, which the model can call by name. It is run where the program
60
+ * runs — it has the program's variables, and can do what the program can.
61
+ */
62
+ export interface AgentTool {
63
+ /** As the model calls it: letters, digits, "_" and "-". Not the name of another tool the agent has. */
64
+ name: string;
65
+ /** What it is for. This, and what its parameters are called, is all the model is told of it. */
66
+ description: string;
67
+ /**
68
+ * What it is called with, written as the shape of a typed answer is (see
69
+ * `Schema`): `{ id: "string: the order's id", lines: ["number"] }`. The
70
+ * model's call is held to it before `run` is called: every field there,
71
+ * each of its kind, and no other. Without it, the tool is called with `{}`.
72
+ */
73
+ parameters?: Schema;
74
+ /**
75
+ * It may run while another tool does. Without it, the tools a model calls
76
+ * in one reply are run one after the other, in the order it called them —
77
+ * the agent's own among them, where one of the program's is called beside.
78
+ */
79
+ parallel?: boolean;
80
+ /**
81
+ * What it returns is the end of the agent's work, and the answer of the
82
+ * call: the model is not asked again. For a call whose answer is to be
83
+ * something the model hands over, held to a shape, rather than its last
84
+ * words — `{ name: "verdict", ends: true, parameters: { ok: "boolean" }, … }`.
85
+ * Not where it throws: the model then reads why, and may call it again.
86
+ * (And not where the model called, in the same reply, a tool that ends
87
+ * nothing: it is then asked again, as after any tool.)
88
+ */
89
+ ends?: boolean;
90
+ /**
91
+ * Called each time the model calls the tool, with its arguments. What it
92
+ * returns is the model's to read: a string as it is, anything else as
93
+ * JSON says it (nothing at all as "Done."). Bytes — a Buffer, a
94
+ * Uint8Array — are an image for the model to see: PNG, JPEG, GIF or WebP,
95
+ * told by how they begin; a list with bytes in it is each of those as an
96
+ * image, and the rest as words. What it throws is the model's
97
+ * to read too, as the tool's failure — and not the failure of the call,
98
+ * which goes on. `signal` says when the call it is run for is to go no
99
+ * further (it was cancelled, or its budget is spent): what it returns
100
+ * after that is nobody's.
101
+ */
102
+ run(args: any, context: {
103
+ signal: AbortSignal;
104
+ }): unknown;
105
+ }
57
106
  /**
58
107
  * What a call may say about how it is served. Each is honoured or the call
59
108
  * fails: nothing asked for here is quietly left out. (But by an extension
@@ -71,9 +120,12 @@ export interface AgentOptions {
71
120
  * the answer is then made from the prompt alone, and nothing is read, run
72
121
  * or written. Without it the agent has its own choice of them (read, bash,
73
122
  * edit, write); pi has more than it chooses (grep, find, ls). A name the
74
- * agent has no tool for is an error.
123
+ * agent has no tool for is an error. A tool of the program's own is given
124
+ * as itself (see `AgentTool`), beside the names — and is then the agent's
125
+ * like any: a call that names tools of its own and nothing else has those
126
+ * and no other.
75
127
  */
76
- tools?: string[];
128
+ tools?: Array<string | AgentTool>;
77
129
  /**
78
130
  * The skills the agent has for this call: `true` for all that pi finds
79
131
  * for the user and for the project (its `.pi/skills` among them; of two
@@ -152,6 +204,123 @@ export interface Agent {
152
204
  prompt: string;
153
205
  schema: Schema;
154
206
  }): Promise<T>;
207
+ /**
208
+ * Ask the model once, and have its one reply: no agent is at work, no
209
+ * tool is run, and nothing is asked again. For a program that is its own
210
+ * harness — it keeps the conversation, runs the tools the model calls,
211
+ * and decides when to ask again and when to stop:
212
+ *
213
+ * const messages: ModelMessage[] = [{ role: "user", content: "…" }];
214
+ * for (;;) {
215
+ * const reply = await agent.complete({ system, messages, tools });
216
+ * messages.push(reply); // a reply goes back as it came
217
+ * if (reply.stopReason !== "toolUse") break; // read why it stopped: see ModelReply
218
+ * for (const part of reply.content) {
219
+ * if (part.type !== "toolCall") continue;
220
+ * messages.push({ role: "toolResult", toolCallId: part.id, toolName: part.name, content: await mine(part) });
221
+ * }
222
+ * }
223
+ *
224
+ * Each is a call to a run's budget, counted for what its reply used: a
225
+ * loop is better held by a cap on tokens or cost than on calls.
226
+ */
227
+ complete(request: ModelRequest): Promise<ModelReply>;
228
+ }
229
+ /** A part of a message that is text. */
230
+ export interface TextPart {
231
+ type: "text";
232
+ text: string;
233
+ }
234
+ /** An image in a message: its kind — image/png, image/jpeg, image/gif or image/webp — and its bytes in base64. */
235
+ export interface ImagePart {
236
+ type: "image";
237
+ mimeType: string;
238
+ data: string;
239
+ }
240
+ /** What a model thought before it answered, where it shows that. */
241
+ export interface ThinkingPart {
242
+ type: "thinking";
243
+ thinking: string;
244
+ }
245
+ /**
246
+ * A model's call of a tool it was told of: to be answered by a message of
247
+ * role "toolResult" with its `id`, before the model is asked again. Its
248
+ * arguments are as the model wrote them — held to nothing: where they were
249
+ * no JSON at all, `argumentsError` says so, and they are `{}`.
250
+ */
251
+ export interface ToolCallPart {
252
+ type: "toolCall";
253
+ id: string;
254
+ name: string;
255
+ arguments: Record<string, unknown>;
256
+ argumentsError?: string;
257
+ }
258
+ /**
259
+ * A model's reply to one request. What is declared here is what a program
260
+ * may read. There is more on it — what its provider wants to see again when
261
+ * the conversation goes on: so a reply goes back into `messages` as it came,
262
+ * all of it. (It is plain data, and can be kept in state.)
263
+ */
264
+ export interface ModelReply {
265
+ role: "assistant";
266
+ content: Array<TextPart | ThinkingPart | ToolCallPart>;
267
+ /**
268
+ * Why the model stopped. "stop": it has answered. "toolUse": it called
269
+ * tools, and waits for what they say. "length": it was cut off at its
270
+ * output limit — what there is of the reply is here. "error": the
271
+ * provider failed, and `errorMessage` says how; whether to ask again is
272
+ * the program's to decide.
273
+ */
274
+ stopReason: "stop" | "toolUse" | "length" | "error";
275
+ errorMessage?: string;
276
+ /** The model that answered, as its provider names it. */
277
+ model: string;
278
+ /** What the reply used: tokens read and written, from a cache and to one, and what pi's price list makes of them in US dollars. */
279
+ usage: {
280
+ input: number;
281
+ output: number;
282
+ cacheRead: number;
283
+ cacheWrite: number;
284
+ cost: {
285
+ total: number;
286
+ };
287
+ };
288
+ [carried: string]: unknown;
289
+ }
290
+ /** A message of the conversation a model is sent: the user's, a reply as it came, or what a tool the model called said. */
291
+ export type ModelMessage = {
292
+ role: "user";
293
+ content: string | Array<TextPart | ImagePart>;
294
+ } | ModelReply | {
295
+ role: "toolResult";
296
+ toolCallId: string;
297
+ toolName: string;
298
+ content: string | Array<TextPart | ImagePart>;
299
+ isError?: boolean;
300
+ };
301
+ export interface ModelRequest {
302
+ /** The conversation so far, oldest first. It is the program's to keep: nothing of it is remembered between requests. */
303
+ messages: ModelMessage[];
304
+ /** What the model is told to be, before the conversation. */
305
+ system?: string;
306
+ /**
307
+ * The tools the model may call, each declared as a tool of the program's
308
+ * is to an agent (see `AgentTool`): its name, description and parameters.
309
+ * Nothing runs one — the model's call comes back in the reply, and the
310
+ * program does with it what it will; so a tool's `run` may be left out.
311
+ */
312
+ tools?: Array<Pick<AgentTool, "name" | "description" | "parameters"> & Partial<AgentTool>>;
313
+ /** The model, as "provider/model". Without it, the project's — which is then one pi has, or the call fails. */
314
+ model?: string;
315
+ /** How much the model is to think. A level the model has not got is an error. */
316
+ thinking?: Thinking;
317
+ /** The most the reply may come to, in tokens. */
318
+ maxTokens?: number;
319
+ temperature?: number;
320
+ /** "none": the model answers without calling a tool, though it is told of them. */
321
+ toolChoice?: "auto" | "none";
322
+ /** How long the provider is waited for, in milliseconds: five minutes without it. */
323
+ timeout?: number;
155
324
  }
156
325
  export interface ShellResult {
157
326
  exitCode: number;
@@ -206,4 +375,15 @@ export interface Workspace {
206
375
  expect?: number;
207
376
  timeout?: number;
208
377
  }): Promise<ObserveResult>;
378
+ /**
379
+ * Execute a shell command in the workspace: as `tools.shell`, but it
380
+ * begins in the workspace's directory — or, with `cwd`, in a directory
381
+ * of it. For a program whose work is in a directory that is not its own:
382
+ * one that was handed another project to work on, say.
383
+ */
384
+ shell(command: string, options?: {
385
+ cwd?: string;
386
+ timeout?: number;
387
+ env?: Record<string, string | undefined>;
388
+ }): Promise<ShellResult>;
209
389
  }
@@ -1,4 +1,25 @@
1
1
  import type { Workspace } from "./types.js";
2
+ import { type ToolsWithCleanup } from "./tools.js";
3
+ /**
4
+ * Read a simple glob pattern for matching relative paths: `*` is any run of
5
+ * characters within a segment, `?` one of them, `**` any run of characters
6
+ * at all, and `**` with its slash any number of whole segments, none included
7
+ * (so `**` + `/*.md` matches at the root too). Every other character is itself.
8
+ *
9
+ * The pattern is taken apart at its operators, and each piece between them
10
+ * is itself, character for character — there is no text a pattern could
11
+ * hold that is mistaken for an operator.
12
+ *
13
+ * A path is held against it step by step, and no step is taken twice: where
14
+ * the pattern is at a given place and the path at a given place, whether the
15
+ * rest matches is found once. (A pattern handed to the system's own matcher
16
+ * of expressions is tried every way round instead, and one that says "any
17
+ * segments" a dozen times is not done with a path of some depth in any time
18
+ * a caller would wait — which, here, is everyone the runner serves.)
19
+ */
20
+ export declare function compileGlob(pattern: string): {
21
+ test(path: string): boolean;
22
+ };
2
23
  /**
3
24
  * Make sure a workspace directory exists where `workspaceDir` leads, and
4
25
  * return its resolved path. Unlike a project, a workspace is nothing but its
@@ -6,4 +27,10 @@ import type { Workspace } from "./types.js";
6
27
  * is not there yet.
7
28
  */
8
29
  export declare function ensureWorkspaceDir(workspaceDir: string): string;
9
- export declare function createWorkspace(workspaceDir: string, signal?: AbortSignal): Workspace;
30
+ /**
31
+ * The workspace in a directory. `shellIn`: the shell its commands are run by
32
+ * — a run's own, so that they are the run's to stop, and have its variables.
33
+ * Without it the workspace has a shell of its own: commands it started end
34
+ * with this process.
35
+ */
36
+ export declare function createWorkspace(workspaceDir: string, signal?: AbortSignal, shellIn?: ToolsWithCleanup["shellIn"]): Workspace;
package/dist/workspace.js CHANGED
@@ -1,24 +1,88 @@
1
1
  import { readFileSync, mkdirSync, readdirSync, statSync } from "fs";
2
2
  import { resolve, relative, sep } from "path";
3
+ import { createTools } from "./tools.js";
3
4
  import { onAbort } from "./abort.js";
4
5
  import { guardPath, realRootOf } from "./path-guard.js";
5
6
  import { isStagedName, stageFile } from "./replace-file.js";
6
7
  const OBSERVE_POLL_MS = 250;
7
8
  /**
8
- * Compile a simple glob pattern for matching relative paths: `*` is any run
9
- * of characters within a segment, `?` one of them, `**` any run of characters
9
+ * Read a simple glob pattern for matching relative paths: `*` is any run of
10
+ * characters within a segment, `?` one of them, `**` any run of characters
10
11
  * at all, and `**` with its slash any number of whole segments, none included
11
12
  * (so `**` + `/*.md` matches at the root too). Every other character is itself.
12
13
  *
13
- * The pattern is taken apart at its operators and each piece between them
14
- * escaped whole — nothing is put into the pattern on the way, so there is no
15
- * text a pattern could hold that is mistaken for an operator.
14
+ * The pattern is taken apart at its operators, and each piece between them
15
+ * is itself, character for character — there is no text a pattern could
16
+ * hold that is mistaken for an operator.
17
+ *
18
+ * A path is held against it step by step, and no step is taken twice: where
19
+ * the pattern is at a given place and the path at a given place, whether the
20
+ * rest matches is found once. (A pattern handed to the system's own matcher
21
+ * of expressions is tried every way round instead, and one that says "any
22
+ * segments" a dozen times is not done with a path of some depth in any time
23
+ * a caller would wait — which, here, is everyone the runner serves.)
16
24
  */
17
- function compileGlob(pattern) {
18
- const literal = (text) => text.replace(/[.+^${}()|[\]\\]/g, "\\$&");
19
- const within = (segment) => segment.split("?").map((part) => part.split("*").map(literal).join("[^/]*")).join("[^/]");
20
- const regex = pattern.split("**/").map((part) => part.split("**").map(within).join(".*")).join("(?:.+/)?");
21
- return new RegExp(`^${regex}$`);
25
+ export function compileGlob(pattern) {
26
+ const steps = [];
27
+ pattern.split("**/").forEach((part, whole) => {
28
+ if (whole > 0)
29
+ steps.push("whole segments");
30
+ part.split("**").forEach((within, any) => {
31
+ if (any > 0)
32
+ steps.push("anything");
33
+ within.split("?").forEach((run, one) => {
34
+ if (one > 0)
35
+ steps.push("one of a segment");
36
+ run.split("*").forEach((text, some) => {
37
+ if (some > 0)
38
+ steps.push("some of a segment");
39
+ // (Unit by unit, as text is counted: one `?` is one of them, as it was to the matcher before this.)
40
+ for (let at = 0; at < text.length; at += 1)
41
+ steps.push({ one: text[at] });
42
+ });
43
+ });
44
+ });
45
+ });
46
+ return {
47
+ test(characters) {
48
+ /** Whether the rest matches, from a step of the pattern and a place in the path: found once. */
49
+ const found = new Map();
50
+ const rest = (step, at) => {
51
+ if (step === steps.length)
52
+ return at === characters.length;
53
+ const key = step * (characters.length + 1) + at;
54
+ const known = found.get(key);
55
+ if (known !== undefined)
56
+ return known;
57
+ const is = steps[step];
58
+ let matches = false;
59
+ if (typeof is === "object")
60
+ matches = characters[at] === is.one && rest(step + 1, at + 1);
61
+ else if (is === "one of a segment")
62
+ matches = at < characters.length && characters[at] !== "/" && rest(step + 1, at + 1);
63
+ else if (is === "some of a segment") {
64
+ for (let to = at; !matches; to += 1) {
65
+ matches = rest(step + 1, to);
66
+ if (to >= characters.length || characters[to] === "/")
67
+ break;
68
+ }
69
+ }
70
+ else if (is === "anything") {
71
+ for (let to = at; to <= characters.length && !matches; to += 1)
72
+ matches = rest(step + 1, to);
73
+ }
74
+ else {
75
+ // None — or what ends in a slash and has something before it.
76
+ matches = rest(step + 1, at);
77
+ for (let to = at + 2; to <= characters.length && !matches; to += 1)
78
+ matches = characters[to - 1] === "/" && rest(step + 1, to);
79
+ }
80
+ found.set(key, matches);
81
+ return matches;
82
+ };
83
+ return rest(0, 0);
84
+ },
85
+ };
22
86
  }
23
87
  /**
24
88
  * A pattern with no glob operators names exactly one artifact.
@@ -78,6 +142,7 @@ function listFiles(dir, root, found, byLink = false) {
78
142
  }
79
143
  }
80
144
  }
145
+ const observeAborted = () => new Error("workspace.observe() aborted");
81
146
  /** Resolve after `ms`, or reject as soon as `signal` aborts. */
82
147
  function sleep(ms, signal) {
83
148
  return new Promise((resolve, reject) => {
@@ -87,7 +152,7 @@ function sleep(ms, signal) {
87
152
  }, ms);
88
153
  const offAbort = onAbort(signal, () => {
89
154
  clearTimeout(timer);
90
- reject(new Error("workspace.observe() aborted"));
155
+ reject(observeAborted());
91
156
  });
92
157
  });
93
158
  }
@@ -102,8 +167,15 @@ export function ensureWorkspaceDir(workspaceDir) {
102
167
  mkdirSync(realRootOf(root), { recursive: true });
103
168
  return root;
104
169
  }
105
- export function createWorkspace(workspaceDir, signal) {
170
+ /**
171
+ * The workspace in a directory. `shellIn`: the shell its commands are run by
172
+ * — a run's own, so that they are the run's to stop, and have its variables.
173
+ * Without it the workspace has a shell of its own: commands it started end
174
+ * with this process.
175
+ */
176
+ export function createWorkspace(workspaceDir, signal, shellIn) {
106
177
  const root = ensureWorkspaceDir(workspaceDir);
178
+ let ownShell;
107
179
  /** All artifact paths matching a glob, sorted. */
108
180
  const listMatching = (pattern) => {
109
181
  const re = compileGlob(pattern);
@@ -140,6 +212,9 @@ export function createWorkspace(workspaceDir, signal) {
140
212
  async list(pattern) {
141
213
  return listMatching(pattern);
142
214
  },
215
+ async shell(command, options) {
216
+ return (shellIn ?? (ownShell ??= createTools(root, signal)).shellIn)(root, command, options);
217
+ },
143
218
  async observe(pattern, options = {}) {
144
219
  const { expect, timeout } = options;
145
220
  if (expect !== undefined && (!Number.isInteger(expect) || expect < 1)) {
@@ -180,7 +255,7 @@ export function createWorkspace(workspaceDir, signal) {
180
255
  const startTime = performance.now();
181
256
  while (true) {
182
257
  if (signal?.aborted)
183
- throw new Error("workspace.observe() aborted");
258
+ throw observeAborted();
184
259
  if (single && isDirectory()) {
185
260
  throw Object.assign(new Error(`EISDIR: illegal operation on a directory, read '${pattern}'`), { code: "EISDIR" });
186
261
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trama-dev/runtime",
3
- "version": "0.6.1",
3
+ "version": "0.8.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -37,7 +37,7 @@
37
37
  "node": ">=22.19.0"
38
38
  },
39
39
  "dependencies": {
40
- "@earendil-works/pi-coding-agent": "1.5.2",
40
+ "@earendil-works/pi-coding-agent": "1.6.0",
41
41
  "tsx": "4.23.15"
42
42
  }
43
43
  }