@trama-dev/runtime 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,5 @@
1
+ /** How long what was asked to stop gets to do so: a process group after SIGTERM, before it is sent SIGKILL; a backend's call after it was cancelled, before the run goes on without it. */
2
+ export declare const KILL_GRACE_MS = 5000;
1
3
  /**
2
4
  * Send a signal to a whole process group. Children spawned with `detached: true`
3
5
  * lead their own group, so this also reaches whatever they started in the background.
@@ -7,6 +9,32 @@
7
9
  * yet to be reaped; to wait for such a group is to wait for nothing.)
8
10
  */
9
11
  export declare function signalGroup(pgid: number, signal: NodeJS.Signals | 0): boolean;
12
+ /**
13
+ * What Linux says of its processes — each its id, its parent's and its
14
+ * group's — in files: there is nothing to start to learn it, and nothing that
15
+ * may be missing (a container often has no `ps`). Nothing, where there are no
16
+ * such files — or where they are not of the processes whoever asks is among:
17
+ * a container may have another's files before it, and a number read there
18
+ * is nobody's here. So the files are taken at their word only where they say
19
+ * of the asker (`self`) what it knows of itself: whose child it is (`parent`).
20
+ *
21
+ * It runs in two processes, here and in the watchdog, which is handed its
22
+ * text: it may use nothing but its arguments. So may the two that follow.
23
+ */
24
+ export declare function processesOnFile(fs: Pick<typeof import("fs"), "readdirSync" | "readFileSync">, self: number, parent: number): number[][];
25
+ /**
26
+ * The process groups of everything a process has under it, as the system has
27
+ * them at this moment — but for the group it leads, and this process's own.
28
+ * A process may start what it starts in groups of their own (pi does so with
29
+ * what an agent runs, and with an MCP server): the group it leads does not
30
+ * hold those, and once it is gone nothing says any more whose they were.
31
+ * (What has cut itself loose of its parent by then is nobody's to find; and
32
+ * where the system cannot be asked — it has no such files, and no `ps` that
33
+ * answers in a while — nothing is found.) Whoever asks is not held while a
34
+ * `ps` answers: it is asked of what is still there, and is to be stopped
35
+ * after.
36
+ */
37
+ export declare function groupsUnder(pid: number): Promise<number[]>;
10
38
  /**
11
39
  * Make sure there is a watchdog before anything is started that would need
12
40
  * one. Throws if one cannot be started: running without it would mean leaving
@@ -15,9 +43,12 @@ export declare function signalGroup(pgid: number, signal: NodeJS.Signals | 0): b
15
43
  export declare function requireWatchdog(): void;
16
44
  /**
17
45
  * Register a process group this process started: if this process ends before
18
- * the returned function is called, the group is stopped.
46
+ * the returned function is called, the group is stopped. `withWhatIsUnder`:
47
+ * and so is what its leader has under it in groups of their own — for a
48
+ * process whose children are nobody's to keep (an agent's host; not a
49
+ * program, which may start what is to outlive it).
19
50
  */
20
- export declare function stopWithThisProcess(pgid: number): () => void;
51
+ export declare function stopWithThisProcess(pgid: number, withWhatIsUnder?: boolean): () => void;
21
52
  /**
22
53
  * Register a temp directory this process created: if this process ends before
23
54
  * the returned function is called, the directory is removed — once the groups
package/dist/stopping.js CHANGED
@@ -22,10 +22,10 @@
22
22
  //
23
23
  // Nothing here listens for a signal or for the process exiting: the process
24
24
  // that hosts a runner keeps its own way of handling both.
25
- import { spawn } from "child_process";
25
+ import { execFile, spawn } from "child_process";
26
26
  import * as fs from "fs";
27
- /** How long a process group gets to exit after SIGTERM before it is sent SIGKILL. */
28
- const KILL_GRACE_MS = 5000;
27
+ /** How long what was asked to stop gets to do so: a process group after SIGTERM, before it is sent SIGKILL; a backend's call after it was cancelled, before the run goes on without it. */
28
+ export const KILL_GRACE_MS = 5000;
29
29
  const STOP_POLL_MS = 25;
30
30
  /** How long a group is waited for after SIGKILL before it is given up on. */
31
31
  const KILL_SETTLE_MS = 1000;
