pi-durable-bot 0.8.8 → 0.8.10

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 (41) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +17 -13
  3. package/dist/agent/agent.js +161 -54
  4. package/dist/agent/agent.js.map +1 -1
  5. package/dist/agent/children.js +397 -96
  6. package/dist/agent/children.js.map +1 -1
  7. package/dist/agent/judge.js +3 -1
  8. package/dist/agent/judge.js.map +1 -1
  9. package/dist/agent/retention.js +58 -0
  10. package/dist/agent/retention.js.map +1 -0
  11. package/dist/bot/bot.js +71 -21
  12. package/dist/bot/bot.js.map +1 -1
  13. package/dist/bot/definition.js +5 -4
  14. package/dist/bot/definition.js.map +1 -1
  15. package/dist/bot/prompt.js +50 -34
  16. package/dist/bot/prompt.js.map +1 -1
  17. package/dist/cli/agent.js +16 -9
  18. package/dist/cli/agent.js.map +1 -1
  19. package/dist/cli/bots.js +1 -1
  20. package/dist/cli/bots.js.map +1 -1
  21. package/dist/core/secrets.js +229 -0
  22. package/dist/core/secrets.js.map +1 -0
  23. package/dist/gateway/config.js.map +1 -1
  24. package/dist/gateway/gateway.js +1 -4
  25. package/dist/gateway/gateway.js.map +1 -1
  26. package/dist/gateway/routines.js +24 -12
  27. package/dist/gateway/routines.js.map +1 -1
  28. package/dist/gateway/timers.js +53 -42
  29. package/dist/gateway/timers.js.map +1 -1
  30. package/dist/gateway/tracing.js +2 -2
  31. package/dist/gateway/tracing.js.map +1 -1
  32. package/dist/pages/desktop.js +5 -1
  33. package/dist/pages/desktop.js.map +1 -1
  34. package/dist/pages/rfb.js +11 -5
  35. package/dist/pages/rfb.js.map +1 -1
  36. package/docs/for-agents.md +6 -6
  37. package/package.json +1 -1
  38. package/skills/desktop-page/SKILL.md +1 -1
  39. package/skills/discord-channel/SKILL.md +1 -1
  40. package/skills/slack-channel/SKILL.md +2 -2
  41. package/skills/slack-channel/slack-app-manifest.yaml +3 -0
