pi-durable-bot 0.3.3 → 0.4.1

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 (57) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +46 -21
  3. package/dist/agent/agent.js +433 -13
  4. package/dist/agent/agent.js.map +1 -1
  5. package/dist/agent/children.js +254 -0
  6. package/dist/agent/children.js.map +1 -0
  7. package/dist/agent/memory.js +573 -0
  8. package/dist/agent/memory.js.map +1 -0
  9. package/dist/agent/screen.js +220 -0
  10. package/dist/agent/screen.js.map +1 -0
  11. package/dist/bot/bot.js +162 -27
  12. package/dist/bot/bot.js.map +1 -1
  13. package/dist/bot/definition.js +30 -3
  14. package/dist/bot/definition.js.map +1 -1
  15. package/dist/bot/machine.js +6 -6
  16. package/dist/bot/machine.js.map +1 -1
  17. package/dist/bot/memory.js +186 -0
  18. package/dist/bot/memory.js.map +1 -0
  19. package/dist/bot/prompt.js +304 -35
  20. package/dist/bot/prompt.js.map +1 -1
  21. package/dist/channels/slack/index.js +24 -0
  22. package/dist/channels/slack/index.js.map +1 -1
  23. package/dist/channels/test/index.js +9 -2
  24. package/dist/channels/test/index.js.map +1 -1
  25. package/dist/cli/agent.js +14 -1
  26. package/dist/cli/agent.js.map +1 -1
  27. package/dist/cli/ai.js +101 -11
  28. package/dist/cli/ai.js.map +1 -1
  29. package/dist/cli/bots.js +1 -1
  30. package/dist/cli/bots.js.map +1 -1
  31. package/dist/cli/commands.js +10 -5
  32. package/dist/cli/commands.js.map +1 -1
  33. package/dist/cli/init.js +11 -7
  34. package/dist/cli/init.js.map +1 -1
  35. package/dist/cli/trace.js +87 -15
  36. package/dist/cli/trace.js.map +1 -1
  37. package/dist/core/channel.js +2 -0
  38. package/dist/core/channel.js.map +1 -1
  39. package/dist/core/home.js +2 -0
  40. package/dist/core/home.js.map +1 -1
  41. package/dist/core/time.js +18 -0
  42. package/dist/core/time.js.map +1 -0
  43. package/dist/core/version.js +4 -0
  44. package/dist/core/version.js.map +1 -0
  45. package/dist/gateway/config.js.map +1 -1
  46. package/dist/gateway/files.js +245 -0
  47. package/dist/gateway/files.js.map +1 -0
  48. package/dist/gateway/gateway.js +21 -3
  49. package/dist/gateway/gateway.js.map +1 -1
  50. package/dist/gateway/log.js +7 -2
  51. package/dist/gateway/log.js.map +1 -1
  52. package/dist/gateway/tracing.js +1 -3
  53. package/dist/gateway/tracing.js.map +1 -1
  54. package/dist/gateway/waker.js +88 -8
  55. package/dist/gateway/waker.js.map +1 -1
  56. package/docs/for-agents.md +6 -5
  57. package/package.json +1 -1