@@ -46,6 +46,89 @@ export function signalGroup(pgid, signal) {
46
46
  return false;
47
47
  }
48
48
  }
49
+ /** How long the system is given to say what processes there are. */
50
+ const PROCESSES_ASKED_MS = 2_000;
51
+ /**
52
+ * What Linux says of its processes — each its id, its parent's and its
53
+ * group's — in files: there is nothing to start to learn it, and nothing that
54
+ * may be missing (a container often has no `ps`). Nothing, where there are no
55
+ * such files — or where they are not of the processes whoever asks is among:
56
+ * a container may have another's files before it, and a number read there
57
+ * is nobody's here. So the files are taken at their word only where they say
58
+ * of the asker (`self`) what it knows of itself: whose child it is (`parent`).
59
+ *
60
+ * It runs in two processes, here and in the watchdog, which is handed its
61
+ * text: it may use nothing but its arguments. So may the two that follow.
62
+ */
63
+ export function processesOnFile(fs, self, parent) {
64
+ const rows = [];
65
+ let names;
66
+ try {
67
+ names = fs.readdirSync("/proc");
68
+ }
69
+ catch {
70
+ return rows;
71
+ }
72
+ for (const name of names) {
73
+ if (!/^[0-9]+$/.test(name))
74
+ continue;
75
+ try {
76
+ // "id (name) state parent group …": a name may hold anything, a ")" and a space among it —
77
+ // what follows the last ")" is what is told apart by spaces.
78
+ const stat = fs.readFileSync("/proc/" + name + "/stat", "utf8");
79
+ const after = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
80
+ const row = [Number(name), Number(after[1]), Number(after[2])];
81
+ if (row.every(Number.isInteger))
82
+ rows.push(row);
83
+ }
84
+ catch { /* gone since it was listed */ }
85
+ }
86
+ return rows.some(row => row[0] === self && row[1] === parent) ? rows : [];
87
+ }
88
+ /** The same, of what `ps -Ao pid=,ppid=,pgid=` printed. */
89
+ function processesListed(listed) {
90
+ return listed.split("\n").map(line => line.trim().split(/\s+/).map(Number)).filter(row => row.length === 3 && row.every(Number.isInteger));
91
+ }
92
+ /**
93
+ * Of such rows, the process groups of everything one process has under it —
94
+ * but for the group it leads, and that of whoever asks (`self`).
95
+ */
96
+ function groupsAmong(rows, pid, self) {
97
+ const under = new Set([pid]);
98
+ for (let grew = true; grew;) {
99
+ grew = false;
100
+ for (const row of rows) {
101
+ if (under.has(row[1]) && !under.has(row[0])) {
102
+ under.add(row[0]);
103
+ grew = true;
104
+ }
105
+ }
106
+ }
107
+ const own = rows.find(row => row[0] === self);
108
+ const groups = new Set(rows.filter(row => under.has(row[0])).map(row => row[2]));
109
+ return [...groups].filter(group => group !== pid && !(own && group === own[2]));
110
+ }
111
+ /**
112
+ * The process groups of everything a process has under it, as the system has
113
+ * them at this moment — but for the group it leads, and this process's own.
114
+ * A process may start what it starts in groups of their own (pi does so with
115
+ * what an agent runs, and with an MCP server): the group it leads does not
116
+ * hold those, and once it is gone nothing says any more whose they were.
117
+ * (What has cut itself loose of its parent by then is nobody's to find; and
118
+ * where the system cannot be asked — it has no such files, and no `ps` that
119
+ * answers in a while — nothing is found.) Whoever asks is not held while a
120
+ * `ps` answers: it is asked of what is still there, and is to be stopped
121
+ * after.
122
+ */
123
+ export async function groupsUnder(pid) {
124
+ let rows = processesOnFile(fs, process.pid, process.ppid);
125
+ if (rows.length === 0) {
126
+ rows = processesListed(await new Promise((resolve) => {
127
+ execFile("ps", ["-Ao", "pid=,ppid=,pgid="], { encoding: "utf-8", timeout: PROCESSES_ASKED_MS, killSignal: "SIGKILL" }, (err, stdout) => resolve(err ? "" : stdout));
128
+ }));
129
+ }
130
+ return groupsAmong(rows, pid, process.pid);
131
+ }
49
132
  // --- Removing what was made ---
