pi-durable-bot 0.3.3 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +42 -18
  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 +19 -4
  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/trace.js +87 -15
  34. package/dist/cli/trace.js.map +1 -1
  35. package/dist/core/channel.js +2 -0
  36. package/dist/core/channel.js.map +1 -1
  37. package/dist/core/home.js +2 -0
  38. package/dist/core/home.js.map +1 -1
  39. package/dist/core/time.js +18 -0
  40. package/dist/core/time.js.map +1 -0
  41. package/dist/core/version.js +4 -0
  42. package/dist/core/version.js.map +1 -0
  43. package/dist/gateway/config.js.map +1 -1
  44. package/dist/gateway/files.js +245 -0
  45. package/dist/gateway/files.js.map +1 -0
  46. package/dist/gateway/gateway.js +21 -3
  47. package/dist/gateway/gateway.js.map +1 -1
  48. package/dist/gateway/log.js +7 -2
  49. package/dist/gateway/log.js.map +1 -1
  50. package/dist/gateway/tracing.js +1 -3
  51. package/dist/gateway/tracing.js.map +1 -1
  52. package/dist/gateway/waker.js +64 -5
  53. package/dist/gateway/waker.js.map +1 -1
  54. package/docs/for-agents.md +4 -3
  55. package/package.json +1 -1
@@ -0,0 +1,573 @@
1
+ import { lstat, readdir, stat } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { isAbsolute, join, resolve, sep } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { AssistantEntry, configure, defineExtension, GenerationTask, hook, ProviderDoc, ROOT_CONVERSATION_ID, ToolTask, } from "@earendil-works/pi-durable";
6
+ /** An extraction pass has at most this many turns, as in Claude Code; a dream has no cap, as there. */
7
+ const EXTRACTION_TURNS = 5;
8
+ /** Claude Code's auto dream: 24 hours since the last one, and 5 sessions (here: memory changes) since then. */
9
+ const DREAM_HOURS = 24;
10
+ const DREAM_CHANGES = 5;
11
+ const DAY = 86_400_000;
12
+ /** A fork's shell command without a timeout of its own ends after this long, as Claude Code's Bash does by default. */
13
+ const SHELL_TIMEOUT_SECONDS = 120;
14
+ /** Whether a dream is due after a pass. */
15
+ export function dreamDue(progress, now = Date.now()) {
16
+ return progress.changes >= DREAM_CHANGES && (progress.dreamAt === undefined || now - progress.dreamAt >= DREAM_HOURS * 3_600_000);
17
+ }
18
+ // ---- Paths ----
19
+ /** A path as pi's file tools take it: no leading "@", odd spaces as spaces, ~ for home, relative to the working directory. */
20
+ function toolPath(cwd, path) {
21
+ let normalized = path.replace(/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g, " ");
22
+ if (normalized.startsWith("@"))
23
+ normalized = normalized.slice(1);
24
+ if (normalized === "~")
25
+ normalized = homedir();
26
+ else if (normalized.startsWith("~/") || (process.platform === "win32" && normalized.startsWith("~\\")))
27
+ normalized = join(homedir(), normalized.slice(2));
28
+ else if (normalized.startsWith("file://")) {
29
+ try {
30
+ normalized = fileURLToPath(normalized);
31
+ }
32
+ catch {
33
+ // As in pi: a malformed URL is an ordinary path.
34
+ }
35
+ }
36
+ return resolve(cwd, normalized);
37
+ }
38
+ function within(path, folder) {
39
+ return path.startsWith(folder.endsWith(sep) ? folder : folder + sep);
40
+ }
41
+ /** The memory folder a path is in, by its name alone. */
42
+ function folderOf(path, folders) {
43
+ return [folders.own, folders.shared].find((folder) => within(path, folder));
44
+ }
45
+ /**
46
+ * Whether a path, absolute and normalized, is a .md file inside a memory folder with no symbolic link below the folder,
47
+ * also a dangling one: a tool that follows a link would write or delete outside the folder.
48
+ */
49
+ async function memoryFile(path, folders) {
50
+ const folder = folderOf(path, folders);
51
+ if (!folder || !path.endsWith(".md"))
52
+ return false;
53
+ let current = folder;
54
+ for (const part of path.slice(folder.length).split(sep).filter(Boolean)) {
55
+ current = join(current, part);
56
+ try {
57
+ if ((await lstat(current)).isSymbolicLink())
58
+ return false;
59
+ }
60
+ catch (error) {
61
+ // Nothing more of the path exists, so no link either; anything else is refused.
62
+ return error.code === "ENOENT";
63
+ }
64
+ }
65
+ return true;
66
+ }
67
+ // ---- Shell commands ----
68
+ //
69
+ // A fork's bash command is checked as bash runs it. The words are taken only from what bash passes on unchanged: plain
70
+ // characters, single quotes, and double quotes without $, backticks or backslashes. Anything bash would expand or
71
+ // interpret ($, backticks, backslashes, globs, braces, ~, ;, &, (, ), <, and > but in a redirect alone) is refused, so the
72
+ // words checked are the words that run. Then each command of the pipeline must be one of a short list, with its options
73
+ // allowlisted where an option could write or run something.
74
+ /** The commands a memory fork may run, also joined by pipes; rm only alone, of .md files in the memory folders. */
75
+ const READ_ONLY = new Set(["ls", "find", "grep", "cat", "stat", "wc", "head", "tail", "sqlite3"]);
76
+ /** find's tests and actions that only read and print, and the operators. */
77
+ const FIND_PRIMARIES = new Set(["-print", "-print0", "-ls", "-empty", "!", "-not", "-a", "-and", "-o", "-or", "(", ")"]);
78
+ /** find's tests and options that take one argument. */
79
+ const FIND_WITH_ARGUMENT = new Set(["-name", "-iname", "-path", "-ipath", "-type", "-maxdepth", "-mindepth", "-mtime", "-mmin", "-newer", "-size"]);
80
+ /** sqlite3's output-format flags, after -readonly -safe. */
81
+ const SQLITE_FORMATS = new Set(["-ascii", "-box", "-column", "-csv", "-html", "-json", "-line", "-list", "-markdown", "-quote", "-table", "-tabs", "-header", "-noheader"]);
82
+ const SQLITE_FORMATS_WITH_ARGUMENT = new Set(["-separator", "-newline", "-nullvalue"]);
83
+ /** A redirect that writes nothing, alone as a word: errors to /dev/null, or one output into another. */
84
+ const REDIRECT = /^(?:2>\/dev\/null|\d>&\d)(?=[ \t|]|$)/;
85
+ /** A command as the words of its piped commands, as bash passes them; or why it is refused. */
86
+ export function parseShell(command) {
87
+ const pipeline = [[]];
88
+ let word;
89
+ const end = () => {
90
+ if (word !== undefined)
91
+ pipeline.at(-1).push(word);
92
+ word = undefined;
93
+ };
94
+ for (let i = 0; i < command.length; i++) {
95
+ const char = command[i];
96
+ if (char === " " || char === "\t") {
97
+ end();
98
+ }
99
+ else if (char === "'") {
100
+ const close = command.indexOf("'", i + 1);
101
+ if (close < 0)
102
+ return "a quote is not closed";
103
+ word = (word ?? "") + command.slice(i + 1, close);
104
+ i = close;
105
+ }
106
+ else if (char === '"') {
107
+ const close = command.indexOf('"', i + 1);
108
+ if (close < 0)
109
+ return "a quote is not closed";
110
+ const text = command.slice(i + 1, close);
111
+ if (/[$`\\]/.test(text))
112
+ return "$, backticks and backslashes are refused in double quotes; use single quotes";
113
+ word = (word ?? "") + text;
114
+ i = close;
115
+ }
116
+ else if (char === "|") {
117
+ if (command[i + 1] === "|" || command[i + 1] === "&")
118
+ return "|| and |& are refused";
119
+ end();
120
+ if (pipeline.at(-1).length === 0)
121
+ return "a pipe has no command before it";
122
+ pipeline.push([]);
123
+ }
124
+ else if (word === undefined && REDIRECT.test(command.slice(i))) {
125
+ // Not a word of the command: bash takes it away.
126
+ i += REDIRECT.exec(command.slice(i))[0].length - 1;
127
+ }
128
+ else if ("$`\\*?[]{}~;&()<>#\n\r".includes(char)) {
129
+ return `${char === "\n" || char === "\r" ? "a new line" : char} is refused outside single quotes; a redirect may only be 2>/dev/null or N>&M, alone`;
130
+ }
131
+ else {
132
+ word = (word ?? "") + char;
133
+ }
134
+ }
135
+ end();
136
+ if (pipeline.some((words) => words.length === 0))
137
+ return "a pipe has no command after it";
138
+ return pipeline;
139
+ }
140
+ /** Why a command of a pipeline is not one of the read-only ones, or undefined when it is. */
141
+ function notReadOnly(words, first) {
142
+ const [program, ...args] = words;
143
+ if (!program || !READ_ONLY.has(program))
144
+ return `${program ?? "it"} is not one of the commands that are permitted`;
145
+ if (program === "find") {
146
+ let i = 0;
147
+ while (i < args.length && !args[i].startsWith("-") && !["!", "(", ")"].includes(args[i]))
148
+ i++;
149
+ for (; i < args.length; i++) {
150
+ if (FIND_WITH_ARGUMENT.has(args[i]) && i + 1 < args.length)
151
+ i++;
152
+ else if (!FIND_PRIMARIES.has(args[i]))
153
+ return `find takes only ${[...FIND_WITH_ARGUMENT, ...FIND_PRIMARIES].join(" ")} here, not ${args[i]}`;
154
+ }
155
+ }
156
+ if (program === "sqlite3") {
157
+ if (!first)
158
+ return "sqlite3 may not read from a pipe";
159
+ if (args[0] !== "-readonly" || args[1] !== "-safe")
160
+ return "sqlite3 must start with -readonly -safe";
161
+ let i = 2;
162
+ for (; i < args.length && args[i].startsWith("-"); i++) {
163
+ if (SQLITE_FORMATS_WITH_ARGUMENT.has(args[i]) && i + 1 < args.length)
164
+ i++;
165
+ else if (!SQLITE_FORMATS.has(args[i]))
166
+ return `sqlite3 takes only output-format flags after -readonly -safe, not ${args[i]}`;
167
+ }
168
+ // The database, then SQL: a word that starts with "-" would be an option, one that starts with "." a dot-command.
169
+ if (args.slice(i).some((arg) => /^\s*[-.]/.test(arg)))
170
+ return 'after the database, sqlite3 takes only SQL, no word that starts with "-" or "."';
171
+ }
172
+ return undefined;
173
+ }
174
+ /** The files of an rm as Claude Code allows it: one command, no flags but -f, absolute paths with no "..". */
175
+ function rmTargets(pipeline) {
176
+ if (pipeline.length !== 1 || pipeline[0][0] !== "rm")
177
+ return undefined;
178
+ const paths = [];
179
+ let options = true;
180
+ for (const arg of pipeline[0].slice(1)) {
181
+ if (options && arg === "--")
182
+ options = false;
183
+ else if (options && arg.startsWith("-")) {
184
+ if (arg !== "-f" && arg !== "--force")
185
+ return undefined;
186
+ }
187
+ else if (!isAbsolute(arg) || arg.split(/[/\\]/).includes(".."))
188
+ return undefined;
189
+ else
190
+ paths.push(resolve(arg));
191
+ }
192
+ return paths.length > 0 ? paths : undefined;
193
+ }
194
+ /** The constraints a fork's refused bash command is told, with why it was refused. */
195
+ function shellConstraints(why, where) {
196
+ return (`Refused: ${why}. Only read-only shell commands (ls, find, grep, cat, stat, wc, head, tail and sqlite3 -readonly -safe, also joined by pipes) and rm (no flags except -f) of .md files under ${where} are permitted in this context. ` +
197
+ "Anything else that writes, redirects to a file, runs other programs or modifies state is denied.");
198
+ }
199
+ /** The files a fork's tool call changes: write and edit's path, rm's files. */
200
+ function targets(name, args, cwd) {
201
+ if ((name === "write" || name === "edit") && typeof args.path === "string")
202
+ return [toolPath(cwd, args.path)];
203
+ if (name !== "bash" || typeof args.command !== "string")
204
+ return [];
205
+ const pipeline = parseShell(args.command);
206
+ return (typeof pipeline !== "string" && rmTargets(pipeline)) || [];
207
+ }
208
+ /** Why a memory fork may not run this tool call, or undefined when it may. */
209
+ export async function forkRefusal(name, args, folders, cwd) {
210
+ const where = `${folders.own} or ${folders.shared}`;
211
+ if (name === "read")
212
+ return undefined;
213
+ if ((name === "write" || name === "edit") && typeof args.path === "string" && (await memoryFile(toolPath(cwd, args.path), folders)))
214
+ return undefined;
215
+ if (name === "bash") {
216
+ const pipeline = typeof args.command === "string" ? parseShell(args.command) : "there is no command";
217
+ if (typeof pipeline === "string")
218
+ return shellConstraints(pipeline, where);
219
+ const why = pipeline.map((words, index) => notReadOnly(words, index === 0)).find((each) => each !== undefined);
220
+ if (why === undefined)
221
+ return undefined;
222
+ if (pipeline[0][0] !== "rm")
223
+ return shellConstraints(why, where);
224
+ const files = rmTargets(pipeline);
225
+ if (!files)
226
+ return shellConstraints("rm runs only alone, with no flags but -f, of absolute paths without ..", where);
227
+ for (const file of files)
228
+ if (!(await memoryFile(file, folders)))
229
+ return shellConstraints(`${file} is not a .md file in a memory folder, or a link is on its way`, where);
230
+ return undefined;
231
+ }
232
+ return `only read, read-only bash, and write/edit of .md files within ${where} are allowed in this context`;
233
+ }
234
+ /**
235
+ * Whether a main agent's tool call meant to write, edit or delete a file in a memory folder: write or edit of a path
236
+ * there, an rm of a .md file there, or a command that names a path there and is not read-only by the fork's list. A
237
+ * command the checker cannot read says nothing either way, and does not count.
238
+ */
239
+ function writesMemory(name, args, folders, cwd) {
240
+ if ((name === "write" || name === "edit") && typeof args.path === "string")
241
+ return folderOf(toolPath(cwd, args.path), folders) !== undefined;
242
+ if ((name !== "bash" && name !== "screen") || typeof args.command !== "string")
243
+ return false;
244
+ const pipeline = parseShell(args.command);
245
+ if (typeof pipeline === "string")
246
+ return false;
247
+ const removed = rmTargets(pipeline);
248
+ if (removed)
249
+ return removed.some((path) => path.endsWith(".md") && folderOf(path, folders) !== undefined);
250
+ const names = pipeline.some((words) => words.some((word) => folderOf(toolPath(cwd, word), folders) !== undefined));
251
+ return names && pipeline.some((words, index) => notReadOnly(words, index === 0) !== undefined);
252
+ }
253
+ // ---- The age note ----
254
+ /** Claude Code's note on a memory read 2 days or more after it last changed. */
255
+ function ageNote(days) {
256
+ return `<system-reminder>This memory is ${days} days old. Memories are point-in-time observations, not live state — claims about people, places, files or plans may be outdated. Verify against what is true now before asserting as fact.</system-reminder>\n`;
257
+ }
258
+ /** A read result, with the age note in front when the file is in a memory folder and 2 days old or more, as in Claude Code. */
259
+ export async function withAgeNote(result, path, folders, cwd) {
260
+ const file = toolPath(cwd, path);
261
+ const [first, ...rest] = result.output ?? [];
262
+ if (!folders || !folderOf(file, folders) || first?.type !== "text")
263
+ return result;
264
+ const changed = (await stat(file).catch(() => undefined))?.mtimeMs;
265
+ const days = changed === undefined ? 0 : Math.floor((Date.now() - changed) / DAY);
266
+ return days < 2 ? result : { ...result, output: [{ ...first, text: ageNote(days) + first.text }, ...rest] };
267
+ }
268
+ async function stateOf(path) {
269
+ return (await lstat(path).catch(() => undefined))?.mtimeMs;
270
+ }
271
+ /** Every file of the memory folders and their subfolders, with its modification time. */
272
+ async function snapshotOf(folders) {
273
+ const snapshot = new Map();
274
+ for (const folder of [folders.own, folders.shared]) {
275
+ for (const name of await readdir(folder, { recursive: true }).catch(() => [])) {
276
+ const path = join(folder, name);
277
+ const state = await stateOf(path);
278
+ if (state !== undefined)
279
+ snapshot.set(path, state);
280
+ }
281
+ }
282
+ return snapshot;
283
+ }
284
+ /** What a file should be for the fork to change it: as the fork left it, or else as it was when the pass began. */
285
+ function expected(state, path) {
286
+ return state.own.has(path) ? state.own.get(path) : state.snapshot.get(path);
287
+ }
288
+ /** The messages of the context after entry `after`, all of them without it: what came in, what the agent said and its tool results. */
289
+ function since(view, after) {
290
+ return view.entries
291
+ .flatMap((entry, index) => (after === undefined || entry.id > after ? [...(view.contributions[index] ?? [])] : []))
292
+ .filter((message) => message.role !== "system");
293
+ }
294
+ export class MemoryPasses {
295
+ /** Selected in a fork only: the tool limits, the turn cap and the record of what it changed. */
296
+ extension;
297
+ #host;
298
+ #sql;
299
+ #cwd;
300
+ #context;
301
+ #log;
302
+ #forks = new Map();
303
+ #harness;
304
+ #root;
305
+ #running;
306
+ /** A run that ended while a pass ran: one trailing pass covers it, as in Claude Code. */
307
+ #trailing;
308
+ #closing = false;
309
+ /** Crash tests: called right before a pass forks the main conversation. */
310
+ beforePass;
311
+ constructor(options) {
312
+ this.#host = options.host;
313
+ this.#sql = options.sql;
314
+ this.#cwd = options.cwd;
315
+ this.#context = options.context;
316
+ this.#log = options.log;
317
+ const fork = (id) => this.#forks.get(Number(id));
318
+ this.extension = defineExtension({
319
+ name: "memory-fork",
320
+ hooks: [
321
+ hook(ToolTask, {
322
+ beforeTool: async (call, api) => {
323
+ const refusal = await forkRefusal(call.name, call.arguments, this.#host.folders, this.#cwd);
324
+ if (refusal !== undefined)
325
+ return { block: refusal };
326
+ // A file another writer, such as the main agent, changed, created or deleted after the pass began: the
327
+ // fork's copy is old.
328
+ const state = fork(api.conversationId);
329
+ for (const path of state ? targets(call.name, call.arguments, this.#cwd) : []) {
330
+ if ((await stateOf(path)) !== expected(state, path)) {
331
+ return { block: `${path} changed after this memory pass began, so this pass may not change it: another writer has a newer copy.` };
332
+ }
333
+ }
334
+ // The passes run one at a time: a command that never ends, such as tail -f, must not hold up the next ones.
335
+ if (call.name === "bash" && call.arguments.timeout === undefined)
336
+ return { arguments: { ...call.arguments, timeout: SHELL_TIMEOUT_SECONDS } };
337
+ return undefined;
338
+ },
339
+ afterTool: async (call, _result, api) => {
340
+ const state = fork(api.conversationId);
341
+ if (!state)
342
+ return undefined;
343
+ // By what is on the disk: an rm that failed for one file may have deleted another.
344
+ for (const path of targets(call.name, call.arguments, this.#cwd)) {
345
+ const now = await stateOf(path);
346
+ const before = expected(state, path);
347
+ if (now === before)
348
+ continue;
349
+ state.own.set(path, now);
350
+ if (now === undefined) {
351
+ state.written.delete(path);
352
+ state.deleted.add(path);
353
+ }
354
+ else {
355
+ state.deleted.delete(path);
356
+ state.written.add(path);
357
+ }
358
+ if (!state.recorded) {
359
+ state.recorded = true;
360
+ await this.#host.changed(state.source);
361
+ }
362
+ }
363
+ return undefined;
364
+ },
365
+ }),
366
+ hook(GenerationTask, {
367
+ afterTools: (_assistant, _results, api) => {
368
+ const state = fork(api.conversationId);
369
+ if (state)
370
+ state.rounds++;
371
+ },
372
+ // After the last turn's tools there is no next request: the run ends, as Claude Code's maxTurns ends it.
373
+ beforeRequest: async (_request, api, context) => {
374
+ const state = fork(api.conversationId);
375
+ if (state?.maxTurns === undefined || state.rounds < state.maxTurns)
376
+ return undefined;
377
+ const signal = context.abortSignal;
378
+ void this.#harness?.abortTask(api.taskId, this.#context).catch(() => { });
379
+ await new Promise((done) => (signal?.aborted ? done(undefined) : signal?.addEventListener("abort", done, { once: true })));
380
+ throw signal?.reason ?? new Error("the memory pass reached its turn cap");
381
+ },
382
+ }),
383
+ ],
384
+ });
385
+ }
386
+ attach(harness, root) {
387
+ this.#harness = harness;
388
+ this.#root = root;
389
+ }
390
+ /** What a fork changed before the last process stopped or died: its note and memory change, before any new pass. */
391
+ async recover() {
392
+ await this.#host.settle({});
393
+ }
394
+ /** A run of the main conversation answered with entry `at`: a pass for it, now or after the one that runs. */
395
+ queue(at) {
396
+ if (this.#closing || !this.#host.enabled())
397
+ return;
398
+ if (this.#running) {
399
+ this.#trailing = Math.max(this.#trailing ?? 0, at);
400
+ return;
401
+ }
402
+ this.#running = (async () => {
403
+ for (let next = at; next !== undefined && !this.#closing; next = this.#takeTrailing()) {
404
+ try {
405
+ await this.#pass(next);
406
+ }
407
+ catch (error) {
408
+ if (!this.#closing)
409
+ this.#log("memory pass could not finish", { error: String(error) });
410
+ }
411
+ }
412
+ })().finally(() => (this.#running = undefined));
413
+ }
414
+ #takeTrailing() {
415
+ const next = this.#trailing;
416
+ this.#trailing = undefined;
417
+ return next;
418
+ }
419
+ /** Stop: the fork that runs is left to the next start, which deletes it and passes again from the cursor. */
420
+ async close() {
421
+ this.#closing = true;
422
+ await this.#running?.catch(() => { });
423
+ }
424
+ async #pass(at) {
425
+ if (!this.#host.enabled())
426
+ return;
427
+ const progress = await this.#host.progress();
428
+ if (progress.cursor !== undefined && at <= progress.cursor)
429
+ return;
430
+ const messages = since(await this.#root.context(this.#context, { at: at }), progress.cursor);
431
+ const folders = this.#host.folders;
432
+ // Only a call whose result says it worked: an edit whose text did not match saved nothing.
433
+ const worked = new Set(messages.flatMap((message) => (message.role === "toolResult" && !message.isError ? [message.toolCallId] : [])));
434
+ const wrote = messages.some((message) => message.role === "assistant" &&
435
+ message.content.some((part) => part.type === "toolCall" && worked.has(part.id) && writesMemory(part.name, part.arguments, folders, this.#cwd)));
436
+ let next;
437
+ if (wrote) {
438
+ // The main agent saved what it wanted itself: that counts as a memory change, as Claude Code skips the pass.
439
+ this.#log("memory pass skipped: the main agent wrote memory itself", { messages: messages.length });
440
+ next = await this.#host.settle({ cursor: at, change: true });
441
+ }
442
+ else {
443
+ this.beforePass?.();
444
+ const ended = await this.#fork("extract", at, await this.#host.extraction(messages.length), EXTRACTION_TURNS);
445
+ if (!ended)
446
+ return;
447
+ // What it changed counts also when its model failed; then the next pass looks at the same messages again.
448
+ next = await this.#host.settle(ended.answered ? { cursor: at } : {});
449
+ this.#tell("extract", ended);
450
+ if (!ended.answered)
451
+ return;
452
+ this.#log("memory pass", { messages: messages.length, written: ended.written.length, deleted: ended.deleted.length });
453
+ }
454
+ if (!this.#closing && this.#host.enabled() && dreamDue(next))
455
+ await this.#dream(at, next);
456
+ }
457
+ async #dream(at, progress) {
458
+ const ended = await this.#fork("dream", at, await this.#host.dream(progress));
459
+ if (!ended)
460
+ return;
461
+ await this.#host.settle(ended.answered ? { dreamt: Date.now() } : {});
462
+ this.#tell("dream", ended);
463
+ if (ended.answered)
464
+ this.#log("memory dream", { written: ended.written.length, deleted: ended.deleted.length });
465
+ }
466
+ /** The note of what a fork changed, for the main agent's next wake. */
467
+ #tell(source, changed) {
468
+ if (changed.written.length + changed.deleted.length > 0)
469
+ this.#host.noted({ source, written: changed.written, deleted: changed.deleted });
470
+ }
471
+ /**
472
+ * Fork the main conversation at `at`, give the fork the message, and wait until it ends. Returns whether it ended as
473
+ * it should (answered, or at its turn cap) and the files it wrote and deleted, or undefined when the gateway stops.
474
+ * The fork is deleted after.
475
+ */
476
+ async #fork(source, at, message, maxTurns) {
477
+ const root = this.#root;
478
+ const context = this.#context;
479
+ // Before the fork exists: a file that changes after this, the fork may not change.
480
+ const snapshot = await snapshotOf(this.#host.folders);
481
+ const id = await root.commit(async (tx) => {
482
+ const conversation = await tx.forkConversation(ROOT_CONVERSATION_ID, at, { ownership: { kind: "ownerless" } });
483
+ // pi-durable gives a fork a session of its own; with the main conversation's, the provider finds its cache.
484
+ (await tx.doc(ProviderDoc, conversation.id)).sessionId = (await tx.doc(ProviderDoc, ROOT_CONVERSATION_ID)).sessionId;
485
+ // Only hooks: the sections and tools stay those of the main conversation, so the start of the request does.
486
+ await configure(tx, conversation.id, { extensions: { add: [this.extension] } });
487
+ return conversation.id;
488
+ }, context);
489
+ const state = { source, snapshot, own: new Map(), recorded: false, rounds: 0, ...(maxTurns === undefined ? {} : { maxTurns }), written: new Set(), deleted: new Set() };
490
+ this.#forks.set(Number(id), state);
491
+ try {
492
+ const fork = (await this.#harness.conversation(id, context));
493
+ const submission = await fork.submit({ type: "input", content: message, requestId: `memory:${String(id)}`, whenBusy: "followUp", entry: { kind: "bot.memory" } }, context);
494
+ const settled = await submission.wait(context);
495
+ if (this.#closing)
496
+ return undefined;
497
+ const capped = state.maxTurns !== undefined && state.rounds >= state.maxTurns;
498
+ const answered = settled.status === "done" || capped;
499
+ if (!answered)
500
+ this.#log("memory pass got no answer", { source, reason: settled.status === "unanswered" ? settled.reason : "unknown" });
501
+ return { answered, written: [...state.written], deleted: [...state.deleted] };
502
+ }
503
+ finally {
504
+ this.#forks.delete(Number(id));
505
+ if (!this.#closing)
506
+ await this.#delete(id);
507
+ }
508
+ }
509
+ /** Delete a fork once nothing of it runs any more. */
510
+ async #delete(id) {
511
+ const live = await this.#sql.all("SELECT id FROM pi_tasks WHERE conversation_id = ? AND status != 'terminal'", Number(id));
512
+ for (const task of live) {
513
+ await this.#harness.abortTask(task.id, this.#context);
514
+ await this.#harness.waitForTask(task.id, this.#context);
515
+ }
516
+ await deleteConversation(this.#sql, Number(id));
517
+ }
518
+ }
519
+ /**
520
+ * Delete a conversation and everything of it from pi-durable's tables: its entries, submissions, tasks and documents.
521
+ * pi-durable has no call for this; it is safe for a fork whose tasks have all ended, which nothing refers to.
522
+ */
523
+ async function deleteConversation(sql, id) {
524
+ const documents = "SELECT id FROM pi_documents WHERE (scope_kind = 'conversation' AND owner_id = ?) OR (scope_kind = 'task' AND owner_id IN (SELECT id FROM pi_tasks WHERE conversation_id = ?))";
525
+ await sql.transaction(async (tx) => {
526
+ await tx.run(`DELETE FROM pi_document_revisions WHERE document_id IN (${documents})`, id, id);
527
+ await tx.run(`DELETE FROM pi_record_ids WHERE id IN (${documents})`, id, id);
528
+ await tx.run(`DELETE FROM pi_documents WHERE id IN (${documents})`, id, id);
529
+ for (const table of ["pi_entries", "pi_submissions", "pi_tasks"]) {
530
+ await tx.run(`DELETE FROM pi_record_ids WHERE id IN (SELECT id FROM ${table} WHERE conversation_id = ?)`, id);
531
+ await tx.run(`DELETE FROM ${table} WHERE conversation_id = ?`, id);
532
+ }
533
+ await tx.run("DELETE FROM pi_record_ids WHERE id = ?", id);
534
+ await tx.run("DELETE FROM pi_conversations WHERE id = ?", id);
535
+ });
536
+ }
537
+ /**
538
+ * Delete the memory forks a pass left when the last process stopped or died in the middle of it: forks of the main
539
+ * conversation that nothing owns. Before pi-durable opens, so none of them runs again.
540
+ */
541
+ export async function deleteLeftForks(sql) {
542
+ const forks = await sql.all("SELECT id FROM pi_conversations WHERE id != ? AND owner_conversation_id IS NULL AND owner_task_id IS NULL AND json_extract(record, '$.parent.conversationId') = ?", ROOT_CONVERSATION_ID, ROOT_CONVERSATION_ID);
543
+ for (const fork of forks)
544
+ await deleteConversation(sql, fork.id);
545
+ return forks.length;
546
+ }
547
+ /** The newest answer of the main conversation that ended a run, for a pass that the last process did not make. */
548
+ export async function lastAnswer(root, context) {
549
+ const page = await root.entries({}, 50, undefined, context);
550
+ for (const entry of page.items) {
551
+ if (!AssistantEntry.is(entry))
552
+ continue;
553
+ const stop = entry.model?.[0]?.stopReason;
554
+ if (stop === "stop" || stop === "length")
555
+ return entry.id;
556
+ if (stop === "toolUse")
557
+ return undefined;
558
+ }
559
+ return undefined;
560
+ }
561
+ /** The files the main agent read with the read tool in this context. */
562
+ export function readPaths(messages, cwd) {
563
+ const paths = new Set();
564
+ for (const message of messages) {
565
+ if (message.role !== "assistant")
566
+ continue;
567
+ for (const part of message.content)
568
+ if (part.type === "toolCall" && part.name === "read" && typeof part.arguments.path === "string")
569
+ paths.add(toolPath(cwd, part.arguments.path));
570
+ }
571
+ return paths;
572
+ }
573
+ //# sourceMappingURL=memory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory.js","sourceRoot":"","sources":["../../src/agent/memory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AACxD,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAC3D,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAGzC,OAAO,EACL,cAAc,EAId,SAAS,EACT,eAAe,EAGf,cAAc,EAEd,IAAI,EACJ,WAAW,EACX,oBAAoB,EAGpB,QAAQ,GACT,MAAM,4BAA4B,CAAC;AAqEpC,uGAAuG;AACvG,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAC3B,+GAA+G;AAC/G,MAAM,WAAW,GAAG,EAAE,CAAC;AACvB,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,GAAG,GAAG,UAAU,CAAC;AACvB,uHAAuH;AACvH,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAElC,2CAA2C;AAC3C,MAAM,UAAU,QAAQ,CAAC,QAAwB,EAAE,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE;IACjE,OAAO,QAAQ,CAAC,OAAO,IAAI,aAAa,IAAI,CAAC,QAAQ,CAAC,OAAO,KAAK,SAAS,IAAI,GAAG,GAAG,QAAQ,CAA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