package/CHANGELOG.md CHANGED
@@ -2,6 +2,45 @@
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.10 (2026-11-24)
6
+
7
+ The bot looks around on its own. A few times a day a child looks for what its people would want to know or have done, and wakes the bot only when it finds something. This look replaces the fallback check-in. Children can start children of their own and wait for them, and a child that fails wakes the bot once. The bot hands people fewer steps that it can do itself. Known secrets in tool output become `[secret]` before the model and the log get them.
8
+
9
+ ### Added
10
+ - **Known secrets are masked in tool output.** When a value of Pots' own secrets shows up in a tool's result, the model, the log (`bot.sqlite`) and a `codemode` script get `[secret]` in its place: in `bash`, `screen` and `codemode` output also while the command still runs, and also when a secret comes split across two pieces of output; in `read`, `grep`, MCP tools and every other tool's result; also in a routine's output and error and in a span's error, before `bot.sqlite` keeps them. Known secrets are the values in the files of the secrets folder (`KEY=value` files, files of one value, and a VNC password file as `vncpasswd` writes it) and in the files `bot.json` names (its channels' `secrets`, `vnc.passwordFile`). Values are taken as they are. Values under 8 characters, values with fewer than 4 different characters, and values of keys that name a thing (`*_NAME`, `*_USER`, `*_EMAIL`, `*_URL`, `*_HOST`, `*_PORT`, `*_ID`, `*_CLIENTID`, …) are not masked. pi's own files, such as its logins in `auth.json` and its MCP settings, are not read. A file that could not be read is read again at the next look. The files are looked at at most once a second and read again when one changes; a tool call costs one regular expression over its output (under 5 ms for 50 secrets over 50 KB). The files and the programs that read them keep the real values. Every agent's prompt says in one line what `[secret]` means. It is a best effort, not a wall.
11
+ - **The look.** At its first start, Pots gives each bot a routine `look`, which starts a child at 8:00, 11:00, 14:00, 17:00 and 20:00 in the computer's time zone (`--cron "0 8-22/3 * * *"`). The child looks, unasked, for what the people the bot works for would want to know or have done, with what the bot has: its memory, the message log, its tools and the logins on its computer. The log shows it what was said before and how people took it. When it finds something worth their attention, it wakes the bot with it and where it found it (`pots wake`); otherwise it ends quietly and nothing goes into the bot's conversation. The bot decides whether and when to tell people. There are no caps on messages: the model judges. It is a routine like any other, so `pots routine list` shows it and the bot changes or removes it when people ask. Pots adds it only once per bot, so a removed or changed `look` stays as it was, also across restarts and upgrades. The main agent's prompt calls it a default that Pots added once and that may since have been changed or removed, and points to `pots routine list` for what runs.
12
+ - **The `task` tool's `wait`** waits until all the children it names have ended, or any one of them, or until a number of seconds, then says which of these ended it and gives how each child ended and its final message then: a later message to that child does not change it. The caller must name the children; there is no default list. A batch too long for a tool's output is saved whole to one file. It holds no process while it waits and goes on waiting after a restart. The bot can use it too, but cannot answer anyone while it waits; its prompt says so.
13
+ - **`pots children --stop` and `--stop-all` in a child's commands** stop only the children that child started.
14
+
15
+ ### Removed
16
+ - **The fallback check-in.** Before, while no wake set with `pots wake` was pending, Pots woke the bot every 120 minutes (`settings.fallbackWakeMinutes`) in its main conversation. In practice the bot only checked for new messages: on four bots in 12 days, 52 check-ins led to no message; it was also expensive, because two hours is longer than the main conversation's prompt cache lasts, and it stopped for good once the bot set one wake far ahead. The look does its job. `pots routine list` no longer shows it.
17
+
18
+ ### Changed
19
+ - **Children can start children.** A child now has the `task` tool too, also in its `codemode` scripts, so it can split its work into children of its own and orchestrate them, to any depth. All of them share one cap, `settings.maxChildren`; at the cap, `start` says so and lists who works. A grandchild works for its parent's place and has its parent's model unless the parent chooses another. Its result goes to the child that started it; its failure goes there too, as a message, while that child works, also when a `wait` gives it too, and wakes the bot only once that child no longer works. A stop of the grandchild withdraws that message while it still waits. The bot sees the whole tree in `task`'s `list` and in `pots children`, and can stop any child; a stop also stops what the child started. A child manages only what it started. The prompts of the main agent and of children say so.
20
+ - **A child that fails wakes the bot once.** Since 0.8.9 a child's end wakes no one, so the bot did not learn that a child had stopped for good, such as when its model failed after its retries, had no model, or hit a limit. Now such a failure wakes the main agent once, also across restarts, for the place the child works for: the wake says which child, why, and what it did last. An answer, a stop, an interrupt and a retry still wake no one. A routine's child that fails wakes the bot each time; the bot decides what to do, such as remove the routine. The `task` tool's description says so.
21
+ - **The bot hands people less.** In the bots' logs, 13 times in 12 days a bot handed its person a step it could do itself, such as a sign-in with an account its browser already had, joining a Slack channel, or creating a key that costs nothing; 8 times it did the step at once when the person pointed this out. The prompt now says what a bot usually has: the sign-ins people made in the browsers, a password manager, the person's mailbox for codes, and the settings of its own apps. It says to look at these and try before it says a step needs a person. When it needs them, it asks once, first in its message, and goes on with the rest. For an action that may cost money it still asks first, and after the person's OK on the cost it does the rest itself. Looking something up, measuring or drafting needs no OK: it does it and says what it found.
22
+ - **The texts that sent the bot to a person.** `pots mcp login` is now the bot's to run, in the browser on its screen, in the prompt and in docs/for-agents.md. A new bot's first task asks the person only for things such as a code on their phone or an admin's approval, not for a sign-in. The Slack and Discord skills sign in with what the computer has and use a desktop page only for a step that needs the person; the desktop-page skill's description says so too.
23
+ - **The bot joins Slack channels itself.** The Slack app manifest in the slack-channel skill adds the scopes `channels:join`, `channels:manage` and `groups:write`, and the skill says to DM the person, join the right public channels, and create channels and invite people itself; only a private channel needs an invite. A bot whose Slack app was made before this adds the scopes in its app's settings and reinstalls the app; until then, these calls fail with `missing_scope`.
24
+ - **At the upgrade**, each bot gets the `look` routine at its next start. The section about the computer in every agent's prompt gains a line about `[secret]`. A pending fallback check-in is dropped, not fired; `bot_timers` keeps the old ones with `set_by = 'fallback'`. `settings.fallbackWakeMinutes` in `bot.json` is ignored. A child that works gets the `task` tool at its next request; the children it already has stay its own, with no parent. The prompts of the main agent and of children change, so each bot's prompt cache is written once more after the upgrade.
25
+
26
+ ### Fixed
27
+ - **Cron routines on the mornings the clocks change.** A `--cron` routine counted its times in the computer's offset from UTC, not in its time zone, so on the morning of a daylight-saving change it came an hour late, or twice. Now it counts in the computer's time zone, also when `pots routine add` checks the expression. At each start the gateway counts each cron routine's next time again, so a computer moved to another time zone gets its routines at the new local times.
28
+
29
+ ## 0.8.9 (2026-11-23)
30
+
31
+ 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.
32
+
33
+ ### Changed
34
+ - **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.
35
+ - **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.
36
+ - **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.
37
+ - **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.
38
+ - **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)`.
39
+ - **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.
40
+
41
+ ### Added
42
+ - **`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.
43
+
5
44
  ## 0.8.8 (2026-11-21)
6
45
 
7
46
  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.
package/README.md CHANGED
@@ -80,7 +80,7 @@ It is woken in three ways, the same three ways a person notices work:
80
80
  |---|---|---|