50
133
  /**
51
134
  * Remove a directory tree, whatever has been done to it since it was made. A
@@ -83,10 +166,24 @@ function removeTree(fs, dir) {
83
166
  // the runner had already asked to stop is not asked a second time.
84
167
  const WATCHDOG = `
85
168
  const fs = require("fs");
169
+ const { execFileSync } = require("child_process");
86
170
  ${removeTree}
87
171
  ${signalGroup}
88
- const { grace, settle, poll } = JSON.parse(process.argv[1]);
89
- const lists = { g: new Set(), d: new Set(), asked: new Set() };
172
+ ${processesOnFile}
173
+ ${processesListed}
174
+ ${groupsAmong}
175
+ const { grace, settle, poll, asking } = JSON.parse(process.argv[1]);
176
+ const lists = { g: new Set(), d: new Set(), asked: new Set(), u: new Set() };
177
+ // What the system says of its processes: by its files, or by ps — which this process can wait for.
178
+ const processes = () => {
179
+ const rows = processesOnFile(fs, process.pid, process.ppid);
180
+ if (rows.length > 0) return rows;
181
+ try {
182
+ return processesListed(execFileSync("ps", ["-Ao", "pid=,ppid=,pgid="], { encoding: "utf8", timeout: asking, killSignal: "SIGKILL", stdio: ["ignore", "pipe", "ignore"] }));
183
+ } catch {
184
+ return [];
185
+ }
186
+ };
90
187
  const alive = (pgid) => signalGroup(pgid, 0);
91
188
  const signal = signalGroup;
92
189
 
@@ -109,7 +206,12 @@ const takeOver = () => {
109
206
  for (const dir of lists.d) removeTree(fs, dir);
110
207
  process.exit(0);
111
208
  };
112
- let left = [...lists.g].filter(alive);
209
+ // A group that is to be stopped with what is under it: what it started in groups of their own is
210
+ // looked for now, while it is there to be asked of — it may not be able to end them itself.
211
+ const led = [...lists.u].filter(alive);
212
+ const rows = led.length > 0 ? processes() : [];
213
+ const below = led.flatMap((pid) => groupsAmong(rows, pid, process.pid));
214
+ let left = [...new Set([...lists.g, ...below])].filter(alive);
113
215
  for (const pgid of left) { if (!lists.asked.has(pgid)) signal(pgid, "SIGTERM"); }
114
216
  let deadline = performance.now() + grace;
115
217
  let killed = false;
@@ -131,7 +233,7 @@ process.stdin.on("close", takeOver);
131
233
  process.stdin.on("error", takeOver);
132
234
  `;
133
235
  /** What the watchdog has been told about and not yet told to forget. */
134
- const listed = { g: new Set(), d: new Set(), asked: new Set() };
236
+ const listed = { g: new Set(), d: new Set(), asked: new Set(), u: new Set() };
135
237
  let watchdog = null;