@@ -0,0 +1,220 @@
1
+ import { tmpdir } from "node:os";
2
+ import { join } from "node:path";
3
+ import { DatabaseSync } from "node:sqlite";
4
+ import { formatTime } from "../core/time.js";
5
+ // A screen runs one computer-use task at a time, as a person's desktop does. The agents find their own commands for the
6
+ // screen, so code cannot see screen use in bash; the screen tool is how an agent says it uses the screen. It holds a
7
+ // lease on the screen for its conversation, in a file every Pots process of this user on the machine shares.
8
+ /** The variables that point a program at a screen. bash runs without them; the screen tool has them. */
9
+ export const SCREEN_VARIABLES = ["DISPLAY", "XAUTHORITY", "WAYLAND_DISPLAY"];
10
+ /** A lease frees when its holder has not used the screen for this long. */
11
+ export const SCREEN_IDLE_MS = 10 * 60_000;
12
+ /** While a screen command runs, its lease counts as used; this often the holder says so again. */
13
+ const HEARTBEAT_MS = 30_000;
14
+ /**
15
+ * The bot's screen: the screen setting of bot.json, else the gateway's own screen variables. macOS and Windows have one
16
+ * screen per machine, so every agent shares one key there; elsewhere the key is the X display or the Wayland socket.
17
+ */
18
+ export function screenOf(setting, gatewayEnv, platform = process.platform) {
19
+ const env = {};
20
+ if (setting)
21
+ Object.assign(env, setting);
22
+ else
23
+ for (const name of SCREEN_VARIABLES)
24
+ if (gatewayEnv[name])
25
+ env[name] = gatewayEnv[name];
26
+ if (platform === "darwin")
27
+ return { key: "macos", label: "the screen of this Mac", env };
28
+ if (platform === "win32")
29
+ return { key: "windows", label: "the screen of this Windows computer", env };
30
+ if (env.DISPLAY)
31
+ return { key: x11Key(env.DISPLAY), label: `DISPLAY=${env.DISPLAY}`, env };
32
+ const wayland = env.WAYLAND_DISPLAY;
33
+ if (wayland) {
34
+ const socket = wayland.startsWith("/") ? wayland : join(env.XDG_RUNTIME_DIR ?? gatewayEnv.XDG_RUNTIME_DIR ?? "", wayland);
35
+ return { key: `wayland:${socket}`, label: `WAYLAND_DISPLAY=${wayland}`, env };
36
+ }
37
+ return { key: undefined, label: "no screen", env };
38
+ }
39
+ /** ":1", ":1.0", "unix:1" and "localhost:1" are one display. */
40
+ function x11Key(display) {
41
+ const match = /^(.*):(\d+)(?:\.\d+)?$/.exec(display);
42
+ if (!match)
43
+ return `x11:${display}`;
44
+ const host = ["", "unix", "localhost", "127.0.0.1"].includes(match[1]) ? "local" : match[1];
45
+ return `x11:${host}:${match[2]}`;
46
+ }
47
+ /** Machine-wide, for the processes of this user: /tmp is the same for a service and a terminal, $TMPDIR is not. */
48
+ function defaultFile() {
49
+ if (process.platform === "win32")
50
+ return join(tmpdir(), "pots-screens.sqlite");
51
+ return join("/tmp", `pots-screens-${process.getuid?.() ?? "user"}.sqlite`);
52
+ }
53
+ const SCHEMA = `
54
+ CREATE TABLE IF NOT EXISTS leases (
55
+ screen TEXT PRIMARY KEY,
56
+ bot TEXT NOT NULL,
57
+ name TEXT NOT NULL,
58
+ agent TEXT NOT NULL,
59
+ conversation TEXT NOT NULL,
60
+ pid INTEGER NOT NULL,
61
+ since INTEGER NOT NULL,
62
+ last_use INTEGER NOT NULL,
63
+ running INTEGER NOT NULL
64
+ );`;
65
+ function processAlive(pid) {
66
+ if (pid === process.pid)
67
+ return true;
68
+ try {
69
+ process.kill(pid, 0);
70
+ return true;
71
+ }
72
+ catch (error) {
73
+ return error.code === "EPERM";
74
+ }
75
+ }
76
+ /**
77
+ * The screen leases of every Pots process of this user on this machine, in one SQLite file. A lease belongs to one
78
+ * conversation and lasts across its calls, until the holder releases it (its run or child ended, the bot stopped),
79
+ * until it has not been used for the idle time, or until the holder's process is gone.
80
+ */
81
+ export class ScreenLeases {
82
+ #db;
83
+ #idleMs;
84
+ /** Running screen commands of this process, by screen and holder, for the heartbeat. */
85
+ #running = new Map();
86
+ #heartbeat;
87
+ constructor(file = defaultFile(), options = {}) {
88
+ this.#db = new DatabaseSync(file, { timeout: 10_000 });
89
+ this.#db.exec(SCHEMA);
90
+ this.#idleMs = options.idleMs ?? SCREEN_IDLE_MS;
91
+ }
92
+ static #shared;
93
+ /** The one store of this process. */
94
+ static shared() {
95
+ return (ScreenLeases.#shared ??= new ScreenLeases());
96
+ }
97
+ /** The one store of this process, once something used it. */
98
+ static get opened() {
99
+ return ScreenLeases.#shared;
100
+ }
101
+ get idleMs() {
102
+ return this.#idleMs;
103
+ }
104
+ /**
105
+ * Take the screen for a screen command of holder, or keep the lease it has. While another holder has a lease that is
106
+ * still in force, gives that lease instead. A holder has one lease: taking a screen gives up the one it had before.
107
+ * done(): the command ended.
108
+ */
109
+ take(screen, holder, now = Date.now()) {
110
+ const busy = this.#transaction(() => {
111
+ const row = this.#db.prepare("SELECT * FROM leases WHERE screen = ?").get(screen);
112
+ const mine = row !== undefined && row.bot === holder.bot && row.conversation === holder.conversation && row.pid === process.pid;
113
+ if (row && !mine && this.#inForce(row, now))
114
+ return lease(row);
115
+ this.#db
116
+ .prepare("DELETE FROM leases WHERE bot = ? AND conversation = ? AND pid = ? AND screen <> ?")
117
+ .run(holder.bot, holder.conversation, process.pid, screen);
118
+ this.#db
119
+ .prepare(`INSERT INTO leases (screen, bot, name, agent, conversation, pid, since, last_use, running) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
120
+ ON CONFLICT (screen) DO UPDATE SET bot = excluded.bot, name = excluded.name, agent = excluded.agent, conversation = excluded.conversation,
121
+ pid = excluded.pid, since = excluded.since, last_use = excluded.last_use, running = excluded.running`)
122
+ .run(screen, holder.bot, holder.name, holder.agent, holder.conversation, process.pid, mine ? row.since : now, now, mine ? row.running + 1 : 1);
123
+ return undefined;
124
+ });
125
+ if (busy)
126
+ return { ok: false, lease: busy };
127
+ const key = JSON.stringify([screen, holder.bot, holder.conversation]);
128
+ this.#running.set(key, (this.#running.get(key) ?? 0) + 1);
129
+ this.#beat();
130
+ let done = false;
131
+ return {
132
+ ok: true,
133
+ done: () => {
134
+ if (done)
135
+ return;
136
+ done = true;
137
+ const left = (this.#running.get(key) ?? 1) - 1;
138
+ if (left > 0)
139
+ this.#running.set(key, left);
140
+ else
141
+ this.#running.delete(key);
142
+ this.#beat();
143
+ this.#db
144
+ .prepare("UPDATE leases SET running = max(running - 1, 0), last_use = ? WHERE screen = ? AND bot = ? AND conversation = ? AND pid = ?")
145
+ .run(Date.now(), screen, holder.bot, holder.conversation, process.pid);
146
+ },
147
+ };
148
+ }
149
+ /** Give up the leases this process holds for the bot: of one conversation, or all of them. */
150
+ release(bot, conversation) {
151
+ if (conversation === undefined)
152
+ this.#db.prepare("DELETE FROM leases WHERE bot = ? AND pid = ?").run(bot, process.pid);
153
+ else
154
+ this.#db.prepare("DELETE FROM leases WHERE bot = ? AND conversation = ? AND pid = ?").run(bot, conversation, process.pid);
155
+ }
156
+ /** The lease in force on the screen, if any. */
157
+ holder(screen, now = Date.now()) {
158
+ const row = this.#db.prepare("SELECT * FROM leases WHERE screen = ?").get(screen);
159
+ return row && this.#inForce(row, now) ? lease(row) : undefined;
160
+ }
161
+ close() {
162
+ this.#running.clear();
163
+ this.#beat();
164
+ this.#db.close();
165
+ }
166
+ #inForce(row, now) {
167
+ return now - row.last_use < this.#idleMs && processAlive(row.pid);
168
+ }
169
+ /** A long screen command keeps its lease: its holder is not idle while it runs. */
170
+ #beat() {
171
+ if (this.#running.size === 0) {
172
+ clearInterval(this.#heartbeat);
173
+ this.#heartbeat = undefined;
174
+ return;
175
+ }
176
+ this.#heartbeat ??= setInterval(() => {
177
+ for (const key of this.#running.keys()) {
178
+ const [screen, bot, conversation] = JSON.parse(key);
179
+ this.#db.prepare("UPDATE leases SET last_use = ? WHERE screen = ? AND bot = ? AND conversation = ? AND pid = ?").run(Date.now(), screen, bot, conversation, process.pid);
180
+ }
181
+ }, HEARTBEAT_MS);
182
+ this.#heartbeat.unref();
183
+ }
184
+ #transaction(work) {
185
+ this.#db.exec("BEGIN IMMEDIATE");
186
+ try {
187
+ const result = work();
188
+ this.#db.exec("COMMIT");
189
+ return result;
190
+ }
191
+ catch (error) {
192
+ this.#db.exec("ROLLBACK");
193
+ throw error;
194
+ }
195
+ }
196
+ }
197
+ function lease(row) {
198
+ return {
199
+ screen: row.screen,
200
+ bot: row.bot,
201
+ name: row.name,
202
+ agent: row.agent,
203
+ conversation: row.conversation,
204
+ pid: row.pid,
205
+ since: row.since,
206
+ lastUse: row.last_use,
207
+ running: row.running,
208
+ };
209
+ }
210
+ /** What an agent learns when another agent has the screen. */
211
+ export function renderBusy(screen, lease, idleMs, self) {
212
+ const who = lease.bot === self ? lease.agent : `${lease.agent} of ${lease.name} (bot folder ${lease.bot})`;
213
+ return (`Not run: ${screen.label} is in use by ${who}, since ${formatTime(lease.since)}. ` +
214
+ `Its last use: ${formatTime(lease.lastUse)}${lease.running > 0 ? ", and a screen command of it is running now" : ""}. ` +
215
+ `The screen frees when that agent's work ends, or when it has not used the screen for ${Math.round(idleMs / 60_000)} minutes` +
216
+ `${lease.running > 0 ? "" : ` (at ${formatTime(lease.lastUse + idleMs)})`}.`);
217
+ }
218
+ export const NO_SCREEN = "Not run: you have no screen. The screen setting in bot.json, or the gateway's environment when that is unset, has no DISPLAY or WAYLAND_DISPLAY. " +
219
+ 'When you have found or set up a desktop, write its environment into the screen setting of bot.json, for example "screen": {"DISPLAY": ":99"}.';
220
+ //# sourceMappingURL=screen.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"screen.js","sourceRoot":"","sources":["../../src/agent/screen.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EA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O,CACL,YAAY,MAAM,CAAC,KAAK,iBAAiB,GAAG,WAAW,UAAU,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI;QAClF,iBAAiB,UAAU,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,KAAK,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC,CAAC,6CAA6C,CAAC,CAAC,CAAC,EAAE,IAAI;QACvH,wFAAwF,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC,UAAU;QAC7H,GAAG,KAAK,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,QAAQ,UAAU,CAAC,KAAK,CAAC,OAAO,GAAG,MAAM,CAAC,GAAG,GAAG,CAC7E,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,MAAM,SAAS,GACpB,mJAAmJ;IACnJ,+IAA+I,CAAC"}
package/dist/bot/bot.js CHANGED
@@ -2,18 +2,22 @@ import { randomUUID } from "node:crypto";
2
2
  import { existsSync, unlinkSync } from "node:fs";