81
81
  | **Someone asks** | gets a message or an @ | A mention or a DM wakes it at once |
82
82
  | **It notices** | overhears something that is their job | Every message that does not mention it comes to it too, and it decides itself whether it is about its work. You can also set a judge that reads these messages first and asks two questions: *is this about me?* and *should I respond?* It sees the bot's own list of responsibilities. The judge is a fast classifier such as TypeSafe's Jev, a local model, or the bot's own model |
83
- | **It checks in** | looks around now and then, and keeps promises | It sets its own timed wakes and routines: "check Acme's pricing every Monday", "follow up at 5 pm". While no timed wake is pending, it looks around every two hours |
83
+ | **It looks around** | looks around now and then, unasked, and keeps promises | A few times a day a helper of its own looks for what you would want to know or have done, with its memory, the message log and its tools, and tells the bot only when it finds something. The bot also sets its own timed wakes and routines: "check Acme's pricing every Monday", "follow up at 5 pm" |
84
84
 
85
85
  Being woken is not the same as speaking. Each time, the agent reads the log and decides if it should say anything, where, and when. Most of the time the right answer is to stay quiet.
86
86
 
@@ -94,15 +94,19 @@ This is **code mode**: the agent gets a few general tools (`read`, `write`, `edi
94
94
 
95
95
  `screen` is `bash` with the screen's environment, such as `DISPLAY`; `bash` does not have it. A screen runs one task at a time, as a person's desktop does: the first `screen` command of an agent takes the screen until its work ends, also across bots and the Pots processes of the same user on the machine. Another agent that tries then learns who has it, since when, and when it frees, and decides itself what to do. A person who takes over the screen from a desktop page link holds it the same way, until they hand it back. A bot that sets up its own desktop, such as an Xvfb display, writes its environment into `screen` in its `bot.json`.
96
96
 
97
+ **Known secrets are masked in tool output.** When a secret Pots knows shows up in a tool's output, such as a token in a file the bot reads or a command prints, the model and the log get `[secret]` in its place, also in the output of a command that is still running and in a `codemode` script's calls. Pots knows only its own secrets: the values in the secrets folder and in the files `bot.json` names, such as the channels' tokens and the VNC password; pi's logins and settings are not read. A routine's output and stored errors are masked too. Values shorter than 8 characters, and names in them such as `*_URL`, `*_ID` or `*_NAME`, are not masked, so ordinary text is not hidden; the files are looked at at most once a second, and a tool call costs one regular expression over its output.
98
+
97
99
  One agent at a time per screen is enforced only on Linux, where plain `bash` has no `DISPLAY` or `WAYLAND_DISPLAY` and so cannot reach the screen. On macOS and Windows the screen does not depend on those variables, so `bash` can still use it; there the agents use the `screen` tool because the prompt tells them to.
98
100
 
99
101
  On Linux with a systemd user manager (a desktop, or a server with lingering, which `pots service install` turns on), each command of `bash`, `screen` and a routine runs in a systemd scope of its own, in one slice per Pots home. When memory runs out, systemd-oomd or the kernel then stops the command that uses it, not the gateway with every bot in it. What a command leaves running when it returns, such as a browser, a dev server or a `nohup` job, keeps running when Pots restarts after an upgrade or a crash, and the bot's next wake lists it, so the bot decides when to stop it. A command Pots still waits on when it stops is stopped, with what it started. When you stop Pots' service on purpose (`systemctl --user stop pots`, `pots service uninstall`), everything its commands left stops too. A scope costs about 25 ms per command. Where there is no user manager (macOS, Windows, `--system` services, most containers), commands run as before.
100
102
 
101
103
  ### 👥 Its own helpers
102
104
 
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.
105
+ 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`, `codemode` and `task`, without the channel actions, 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 that cannot go on, such as when its model fails after its retries, wakes the bot once, also across restarts, with why and what it did last. 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 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.
106
+
107
+ A child can start children of its own with the same `task` tool, also from a `codemode` script, to the depth it needs; all of them share one cap. A grandchild works for its parent's place, with its parent's model unless the parent chooses another, and its brief says which child it came from. Its result goes to the child that started it, which reads it with `task`'s `result`, or with `wait`: `wait` holds until all the children it names have ended, or any one of them, or until a time limit, then gives how each ended, with its final message then, also when Pots restarts in the meantime, and holds no process while it waits. A grandchild's failure goes to its parent too, as a message, while the parent works; once the parent no longer works, it wakes the bot as a child's failure does. The bot sees the whole tree, in `task`'s `list` and in `pots children`, and can stop any of them; a stop also stops what that child started. A child manages only the children it started, also with `pots children` in its commands. The bot can `wait` too, but cannot answer anyone while it waits, so a batch of work to wait for goes to a child that starts and waits for the others.
104
108
 
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.
109
+ 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, counting the children that children started. `pots children` lists them, and `pots children --stop <id>` or `--stop-all` stops them.
106
110
 
107
111
  It works like a [pi](https://github.com/earendil-works/pi) session: it reads `AGENTS.md` and uses [Agent Skills](https://agentskills.io) from the same places pi does, so the skills you give pi, the bot can use too. Screenshots and photos are shrunk to fit the model, as in pi.
108
112
 
@@ -126,16 +130,16 @@ It promises to come back, and it does. A timed wake (`pots wake`) wakes it once,
126
130
 
127
131
  | Command | What it does |
128
132
  |---|---|
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` |
130
- | `pots routine list` | Each routine's schedule, what it does, its next time and its last run; and the fallback check-in |
133
+ | `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` |
134
+ | `pots routine list` | Each routine's schedule, what it does, its next time and its last run |
131
135
  | `pots routine remove <name>` | Remove a routine |
132
136
 
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.
137
+ - `--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.
138
+ - 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
139
  - 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.
140
+ - 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
141
  - 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
- - 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.
142
+ - **The look.** At its first start, Pots gives each bot one routine, `look`: at 8:00, 11:00, 14:00, 17:00 and 20:00 in the computer's time zone (`--cron "0 8-22/3 * * *"`), it starts a child that looks, unasked, for what the bot's people would want to know or have done, with what the bot has: its memory, the message log, its tools and the logins on its computer. It sees what was said before and how people took it. When it finds something worth their attention, it wakes the bot with it and where it found it; otherwise it ends quietly and nothing goes into the bot's conversation. The bot decides whether and when to tell people. Ask the bot for other times, or for none, and it changes or removes the routine; Pots never adds it again, also after an upgrade or a restart.
139
143
 
140
144
  ### 📓 Its own memory
141
145
 
@@ -166,9 +170,9 @@ pots init
166
170
  3. **Who decides on group messages that do not mention it.** By default the bot itself: every such message wakes it. Or Jev, a fast judge from TypeSafe, with your TypeSafe API key, or a judge model you already set up in pi; the bot then wakes only for the messages about its work.
167
171
  4. **In one sentence, what it is for.** Optional. The bot writes its own persona and responsibilities from it.
168
172
 
169
- Then the gateway starts as a background service (it starts again at login) and you are talking to your bot in the terminal. It first checks that it can use the computer's screen and walks you through any permission it needs, such as Screen Recording and Accessibility on a Mac. On a server with no desktop, it works without a screen and asks you before it sets one up. Tell it which chat apps to join. It sets them up itself on its computer and asks you only for what it cannot do, like signing in to Slack or approving the app. Leave with Ctrl+C; come back with `pots chat`.
173
+ Then the gateway starts as a background service (it starts again at login) and you are talking to your bot in the terminal. It first checks that it can use the computer's screen and walks you through any permission it needs, such as Screen Recording and Accessibility on a Mac. On a server with no desktop, it works without a screen and asks you before it sets one up. Tell it which chat apps to join. It sets them up itself on its computer and signs in with what the computer has, such as your accounts in its browser and your password manager. It asks you only for what it cannot do, like a code that comes to your phone or an admin's approval. Leave with Ctrl+C; come back with `pots chat`.
170
174
 
171
- It joins only the places it is invited to, like a new hire who is added to the right channels.
175
+ It works in the places it is in, like a new hire who is added to the right channels. On Slack it can also join public channels and create channels itself; a private channel needs an invite.
172
176
 
173
177
  To add another bot, ask a bot you have to make one, or run `pots bot new <name> --about "<what it is for>"`. The new bot sets itself up the same way, and when another bot already uses the screen, it offers to set up one of its own ([Add another bot](docs/for-agents.md#add-another-bot)).
174
178
 
@@ -325,7 +329,7 @@ One gateway process runs every bot on the machine. Everything lives in `~/.pots/
325
329
 
326
330
  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
331
 
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.
332
+ 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
333
 
330
334
  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
335
 
@@ -346,7 +350,7 @@ pi-durable-bot runs every day as a teammate in a real workspace. What works toda
346
350
  - [x] `pots init`: name, AI, judge and one sentence, then the bot sets up its own chat apps from the terminal
347
351
  - [x] macOS, Linux and Windows, as a background service of the user
348
352
  - [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
353
+ - [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
354
  - [x] Any model pi can use: subscription logins, API keys, OpenAI-compatible endpoints, local models
351
355
  - [x] A judge you choose: the bot's own model, Jev or another classifier, a local llama.cpp model, or none
352
356
  - [x] `AGENTS.md`, Agent Skills and images as in a pi session
@@ -2,7 +2,7 @@ import { mkdir, writeFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { BACKGROUND_CONTEXT, withAbortSignal, withTelemetry } from "@earendil-works/chord/context";
4
4
  import { calculateContextTokens, estimateMessageTokens } from "@earendil-works/pi-ai/utils/estimate";
5
- import { configure, createRegistry, DEFAULT_COMPACTION_POLICY, defineExtension, defineTool, GenerationTask, Harness, hook, InboxDoc, LiveDoc, ROOT_CONVERSATION_ID, SystemEntry, section, } from "@earendil-works/pi-durable";
5
+ import { configure, createRegistry, DEFAULT_COMPACTION_POLICY, defineExtension, defineTool, GenerationTask, Harness, hook, InboxDoc, LiveDoc, ROOT_CONVERSATION_ID, SystemEntry, section, ToolTask, } from "@earendil-works/pi-durable";
6
6
  import { NodeExecutionEnv } from "@earendil-works/pi-durable/env/node";
7
7
  import { createFitImagesExtension } from "@earendil-works/pi-durable/images/fit";
8
8
  import { createNodePhotonImages } from "@earendil-works/pi-durable/images/node";
@@ -10,10 +10,11 @@ import { SqliteStorage } from "@earendil-works/pi-durable/storage/sqlite";
10
10
  import { openNodeSqliteDatabase } from "@earendil-works/pi-durable/storage/sqlite/node";
11
11
  import { createBashTool, createEditTool, createReadTool, createWriteTool } from "@earendil-works/pi-durable/tools";
12
12
  import { bool, map, obj, opt, str, unknown } from "@earendil-works/pi-schema";
13
- import { age, Children, childActivity, childInfo, childrenExtension, describeActivity, reportRequestId, } from "./children.js";
13
+ import { age, Children, DEFAULT_CHILD_THINKING, childActivity, childInfo, childrenExtension, describeActivity, descendants, endWaits, failureRequestId, keepAnswer, lastStep, } from "./children.js";
14
14
  import { deleteLeftForks, lastAnswer, MemoryPasses, readPaths, withAgeNote } from "./memory.js";
15
15
  import { modelRef, POTS_IDENTITY, requireModel } from "./models.js";
16
16
  import { NO_SCREEN, renderBusy, ScreenLeases } from "./screen.js";
17
+ import { CacheRetentions } from "./retention.js";
17
18
  import { CacheWarming } from "./warming.js";
18
19
  const context = BACKGROUND_CONTEXT;
19
20
  /**
@@ -68,14 +69,17 @@ export class Agent {
68
69
  #memory;
69
70
  #warming;
70
71
  #childExtensions = { add: [], remove: [] };
72
+ /** The task extension's start, for children that routines start. */
73
+ #startChild;
71
74
  #closing = false;
72
75
  /** Stops the last process did not finish; resume() finishes them. */
73
76
  #unfinishedStops = [];
74
77
  /** The running tool calls that give output as they run, by tool task, with when their last output came. */
75
78
  #outputs;
76
79
  /**
77
- * Crash tests: called just before and just after a child's end is handed to the main agent, right after a stop
78
- * 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; just before and just after a child's
82
+ * failure is handed to the main agent; and right before a memory pass forks the main conversation.
79
83
  */
80
84
  crashTests = {};
81
85
  constructor(options, harness, root, outputs) {
@@ -119,22 +123,54 @@ export class Agent {
119
123
  execution.inheritEnv = false;
120
124
  execution.env = { ...base, ...extra, ...execution.env };
121
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
+ };
122
134
  // When each running call of bash, screen and codemode last gave output, so a child's description can say how old its
123
135
  // last output is. Only in memory: a call does not run on after a restart.
124
136
  const outputs = new Map();
137
+ const secrets = options.secrets;
125
138
  const timed = (tool) => defineTool({
126
139
  ...tool,
127
140
  execute: async (args, api, call) => {
128
141
  const key = String(api.taskId);
129
142
  outputs.set(key, undefined);
143
+ // Masked as it streams, since what a call has given so far is kept in the log while it runs.
144
+ const masked = secrets?.stream();
145
+ const decoder = new TextDecoder();
130
146
  const output = (chunk, skipped) => {
131
147
  outputs.set(key, Date.now());
132
- api.output(chunk, skipped);
148
+ if (!masked)
149
+ return api.output(chunk, skipped);
150
+ const text = masked.write(typeof chunk === "string" ? chunk : decoder.decode(chunk, { stream: true }));
151
+ if (text !== "" || skipped !== undefined)
152
+ api.output(text, skipped);
153
+ };
154
+ const flush = () => {
155
+ const rest = masked?.flush();
156
+ if (rest)
157
+ api.output(rest);
133
158
  };
159
+ const wrapped = new Proxy(api, {
160
+ get: (target, property) => property === "output"
161
+ ? output
162
+ : property === "retainedOutput"
163
+ ? () => {
164
+ flush();
165
+ return target.retainedOutput();
166
+ }
167
+ : Reflect.get(target, property, target),
168
+ });
134
169
  try {
135
- return await tool.execute(args, new Proxy(api, { get: (target, property) => (property === "output" ? output : Reflect.get(target, property, target)) }), call);
170
+ return await tool.execute(args, wrapped, call);
136
171
  }
137
172
  finally {
173
+ flush();
138
174
  outputs.delete(key);
139
175
  }
140
176
  },
@@ -203,7 +239,7 @@ export class Agent {
203
239
  if (!taken.ok)
204
240
  return { output: text(renderBusy(screen, taken.lease, leases().idleMs, options.screen.bot)), isError: true };
205
241
  try {
206
- return await createBashTool({ prepare: environment(screen.env) }).execute(args, api, call);
242
+ return await createBashTool({ prepare: environment({ ...screen.env, ...(await childEnv(api.conversationId, () => api.snapshot(Children, ROOT_CONVERSATION_ID, call))) }) }).execute(args, api, call);
207
243
  }
208
244
  finally {
209
245
  taken.done();
@@ -275,7 +311,7 @@ export class Agent {
275
311
  return text;
276
312
  return input.shown[part.name] ?? (await firstText(input.conversationId, part.name, context)) ?? text;
277
313
  };
278
- // A child has the main agent's coding tools and screen, with its own prompt: no channel actions and no task tool.
314
+ // A child has the main agent's coding tools, screen and task tool, with its own prompt: no channel actions.
279
315
  const child = defineExtension({
280
316
  name: "child",
281
317
  tools: [screenTool],
@@ -284,11 +320,16 @@ export class Agent {
284
320
  // pi's prompt cache warming, for the main conversation and the children that are not stopped; not for memory forks.
285
321
  const warmable = (conversation) => !(agent && agent.#closing) && (conversation === String(ROOT_CONVERSATION_ID) || children.some((each) => each.conversationId === conversation && each.stoppedAt === undefined));
286
322
  const warming = options.cacheWarming ? await CacheWarming.open(models, options.cacheWarming, warmable) : undefined;
323
+ // The long prompt cache entry for the main conversation only, where pi's model data has one: it is woken minutes to an
324
+ // hour apart, children rarely pause.
325
+ const retentions = new CacheRetentions((conversation) => conversation === String(ROOT_CONVERSATION_ID));
287
326
  // pi-durable hands a hook the task's runtime, whose abort signal is the request's: so the request is known as the
288
327
  // conversation's when it goes out.
289
- const warmingHooks = hook(GenerationTask, {
328
+ const requestHooks = hook(GenerationTask, {
290
329
  beforeRequest: (_request, api) => {
291
- warming?.request(String(api.conversationId), api.signal);
330
+ const signal = api.signal;
331
+ retentions.request(String(api.conversationId), signal);
332
+ warming?.request(String(api.conversationId), signal);
292
333
  return undefined;
293
334
  },
294
335
  afterResponse: (message, api) => warming?.response(String(api.conversationId), message),
@@ -319,11 +360,12 @@ export class Agent {
319
360
  defineTool({ ...read, execute: async (args, api, call) => withAgeNote(await read.execute(args, api, call), args.path, memoryFolders(), options.workspace) }),
320
361
  createWriteTool(),
321
362
  createEditTool(),
322
- timed(createBashTool({ prepare: environment() })),
363
+ 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) })),
323
364
  searchTool(createGrepToolDefinition(options.workspace)),
324
365
  searchTool(createFindToolDefinition(options.workspace)),
325
366
  ],
326
- hooks: warming ? [warmingHooks] : [],
367
+ // Every agent has these tools, so every tool result of every agent, also of a codemode script's calls, passes here.
368
+ hooks: [requestHooks, ...(secrets ? [hook(ToolTask, { afterTool: (_call, result) => secrets.maskResult(result) })] : [])],
327
369
  });
328
370
  // 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
329
371
  // all of them when it looks tools up, so it sees their tools. A server that connected meanwhile came after this
@@ -350,25 +392,40 @@ export class Agent {
350
392
  throw new Error("the agent is still starting");
351
393
  return agent;
352
394
  };
353
- const tasks = childrenExtension({
395
+ const childrenTools = childrenExtension({
354
396
  mainModel: () => self().#model,
355
397
  childModel: (model) => childModel(models, model),
356
398
  max: () => options.children.max(),
357
399
  place: () => options.children.place(),
358
400
  extensions: () => childExtensions,
359
- ended: (end, context) => options.children.ended(end, context),
360
- withdraw: async (submission) => {
361
- await self().#harness.abortSubmission(Number(submission), context, ROOT_CONVERSATION_ID);
401
+ last: async (conversationId, context) => lastStep(await self().#harness.conversation(conversationId, context), context).catch(() => undefined),
402
+ // With what the child did last, read from its conversation.
403
+ failed: async (failure, context) => {
404
+ const last = await lastStep(await self().#harness.conversation(Number(failure.child.conversationId), context), context).catch(() => undefined);
405
+ return options.children.failed(last === undefined ? failure : { ...failure, last }, context);
406
+ },
407
+ withdraw: async (submission, conversation = ROOT_CONVERSATION_ID) => {
408
+ await self().#harness.abortSubmission(Number(submission), context, conversation);
362
409
  },
363
410
  stop: (id) => self().stopChild(id),
364
411
  activity: (conversation) => self().#activity(conversation),
365
412
  interrupt: (child) => self().interruptChild(child),
366
413
  settled: (conversation) => self().#releaseScreen(conversation),
367
- beforeReport: (reporter) => self().crashTests.beforeReport?.(reporter),
368
- afterReport: (reporter) => self().crashTests.afterReport?.(reporter),
414
+ saveResult: async (child, result) => {
415
+ const dir = join(options.workspace, "child-results");
416
+ await mkdir(dir, { recursive: true });
417
+ const file = join(dir, `${child}-${Date.now()}.md`);
418
+ await writeFile(file, result);
419
+ return file;
420
+ },
421
+ beforeKeep: async (child, signal) => agent?.crashTests.beforeChildKeep?.(child, signal),
422
+ beforeStart: async (starter) => agent?.crashTests.holdChildStart?.(starter),
423
+ beforeFailed: (reporter) => agent?.crashTests.beforeChildFailure?.(reporter),
424
+ afterFailed: (reporter) => agent?.crashTests.afterChildFailure?.(reporter),
369
425
  });
370
- // A child has the main agent's extensions without its channel actions and its task tool, and with its own prompt.
371
- const childExtensions = { add: [child], remove: [bot, tasks] };
426
+ const tasks = childrenTools.extension;
427
+ // A child has the main agent's extensions without its channel actions, and with its own prompt.
428
+ const childExtensions = { add: [child], remove: [bot] };
372
429
  const memory = options.memory ? new MemoryPasses({ host: options.memory, sql: options.database, cwd: options.workspace, context, log: options.log }) : undefined;
373
430
  const registry = createRegistry();
374
431
  registry.install(fitImages);
@@ -393,7 +450,8 @@ export class Agent {
393
450
  if (memory)
394
451
  registry.install(memory.extension);
395
452
  harness = await Harness.open(storage, {
396
- models: warming ? warming.wrap(models) : models,
453
+ // The retention first, so a warm repeats the request with it, and pi times the warm by that entry's lifetime.
454
+ models: retentions.wrap(warming ? warming.wrap(models) : models),
397
455
  // pi-durable names pi to providers unless told otherwise.
398
456
  identity: POTS_IDENTITY,
399
457
  registry,
@@ -430,6 +488,7 @@ export class Agent {
430
488
  agent = new Agent(options, harness, root, outputs);
431
489
  agent.#warming = warming;
432
490
  agent.#childExtensions = childExtensions;
491
+ agent.#startChild = childrenTools.start;
433
492
  if (memory) {
434
493
  memory.attach(harness, root);
435
494
  memory.beforePass = () => agent?.crashTests.beforeMemoryPass?.();
@@ -480,7 +539,7 @@ export class Agent {
480
539
  for (const stop of stops) {
481
540
  for (const reporter of stop.live)
482
541
  await this.#harness.abortTask(Number(reporter), context);
483
- await this.#withdrawReports(stop);
542
+ await this.#withdrawFailures(stop);
484
543
  }
485
544
  this.#unfinishedStops = stops;
486
545
  }
@@ -675,28 +734,44 @@ export class Agent {
675
734
  * Stop a child: its work and what it runs end, the messages it has not taken are withdrawn, and nothing comes back
676
735
  * from it, also a report that waits in the main agent's queue. Returns what happened, in words for the model.
677
736
  */
678
- async stopChild(id) {
737
+ async stopChild(id, by) {
679
738
  const found = await this.#root.commit(async (tx) => {
680
739
  const state = await tx.doc(Children, ROOT_CONVERSATION_ID);
681
740
  const record = Object.hasOwn(state.children, id) ? state.children[id] : undefined;
682
- if (!record)
741
+ if (!record || (by !== undefined && record.parent !== by))
683
742
  return undefined;
684
- if (record.stopFinished)
685
- return { title: record.title, stopped: true };
686
- // A stop that a crash cut off is done again from here.
687
- const marked = record.stoppedAt === undefined;
688
- record.stoppedAt ??= Date.now();
689
- delete record.since;
690
- return { stopped: false, marked, ...stopOf(state, record) };
743
+ // With the children it started, and theirs, in the same commit, so none of them goes on without the others.
744
+ const records = [record, ...descendants(state, id).map((below) => state.children[below])].filter((each) => !each.stopFinished);
745
+ // An answer a child gave before the stop, which its reporter has not kept yet, is kept before its waits wake.
746
+ for (const each of records) {
747
+ for (const reporter of stopOf(state, each).live) {
748
+ const submission = await tx.submissionByRequest(each.conversationId, `child:${reporter}`);
749
+ if (submission?.type === "input" && submission.status === "done")
750
+ keepAnswer(each, submission.answer, Date.now());
751
+ }
752
+ }
753
+ const stops = records.map((each) => {
754
+ // A stop that a crash cut off is done again from here.
755
+ const marked = each.stoppedAt === undefined;
756
+ each.stoppedAt ??= Date.now();
757
+ delete each.since;
758
+ return { marked, ...stopOf(state, each) };
759
+ });
760
+ await endWaits(tx, records);
761
+ return { title: record.title, stops };
691
762
  }, context);
692
763
  if (!found)
693
- return `No child ${id}.`;
694
- if (found.stopped)
764
+ return `No child ${id}${by === undefined ? "" : " of yours"}.`;
765
+ for (const stop of found.stops)
766
+ if (stop.marked)
767
+ this.crashTests.afterStopMark?.(stop.id);
768
+ await this.crashTests.holdAfterStopMark?.(id);
769
+ for (const stop of found.stops)
770
+ await this.#finishStop(stop);
771
+ if (found.stops[0]?.id !== id)
695
772
  return `${id} ("${found.title}") was stopped before.`;
696
- if (found.marked)
697
- this.crashTests.afterStopMark?.(id);
698
- await this.#finishStop(found);
699
- return `Stopped ${id} ("${found.title}"). Nothing comes back from it.`;
773
+ const below = found.stops.slice(1).map((stop) => stop.id);
774
+ return `Stopped ${id} ("${found.title}")${below.length > 0 ? ` and the children it started: ${below.join(", ")}` : ""}. Nothing comes back from ${below.length > 0 ? "them" : "it"}.`;
700
775
  }
701
776
  /** End a stopped child's work, then record that, so a stop cut off by a crash is finished at the next start. */
702
777
  async #finishStop(stop) {
@@ -708,7 +783,7 @@ export class Agent {
708
783
  }
709
784
  this.#warming?.cancel(String(stop.conversationId));
710
785
  await (await this.#harness.conversation(stop.conversationId, context))?.abort(context);
711
- await this.#withdrawReports(stop);
786
+ await this.#withdrawFailures(stop);
712
787
  this.#releaseScreen(String(stop.conversationId));
713
788
  await this.#root.commit(async (tx) => {
714
789
  const record = (await tx.doc(Children, ROOT_CONVERSATION_ID)).children[stop.id];
@@ -716,26 +791,59 @@ export class Agent {
716
791
  record.stopFinished = true;
717
792
  }, context);
718
793
  }
719
- /** Withdraw the reports of a stopped child that wait in the main agent's queue. */
720
- async #withdrawReports(stop) {
794
+ /**
795
+ * Withdraw the messages of a stopped child's failures that wait in a queue: the main agent's wakes, and the messages to
796
+ * the child that started it.
797
+ */
798
+ async #withdrawFailures(stop) {
721
799
  const queued = await this.#root.commit(async (tx) => {
722
- const ids = [];
723
- for (const reporter of stop.reporters) {
724
- const submission = await tx.submissionByRequest(ROOT_CONVERSATION_ID, reportRequestId(reporter));
800
+ const state = await tx.doc(Children, ROOT_CONVERSATION_ID);
801
+ const record = state.children[stop.id];
802
+ const parent = record?.parent === undefined ? undefined : state.children[record.parent];
803
+ const found = [];
804
+ const look = async (conversation, request) => {
805
+ const submission = await tx.submissionByRequest(conversation, request);
725
806
  if (submission?.status === "queued")
726
- ids.push(submission.id);
727
- }
728
- return ids;
807
+ found.push({ submission: submission.id, conversation });
808
+ };
809
+ for (const reporter of record?.reporters ?? [])
810
+ await look(ROOT_CONVERSATION_ID, failureRequestId(reporter));
811
+ if (parent)
812
+ for (const reporter of record?.told ?? [])
813
+ await look(parent.conversationId, `child:${reporter}`);
814
+ return found;
729
815
  }, context);
730
- for (const submission of queued)
731
- await this.#harness.abortSubmission(submission, context, ROOT_CONVERSATION_ID);
816
+ for (const { submission, conversation } of queued)
817
+ await this.#harness.abortSubmission(submission, context, conversation);
732
818
  }
733
- /** Stop every child that is not stopped yet. Returns what happened to each. */
734
- async stopChildren() {
819
+ /**
820
+ * Start a child for a routine, with the main agent's model and the default thinking level, for no place. The child
821
+ * keeps the routine's name, in the same commit, so the routine knows while it works. Returns its ID; why it did not
822
+ * start at the cap; or the routine's earlier child, which works again.
823
+ */
824
+ async startChild(routine, brief) {
825
+ const start = this.#startChild;
826
+ if (!start)
827
+ throw new Error("the agent is still starting");
828
+ 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);
829
+ if ("stopped" in started)
830
+ throw new Error("a routine's child has no parent");
831
+ if (!("full" in started))
832
+ return started;
833
+ return { refused: `${started.full.length} children work now, as many as the cap (settings.maxChildren in bot.json)` };
834
+ }
835
+ /** Stop every child that is not stopped yet, or, by a child, every child it started. Returns what happened to each. */
836
+ async stopChildren(by) {
735
837
  const results = [];
736
- for (const child of this.#children)
737
- if (child.stoppedAt === undefined)
738
- results.push(await this.stopChild(child.id));
838
+ // A child stops with the one that started it.
839
+ const live = new Set(this.#children.flatMap((child) => (child.stoppedAt === undefined ? [child.id] : [])));
840
+ for (const child of this.#children) {
841
+ if (!live.has(child.id))
842
+ continue;
843
+ if (by === undefined ? child.parent && live.has(child.parent) : child.parent !== by)
844
+ continue;
845
+ results.push(await this.stopChild(child.id, by));
846
+ }
739
847
  return results;
740
848
  }
741
849
  async close() {
@@ -878,7 +986,6 @@ function stopOf(state, record) {
878
986
  id: record.id,
879
987
  title: record.title,
880
988
  conversationId: record.conversationId,
881
- reporters: [...record.reporters],
882
989
  live: Object.entries(state.live).flatMap(([reporter, child]) => (child === record.id ? [reporter] : [])),
883
990
  };
884
991
  }