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
@@ -1,6 +1,6 @@
1
1
  import { StringEnum } from "@earendil-works/pi-ai";
2
- import { AssistantEntry, configure, defineDoc, defineExtension, defineTask, defineTool, } from "@earendil-works/pi-durable";
3
- import { obj, opt, str } from "@earendil-works/pi-schema";
2
+ import { AssistantEntry, configure, defineDoc, defineExtension, defineSignal, defineTask, defineTool, LiveDoc, ROOT_CONVERSATION_ID, } from "@earendil-works/pi-durable";
3
+ import { arr, bool, num, obj, opt, str } from "@earendil-works/pi-schema";
4
4
  export const Children = defineDoc({
5
5
  checkpointWhen: () => false,
6
6
  kind: "bot.children",
@@ -46,6 +46,9 @@ export function childActivity(live, inbox, tasks, outputs) {
46
46
  waiting: (inbox?.items ?? []).filter((item) => item.mode !== "write").length,
47
47
  };
48
48
  }
49
+ /** The longest result the task tool gives in its output, under pi's cut at 50 KB or 2,000 lines; a longer one goes to a file. */
50
+ const RESULT_BYTES = 40_000;
51
+ const RESULT_LINES = 1_500;
49
52
  /** How much of a command or an output line a description shows. */
50
53
  const SHOWN_CHARS = 150;
51
54
  function clip(text) {
@@ -75,14 +78,76 @@ export function childInfo(record) {
75
78
  title: record.title,
76
79
  conversationId: String(record.conversationId),
77
80
  ...(record.place === undefined ? {} : { place: record.place }),
81
+ ...(record.routine === undefined ? {} : { routine: record.routine }),
82
+ ...(record.parent === undefined ? {} : { parent: record.parent }),
78
83
  ...(record.model === undefined ? {} : { model: record.model }),
79
84
  thinking: record.thinking,
80
85
  startedAt: record.startedAt,
81
86
  ...(record.since === undefined ? {} : { since: record.since }),
82
87
  ...(record.endedAt === undefined ? {} : { endedAt: record.endedAt }),
83
88
  ...(record.stoppedAt === undefined ? {} : { stoppedAt: record.stoppedAt }),
89
+ ...(record.result?.failed === undefined ? {} : { failed: record.result.failed }),
84
90
  };
85
91
  }
92
+ /** A child's end, for the task tool's waits, under the child's ID: how it ended. */
93
+ const ChildEnded = defineSignal({ name: "bot.child-ended", version: 1, schema: obj({ answer: opt(num()), failed: opt(str()), stopped: opt(bool()) }) });
94
+ function endOf(record) {
95
+ const failed = record.result?.failed;
96
+ const answer = record.reported.at(-1);
97
+ return { ...(failed !== undefined ? { failed } : answer !== undefined ? { answer: Number(answer) } : {}), ...(record.stoppedAt === undefined ? {} : { stopped: true }) };
98
+ }
99
+ /** A child as it was at an end a wait kept: no longer working, and failed or stopped as it was then. */
100
+ function endedInfo(record, end) {
101
+ const { since: _since, failed: _failed, stoppedAt: _stoppedAt, ...info } = childInfo(record);
102
+ return { ...info, ...(end.failed === undefined ? {} : { failed: end.failed }), ...(end.stopped && record.stoppedAt !== undefined ? { stoppedAt: record.stoppedAt } : {}) };
103
+ }
104
+ /**
105
+ * Children ended or were stopped: wake the waits for them, each with how its child ended. In a commit, before its first
106
+ * table write: each delivery reads its task before it writes it, so all of them start before the first one writes.
107
+ */
108
+ export async function endWaits(tx, records) {
109
+ const deliveries = records.flatMap((record) => [...new Set(record.waiters ?? [])].map((task) => tx.signal(Number(task), ChildEnded, record.id, endOf(record))));
110
+ for (const record of records)
111
+ delete record.waiters;
112
+ await Promise.all(deliveries);
113
+ }
114
+ /** Keep an answer of a child, once: several messages can end in one answer. */
115
+ export function keepAnswer(record, answer, now) {
116
+ if (record.reported.includes(answer))
117
+ return;
118
+ record.reported.push(answer);
119
+ record.result = { at: now };
120
+ }
121
+ /**
122
+ * Which children a list shows: those that work, the last `limit` of the others, and the chain of children that started
123
+ * each shown one, so none shows apart from the one that started it.
124
+ */
125
+ export function shownChildren(listed, limit = 20) {
126
+ const byId = new Map(listed.map((child) => [child.id, child]));
127
+ const shown = new Set([...listed.filter(isWorking), ...listed.filter((child) => !isWorking(child)).slice(-limit)].map((child) => child.id));
128
+ for (const id of [...shown]) {
129
+ for (let up = byId.get(id)?.parent; up !== undefined && byId.has(up) && !shown.has(up); up = byId.get(up)?.parent)
130
+ shown.add(up);
131
+ }
132
+ return listed.filter((child) => shown.has(child.id));
133
+ }
134
+ /** Whether a child works now. */
135
+ const isWorking = (child) => child.since !== undefined && child.stoppedAt === undefined;
136
+ /** The IDs of a child's descendants, nearest first. */
137
+ export function descendants(state, id) {
138
+ const found = [];
139
+ const queue = [id];
140
+ while (queue.length > 0) {
141
+ const parent = queue.shift();
142
+ for (const child of Object.values(state.children)) {
143
+ if (child.parent === parent) {
144
+ found.push(child.id);
145
+ queue.push(child.id);
146
+ }
147
+ }
148
+ }
149
+ return found;
150
+ }
86
151
  /** The thinking level of a child the main agent starts without choosing one. */
87
152
  export const DEFAULT_CHILD_THINKING = "xhigh";
88
153
  /** How long, in words: "12 s", "4 min", "2.5 h". */
@@ -103,8 +168,8 @@ export function describeChild(child, now = Date.now(), options = {}) {
103
168
  ? `stopped ${age(now - child.stoppedAt)} ago`
104
169
  : child.since !== undefined
105
170
  ? `working, for ${age(now - child.since)}`
106
- : `ended ${age(now - (child.endedAt ?? child.startedAt))} ago, waits for a message`;
107
- const line = `${child.id} "${child.title}": ${state}${child.place ? `, for ${child.place}` : ""}${options.thinking ? `${child.model ? `, model ${child.model}` : ""}, thinking ${child.thinking}` : ""}`;
171
+ : `${child.failed === undefined ? "ended" : `failed (${clip(child.failed) ?? "no reason"})`} ${age(now - (child.endedAt ?? child.startedAt))} ago, waits for a message`;
172
+ const line = `${child.id} "${child.title}": ${state}${child.parent ? `, started by ${child.parent}` : ""}${child.place ? `, for ${child.place}` : ""}${options.thinking ? `${child.model ? `, model ${child.model}` : ""}, thinking ${child.thinking}` : ""}`;
108
173
  if (child.activity === undefined || child.since === undefined || child.stoppedAt !== undefined)
109
174
  return line;
110
175
  return [line, ...describeActivity(child.activity, now).map((each) => ` ${each}`)].join("\n");
@@ -141,6 +206,30 @@ export function describeActivity(activity, now = Date.now()) {
141
206
  function textOf(message) {
142
207
  return (message?.content ?? []).flatMap((part) => (part.type === "text" ? [part.text] : [])).join("");
143
208
  }
209
+ /** What a child did last, from the newest step in its conversation: the tools it called, or the start of its text. */
210
+ export async function lastStep(conversation, context) {
211
+ const page = await conversation?.entries({}, 20, undefined, context);
212
+ // Not a failed or aborted request's entry: its tool calls never ran.
213
+ const message = page?.items
214
+ .flatMap((entry) => (AssistantEntry.is(entry) ? [entry.model?.[0]] : []))
215
+ .find((each) => each && each.content.length > 0 && each.stopReason !== "error" && each.stopReason !== "aborted");
216
+ if (!message)
217
+ return undefined;
218
+ const calls = message.content.flatMap((part) => (part.type === "toolCall" ? [`${part.name}${commandOf(part.arguments) ? `: ${commandOf(part.arguments)}` : ""}`] : []));
219
+ if (calls.length > 0)
220
+ return `called ${calls.join("; ")}`;
221
+ const said = clip(textOf(message));
222
+ return said === undefined ? undefined : `wrote: ${said}`;
223
+ }
224
+ /** A child's last final message, or why it could not answer; undefined while it has neither. */
225
+ async function childResult(tx, record) {
226
+ if (record.result?.failed !== undefined)
227
+ return `It could not answer: ${record.result.failed}`;
228
+ const answer = record.reported.at(-1);
229
+ if (answer === undefined)
230
+ return undefined;
231
+ return textOf((await tx.entry(AssistantEntry, answer))?.model?.[0]).trim() || "(empty)";
232
+ }
144
233
  /**
145
234
  * The task extension of the main agent: the task tool and the tasks behind it. Installed once per bot, so pending
146
235
  * reporters go on after a restart.
@@ -157,8 +246,11 @@ export function childrenExtension(host) {
157
246
  },
158
247
  abort: (_anchor, runtime, context) => runtime.commit(() => ({ status: "terminal", outcome: { status: "aborted" } }), context),
159
248
  });
160
- /** The reporter ends: it is no longer live, and its child waits for a message once no other reporter is live. */
161
- const finish = (state, reporter, now) => {
249
+ /**
250
+ * The reporter ends: it is no longer live, and its child waits for a message once no other reporter is live, which
251
+ * wakes the waits for it. Before the commit's first table write.
252
+ */
253
+ const finish = async (tx, state, reporter, now) => {
162
254
  const id = state.live[reporter];
163
255
  delete state.live[reporter];
164
256
  const child = id === undefined ? undefined : state.children[id];
@@ -167,10 +259,22 @@ export function childrenExtension(host) {
167
259
  if (child.since !== undefined && child.stoppedAt === undefined)
168
260
  child.endedAt = now;
169
261
  delete child.since;
262
+ await endWaits(tx, [child]);
263
+ };
264
+ // Every reporter and anchor is a task of the main conversation, also for a child that a child starts.
265
+ const background = { ownership: { kind: "conversation" }, background: true, conversationId: ROOT_CONVERSATION_ID };
266
+ /** Give a child a message, for one of a child's failure about that child: a reporter delivers it. Returns the reporter. */
267
+ const deliver = async (tx, state, record, message, now, about) => {
268
+ const reporter = String(await tx.createTask(Reporter, { child: record.id, conversationId: record.conversationId, message, ...(about === undefined ? {} : { about }) }, background));
269
+ record.reporters.push(reporter);
270
+ record.since ??= now;
271
+ state.live[reporter] = record.id;
272
+ return reporter;
170
273
  };
171
- // Delivers one message to a child, waits for its answer and reports it to the main agent. A background task of the
172
- // main conversation; each phase ends with a checkpoint, and request IDs make a phase that runs again after a restart
173
- // find the first submission, so the child gets the message once and the main agent the report once.
274
+ // Delivers one message to a child, waits for its answer and keeps how it ended; only a failure wakes the main agent.
275
+ // A background task of the main conversation; each phase ends with a checkpoint, and request IDs make a phase that
276
+ // runs again after a restart find the first submission, so the child gets the message once and the main agent the
277
+ // failure once.
174
278
  const Reporter = defineTask({
175
279
  name: "bot.child-reporter",
176
280
  version: 1,
@@ -178,65 +282,110 @@ export function childrenExtension(host) {
178
282
  phases: {
179
283
  deliver: async (reporter, runtime, context) => {
180
284
  const { conversationId, message } = reporter.input;
181
- // Stopped before its message reached the child: the child does not get it.
285
+ // Run again after a restart, this phase finds the message it gave.
286
+ let given;
287
+ await runtime.commit(async (tx) => {
288
+ given = await tx.submissionByRequest(conversationId, `child:${reporter.id}`);
289
+ }, context);
290
+ // Stopped before its message reached the child, or the child the message is about: the child does not get it, and
291
+ // a message that waits in its queue is withdrawn. One the child took already is followed to its answer.
182
292
  const state = await runtime.snapshot(Children, runtime.conversationId, context);
183
- if (state?.children[reporter.input.child]?.stoppedAt !== undefined) {
184
- await runtime.commit(() => ({ status: "running", checkpoint: { phase: "report" } }), context);
185
- return;
293
+ const stopped = (id) => id !== undefined && state?.children[id]?.stoppedAt !== undefined;
294
+ if (stopped(reporter.input.child) || stopped(reporter.input.about)) {
295
+ if (given === undefined) {
296
+ await runtime.commit(() => ({ status: "running", checkpoint: { phase: "report" } }), context);
297
+ return;
298
+ }
299
+ if (given.status === "queued")
300
+ await host.withdraw(String(given.id), conversationId);
186
301
  }
187
302
  const child = (await runtime.conversation(conversationId, context));
188
303
  const submission = await child.submit({ type: "input", content: message, whenBusy: "steer", requestId: `child:${reporter.id}`, entry: { kind: "bot.brief" } }, context);
189
304
  const settled = await submission.wait(context);
190
305
  host.settled(String(conversationId));
191
- // One commit decides the report and records the answer as reported, so a restart does not decide again.
306
+ await host.beforeKeep?.(reporter.input.child, runtime.signal);
307
+ // One commit keeps how the child ended, so a restart does not decide again.
192
308
  await runtime.commit(async (tx) => {
193
- const next = (end) => ({
194
- status: "running",
195
- checkpoint: end ? { phase: "report", end } : { phase: "report" },
196
- });
309
+ const next = { status: "running", checkpoint: { phase: "report" } };
197
310
  const state = await tx.doc(Children, runtime.conversationId);
198
311
  const record = state.children[reporter.input.child];
199
- // Stopped, or withdrawn while queued: nothing to report.
200
- if (!record || record.stoppedAt !== undefined)
201
- return next();
312
+ if (!record)
313
+ return next;
202
314
  if (settled.status === "unanswered") {
203
- if (settled.reason === "aborted")
204
- return next();
315
+ // Stopped, or withdrawn while queued: nothing to keep.
316
+ if (settled.reason === "aborted" || record.stoppedAt !== undefined)
317
+ return next;
205
318
  const detail = settled.detail === undefined ? "" : `: ${typeof settled.detail === "string" ? settled.detail : JSON.stringify(settled.detail)}`;
206
- return next({ status: "failed", text: `${settled.reason}${detail}` });
319
+ const failed = `${settled.reason}${detail}`;
320
+ record.result = { at: runtime.now(), failed };
321
+ // The inputs that joined one run settle together: only the reporter of the run's first input wakes the main
322
+ // agent. When the failure is no longer there to tell, this one wakes.
323
+ const run = (await tx.doc(LiveDoc, conversationId)).runFailure;
324
+ const first = run?.inputs.includes(submission.id) ? await tx.submission(run.inputs[0]) : undefined;
325
+ if (first && first.id !== submission.id && first.requestId?.startsWith("child:"))
326
+ return next;
327
+ return { ...next, checkpoint: { phase: "report", end: { status: "failed", text: failed } } };
207
328
  }
208
- if (settled.type !== "input" || record.reported.includes(settled.answer))
209
- return next();
210
- record.reported.push(settled.answer);
211
- const answer = (await tx.entry(AssistantEntry, settled.answer))?.model?.[0];
212
- return next({ status: "answered", text: textOf(answer) });
329
+ // An answer is kept also when a stop came after it.
330
+ if (settled.type === "input")
331
+ keepAnswer(record, settled.answer, runtime.now());
332
+ return next;
213
333
  }, context);
214
334
  },
215
335
  report: async (reporter, runtime, context) => {
216
336
  const end = reporter.state.checkpoint.end;
217
- const record = () => runtime.snapshot(Children, runtime.conversationId, context).then((state) => state?.children[reporter.input.child]);
218
- const before = await record();
219
- if (end && before && before.stoppedAt === undefined) {
220
- host.beforeReport?.(String(reporter.id));
221
- const submission = await host.ended({ reporter: String(reporter.id), child: childInfo(before), ...end }, context);
222
- host.afterReport?.(String(reporter.id));
223
- // A stop that came in the meantime did not find this report yet; it must not reach the main agent.
224
- if ((await record())?.stoppedAt !== undefined)
225
- await host.withdraw(submission);
337
+ /** The child that started this one, which works, when the failure goes to it. */
338
+ let parent;
339
+ if (end?.status === "failed") {
340
+ const read = () => runtime.snapshot(Children, runtime.conversationId, context);
341
+ const state = await read();
342
+ const before = state?.children[reporter.input.child];
343
+ const started = before?.parent === undefined ? undefined : state?.children[before.parent];
344
+ // To the child that started it while that one works; else to the main agent. Decided once, also across restarts.
345
+ const to = before && before.stoppedAt === undefined ? await runtime.memo("failure-to", started && isWorking(started) ? started.id : "main", context) : undefined;
346
+ if (to === "main") {
347
+ host.beforeFailed?.(String(reporter.id));
348
+ const submission = await host.failed({ reporter: String(reporter.id), child: childInfo(before), reason: end.text }, context);
349
+ host.afterFailed?.(String(reporter.id));
350
+ // A stop that came in the meantime did not find this wake yet; it must not reach the main agent.
351
+ if ((await read())?.children[reporter.input.child]?.stoppedAt !== undefined)
352
+ await host.withdraw(submission);
353
+ }
354
+ else if (to !== undefined) {
355
+ const last = await host.last(reporter.input.conversationId, context);
356
+ const message = [`[your child ${before.id} "${before.title}" failed: ${end.text}]`, ...(last === undefined ? [] : [`Last, it ${last}`])].join("\n");
357
+ parent = { id: to, message };
358
+ }
226
359
  }
227
360
  await runtime.commit(async (tx) => {
228
- finish(await tx.doc(Children, runtime.conversationId), String(reporter.id), runtime.now());
361
+ const state = await tx.doc(Children, runtime.conversationId);
362
+ // An end that 0.8.8 had not kept yet: kept, as now.
363
+ const record = state.children[reporter.input.child];
364
+ if (end && record && (end.status === "answered" || record.stoppedAt === undefined))
365
+ record.result = end.status === "failed" ? { at: runtime.now(), failed: end.text } : { at: runtime.now() };
366
+ await finish(tx, state, String(reporter.id), runtime.now());
367
+ // Also when a wait of the parent gives the failure too. Not when one of them was stopped meanwhile; a later stop
368
+ // of this child withdraws the message while it waits in the parent's queue.
369
+ const to = parent === undefined ? undefined : state.children[parent.id];
370
+ if (to && to.stoppedAt === undefined && record && record.stoppedAt === undefined) {
371
+ record.told = [...(record.told ?? []), await deliver(tx, state, to, parent.message, runtime.now(), record.id)];
372
+ }
229
373
  return { status: "terminal", outcome: { status: "completed", result: null } };
230
374
  }, context);
231
375
  },
232
376
  },
233
377
  abort: (reporter, runtime, context) => runtime.commit(async (tx) => {
234
- finish(await tx.doc(Children, runtime.conversationId), String(reporter.id), runtime.now());
378
+ const state = await tx.doc(Children, runtime.conversationId);
379
+ // A stop that came after the child answered, before the reporter kept the answer: the answer is kept.
380
+ const record = state.children[reporter.input.child];
381
+ const submission = await tx.submissionByRequest(reporter.input.conversationId, `child:${reporter.id}`);
382
+ if (record && submission?.type === "input" && submission.status === "done")
383
+ keepAnswer(record, submission.answer, runtime.now());
384
+ await finish(tx, state, String(reporter.id), runtime.now());
235
385
  return { status: "terminal", outcome: { status: "aborted" } };
236
386
  }, context),
237
387
  });
238
388
  const text = (value) => ({ output: [{ type: "text", text: value }] });
239
- const isWorking = (child) => child.since !== undefined && child.stoppedAt === undefined;
240
389
  /** At the cap, the children that work; checked in the commit that would make one more child work. */
241
390
  const atCap = (state) => {
242
391
  const working = Object.values(state.children).filter(isWorking);
@@ -252,92 +401,247 @@ export function childrenExtension(host) {
252
401
  /** What the model learns at the cap instead. */
253
402
  const capText = async (not, working, at) => `${not}: ${working.length} children work now, as many as the cap (settings.maxChildren in bot.json). They are:\n` +
254
403
  (await Promise.all(working.map(withActivity))).map((child) => describeChild(child, at)).join("\n");
255
- const background = { ownership: { kind: "conversation" }, background: true };
404
+ /** Text for the model after a head: whole, or in a file named after `name` when it is too long for a tool's output. */
405
+ const fitted = async (head, body, name, what) => {
406
+ // Tool output is cut at 2,000 lines or 50 KB: a longer text goes to a file, whole.
407
+ if (Buffer.byteLength(head + body) <= RESULT_BYTES && `${head}\n${body}`.split("\n").length <= RESULT_LINES)
408
+ return `${head}\n${body}`;
409
+ const file = await host.saveResult(name, body);
410
+ return `${head}\n${what} ${body.length} characters; all of it is in ${file}. Its start:\n${body.split("\n").slice(0, 100).join("\n").slice(0, 4_000)}`;
411
+ };
412
+ /** A child's last final message for the model: whole, or in a file when it is too long for a tool's output. */
413
+ const resultText = async (tx, child, at) => {
414
+ const result = await childResult(tx, child);
415
+ const now = describeChild(childInfo(child), at);
416
+ if (result === undefined)
417
+ return `${now}\nNo final message yet.`;
418
+ return fitted(`${now}\nIts last final message:`, result, child.id, "It is");
419
+ };
420
+ /** How a child ended for a wait, with its final message then. */
421
+ const endText = async (tx, end) => {
422
+ if (end.failed !== undefined)
423
+ return `It could not answer: ${end.failed}`;
424
+ if (end.answer === undefined)
425
+ return end.stopped ? "It was stopped before it gave a final message." : "No final message.";
426
+ const answer = textOf((await tx.entry(AssistantEntry, end.answer))?.model?.[0]).trim() || "(empty)";
427
+ return `${end.stopped ? "It was stopped. Its last final message" : "Its final message"}:\n${answer}`;
428
+ };
429
+ /** Take a wait's task out of the children it waits for. */
430
+ const unwait = (state, task) => {
431
+ for (const child of Object.values(state.children)) {
432
+ if (!child.waiters?.includes(String(task)))
433
+ continue;
434
+ child.waiters = child.waiters.filter((each) => each !== String(task));
435
+ if (child.waiters.length === 0)
436
+ delete child.waiters;
437
+ }
438
+ };
439
+ /**
440
+ * A new child, in a commit of the main conversation; none at the cap, or for a routine while its earlier child works,
441
+ * which the routine looked at before, but a message may have made that child work again since. Its first message says
442
+ * its ID.
443
+ */
444
+ const start = async (tx, input, now) => {
445
+ const state = await tx.doc(Children, ROOT_CONVERSATION_ID);
446
+ const earlier = input.routine === undefined ? undefined : Object.values(state.children).find((child) => child.routine === input.routine && isWorking(child));
447
+ if (earlier)
448
+ return { working: earlier.id };
449
+ // A stop marks a child and all it started in one commit: a child stopped since it looked starts none.
450
+ if (input.parent !== undefined && state.children[input.parent]?.stoppedAt !== undefined)
451
+ return { stopped: input.parent };
452
+ const full = atCap(state);
453
+ if (full !== undefined)
454
+ return { full };
455
+ const id = `c${state.next++}`;
456
+ const anchor = await tx.createTask(Anchor, null, background);
457
+ const conversation = await tx.createConversation({ ownership: { kind: "task", taskId: anchor } });
458
+ // The child's tools and prompt, and its model.
459
+ await configure(tx, conversation.id, { extensions: host.extensions(), model: input.model, thinkingLevel: input.thinking });
460
+ const message = `[brief from ${input.from}; you are child ${id}]\n${input.brief}`;
461
+ const reporter = await tx.createTask(Reporter, { child: id, conversationId: conversation.id, message }, background);
462
+ state.children[id] = {
463
+ id,
464
+ title: input.title,
465
+ conversationId: conversation.id,
466
+ ...(input.place ? { place: input.place } : {}),
467
+ ...(input.routine === undefined ? {} : { routine: input.routine }),
468
+ ...(input.parent === undefined ? {} : { parent: input.parent }),
469
+ ...(input.chosen === undefined ? {} : { model: input.chosen }),
470
+ thinking: input.thinking,
471
+ startedAt: now,
472
+ since: now,
473
+ reporters: [String(reporter)],
474
+ reported: [],
475
+ };
476
+ state.live[String(reporter)] = id;
477
+ return { id };
478
+ };
479
+ /** Children in a tree: each under the child that started it, indented, when that one is in the list too. */
480
+ const tree = (children, at) => {
481
+ const shown = new Set(children.map((child) => child.id));
482
+ const lines = [];
483
+ const add = (child, depth) => {
484
+ lines.push(...describeChild(child, at, { thinking: true }).split("\n").map((line) => `${" ".repeat(depth)}${line}`));
485
+ for (const each of children)
486
+ if (each.parent === child.id)
487
+ add(each, depth + 1);
488
+ };
489
+ for (const child of children)
490
+ if (child.parent === undefined || !shown.has(child.parent))
491
+ add(child, 0);
492
+ return lines.join("\n");
493
+ };
256
494
  const task = defineTool({
257
495
  name: "task",
258
496
  description: "Children: agents that work in the background, so you stay free to talk. action start: a new child with a short title and a brief " +
259
497
  "(place: the address of the place it works for, by default the place you work on; model: \"provider/modelId\", which it keeps, by default yours; " +
260
- "thinking: its thinking level, which it keeps, by default xhigh); it starts with an empty conversation and the brief. " +
261
- "list: your children, and what each one that works does now. send: a message to a child (child: its ID); a child that waits starts on it " +
498
+ "thinking: its thinking level, which it keeps, by default xhigh); it starts with an empty conversation and the brief, and has this tool too. " +
499
+ "list: your children and the children they started, and what each one that works does now. result: a child's last final message (child: its ID). " +
500
+ "wait: waits until all the children listed in children have ended, or any one of them (any: true), or until seconds have passed, " +
501
+ "then says which of these ended it and gives, for each child that ended, how it ended and its final message then; while you wait you do nothing else. " +
502
+ "send: a message to a child; a child that waits starts on it " +
262
503
  "at once, and one that works takes it when its current tool calls end. interrupt: ends the tool calls a child is in, such as a command " +
263
504
  "that hangs; the child goes on, sees that they were aborted, and takes the messages that wait for it. " +
264
- "stop: stops a child and what it runs; nothing comes back from it then. A child's final message comes back to you as a wake.",
505
+ "stop: stops a child, what it runs and the children it started. A child's end wakes no one. A child that fails tells the child that started it " +
506
+ "while that one works, and else wakes the main agent, once. Any child can wake the main agent with pots wake. " +
507
+ "All children share the cap settings.maxChildren.",
265
508
  parameters: obj({
266
- action: StringEnum(["start", "list", "send", "interrupt", "stop"]),
509
+ action: StringEnum(["start", "list", "result", "wait", "send", "interrupt", "stop"]),
267
510
  title: opt(str()),
268
511
  brief: opt(str()),
269
512
  place: opt(str()),
270
513
  model: opt(str()),
271
514
  thinking: opt(StringEnum(["off", "minimal", "low", "medium", "high", "xhigh", "max"])),
272
515
  child: opt(str()),
516
+ children: opt(arr(str())),
517
+ any: opt(bool()),
518
+ seconds: opt(num()),
273
519
  message: opt(str()),
274
520
  }, { open: true }),
275
521
  // A call cut off by a crash is not run again: a repeated start would start a second child. The model sees that the
276
- // call was interrupted and can look with list.
522
+ // call was interrupted and can look with list. A wait holds no process and goes on after a restart.
277
523
  replay: "unsafe",
524
+ // A wait that is aborted while it sleeps: the children it waited for no longer name it.
525
+ cancel: async (args, api, call) => {
526
+ if (args.action !== "wait")
527
+ return;
528
+ await api.commit(async (tx) => unwait(await tx.doc(Children, ROOT_CONVERSATION_ID), api.taskId), call);
529
+ },
278
530
  execute: async (args, api, call) => {
279
- const state = (await api.snapshot(Children, api.conversationId, call)) ?? { next: 1, children: {}, live: {} };
531
+ const state = (await api.snapshot(Children, ROOT_CONVERSATION_ID, call)) ?? { next: 1, children: {}, live: {} };
532
+ // The main agent manages every child; a child, those it started.
533
+ const caller = Object.values(state.children).find((child) => child.conversationId === api.conversationId);
534
+ const from = caller ? `child ${caller.id}` : "the main agent";
535
+ const mine = (child) => caller === undefined || child.parent === caller.id;
280
536
  const all = Object.values(state.children).map(childInfo);
281
- const working = all.filter(isWorking);
282
537
  if (args.action === "list") {
283
- if (all.length === 0)
538
+ // A child sees what it started, and what those started.
539
+ const below = caller === undefined ? undefined : new Set(descendants(state, caller.id));
540
+ const listed = all.filter((child) => below === undefined || below.has(child.id));
541
+ if (listed.length === 0)
284
542
  return text("No children.");
285
- const others = all.filter((child) => !working.includes(child)).slice(-20);
286
- const described = [...(await Promise.all(working.map(withActivity))), ...others];
287
- return text(described.map((child) => describeChild(child, api.now(), { thinking: true })).join("\n"));
543
+ return text(tree(await Promise.all(shownChildren(listed).map(withActivity)), api.now()));
288
544
  }
289
545
  if (args.action === "start") {
290
546
  if (!args.title?.trim() || !args.brief?.trim())
291
547
  return text("start needs a title and a brief.");
292
- const place = args.place?.trim() || host.place();
548
+ const place = args.place?.trim() || (caller ? caller.place : host.place());
293
549
  // A model of its own is checked now, so a child never starts with a model it cannot use. Without one, the
294
- // child has the main model, also when bot.json changes it later.
295
- const chosen = args.model?.trim() || undefined;
550
+ // child has its starter's: for the main agent's, the main model, also when bot.json changes it later.
551
+ const chosen = args.model?.trim() || caller?.model;
296
552
  const found = chosen === undefined ? { model: host.mainModel() } : await host.childModel(chosen);
297
553
  if ("refused" in found)
298
554
  return text(`Not started: ${found.refused}`);
299
555
  const { model } = found;
300
556
  // As pi does, a level the model does not have becomes the nearest one it has, at each request (pi-ai).
301
557
  const thinkingLevel = args.thinking ?? DEFAULT_CHILD_THINKING;
302
- const started = await api.commit(async (tx) => {
303
- const state = await tx.doc(Children, api.conversationId);
304
- const full = atCap(state);
305
- if (full !== undefined)
306
- return { full, id: undefined };
307
- const id = `c${state.next++}`;
308
- const anchor = await tx.createTask(Anchor, null, background);
309
- const conversation = await tx.createConversation({ ownership: { kind: "task", taskId: anchor } });
310
- // The child's tools and prompt, and the model for children.
311
- await configure(tx, conversation.id, { extensions: host.extensions(), model, thinkingLevel });
312
- const now = api.now();
313
- const reporter = await tx.createTask(Reporter, { child: id, conversationId: conversation.id, message: `[brief from the main agent]\n${args.brief}` }, background);
314
- state.children[id] = {
315
- id,
316
- title: args.title.trim(),
317
- conversationId: conversation.id,
318
- ...(place ? { place } : {}),
319
- ...(chosen === undefined ? {} : { model: chosen }),
320
- thinking: thinkingLevel,
321
- startedAt: now,
322
- since: now,
323
- reporters: [String(reporter)],
324
- reported: [],
325
- };
326
- state.live[String(reporter)] = id;
327
- return { id, full: undefined };
558
+ const title = args.title.trim();
559
+ if (caller)
560
+ await host.beforeStart?.(caller.id);
561
+ const started = await api.commit((tx) => start(tx, {
562
+ title,
563
+ brief: args.brief,
564
+ from,
565
+ ...(caller ? { parent: caller.id } : {}),
566
+ ...(place ? { place } : {}),
567
+ ...(chosen === undefined ? {} : { chosen }),
568
+ model,
569
+ thinking: thinkingLevel,
570
+ }, api.now()), call);
571
+ if ("stopped" in started)
572
+ return text("Not started: you were stopped.");
573
+ if (!("id" in started))
574
+ return text("full" in started ? await capText("Not started", started.full, api.now()) : "Not started.");
575
+ return text(`Started ${started.id} ("${title}")${place ? ` for ${place}` : ""}, model ${model.provider}/${model.modelId}${args.model?.trim() ? "" : " (yours)"}, ` +
576
+ `thinking ${thinkingLevel}.`);
577
+ }
578
+ if (args.action === "wait") {
579
+ const ids = [...new Set(args.children ?? [])];
580
+ if (ids.length === 0)
581
+ return text("wait needs children: the IDs of the children to wait for.");
582
+ const unknown = ids.filter((id) => !Object.hasOwn(state.children, id) || !mine(state.children[id]));
583
+ if (unknown.length > 0)
584
+ return text(`No child ${unknown.join(", ")} of yours.`);
585
+ const before = api.checkpoint;
586
+ const until = before ? before.until : args.seconds === undefined ? undefined : api.now() + args.seconds * 1_000;
587
+ const ended = { ...before?.ended };
588
+ if (before === undefined) {
589
+ // Looked at and, for those that work, kept in the children document in one commit, so no end comes in between.
590
+ Object.assign(ended, await api.commit(async (tx) => {
591
+ const state = await tx.doc(Children, ROOT_CONVERSATION_ID);
592
+ const now = {};
593
+ for (const id of ids) {
594
+ const record = state.children[id];
595
+ if (isWorking(record))
596
+ record.waiters = [...(record.waiters ?? []), String(api.taskId)];
597
+ else
598
+ now[id] = endOf(record);
599
+ }
600
+ return now;
601
+ }, call));
602
+ }
603
+ else {
604
+ // The first end of each: a later message may make the child work again and answer anew.
605
+ for (const id of ids) {
606
+ if (Object.hasOwn(ended, id))
607
+ continue;
608
+ const signal = await api.readSignal(ChildEnded, id, call);
609
+ if (signal && "value" in signal)
610
+ ended[id] = signal.value;
611
+ }
612
+ }
613
+ const done = ids.filter((id) => Object.hasOwn(ended, id));
614
+ const left = ids.filter((id) => !Object.hasOwn(ended, id));
615
+ const over = left.length === 0 ? "all" : args.any === true && done.length > 0 ? "any" : api.wake?.reason === "expired" || api.wake?.reason === "time" ? "time" : undefined;
616
+ if (over === undefined) {
617
+ const waiting = { ...(until === undefined ? {} : { until }), ended };
618
+ return { sleep: { checkpoint: waiting, signals: left.map((id) => ChildEnded.key(id)), ...(until === undefined ? {} : { until }) } };
619
+ }
620
+ const results = await api.commit(async (tx) => {
621
+ const state = await tx.doc(Children, ROOT_CONVERSATION_ID);
622
+ const texts = await Promise.all(done.map(async (id) => `${describeChild(endedInfo(state.children[id], ended[id]), api.now())}\n${await endText(tx, ended[id])}`));
623
+ unwait(state, api.taskId);
624
+ return texts;
328
625
  }, call);
329
- if (started.id === undefined)
330
- return text(await capText("Not started", started.full, api.now()));
331
- return text(`Started ${started.id} ("${args.title.trim()}")${place ? ` for ${place}` : ""}, model ${model.provider}/${model.modelId}${chosen === undefined ? " (yours)" : ""}, ` +
332
- `thinking ${thinkingLevel}. Its final message comes back to you as a wake.`);
626
+ const works = left.length === 1 ? "still works" : "still work";
627
+ const head = over === "all"
628
+ ? `All of them ended: ${done.join(", ")}.`
629
+ : over === "any"
630
+ ? `${done.length === 1 ? "One of them ended" : "Some of them ended"}: ${done.join(", ")}; ${left.join(", ")} ${works}.`
631
+ : `The time is up; ${left.join(", ")} ${works}.${done.length > 0 ? ` Ended: ${done.join(", ")}.` : ""}`;
632
+ if (done.length === 0)
633
+ return text(head);
634
+ return text(await fitted(head, `\n${results.join("\n\n")}`, `wait-${api.taskId}`, "Together, their final messages are"));
333
635
  }
334
636
  if (!args.child)
335
637
  return text(`${args.action} needs a child ID.`);
336
- const child = Object.hasOwn(state.children, args.child) ? state.children[args.child] : undefined;
638
+ const child = Object.hasOwn(state.children, args.child) && mine(state.children[args.child]) ? state.children[args.child] : undefined;
337
639
  if (!child)
338
- return text(`No child ${args.child}.`);
640
+ return text(`No child ${args.child}${caller ? " of yours" : ""}.`);
339
641
  if (args.action === "stop")
340
642
  return text(await host.stop(child.id));
643
+ if (args.action === "result")
644
+ return text(await api.commit((tx) => resultText(tx, child, api.now()), call));
341
645
  if (child.stoppedAt !== undefined)
342
646
  return text(`${child.id} was stopped; start a new child.`);
343
647
  if (args.action === "interrupt") {
@@ -348,7 +652,7 @@ export function childrenExtension(host) {
348
652
  if (!args.message?.trim())
349
653
  return text("send needs a message.");
350
654
  const sent = await api.commit(async (tx) => {
351
- const state = await tx.doc(Children, api.conversationId);
655
+ const state = await tx.doc(Children, ROOT_CONVERSATION_ID);
352
656
  const record = state.children[child.id];
353
657
  // Again in the commit: a stop or other children may have come since the look above.
354
658
  if (record.stoppedAt !== undefined)
@@ -359,10 +663,7 @@ export function childrenExtension(host) {
359
663
  if (full !== undefined)
360
664
  return { full };
361
665
  }
362
- const reporter = await tx.createTask(Reporter, { child: child.id, conversationId: record.conversationId, message: `[message from the main agent]\n${args.message}` }, background);
363
- record.reporters.push(String(reporter));
364
- record.since ??= api.now();
365
- state.live[String(reporter)] = child.id;
666
+ await deliver(tx, state, record, `[message from ${from}]\n${args.message}`, api.now());
366
667
  return { busy, info: childInfo(record) };
367
668
  }, call);
368
669
  if ("refused" in sent)
@@ -379,10 +680,10 @@ export function childrenExtension(host) {
379
680
  return text(`Sent to ${child.id}; it takes the message ${when}.\n${describeChild({ ...busy, ...(activity ? { activity } : {}) }, api.now())}`);
380
681
  },
381
682
  });
382
- return defineExtension({ name: "tasks", tasks: [Anchor, Reporter], tools: [task] });
683
+ return { extension: defineExtension({ name: "tasks", tasks: [Anchor, Reporter], tools: [task] }), start };
383
684
  }
384
- /** The wake ID of a reporter's report to the main agent, also its request ID there, by which a stop finds it. */
385
- export function reportRequestId(reporter) {
685
+ /** The wake ID of a reporter's failure wake, also its request ID in the main agent's queue, by which a stop finds it. */
686
+ export function failureRequestId(reporter) {
386
687
  return `child-end:${String(reporter)}`;
387
688
  }
388
689
  //# sourceMappingURL=children.js.map