3
3
  import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
4
4
  import { homedir } from "node:os";
5
- import { delimiter, dirname, join } from "node:path";
5
+ import { basename, delimiter, dirname, join } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { Agent, openDatabase } from "../agent/agent.js";
8
+ import { describeChild, reportRequestId } from "../agent/children.js";
9
+ import { SCREEN_VARIABLES, screenOf } from "../agent/screen.js";
8
10
  import { createJudge } from "../agent/judge.js";
9
11
  import { openResources } from "../agent/resources.js";
10
12
  import { loadChannel } from "../channels/load.js";
11
- import { SECRETS_DIR } from "../core/home.js";
13
+ import { MEMORY_DIR, SECRETS_DIR } from "../core/home.js";
14
+ import { VERSION } from "../core/version.js";
12
15
  import { Gateway } from "../gateway/gateway.js";
13
16
  import { ControlServer } from "./control.js";
14
17
  import { botPaths } from "./definition.js";
15
18
  import { describeMachine } from "./machine.js";
16
- import { folderSection, identitySection, logSection, memorySection, renderContext, renderHandoff, renderPlaceWake, renderTimerWake, workSection, } from "./prompt.js";
19
+ import { listMemoryFiles, memoryProgress, readIndex, recordMemoryChange, settleMemory } from "./memory.js";
20
+ import { childMemorySection, childSection, contextSection, folderSection, identitySection, logSection, memorySection, renderCacheUse, renderChildWake, renderContext, renderDream, renderExtraction, renderHandoff, renderMemoryNote, renderPlaceWake, renderTimerWake, workSection, } from "./prompt.js";
17
21
  const WAKES_SCHEMA = `
18
22
  CREATE TABLE IF NOT EXISTS bot_wakes (
19
23
  id TEXT PRIMARY KEY,
@@ -23,9 +27,16 @@ CREATE TABLE IF NOT EXISTS bot_wakes (
23
27
  text TEXT NOT NULL,
24
28
  submission TEXT
25
29
  );
30
+ CREATE TABLE IF NOT EXISTS bot_state (
31
+ key TEXT PRIMARY KEY,
32
+ value TEXT NOT NULL
33
+ );
26
34
  `;