136
238
  const tell = (to, op, list, item) => {
137
239
  to.stdin?.write(JSON.stringify([op, list, item]) + "\n");
@@ -146,7 +248,7 @@ function startWatchdog() {
146
248
  return watchdog;
147
249
  let child;
148
250
  try {
149
- const timings = { grace: KILL_GRACE_MS, settle: KILL_SETTLE_MS, poll: STOP_POLL_MS };
251
+ const timings = { grace: KILL_GRACE_MS, settle: KILL_SETTLE_MS, poll: STOP_POLL_MS, asking: PROCESSES_ASKED_MS };
150
252
  // It is this file's own few lines, and is to start whatever this process was started with:
151
253
  // not with what NODE_OPTIONS would have it load first, or wait for (a debugger, say).
152
254
  const { NODE_OPTIONS: _options, ...env } = process.env;
@@ -170,7 +272,7 @@ function startWatchdog() {
170
272
  child.unref();
171
273
  child.stdin?.unref?.();
172
274
  watchdog = child;
173
- for (const name of ["g", "d", "asked"]) {
275
+ for (const name of ["g", "d", "asked", "u"]) {
174
276
  for (const item of listed[name])
175
277
  tell(child, "+", name, item);
176
278
  }
@@ -200,13 +302,19 @@ function delist(from, item) {
200
302
  }
201
303
  /**
202
304
  * Register a process group this process started: if this process ends before
203
- * the returned function is called, the group is stopped.
305
+ * the returned function is called, the group is stopped. `withWhatIsUnder`:
306
+ * and so is what its leader has under it in groups of their own — for a
307
+ * process whose children are nobody's to keep (an agent's host; not a
308
+ * program, which may start what is to outlive it).
204
309
  */
205
- export function stopWithThisProcess(pgid) {
310
+ export function stopWithThisProcess(pgid, withWhatIsUnder = false) {
206
311
  enlist("g", pgid);
312
+ if (withWhatIsUnder)
313
+ enlist("u", pgid);
207
314
  return () => {
208
315
  delist("g", pgid);
209
316
  delist("asked", pgid);
317
+ delist("u", pgid);
210
318
  };
211
319
  }
212
320
  /**
package/dist/tools.d.ts CHANGED
@@ -3,4 +3,5 @@ export interface ToolsWithCleanup extends Tools {
3
3
  /** Stop every shell command still running, and anything they left in the background. Resolves when they are gone. */
4
4
  stopActiveShells(): Promise<void>;
5
5
  }
6
- export declare function createTools(projectDir: string, signal?: AbortSignal): ToolsWithCleanup;
6
+ /** `env` is the variables the run was started with, over the runner's own: every shell command has them. */
7
+ export declare function createTools(projectDir: string, signal?: AbortSignal, env?: Record<string, string>): ToolsWithCleanup;
package/dist/tools.js CHANGED
@@ -1,14 +1,38 @@
1
1
  import { spawn } from "child_process";
2
- import { readFileSync, writeFileSync } from "fs";
3
- import { resolve, dirname } from "path";
2
+ import { accessSync, constants, readFileSync, statSync, writeFileSync } from "fs";
3
+ import { delimiter, resolve, dirname } from "path";
4
4
  import { guardPath, makeDirsIn, projectAt, realRootOf } from "./path-guard.js";
5
- import { superviseChild } from "./child-process.js";
5
+ import { checkedEnv, superviseChild } from "./child-process.js";
6
6
  import { messageOf } from "./errors.js";
7
7
  import { signalGroup, stopGroups, stopWithThisProcess } from "./stopping.js";
8
8
  const MAX_FETCH_BODY = 10 * 1024 * 1024; // 10 MB
9
9
  const DEFAULT_SHELL_TIMEOUT = 30_000;
10
10
  const GROUP_SWEEP_MS = 250;
11
- export function createTools(projectDir, signal) {
11
+ /**
12
+ * The shell a command is run by: the `sh` that `path` — the runner's own
13
+ * PATH — leads to from where the command runs. Not the one a PATH given for
14
+ * the command would lead to: that PATH is for what the command runs, and one
15
+ * without a shell on it, or with something else of the name, is the
16
+ * command's affair. (Where none is found, the system is left to say so. A
17
+ * runner that has no PATH at all has the system's own, as it would have for
18
+ * anything it started.)
19
+ */
20
+ function shellOn(path, cwd) {
21
+ if (process.platform === "win32")
22
+ return "sh";
23
+ for (const dir of (path ?? "/usr/bin:/bin").split(delimiter)) {
24
+ const at = resolve(cwd, dir, "sh");
25
+ try {
26
+ accessSync(at, constants.X_OK);
27
+ if (statSync(at).isFile())
28
+ return at;
29
+ }
30
+ catch { /* not there, or not to be run: the next */ }
31
+ }
32
+ return "sh";
33
+ }
34
+ /** `env` is the variables the run was started with, over the runner's own: every shell command has them. */
35
+ export function createTools(projectDir, signal, env) {
12
36
  const normalizedProjectDir = resolve(projectDir);
13
37
  // Each shell command leads its own process group, so background processes it
14
38
  // starts stay killable after the shell itself exits. A group is tracked from
@@ -28,7 +52,8 @@ export function createTools(projectDir, signal) {
28
52
  // and update still do when a program calls them. (This covers tools.shell
29
53
  // only: what the agent backend runs on its own takes its environment from
30
54
  // this process.)
31
- const { TRAMA_PORT: _port, TRAMA_INIT: _init, ...shellEnv } = process.env;
55
+ const { TRAMA_PORT: _port, TRAMA_INIT: _init, ...runnersOwn } = process.env;
56
+ const shellEnv = { ...runnersOwn, ...env };
32
57
  const stopSweeping = () => {
33
58
  if (sweeper)
34
59
  clearInterval(sweeper);
@@ -88,13 +113,27 @@ export function createTools(projectDir, signal) {
88
113
  },
89
114
  async shell(command, options = {}) {
90
115
  const cwd = options.cwd ? guardPath(normalizedProjectDir, options.cwd) : normalizedProjectDir;
91
- const child = spawn("sh", ["-c", command], {
92
- cwd,
93
- env: shellEnv,
94
- // Nothing is ever sent to a command: one that reads its input finds it at an end, rather than waiting.
95
- stdio: ["ignore", "pipe", "pipe"],
96
- detached: true,
97
- });
116
+ const env = options.env == null ? shellEnv : { ...shellEnv, ...checkedEnv(options.env) };
117
+ // The shell is started from where the runner finds it, and is `sh` to itself and to whoever it tells of
118
+ // itself, as it was when the system did the finding: in "$0", in what it says of a command it cannot find,
119
+ // and in what is said of a shell that could not be started.
120
+ const shell = shellOn(runnersOwn.PATH, cwd);
121
+ const notStarted = (why) => ({ exitCode: 1, stdout: "", stderr: messageOf(why).replace(`spawn ${shell} `, "spawn sh ") });
122
+ let child;
123
+ try {
124
+ child = spawn(shell, ["-c", command], {
125
+ cwd,
126
+ env,
127
+ argv0: "sh",
128
+ // Nothing is ever sent to a command: one that reads its input finds it at an end, rather than waiting.
129
+ stdio: ["ignore", "pipe", "pipe"],
130
+ detached: true,
131
+ });
132
+ }
133
+ catch (spawnError) {
134
+ // Refused by the system outright (more than it will hand a process, say) — a result, like any failure to start.
135
+ return notStarted(spawnError);
136
+ }
98
137
  const pgid = child.pid;
99
138
  if (pgid) {
100
139
  groups.set(pgid, { shellExited: false, forget: stopWithThisProcess(pgid) });
@@ -111,7 +150,7 @@ export function createTools(projectDir, signal) {
111
150
  }
112
151
  catch (spawnError) {
113
152
  // Failed to start (e.g. cwd does not exist) — a result, not an exception.
114
- return { exitCode: 1, stdout: "", stderr: messageOf(spawnError) };
153
+ return notStarted(spawnError);
115
154
  }
116
155
  },
117
156
  async fetch(url, options = {}) {
package/dist/tree.d.ts CHANGED
@@ -34,8 +34,15 @@ export type Entry =
34
34
  export type Tree = Map<string, Entry>;
35
35
  /** What is at a path — the path itself, not what a link there leads to. Undefined if nothing is. */
36
36
  export declare function entryAt(path: string): Entry | undefined;
37
- /** What a directory is and holds. The directory must be there, and all of it readable. */
38
- export declare function readTree(dir: string): Tree;
37
+ /** The paths at which two readings of a directory differ, a path before every path under it. */
38
+ export declare function differences(before: Tree, after: Tree): string[];
39
+ /**
40
+ * What a directory is and holds. The directory must be there, and all of it
41
+ * readable — or, with `opening`, to be made so: a directory that may not be
42
+ * looked into is opened for the reading, and left allowing what it allowed.
43
+ * (That is for a directory that is the reader's own to open: a copy.)
44
+ */
45
+ export declare function readTree(dir: string, opening?: boolean): Tree;
39
46
  /**
40
47
  * Make `toDir` — an empty directory — what `fromDir` is: allowing what it
41
48
  * allows and holding what it holds. Returns what that was: the directory, and
package/dist/tree.js CHANGED
@@ -64,6 +64,10 @@ function same(a, b) {
64
64
  return a.text === b.text;
65
65
  return false;
66
66
  }
67
+ /** The paths at which two readings of a directory differ, a path before every path under it. */
68
+ export function differences(before, after) {
69
+ return [...new Set([...before.keys(), ...after.keys()])].filter((path) => !same(before.get(path), after.get(path))).sort(inOrder);
70
+ }
67
71
  /** The names in a directory. One that is not text cannot be told from another, or looked up again: it throws. */
68
72
  function namesIn(dir) {
69
73
  return readdirSync(dir, "buffer").map((raw) => {
@@ -143,10 +147,28 @@ function sameBytes(one, other) {
143
147
  closeSync(a);
144
148
  }
145
149
  }
146
- /** What a directory is and holds. The directory must be there, and all of it readable. */
147
- export function readTree(dir) {
150
+ /**
151
+ * What a directory is and holds. The directory must be there, and all of it
152
+ * readable — or, with `opening`, to be made so: a directory that may not be
153
+ * looked into is opened for the reading, and left allowing what it allowed.
154
+ * (That is for a directory that is the reader's own to open: a copy.)
155
+ */
156
+ export function readTree(dir, opening = false) {
148
157
  const tree = new Map();
149
- walk(realRootOf(dir), (path, entry) => { tree.set(path, entry); });
158
+ const opened = [];
159
+ try {
160
+ walk(realRootOf(dir), (path, entry, at) => {
161
+ tree.set(path, entry);
162
+ if (opening && entry.kind === "dir" && (entry.mode & 0o500) !== 0o500) {
163
+ chmodSync(at, entry.mode | 0o500);
164
+ opened.push({ at, mode: entry.mode });
165
+ }
166
+ });
167
+ }
168
+ finally {
169
+ for (const { at, mode } of opened.reverse())
170
+ chmodSync(at, mode);
171
+ }
150
172
  return tree;
151
173
  }
152
174
  /**
package/dist/types.d.ts CHANGED
@@ -52,24 +52,105 @@ export interface Ctx {
52
52
  */
53
53
  yield(reason: string): Promise<never>;
54
54
  }
55
+ /** How much a model is to think before it answers. */
56
+ export type Thinking = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
57
+ /**
58
+ * What a call may say about how it is served. Each is honoured or the call
59
+ * fails: nothing asked for here is quietly left out. (But by an extension
60
+ * the call asked for itself: what one does to a session is its to do.)
61
+ */
62
+ export interface AgentOptions {
63
+ /** Instructions for this call, on top of the agent's own. */
64
+ system?: string;
65
+ /** The model that serves this call, as "provider/model" — in place of the project's. */
66
+ model?: string;
67
+ /** How much the model is to think. A level pi does not have for the model is an error. */
68
+ thinking?: Thinking;
69
+ /**
70
+ * The agent's tools for this call: exactly the ones named. `[]` for none —
71
+ * the answer is then made from the prompt alone, and nothing is read, run
72
+ * or written. Without it the agent has its own choice of them (read, bash,
73
+ * edit, write); pi has more than it chooses (grep, find, ls). A name the
74
+ * agent has no tool for is an error.
75
+ */
76
+ tools?: string[];
77
+ /**
78
+ * The skills the agent has for this call: `true` for all that pi finds
79
+ * for the user and for the project (its `.pi/skills` among them; of two
80
+ * by one name, the project's) — or the ones named. Without it, none. A
81
+ * name pi has no skill by is an error, and so is a call whose agent could
82
+ * not read them: pi tells a model of its skills only where it has `read`
83
+ * or `bash`. A prompt of `instruct` that begins with "/skill:name " is
84
+ * then that skill's text, and after it what followed the space. (A prompt
85
+ * of `generate` is text, whatever it begins with.)
86
+ */
87
+ skills?: boolean | string[];
88
+ /**
89
+ * The prompt templates the call has: `true` for all that pi finds for the
90
+ * user and for the project (its `.pi/prompts`; of two by one name, the
91
+ * project's) — or the ones named. A prompt that begins with "/name" is
92
+ * then the template of that name, with what follows as its arguments:
93
+ * split as a shell splits words — quotes taken off, a line break or a run
94
+ * of spaces become one space. A name pi has no template by is an error.
95
+ * (For `instruct` only: what tells the model how a typed answer is to be
96
+ * written follows the prompt, and a template is free to leave that out.)
97
+ */
98
+ templates?: boolean | string[];
99
+ /**
100
+ * Whether the agent has pi's extensions: `true` for the user's — those of
101
+ * the user's pi directory and settings, and the ones pi has built in, its
102
+ * MCP servers among them — or "project" for the project's own as well (its
103
+ * `.pi/extensions`, the MCP servers it names). With them come the tools
104
+ * they add, the commands a prompt of `instruct` can then begin with
105
+ * ("/name"), and what they do to a session, the skills and templates they
106
+ * bring among it. One pi has something against is an error. A call with
107
+ * extensions is served in a process of its own: what an extension gets
108
+ * wrong ends that call, and nothing else of the run. Without any of
109
+ * `skills`, `templates` and `extensions`, a prompt is the text it is,
110
+ * whatever it begins with.
111
+ */
112
+ extensions?: boolean | "project";
113
+ /**
114
+ * What to make of an answer that was cut off at the model's output limit.
115
+ * "fail", as it is without this: the call fails — the answer is not whole.
116
+ * "keep": the call returns what there was of it, as if it were the answer
117
+ * (and still fails where there was none: a reply cut off before its first
118
+ * word) — for a call whose work is what the agent did with its tools, and
119
+ * whose closing words matter little. (The agent goes no further than the
120
+ * reply that was cut off: where that was leading up to more work, the work
121
+ * was not done. A typed answer that was cut off is seldom whole.)
122
+ */
123
+ cutOff?: "fail" | "keep";
124
+ }
125
+ /**
126
+ * The shape of a typed answer, field by field. A field is "string", "number"
127
+ * or "boolean" — what follows a ":" describes it to the model — or an object
128
+ * of such fields, or a list, written as the shape of its items in brackets:
129
+ *
130
+ * { summary: "string", passed: "boolean: did every test pass",
131
+ * failures: [{ test: "string", line: "number" }], tags: ["string"] }
132
+ */
133
+ export type Schema = {
134
+ readonly [field: string]: SchemaField;
135
+ };
136
+ /** (A list has one element: the shape of every item.) */
137
+ export type SchemaField = string | Schema | readonly SchemaField[];
55
138
  export interface Agent {
56
139
  /**
57
140
  * Instruct the pi-coding-agent to perform a task. Returns plain text.
58
- * The underlying agent may autonomously use its built-in tools
59
- * (bash, file read/write/edit) to fulfill the instruction.
141
+ * The underlying agent may autonomously use its tools to fulfill the
142
+ * instruction.
60
143
  */
61
- instruct(prompt: string, options?: {
62
- system?: string;
63
- }): Promise<string>;
144
+ instruct(prompt: string, options?: AgentOptions): Promise<string>;
64
145
  /**
65
- * Structured LLM call. Returns typed object matching the provided schema.
66
- * Supported schema value prefixes: "string", "number", "boolean".
67
- * Retries once on parse/validation failure.
146
+ * The same, with the answer as a typed object matching the schema: the
147
+ * agent may use its tools to find out what it is asked, and answers in
148
+ * that shape: the fields of the schema and no others, each as declared.
149
+ * Asks once more on a parse/validation failure.
68
150
  */
69
- generate<T>(input: {
151
+ generate<T>(input: Omit<AgentOptions, "templates"> & {
70
152
  prompt: string;
71
- schema: Record<string, string>;
72
- system?: string;
153
+ schema: Schema;
73
154
  }): Promise<T>;
74
155
  }
75
156
  export interface ShellResult {
@@ -82,10 +163,17 @@ export interface Tools {
82
163
  read(path: string): Promise<string>;
83
164
  /** Write a file. Path is relative to project dir. */
84
165
  write(path: string, content: string): Promise<void>;
85
- /** Execute a shell command. Returns structured result. */
166
+ /**
167
+ * Execute a shell command. Returns structured result.
168
+ * `env` is variables for the command, over those it has anyway: the
169
+ * runner's, and those the run was started with. (What a program sets in
170
+ * its own process.env is the program's, and is not handed on unless it is
171
+ * given here: `env: process.env` hands on all of it.)
172
+ */
86
173
  shell(command: string, options?: {
87
174
  cwd?: string;
88
175
  timeout?: number;
176
+ env?: Record<string, string | undefined>;
89
177
  }): Promise<ShellResult>;
90
178
  /** HTTP fetch. Returns response body as string. */
91
179
  fetch(url: string, options?: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trama-dev/runtime",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {