pi-durable-bot 0.8.7 → 0.8.9

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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,41 @@
2
2
 
3
3
  What changed in each version of pi-durable-bot (Pots). To upgrade, run `npm install -g pi-durable-bot@latest`, then `pots service restart`.
4
4
 
5
+ ## 0.8.9 (2026-11-23)
6
+
7
+ The bot spends less context and fewer tokens. A child's end no longer wakes it, and a routine can start a child at its time without waking it. The main conversation keeps its prompt cache for an hour where the model has that. The bot hands children the work that runs commands and keeps the discussion itself.
8
+
9
+ ### Changed
10
+ - **A child wakes the bot itself.** Before, every end of a child became a wake of the main agent, also when the child had found nothing worth telling. Now the end wakes no one: the child's final message is kept, also across restarts, and the `task` tool's new `result` action gives it, or why the child could not answer; a result too long for a tool's output is saved whole to a file in `workspace/child-results/`. A child wakes the main agent with `pots wake`, which comes as a wake from that child, for the place the child works for: Pots sets `POTS_CHILD` to the child's ID in its commands, so a script's `--from` never makes a wake look like a child's. When the main agent hands work to a child, its prompt says to write in the brief that this is delegated work, so the child must tell it when it is done; a routine's child decides for itself. A child's brief now starts with its ID. A child's answer is kept also when a stop comes right after it. The prompts of the main agent and of children say so.
11
+ - **What goes to a child, and what stays with the bot.** Before, the prompt said that children think deeper than the main agent, so it should hand them as much of the work as it can, also questions that need careful thought. Now it says: work that runs commands, looks things up, or takes more than a minute or two goes to a child, so the bot stays free to answer people quickly; discussion and judgment that depend on the conversation stay with the bot; and the bot checks what a child reports before it tells people.
12
+ - **The main conversation keeps its prompt cache for an hour.** The main agent is often woken minutes to an hour apart, and a provider's default cache entry lasts about 5 minutes, so each such wake wrote its whole context to the cache again. Now the main agent's requests ask for the provider's long entry (1 hour at Anthropic) on models that pi knows one for, today Anthropic's Claude models; other models keep the provider's default, as before. A long entry costs more to write (at Anthropic, twice the input price instead of 1.25 times), so children, which rarely pause, and memory passes and the judge, which run once, ask for the short one, also with pi's `PI_CACHE_RETENTION=long`. Prompt cache warming times its warms by the long entry's lifetime. On four bots' requests of seven days, the long entry would have made the main conversations 19 to 47% cheaper, and children 14 to 29% dearer. A model in pi's `models.json` with `promptCache.long` gets the long entry too.
13
+ - **The bot looks in on long child work about every 10 minutes.** Before, its prompt said only that it can set itself a wake to look in on a child. Now it says that while a child does long work for a person, the bot sets itself a wake about every 10 minutes to see how it is going, tell the person briefly, and set the next one until the child has ended.
14
+ - **Bare URLs next to other text.** The prompt's facts about chat apps now say that a bare URL touching other text, such as Chinese characters or punctuation, often does not become a link or takes that text in, and to leave a space on both sides or write `[text](url)`.
15
+ - **At the upgrade**, a child that still works keeps working and ends quietly. An end that 0.8.8 had already handed to the main agent still arrives as before; an end it had decided but not handed over yet is kept, not handed over. The prompts of the main agent and of children change, so each bot's prompt cache is written once more after the upgrade. The crash-test files `crash-before-child-report` and `crash-after-child-report` are gone.
16
+
17
+ ### Added
18
+ - **`pots routine add <name> ... --child "<brief>"`** starts a child at each time with the brief, for no place, with the bot's model and thinking `xhigh`, without waking the bot; the child decides itself whether to wake it. The routine's time is skipped while a child it started still works, also when a message made that child work again just before the time; the child keeps the routine's name, so this holds also after a crash and after the run is dropped. A child that cannot start, for example at `settings.maxChildren`, counts as a failed run: it wakes the bot once, until one starts. `pots routine list` shows which child each run started. Existing routines do not change.
19
+
20
+ ## 0.8.8 (2026-11-21)
21
+
22
+ Pots runs on pi 1.6.0: GPT-6.2 Astra and GPT-6.2 Sol, with GPT-6.2 Sol as the default model. Images that any tool gives the bot are fitted to the model's limits, as in the pi command line, and each MCP server is a namespace of its own in code mode. After this upgrade, a bot's database cannot go back to 0.8.7.
23
+
24
+ ### Added
25
+ - **GPT-6.2 Astra and GPT-6.2 Sol**, on `openai`, `azure` and `openai-codex` (the ChatGPT login). With the ChatGPT login, Sol has a 500K context window and Astra 272K; Azure gives both 1.05M. Neither has thinking `off` or `minimal`; a level a model does not have becomes the nearest one it has.
26
+ - **Images from every tool are fitted to the model.** Before, only `read` shrank its images, so a large image from an MCP tool or from a script's `image()` could make the provider refuse the request. Now pi's image fitting fits every image a tool returns to the limits of the conversation's model before it is stored, for the main agent and its children, as the pi command line does. An image that cannot be prepared is left out with a note.
27
+
28
+ ### Changed
29
+ - **After the upgrade, a bot's database cannot go back to 0.8.7.** pi 1.6.0 stores the bot's tool calls and model requests in a newer format, which 0.8.7 and older do not read correctly. If you may want to go back, stop Pots and copy each bot's `bot.sqlite` before you upgrade.
30
+ - **pi 1.6.0** (was 1.5.2). What the bot gains:
31
+ - **Models.** A request that fails with `Connection closed.` or a socket error such as `ECONNRESET`, `EPIPE` or `ETIMEDOUT` is tried again. With the ChatGPT login, a request that reaches the connection's 60-minute limit during the answer, for example during long thinking, is tried again on a new connection; GPT-6.2 now gets prompt cache hits on the system prompt; a change of thinking level no longer loses the prompt cache on GPT-6 models; and a model's `maxTokens` is used. OpenAI no longer refuses a request whose tool schema has a part without a `type`; such a tool is sent as not strict. Mistral Large 4 tool calls no longer stall for minutes. OpenAI-compatible providers other than OpenAI get system messages with the `system` role, so Groq's Qwen models no longer fail with `400 Unexpected message role`. The Qwen Token Plan providers have new models and use the current gateways.
32
+ - **llama.cpp.** pi's llama.cpp provider connects to `http://127.0.0.1:9931` by default, the current default port of llama-server, instead of 8080. A llama.cpp classifier that takes images, such as Clef with its `mmproj`, now gets the images of `models.classify()`.
33
+ - **Tools.** `read` no longer keeps a note that the model takes no images, which stayed in the conversation after a change to a model that takes them. `bash` shows the end of its output when the output ends in one very long line (over about 100KB, such as a `grep` match in a minified file); before, it showed nothing.
34
+ - **undici 8.12.4** (was 8.12.3), for six security advisories.
35
+ - **`find` path patterns start at the folder searched** (pi 1.6.0). A pattern with `/` now matches from the folder `find` searches, as the `glob` of `grep` does: searching `src`, `slack/*.ts` no longer finds `src/channels/slack/sdk.ts`, and `**/slack/*.ts` finds it at any depth. A pattern without `/` still matches file names at any depth, and a pattern that starts with `./` now works.
36
+ - **Each MCP server is a namespace of its own in code mode.** The `codemode` section lists each server as `mcp__<server>`, with pi's one-line summary of it (the first line of its `description` in `mcp.json`, or else of the instructions the server sends, at most 250 characters), also before it connects. `describeNamespace("mcp__<server>")` gives the whole description, the instructions and the server's tools, and `searchTools()` searches them. A server whose every tool is `hidden` is not named. For a bot with MCP servers, the `codemode` section changes, so its prompt cache is written once more after the upgrade.
37
+ - **Children follow the bot's MCP servers.** A child has the main agent's tools without the channel actions and `task`, and keeps them as that difference, so a server added to `mcp.json` while a child works reaches the child too, and a server removed there goes from it. Children that 0.8.7 started are changed this way when the bot starts. The order of their tools changes, so each such child's prompt cache is written once more.
38
+ - **The default model is `openai/gpt-6.2-sol`** (was `openai/gpt-6.1-sol`), as pi's default for `openai`. A bot whose `bot.json` has no `model` uses it after the restart.
39
+
5
40
  ## 0.8.7 (2026-11-19)
6
41
 
7
42
  A bot can make and edit images with the ChatGPT subscription signed in to pi, as the Codex CLI does, without an OpenRouter key.
package/README.md CHANGED
@@ -100,7 +100,7 @@ On Linux with a systemd user manager (a desktop, or a server with lingering, whi
100
100
 
101
101
  ### 👥 Its own helpers
102
102
 
103
- Longer work does not keep it from talking. With its `task` tool the bot starts **children**: agents that work in the background with `read`, `write`, `edit`, `bash`, `grep`, `find`, `screen` and `codemode`, without the channel actions and `task`, on a brief it writes for them. It answers the person first, hands the work to a child, and stays free for the next message. A child starts from an empty conversation and its brief, so the bot's own context stays small; it sees the bot's memory index as it was when it started. When a child ends, done, failed or with a question for a person, its final message comes back to the bot as a wake, exactly once, also across crashes and restarts; the bot passes on what matters, and sends the child the answer to its question. While a child works for a place, new messages there go to the bot, so it can pass them on. A child takes the bot's messages only between its steps, so a message sent while it is in a long command waits until the command ends. Wherever the bot sees a child that works (its timed and fallback wakes, the wakes from the child's place, the task tool's list and the answer to a message it sends), it sees what the child does now: the tool call it is in and for how long, the start of the command, its last line of output and how old that is, and how many of the bot's messages wait for it. When a command hangs, the bot can interrupt the child's current tool calls: the child goes on with its work so far, sees that they were aborted, and takes the messages that waited. A stopped child reports nothing and does nothing more, also when the process dies in the middle of the stop.
103
+ Longer work does not keep it from talking. With its `task` tool the bot starts **children**: agents that work in the background with `read`, `write`, `edit`, `bash`, `grep`, `find`, `screen` and `codemode`, without the channel actions and `task`, on a brief it writes for them. It answers the person first, hands the work to a child, and stays free for the next message. A child starts from an empty conversation and its brief, so the bot's own context stays small; it sees the bot's memory index as it was when it started. When a child ends, its final message is kept, also across crashes and restarts, and wakes no one: the bot reads it with the `task` tool when it wants, and looks in on longer work with its own timed wakes. A child wakes the bot itself with `pots wake`: when the bot hands it work, the brief says to tell the bot when it is done, and a child can also wake it with a question for a person. The bot checks what a child reports, passes on what matters, and sends the child the answer. While a child works for a place, new messages there go to the bot, so it can pass them on. A child takes the bot's messages only between its steps, so a message sent while it is in a long command waits until the command ends. Wherever the bot sees a child that works (its timed and fallback wakes, the wakes from the child's place, the task tool's list and the answer to a message it sends), it sees what the child does now: the tool call it is in and for how long, the start of the command, its last line of output and how old that is, and how many of the bot's messages wait for it. When a command hangs, the bot can interrupt the child's current tool calls: the child goes on with its work so far, sees that they were aborted, and takes the messages that waited. A stopped child does nothing more, also when the process dies in the middle of the stop.
104
104
 
105
105
  The bot chooses each child's model and thinking level when it starts it: any model signed in on this computer, and any of pi's levels. A child it starts without a choice has the bot's `model`, also after a change in `bot.json`, and thinking `xhigh`. A child keeps the model chosen for it and its level for its whole life, also across restarts; a level the model does not have becomes the nearest one it has, as in pi. A model that is unknown or not signed in is refused before the child starts, with the reason, so the bot can take another or ask you to run `pots login`. By default the bot talks at the `thinking` of `bot.json` (`medium`), and its children do the work at `xhigh` or `max`. Which model does which work is yours to say: the bot asks at its first start and keeps your answer in its `AGENTS.md`. `settings.maxChildren` (50 by default) caps how many work at once. `pots children` lists them, and `pots children --stop <id>` or `--stop-all` stops them.
106
106
 
@@ -126,14 +126,14 @@ It promises to come back, and it does. A timed wake (`pots wake`) wakes it once,
126
126
 
127
127
  | Command | What it does |
128
128
  |---|---|
129
- | `pots routine add <name> (--every <duration> \| --cron "<expr>") (--note "<text>" \| --run "<command>") [--timeout <duration>]` | Add a routine, or replace the one with that name. Names are letters, digits, `-` and `_`; durations are as in `pots wake --in`: `90s`, `30m`, `2h`, `1d` |
129
+ | `pots routine add <name> (--every <duration> \| --cron "<expr>") (--note "<text>" \| --run "<command>" \| --child "<brief>") [--timeout <duration>]` | Add a routine, or replace the one with that name. Names are letters, digits, `-` and `_`; durations are as in `pots wake --in`: `90s`, `30m`, `2h`, `1d` |
130
130
  | `pots routine list` | Each routine's schedule, what it does, its next time and its last run; and the fallback check-in |
131
131
  | `pots routine remove <name>` | Remove a routine |
132
132
 
133
- - `--note` wakes the bot with the note at each time. `--run` makes Pots run the command at each time, in the bot's shell, folder and environment, with `POTS_FROM` set to the routine's name. The command decides itself whether to wake the bot with `pots wake`, so watching an inbox every few minutes costs no model request until there is mail.
134
- - A run is skipped while the last run of the same routine still runs. Times missed while the gateway was stopped or the computer was off or asleep are skipped, not made up: the next run is the next time from now.
133
+ - `--note` wakes the bot with the note at each time. `--run` makes Pots run the command at each time, in the bot's shell, folder and environment, with `POTS_FROM` set to the routine's name. The command decides itself whether to wake the bot with `pots wake`, so watching an inbox every few minutes costs no model request until there is mail. `--child` starts a child at each time with the text as its brief, without waking the bot; the child decides itself whether to wake it, so a check that finds nothing leaves nothing in the bot's conversation.
134
+ - A run is skipped while the last run of the same routine still runs, or the child it started still works. Times missed while the gateway was stopped or the computer was off or asleep are skipped, not made up: the next run is the next time from now.
135
135
  - A command runs at most 10 minutes, or its `--timeout`; then Pots stops it and the processes it started. When the gateway stops, it stops the commands it runs.
136
- - Pots keeps each run's start, end, exit code and last lines of output for 7 days. A failed run (a non-zero exit code, or the timeout) wakes the bot once, with that output; later failures of the same routine do not, until one of its runs succeeds.
136
+ - Pots keeps each run's start, end, exit code and last lines of output for 7 days. A failed run (a non-zero exit code, the timeout, or a child that could not start, such as at `settings.maxChildren`) wakes the bot once, with that output; later failures of the same routine do not, until one of its runs succeeds.
137
137
  - A script that calls `pots wake` says where the wake comes from with `--from <name>` (letters, digits, `-` and `_`), or `$POTS_FROM`. The wake then tells the bot that it comes from a command on this computer, not from a person, so outside text in its note, such as an email's subject, does not read as the bot's own plan. With `--id <id>`, a second `pots wake` with the same ID gives back the first wake and sets none, as `pots send --id` does.
138
138
  - The fallback check-in (`fallbackWakeMinutes` in `bot.json`, 120 by default) comes while no wake set with `pots wake` is pending. Routines do not hold it back.
139
139
 
@@ -195,7 +195,7 @@ The bot's children, which do its longer work, have the bot's model unless it cho
195
195
 
196
196
  | Field | What it does | Values |
197
197
  |---|---|---|
198
- | `model` | The agent that reads, thinks and acts | Any pi model as `provider/modelId`, for example `openai/gpt-6.1-sol` or `anthropic/claude-opus-5-5` |
198
+ | `model` | The agent that reads, thinks and acts | Any pi model as `provider/modelId`, for example `openai/gpt-6.2-sol` or `anthropic/claude-opus-5-5` |
199
199
  | `thinking` | How hard the agent thinks. A level the model does not have becomes the nearest one it has, as in pi | `off`, `minimal`, `low`, `medium` (default), `high`, `xhigh`, `max` |
200
200
  | `judge` | Decides which messages that do not mention the bot should wake it | `off` (default): every message wakes the bot, and the agent decides<br>`provider/modelId` of a classifier: `typesafe/jev-latest`, `openrouter/typesafe/jev-1.14`, `opencode/jev-1.13-free`, or a llama.cpp model<br>`main`: the bot's own model judges, no extra account, but slower |
201
201
 
@@ -325,7 +325,7 @@ One gateway process runs every bot on the machine. Everything lives in `~/.pots/
325
325
 
326
326
  The same `pots` command gives the bot (and its scripts and cron jobs) its actions from a shell: `pots send`, `pots react`, `pots call`, `pots wake`, `pots routine`, `pots context`, `pots turn-page`, `pots children`. Tokens stay inside the running gateway; the agent never sees them.
327
327
 
328
- The bot sends its whole conversation with each model request, so the provider's prompt cache matters: a request whose start the provider has cached costs a fraction. The system prompt holds only facts that stay the same, and the bot's own parts of it, its memory too, keep their text for the whole page; a change, such as a new `settings` value in `bot.json`, shows after the page turns, after pi compacts, or after an upgrade. What changes from one wake to the next, such as the time, the context use and the bot's own address in a channel, is in the wake. `pots trace` and `pots context` show how much of the input the cache served and what the requests that missed it cost.
328
+ The bot sends its whole conversation with each model request, so the provider's prompt cache matters: a request whose start the provider has cached costs a fraction. The system prompt holds only facts that stay the same, and the bot's own parts of it, its memory too, keep their text for the whole page; a change, such as a new `settings` value in `bot.json`, shows after the page turns, after pi compacts, or after an upgrade. What changes from one wake to the next, such as the time, the context use and the bot's own address in a channel, is in the wake. The main agent's requests ask for the provider's long cache entry (1 hour at Anthropic instead of 5 minutes) on models pi knows it for, as its wakes are often minutes to an hour apart; other models keep the provider's default. Children, memory passes and the judge, which rarely pause, keep the short one, also with pi's `PI_CACHE_RETENTION=long`. `pots trace` and `pots context` show how much of the input the cache served and what the requests that missed it cost.
329
329
 
330
330
  A cache entry lasts about 5 minutes, and the bot often waits longer: for a person's answer, or for a child's work. So Pots warms the cache as the pi command line does: shortly before the entry of the main agent's or a child's last request expires, it sends that request again with a one-token answer, but only when pi's numbers say the warm costs less than the miss it saves. It warms during a run for up to an hour after the request, and after the run for up to 30 minutes. pi's setting `cacheWarming` in `~/.pi/agent/settings.json` is the switch for both: `idle` (the default), `streaming` (only during a run) or `off`. Memory passes, compaction and the judge are not warmed. A warm is in `pots trace`, beside the request it repeats.
331
331
 
@@ -346,7 +346,7 @@ pi-durable-bot runs every day as a teammate in a real workspace. What works toda
346
346
  - [x] `pots init`: name, AI, judge and one sentence, then the bot sets up its own chat apps from the terminal
347
347
  - [x] macOS, Linux and Windows, as a background service of the user
348
348
  - [x] The screen, mouse and keyboard of its computer, used like a person (computer use), or no screen on a server
349
- - [x] Children for longer work in the background, reported back once, also across restarts
349
+ - [x] Children for longer work in the background, whose final messages are kept across restarts; they wake the bot themselves when it needs to know
350
350
  - [x] Any model pi can use: subscription logins, API keys, OpenAI-compatible endpoints, local models
351
351
  - [x] A judge you choose: the bot's own model, Jev or another classifier, a local llama.cpp model, or none
352
352
  - [x] `AGENTS.md`, Agent Skills and images as in a pi session
@@ -4,15 +4,17 @@ import { BACKGROUND_CONTEXT, withAbortSignal, withTelemetry } from "@earendil-wo
4
4
  import { calculateContextTokens, estimateMessageTokens } from "@earendil-works/pi-ai/utils/estimate";
5
5
  import { configure, createRegistry, DEFAULT_COMPACTION_POLICY, defineExtension, defineTool, GenerationTask, Harness, hook, InboxDoc, LiveDoc, ROOT_CONVERSATION_ID, SystemEntry, section, } from "@earendil-works/pi-durable";
6
6
  import { NodeExecutionEnv } from "@earendil-works/pi-durable/env/node";
7
+ import { createFitImagesExtension } from "@earendil-works/pi-durable/images/fit";
7
8
  import { createNodePhotonImages } from "@earendil-works/pi-durable/images/node";
8
9
  import { SqliteStorage } from "@earendil-works/pi-durable/storage/sqlite";
9
10
  import { openNodeSqliteDatabase } from "@earendil-works/pi-durable/storage/sqlite/node";
10
11
  import { createBashTool, createEditTool, createReadTool, createWriteTool } from "@earendil-works/pi-durable/tools";
11
12
  import { bool, map, obj, opt, str, unknown } from "@earendil-works/pi-schema";
12
- import { age, Children, childActivity, childInfo, childrenExtension, describeActivity, reportRequestId, } from "./children.js";
13
+ import { age, Children, DEFAULT_CHILD_THINKING, childActivity, childInfo, childrenExtension, describeActivity, } from "./children.js";
13
14
  import { deleteLeftForks, lastAnswer, MemoryPasses, readPaths, withAgeNote } from "./memory.js";
14
15
  import { modelRef, POTS_IDENTITY, requireModel } from "./models.js";
15
16
  import { NO_SCREEN, renderBusy, ScreenLeases } from "./screen.js";
17
+ import { CacheRetentions } from "./retention.js";
16
18
  import { CacheWarming } from "./warming.js";
17
19
  const context = BACKGROUND_CONTEXT;
18
20
  /**
@@ -66,14 +68,18 @@ export class Agent {
66
68
  #disposeChildren;
67
69
  #memory;
68
70
  #warming;
71
+ #childExtensions = { add: [], remove: [] };
72
+ /** The task extension's start, for children that routines start. */
73
+ #startChild;
69
74
  #closing = false;
70
75
  /** Stops the last process did not finish; resume() finishes them. */
71
76
  #unfinishedStops = [];
72
77
  /** The running tool calls that give output as they run, by tool task, with when their last output came. */
73
78
  #outputs;
74
79
  /**
75
- * Crash tests: called just before and just after a child's end is handed to the main agent, right after a stop
76
- * marked a child stopped, before its work ended, and right before a memory pass forks the main conversation.
80
+ * Crash tests: called right after a stop marked a child stopped, before its work ended; before a child's reporter
81
+ * keeps how the child ended, which it may hold up until its reporter is aborted; and right before a memory pass forks
82
+ * the main conversation.
77
83
  */
78
84
  crashTests = {};
79
85
  constructor(options, harness, root, outputs) {
@@ -117,6 +123,14 @@ export class Agent {
117
123
  execution.inheritEnv = false;
118
124
  execution.env = { ...base, ...extra, ...execution.env };
119
125
  };
126
+ // A child's commands also have POTS_CHILD, its ID, which only Pots sets: pots wake in them comes from the child.
127
+ // Read from the children document, so it holds from a child's first command.
128
+ const childEnv = async (conversation, read) => {
129
+ if (conversation === ROOT_CONVERSATION_ID)
130
+ return {};
131
+ const child = Object.values((await read())?.children ?? {}).find((each) => each.conversationId === conversation);
132
+ return child ? { POTS_CHILD: child.id } : {};
133
+ };
120
134
  // When each running call of bash, screen and codemode last gave output, so a child's description can say how old its
121
135
  // last output is. Only in memory: a call does not run on after a restart.
122
136
  const outputs = new Map();
@@ -201,7 +215,7 @@ export class Agent {
201
215
  if (!taken.ok)
202
216
  return { output: text(renderBusy(screen, taken.lease, leases().idleMs, options.screen.bot)), isError: true };
203
217
  try {
204
- return await createBashTool({ prepare: environment(screen.env) }).execute(args, api, call);
218
+ return await createBashTool({ prepare: environment({ ...screen.env, ...(await childEnv(api.conversationId, () => api.snapshot(Children, ROOT_CONVERSATION_ID, call))) }) }).execute(args, api, call);
205
219
  }
206
220
  finally {
207
221
  taken.done();
@@ -282,16 +296,37 @@ export class Agent {
282
296
  // pi's prompt cache warming, for the main conversation and the children that are not stopped; not for memory forks.
283
297
  const warmable = (conversation) => !(agent && agent.#closing) && (conversation === String(ROOT_CONVERSATION_ID) || children.some((each) => each.conversationId === conversation && each.stoppedAt === undefined));
284
298
  const warming = options.cacheWarming ? await CacheWarming.open(models, options.cacheWarming, warmable) : undefined;
299
+ // The long prompt cache entry for the main conversation only, where pi's model data has one: it is woken minutes to an
300
+ // hour apart, children rarely pause.
301
+ const retentions = new CacheRetentions((conversation) => conversation === String(ROOT_CONVERSATION_ID));
285
302
  // pi-durable hands a hook the task's runtime, whose abort signal is the request's: so the request is known as the
286
303
  // conversation's when it goes out.
287
- const warmingHooks = hook(GenerationTask, {
304
+ const requestHooks = hook(GenerationTask, {
288
305
  beforeRequest: (_request, api) => {
289
- warming?.request(String(api.conversationId), api.signal);
306
+ const signal = api.signal;
307
+ retentions.request(String(api.conversationId), signal);
308
+ warming?.request(String(api.conversationId), signal);
290
309
  return undefined;
291
310
  },
292
311
  afterResponse: (message, api) => warming?.response(String(api.conversationId), message),
293
312
  });
294
- const read = createReadTool({ images: await (images ??= createNodePhotonImages()) });
313
+ const processor = await (images ??= createNodePhotonImages());
314
+ const read = createReadTool({ images: processor });
315
+ // pi's fitting of the images every other tool returns (MCP tools, code mode's image()) to the model's limits, as
316
+ // the pi CLI does, so a large image does not make the provider refuse the request. First, so the hooks of the other
317
+ // extensions see the fitted images.
318
+ // read fits its images itself, to the same limits: its results are not decoded again.
319
+ const fitAll = createFitImagesExtension(processor);
320
+ const fitImages = defineExtension({
321
+ ...fitAll,
322
+ hooks: (fitAll.hooks ?? []).map((each) => {
323
+ const afterTool = each.handlers.afterTool;
324
+ if (!afterTool)
325
+ return each;
326
+ const handlers = { ...each.handlers, afterTool: (call, result, api, context) => (call.name === read.name ? undefined : afterTool(call, result, api, context)) };
327
+ return { ...each, handlers };
328
+ }),
329
+ });
295
330
  const { createGrepToolDefinition, createFindToolDefinition } = await import("@earendil-works/pi-coding-agent");
296
331
  const memoryFolders = () => (options.memory?.enabled() ? options.memory.folders : undefined);
297
332
  const coding = defineExtension({
@@ -301,11 +336,11 @@ export class Agent {
301
336
  defineTool({ ...read, execute: async (args, api, call) => withAgeNote(await read.execute(args, api, call), args.path, memoryFolders(), options.workspace) }),
302
337
  createWriteTool(),
303
338
  createEditTool(),
304
- timed(createBashTool({ prepare: environment() })),
339
+ timed(defineTool({ ...createBashTool(), execute: async (args, api, call) => createBashTool({ prepare: environment(await childEnv(api.conversationId, () => api.snapshot(Children, ROOT_CONVERSATION_ID, call))) }).execute(args, api, call) })),
305
340
  searchTool(createGrepToolDefinition(options.workspace)),
306
341
  searchTool(createFindToolDefinition(options.workspace)),
307
342
  ],
308
- hooks: warming ? [warmingHooks] : [],
343
+ hooks: [requestHooks],
309
344
  });
310
345
  // pi's code mode, for the main agent and its children. As in pi, a script waits for the MCP servers it names, or for
311
346
  // all of them when it looks tools up, so it sees their tools. A server that connected meanwhile came after this
@@ -323,50 +358,71 @@ export class Agent {
323
358
  },
324
359
  }));
325
360
  const codemode = defineExtension({ name: "codemode", tools: [codemodeTool, ...scriptModels] });
326
- // The servers' tools, which only scripts call: a new extension of the same name each time servers connect or go.
327
- const mcp = () => options.mcp?.extension() ?? defineExtension({ name: "mcp" });
361
+ // The servers' tools, which only scripts call: an extension per server, with its namespace; new ones each time
362
+ // servers connect or go.
363
+ const mcp = () => options.mcp?.extensions() ?? [];
328
364
  let agent;
329
365
  const self = () => {
330
366
  if (!agent)
331
367
  throw new Error("the agent is still starting");
332
368
  return agent;
333
369
  };
334
- const tasks = childrenExtension({
370
+ const childrenTools = childrenExtension({
335
371
  mainModel: () => self().#model,
336
372
  childModel: (model) => childModel(models, model),
337
373
  max: () => options.children.max(),
338
374
  place: () => options.children.place(),
339
- extensions: () => ({ child: [coding, child, codemode, mcp()] }),
340
- ended: (end, context) => options.children.ended(end, context),
341
- withdraw: async (submission) => {
342
- await self().#harness.abortSubmission(Number(submission), context, ROOT_CONVERSATION_ID);
343
- },
375
+ extensions: () => childExtensions,
344
376
  stop: (id) => self().stopChild(id),
345
377
  activity: (conversation) => self().#activity(conversation),
346
378
  interrupt: (child) => self().interruptChild(child),
347
379
  settled: (conversation) => self().#releaseScreen(conversation),
348
- beforeReport: (reporter) => self().crashTests.beforeReport?.(reporter),
349
- afterReport: (reporter) => self().crashTests.afterReport?.(reporter),
380
+ saveResult: async (child, result) => {
381
+ const dir = join(options.workspace, "child-results");
382
+ await mkdir(dir, { recursive: true });
383
+ const file = join(dir, `${child}-${Date.now()}.md`);
384
+ await writeFile(file, result);
385
+ return file;
386
+ },
387
+ beforeKeep: async (child, signal) => agent?.crashTests.beforeChildKeep?.(child, signal),
350
388
  });
389
+ const tasks = childrenTools.extension;
390
+ // A child has the main agent's extensions without its channel actions and its task tool, and with its own prompt.
391
+ const childExtensions = { add: [child], remove: [bot, tasks] };
351
392
  const memory = options.memory ? new MemoryPasses({ host: options.memory, sql: options.database, cwd: options.workspace, context, log: options.log }) : undefined;
352
393
  const registry = createRegistry();
394
+ registry.install(fitImages);
353
395
  registry.install(coding);
354
396
  registry.install(bot);
355
397
  registry.install(tasks);
356
398
  registry.install(child);
357
399
  registry.install(codemode);
358
- registry.install(mcp());
359
- options.mcp?.onChange(() => registry.install(mcp()));
400
+ let servers = mcp();
401
+ for (const extension of servers)
402
+ registry.install(extension);
403
+ options.mcp?.onChange(() => {
404
+ const next = mcp();
405
+ const names = new Set(next.map((extension) => extension.name));
406
+ for (const gone of servers)
407
+ if (!names.has(gone.name))
408
+ registry.uninstall(gone);
409
+ for (const extension of next)
410
+ registry.install(extension);
411
+ servers = next;
412
+ });
360
413
  if (memory)
361
414
  registry.install(memory.extension);
362
415
  harness = await Harness.open(storage, {
363
- models: warming ? warming.wrap(models) : models,
416
+ // The retention first, so a warm repeats the request with it, and pi times the warm by that entry's lifetime.
417
+ models: retentions.wrap(warming ? warming.wrap(models) : models),
364
418
  // pi-durable names pi to providers unless told otherwise.
365
419
  identity: POTS_IDENTITY,
366
420
  registry,
367
421
  settings: {
368
- // The main agent's; a child selects its own.
369
- extensions: [coding, bot, tasks, codemode, mcp()],
422
+ // The main agent's, with the servers there are now; a child selects its own.
423
+ get extensions() {
424
+ return [fitImages, coding, bot, tasks, codemode, ...mcp()];
425
+ },
370
426
  // Several queued wakes go into one run.
371
427
  steeringMode: "all",
372
428
  followUpMode: "all",
@@ -394,6 +450,8 @@ export class Agent {
394
450
  await root.configure({ model, thinkingLevel: options.thinking, cwd: options.workspace }, context);
395
451
  agent = new Agent(options, harness, root, outputs);
396
452
  agent.#warming = warming;
453
+ agent.#childExtensions = childExtensions;
454
+ agent.#startChild = childrenTools.start;
397
455
  if (memory) {
398
456
  memory.attach(harness, root);
399
457
  memory.beforePass = () => agent?.crashTests.beforeMemoryPass?.();
@@ -403,6 +461,8 @@ export class Agent {
403
461
  await agent.#watchChildren((list) => (children = list));
404
462
  await agent.#holdUnfinishedStops();
405
463
  // bot.json may have changed the model while the bot was stopped: the children without a model of their own get it.
464
+ // A child that an earlier version started has its extensions as a list of names, from before each MCP server was an
465
+ // extension of its own: it gets the change to the main agent's extensions.
406
466
  await agent.#configureChildren();
407
467
  return agent;
408
468
  }
@@ -442,7 +502,6 @@ export class Agent {
442
502
  for (const stop of stops) {
443
503
  for (const reporter of stop.live)
444
504
  await this.#harness.abortTask(Number(reporter), context);
445
- await this.#withdrawReports(stop);
446
505
  }
447
506
  this.#unfinishedStops = stops;
448
507
  }
@@ -617,17 +676,20 @@ export class Agent {
617
676
  return lines.join("\n");
618
677
  }
619
678
  /**
620
- * Give the main model to every child that is not stopped and has no model of its own. A child with its own model
621
- * keeps it, and every child keeps its thinking level.
679
+ * Give the main model to every child that is not stopped and has no model of its own, and every such child its
680
+ * extensions as a change to the main agent's. A child with its own model keeps it, and every child keeps its thinking
681
+ * level.
622
682
  */
623
683
  async #configureChildren() {
624
- const children = this.#children.filter((child) => child.stoppedAt === undefined && child.model === undefined);
684
+ const children = this.#children.filter((child) => child.stoppedAt === undefined);
625
685
  if (children.length === 0)
626
686
  return;
627
687
  const model = this.#model;
688
+ // Writing what a child has already changes nothing.
628
689
  await this.#root.commit(async (tx) => {
629
- for (const child of children)
630
- await configure(tx, Number(child.conversationId), { model });
690
+ for (const child of children) {
691
+ await configure(tx, Number(child.conversationId), { extensions: this.#childExtensions, ...(child.model === undefined ? { model } : {}) });
692
+ }
631
693
  }, context);
632
694
  }
633
695
  /**
@@ -667,7 +729,6 @@ export class Agent {
667
729
  }
668
730
  this.#warming?.cancel(String(stop.conversationId));
669
731
  await (await this.#harness.conversation(stop.conversationId, context))?.abort(context);
670
- await this.#withdrawReports(stop);
671
732
  this.#releaseScreen(String(stop.conversationId));
672
733
  await this.#root.commit(async (tx) => {
673
734
  const record = (await tx.doc(Children, ROOT_CONVERSATION_ID)).children[stop.id];
@@ -675,19 +736,19 @@ export class Agent {
675
736
  record.stopFinished = true;
676
737
  }, context);
677
738
  }
678
- /** Withdraw the reports of a stopped child that wait in the main agent's queue. */
679
- async #withdrawReports(stop) {
680
- const queued = await this.#root.commit(async (tx) => {
681
- const ids = [];
682
- for (const reporter of stop.reporters) {
683
- const submission = await tx.submissionByRequest(ROOT_CONVERSATION_ID, reportRequestId(reporter));
684
- if (submission?.status === "queued")
685
- ids.push(submission.id);
686
- }
687
- return ids;
688
- }, context);
689
- for (const submission of queued)
690
- await this.#harness.abortSubmission(submission, context, ROOT_CONVERSATION_ID);
739
+ /**
740
+ * Start a child for a routine, with the main agent's model and the default thinking level, for no place. The child
741
+ * keeps the routine's name, in the same commit, so the routine knows while it works. Returns its ID; why it did not
742
+ * start at the cap; or the routine's earlier child, which works again.
743
+ */
744
+ async startChild(routine, brief) {
745
+ const start = this.#startChild;
746
+ if (!start)
747
+ throw new Error("the agent is still starting");
748
+ const started = await this.#root.commit((tx) => start(tx, { title: routine, brief, from: `routine ${routine}`, routine, model: this.#model, thinking: DEFAULT_CHILD_THINKING }, Date.now()), context);
749
+ if (!("full" in started))
750
+ return started;
751
+ return { refused: `${started.full.length} children work now, as many as the cap (settings.maxChildren in bot.json)` };
691
752
  }
692
753
  /** Stop every child that is not stopped yet. Returns what happened to each. */
693
754
  async stopChildren() {
@@ -730,6 +791,9 @@ export class Agent {
730
791
  * one for a submission made before.
731
792
  */
732
793
  async submit(input) {
794
+ // mcp.json is read again before the wake, so the request it starts names the servers there are now: the agent of a
795
+ // request is resolved before its sections render, where mcp_servers reads it too.
796
+ this.#options.mcp?.reload();
733
797
  const submission = await this.#root.submit({
734
798
  type: "input",
735
799
  content: input.text,
@@ -834,7 +898,6 @@ function stopOf(state, record) {
834
898
  id: record.id,
835
899
  title: record.title,
836
900
  conversationId: record.conversationId,
837
- reporters: [...record.reporters],
838
901
  live: Object.entries(state.live).flatMap(([reporter, child]) => (child === record.id ? [reporter] : [])),
839
902
  };
840
903
  }