27
35
  /** What the agent is told about the computer it runs on. Checked once per process, from when the gateway loads. */
28
36
  const MACHINE = describeMachine();
37
+ /** In place of pi's sections when there is nothing to list, so that the sections after them stay where they are. */
38
+ const NO_PROJECT_CONTEXT = "Project-specific instructions and guidelines: none found.";
39
+ const NO_SKILLS = "Skills: none found.";
29
40
  /** What the bot says where it was woken when its model fails. */
30
41
  const FAILURE_NOTICE = "I could not work on this: my model did not answer. The reason is in pots status on the computer I run on.";
31
42
  /** docs/ of this package, next to src/ or dist/. */
@@ -44,6 +55,8 @@ export class Bot {
44
55
  #gateway;
45
56
  #timers;
46
57
  #agent;
58
+ /** The notes of what the memory passes changed, which the next wake that goes out takes. */
59
+ #notes;
47
60
  /** Undefined when bot.json says "judge": "off". */
48
61
  #judge;
49
62
  #control;
@@ -69,6 +82,7 @@ export class Bot {
69
82
  this.#gateway = init.gateway;
70
83
  this.#timers = init.timers;
71
84
  this.#agent = init.agent;
85
+ this.#notes = init.notes;
72
86
  this.#judge = init.judge;
73
87
  this.#control = new ControlServer(init.paths.socket, this.#routes());
74
88
  let working = [];
@@ -96,6 +110,8 @@ export class Bot {
96
110
  static async start(id, dir, definition, env, print) {
97
111
  const paths = botPaths(dir);
98
112
  await mkdir(paths.workspace, { recursive: true, mode: 0o700 });
113
+ for (const folder of [paths.memory, MEMORY_DIR])
114
+ await mkdir(folder, { recursive: true, mode: 0o700 });
99
115
  // Before 0.3 the bot's AGENTS.md was persona.md.
100
116
  const persona = join(dir, "persona.md");
101
117
  if (existsSync(persona) && !existsSync(paths.agents))
@@ -120,6 +136,8 @@ export class Bot {
120
136
  }
121
137
  static async #open(id, paths, sql, definition, env, print, opened) {
122
138
  await sql.exec(WAKES_SCHEMA);
139
+ // The version whose prompt the conversation shows.
140
+ const shownVersion = (await sql.all("SELECT value FROM bot_state WHERE key = 'prompt_version'"))[0]?.value;
123
141
  let bot;
124
142
  const self = () => {
125
143
  if (!bot)
@@ -135,6 +153,7 @@ export class Bot {
135
153
  settings,
136
154
  fallbackWakeMinutes: () => settings().fallbackWakeMinutes,
137
155
  fireTimer: (timer, caller) => self().#deliverTimer(timer, caller),
156
+ filesDir: paths.files,
138
157
  print,
139
158
  });
140
159
  const timers = gateway.timers;
@@ -149,10 +168,26 @@ export class Bot {
149
168
  docs: DOCS_DIR,
150
169
  secretsDir: SECRETS_DIR,
151
170
  fallbackWakeMinutes: current().settings.fallbackWakeMinutes,
152
- accounts: gateway.channels.map((channel) => ({ channel: channel.id, ...(channel.me ? { me: channel.me } : {}) })),
171
+ sharedMemory: MEMORY_DIR,
153
172
  });
154
173
  // AGENTS.md and skills as a pi session finds them from the bot's working directory, so its own folder's AGENTS.md.
155
174
  const resources = await openResources(paths.workspace, print);
175
+ // After the bot's own sections, as pi puts them after a custom system prompt. Rendered in this order, so the skills
176
+ // are those of the same scan.
177
+ const projectContext = {
178
+ name: "project_context",
179
+ render: async () => {
180
+ await resources.reload();
181
+ return resources.projectContext() ?? NO_PROJECT_CONTEXT;
182
+ },
183
+ };
184
+ const skills = { name: "skills", render: () => resources.skills() ?? NO_SKILLS };
185
+ // The memory, as Claude Code's auto memory: files in the bot's memory folder and in the one all bots share.
186
+ const folders = { own: paths.memory, shared: MEMORY_DIR };
187
+ const memoryOn = () => settings().autoMemory;
188
+ const indexes = async () => ({ own: await readIndex(folders.own), shared: await readIndex(folders.shared) });
189
+ /** The notes of what the memory passes changed, for the next wake: in the process, as in Claude Code. */
190
+ const notes = [];
156
191
  const agent = await Agent.open({
157
192
  database: sql,
158
193
  models: env.models,
@@ -160,29 +195,64 @@ export class Bot {
160
195
  thinking: definition.thinking,
161
196
  compaction: () => settings().compaction,
162
197
  workspace: paths.workspace,
198
+ // Without the screen's variables: a command that uses the screen goes through the screen tool, which holds the
199
+ // screen for one agent at a time.
163
200
  shellEnv: {
164
- ...process.env,
201
+ ...Object.fromEntries(Object.entries(process.env).filter(([name]) => !SCREEN_VARIABLES.includes(name))),
165
202
  POTS_BOT: id,
166
203
  PATH: `${dirname(env.potsCommand)}${delimiter}${process.env.PATH ?? ""}`,
167
204
  HOME: process.env.HOME ?? homedir(),
168
205
  },
206
+ screen: { current: () => screenOf(current().screen, process.env), bot: paths.dir, name: () => current().name },
207
+ // The start of every request, so the provider's prompt cache can keep it: only facts that stay the same. What
208
+ // changes from one wake to the next (the time, the context use, the bot's own address in a channel) is in the
209
+ // wake. The bot's own sections are pinned for the page; a new name shows at once, as AGENTS.md and skills do,
210
+ // since people change them on purpose. New sections go at the end, and every section always has a text.
169
211
  sections: [
170
212
  { name: "identity", render: () => identitySection(facts()) },
171
- { name: "work", render: () => workSection(facts()) },
172
- { name: "log", render: () => logSection(facts()) },
173
- { name: "folder", render: () => folderSection(facts()) },
174
- { name: "memory", render: () => memorySection(facts()) },
175
- // After the bot's own sections, as pi puts them after a custom system prompt. Rendered in this order, so the
176
- // skills are those of the same scan.
177
- {
178
- name: "project_context",
179
- render: async () => {
180
- await resources.reload();
181
- return resources.projectContext();
182
- },
183
- },
184
- { name: "skills", render: () => resources.skills() },
213
+ { name: "work", render: () => workSection(facts()), pin: true },
214
+ { name: "log", render: () => logSection(facts()), pin: true },
215
+ { name: "folder", render: () => folderSection(facts()), pin: true },
216
+ // About the context; its name is from before the bot had a memory, and a new name would move it.
217
+ { name: "memory", render: () => contextSection(facts()), pin: true },
218
+ projectContext,
219
+ skills,
220
+ // Without the memory, no section: it is the last one, so the others stay where they are.
221
+ { name: "remembered", render: async () => (memoryOn() ? memorySection(facts(), await indexes()) : undefined), pin: true },
185
222
  ],
223
+ children: {
224
+ model: () => current().childModel,
225
+ thinking: () => current().childThinking,
226
+ max: () => settings().maxChildren,
227
+ // The same for every child, so children share the start of their requests; then the memory's indexes, as they
228
+ // were when the child started.
229
+ sections: [
230
+ { name: "child", render: () => childSection(facts()) },
231
+ { name: "log", render: () => logSection(facts()) },
232
+ { name: "folder", render: () => folderSection(facts(), true) },
233
+ projectContext,
234
+ skills,
235
+ { name: "remembered", render: async () => (memoryOn() ? childMemorySection(facts(), await indexes()) : undefined), pin: true },
236
+ ],
237
+ place: () => (bot ? bot.#currentPlace() : undefined),
238
+ ended: (end) => self().#deliverChildEnd(end),
239
+ },
240
+ // What a new version says counts at once; without an upgrade, the sections stay as the page began.
241
+ ...(shownVersion === VERSION
242
+ ? {}
243
+ : {
244
+ refreshPinned: () => sql.run("INSERT INTO bot_state (key, value) VALUES ('prompt_version', ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value", VERSION),
245
+ }),
246
+ memory: {
247
+ enabled: memoryOn,
248
+ folders,
249
+ extraction: async (messages) => renderExtraction(messages, await listMemoryFiles(folders), folders),
250
+ dream: async (progress) => renderDream(facts(), progress),
251
+ progress: () => memoryProgress(sql),
252
+ changed: (source) => recordMemoryChange(sql, source),
253
+ settle: (update) => settleMemory(sql, update),
254
+ noted: (note) => notes.push(note),
255
+ },
186
256
  actions: {
187
257
  send: (to, text, sendId, trace) => self().send(to, text, sendId, trace),
188
258
  react: (message, emoji, remove, trace) => self().react(message, emoji, remove, trace),
@@ -195,7 +265,7 @@ export class Bot {
195
265
  throw error;
196
266
  });
197
267
  opened(agent);
198
- bot = new Bot({ id, paths, definition, env, print, sql, gateway, timers, agent, judge });
268
+ bot = new Bot({ id, paths, definition, env, print, sql, gateway, timers, agent, judge, notes });
199
269
  // Crash tests: with one of these files in the bot folder, the process dies at that point, once.
200
270
  const crashTest = (file, message, key) => (id) => {
201
271
  if (!existsSync(file))
@@ -210,6 +280,13 @@ export class Bot {
210
280
  // Right after the bot took a wake, before the gateway records that. The next start must deliver the same wake again,
211
281
  // which the agent counts once, instead of deciding its events anew.
212
282
  gateway.waker.afterDeliver = crashTest(paths.crashAfterWake, "crash test: dying after the wake", "wakeId");
283
+ // Around the report of a child's end to the main agent. The next start must report it once.
284
+ agent.crashTests.beforeReport = crashTest(paths.crashBeforeChildReport, "crash test: dying before the child's report", "reporter");
285
+ agent.crashTests.afterReport = crashTest(paths.crashAfterChildReport, "crash test: dying after the child's report", "reporter");
286
+ // Right after a stop marked a child stopped, before its work ended. The next start must end that work.
287
+ agent.crashTests.afterStopMark = crashTest(paths.crashAfterChildStop, "crash test: dying after marking the child stopped", "child");
288
+ // Right before a memory pass forks the main conversation. The next start must make the pass.
289
+ agent.crashTests.beforeMemoryPass = () => crashTest(paths.crashBeforeMemoryPass, "crash test: dying before the memory pass", "bot")(id);
213
290
  for (const row of await sql.all("SELECT submission, place FROM bot_wakes WHERE submission IS NOT NULL AND place IS NOT NULL ORDER BY at DESC LIMIT 1000")) {
214
291
  bot.#submissionPlaces.set(row.submission, row.place);
215
292
  }
@@ -217,7 +294,7 @@ export class Bot {
217
294
  try {
218
295
  adapters = await Promise.all(definition.channels.map((channel) => bot.#loadChannel(channel)));
219
296
  await gateway.start(bot, adapters);
220
- agent.resume();
297
+ await agent.resume();
221
298
  await timers.start();
222
299
  if (existsSync(paths.firstWake)) {
223
300
  await timers.add(Date.now(), await readFile(paths.firstWake, "utf8"));
@@ -260,6 +337,10 @@ export class Bot {
260
337
  const before = this.#definition;
261
338
  if (before.model !== next.model || before.thinking !== next.thinking)
262
339
  await this.#agent.configure(next.model, next.thinking);
340
+ // Also for the children that exist: those without a model of their own use the main one. A child keeps its thinking
341
+ // level; childThinking counts for new children.
342
+ if (before.model !== next.model || before.childModel !== next.childModel)
343
+ await this.#agent.configureChildren(next.childModel);
263
344
  const old = new Map(before.channels.map((channel) => [channel.id, JSON.stringify(channel)]));
264
345
  const fresh = new Map(next.channels.map((channel) => [channel.id, JSON.stringify(channel)]));
265
346
  const nameChanged = before.name !== next.name;
@@ -291,6 +372,9 @@ export class Bot {
291
372
  return this.#definition.name;
292
373
  }
293
374
  isWorkingOn(place) {
375
+ // A child that works for the place: new events there go to the main agent, which can pass them on.
376
+ if (this.#workingChildren(place).length > 0)
377
+ return true;
294
378
  const inputs = this.#agent.runInputs;
295
379
  if (!inputs)
296
380
  return false;
@@ -298,19 +382,57 @@ export class Bot {
298
382
  return true;
299
383
  return inputs.some((submission) => this.#submissionPlaces.get(submission) === place);
300
384
  }
385
+ /** The children that work now, for one place or all. */
386
+ #workingChildren(place) {
387
+ return this.#agent.children.filter((child) => child.since !== undefined && child.stoppedAt === undefined && (place === undefined || child.place === place));
388
+ }
389
+ /** The place the main agent works on now, when its run is about one place. */
390
+ #currentPlace() {
391
+ const places = new Set((this.#agent.runInputs ?? []).map((submission) => this.#submissionPlaces.get(submission)).filter((place) => place !== undefined));
392
+ return places.size === 1 ? [...places][0] : undefined;
393
+ }
301
394
  async deliver(wake, caller) {
302
- const text = renderPlaceWake(wake, await this.#agent.contextStatus());
395
+ const me = this.#gateway.channels.find((channel) => channel.owns(wake.place.address))?.me;
396
+ const text = renderPlaceWake(wake, await this.#agent.contextStatus(), me, this.#workingChildren(wake.place.address));
303
397
  return this.#submit(wake.id, wake.reason, wake.place.address, text, wake.reason === "steer", caller);
304
398
  }
305
399
  responsibilities() {
306
400
  return readFile(this.paths.responsibilities, "utf8").catch(() => "");
307
401
  }
308
402
  async #deliverTimer(timer, caller) {
309
- const text = renderTimerWake(timer, await this.#agent.contextStatus(), this.#definition.settings.fallbackWakeMinutes);
403
+ const text = renderTimerWake(timer, await this.#agent.contextStatus(), this.#definition.settings.fallbackWakeMinutes, this.#workingChildren());
310
404
  return this.#submit(`timer:${timer.id}`, timer.set_by === "fallback" ? "fallback" : "timer", undefined, text, false, caller);
311
405
  }
406
+ /** A child ended: a wake for the main agent, once per reporter, also when this runs again after a restart. */
407
+ async #deliverChildEnd(end) {
408
+ // Handed over before a restart: the same submission, and no second wake in the trace.
409
+ const id = reportRequestId(end.reporter);
410
+ const before = (await this.#sql.all("SELECT submission FROM bot_wakes WHERE id = ?", id))[0];
411
+ if (before)
412
+ return before.submission;
413
+ const text = renderChildWake(end, await this.#agent.contextStatus());
414
+ const delivered = await this.#gateway.wake({ reason: "child", child: end.child.id, ...(end.child.place ? { place: end.child.place } : {}) }, (caller) => this.#submit(id, "child", end.child.place, text, false, caller));
415
+ return delivered.submission;
416
+ }
312
417
  async #submit(id, reason, place, text, steer, caller) {
313
- const { id: submission, trace } = await this.#agent.submit({ id, text, steer, data: { reason, ...(place ? { place } : {}) }, caller });
418
+ // What the memory passes changed since the last wake, once, at the end of this one, as Claude Code tells it. Taken
419
+ // at once, so two wakes never give the same note; not by a wake given again after a crash, which does not go out
420
+ // again; and put back when the wake could not go out.
421
+ const notes = (await this.#agent.submitted(id)) ? [] : this.#notes.splice(0);
422
+ if (notes.length > 0) {
423
+ const read = await this.#agent.readFiles().catch(() => new Set());
424
+ const stale = (paths) => paths.filter((path) => basename(path) === "MEMORY.md" || read.has(path));
425
+ text = [text, ...notes.map((note) => renderMemoryNote(note, stale([...note.written, ...note.deleted])))].join("\n\n");
426
+ }
427
+ let submitted;
428
+ try {
429
+ submitted = await this.#agent.submit({ id, text, steer, data: { reason, ...(place ? { place } : {}) }, caller });
430
+ }
431
+ catch (error) {
432
+ this.#notes.unshift(...notes);
433
+ throw error;
434
+ }
435
+ const { id: submission, trace } = submitted;
314
436
  if (place)
315
437
  this.#submissionPlaces.set(submission, place);
316
438
  await this.#sql.run("INSERT OR IGNORE INTO bot_wakes (id, at, reason, place, text, submission) VALUES (?, ?, ?, ?, ?, ?)", id, Date.now(), reason, place ?? null, text, submission);
@@ -359,7 +481,7 @@ export class Bot {
359
481
  }
360
482
  async turnPage(note) {
361
483
  const notes = await readFile(this.paths.notes, "utf8").catch(() => "");
362
- await this.#agent.turnPage(renderHandoff(note, notes, this.paths.notes));
484
+ await this.#agent.turnPage(renderHandoff(note, notes, this.paths.notes, this.#workingChildren()));
363
485
  this.#print("turn page", { notesChars: notes.length });
364
486
  return { notesChars: notes.length };
365
487
  }
@@ -387,16 +509,29 @@ export class Bot {
387
509
  return "cancelled";
388
510
  },
389
511
  "GET /context": async () => {
390
- const status = await this.#agent.contextStatus();
391
- return { ...status, text: renderContext(status) };
512
+ const [status, cache] = await Promise.all([this.#agent.contextStatus(), this.#agent.cacheUse()]);
513
+ return { ...status, cache, text: `${renderContext(status)}\n${renderCacheUse(cache)}` };
392
514
  },
393
515
  "POST /turn-page": async (body) => this.turnPage(text(body.note, "note")),
516
+ "GET /children": async () => {
517
+ const now = Date.now();
518
+ const children = this.#agent.children;
519
+ return { children, text: children.length === 0 ? "No children." : children.map((child) => describeChild(child, now, { thinking: true })).join("\n") };
520
+ },
521
+ "POST /children/stop": async (body) => {
522
+ if (body.all === true) {
523
+ const results = await this.#agent.stopChildren();
524
+ return results.length === 0 ? "No children to stop." : results.join("\n");
525
+ }
526
+ return this.#agent.stopChild(text(body.id, "id"));
527
+ },
394
528
  "GET /status": async () => ({
395
529
  id: this.id,
396
530
  name: this.#definition.name,
397
531
  model: this.#definition.model,
398
532
  judge: this.#definition.judge,
399
533
  busy: this.#agent.runInputs !== undefined,
534
+ children: this.#workingChildren().length,
400
535
  ...(this.#lastError ? { lastError: this.#lastError } : {}),
401
536
  channels: this.#gateway.channels.map((channel) => ({ id: channel.id, me: channel.me?.address })),
402
537
  }),