pi-durable-bot 0.8.9 → 0.8.11

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.
@@ -1,6 +1,6 @@
1
1
  import { StringEnum } from "@earendil-works/pi-ai";
2
- import { AssistantEntry, configure, defineDoc, defineExtension, defineTask, defineTool, ROOT_CONVERSATION_ID, } 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,8 +46,8 @@ 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; a longer one goes to a file. */
50
- const RESULT_CHARS = 30_000;
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
51
  const RESULT_LINES = 1_500;
52
52
  /** How much of a command or an output line a description shows. */
53
53
  const SHOWN_CHARS = 150;
@@ -79,6 +79,7 @@ export function childInfo(record) {
79
79
  conversationId: String(record.conversationId),
80
80
  ...(record.place === undefined ? {} : { place: record.place }),
81
81
  ...(record.routine === undefined ? {} : { routine: record.routine }),
82
+ ...(record.parent === undefined ? {} : { parent: record.parent }),
82
83
  ...(record.model === undefined ? {} : { model: record.model }),
83
84
  thinking: record.thinking,
84
85
  startedAt: record.startedAt,
@@ -88,6 +89,65 @@ export function childInfo(record) {
88
89
  ...(record.result?.failed === undefined ? {} : { failed: record.result.failed }),
89
90
  };
90
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
+ }
91
151
  /** The thinking level of a child the main agent starts without choosing one. */
92
152
  export const DEFAULT_CHILD_THINKING = "xhigh";
93
153
  /** How long, in words: "12 s", "4 min", "2.5 h". */
@@ -109,7 +169,7 @@ export function describeChild(child, now = Date.now(), options = {}) {
109
169
  : child.since !== undefined
110
170
  ? `working, for ${age(now - child.since)}`
111
171
  : `${child.failed === undefined ? "ended" : `failed (${clip(child.failed) ?? "no reason"})`} ${age(now - (child.endedAt ?? child.startedAt))} ago, waits for a message`;
112
- const line = `${child.id} "${child.title}": ${state}${child.place ? `, for ${child.place}` : ""}${options.thinking ? `${child.model ? `, model ${child.model}` : ""}, thinking ${child.thinking}` : ""}`;
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}` : ""}`;
113
173
  if (child.activity === undefined || child.since === undefined || child.stoppedAt !== undefined)
114
174
  return line;
115
175
  return [line, ...describeActivity(child.activity, now).map((each) => ` ${each}`)].join("\n");
@@ -146,6 +206,21 @@ export function describeActivity(activity, now = Date.now()) {
146
206
  function textOf(message) {
147
207
  return (message?.content ?? []).flatMap((part) => (part.type === "text" ? [part.text] : [])).join("");
148
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
+ }
149
224
  /** A child's last final message, or why it could not answer; undefined while it has neither. */
150
225
  async function childResult(tx, record) {
151
226
  if (record.result?.failed !== undefined)
@@ -171,15 +246,11 @@ export function childrenExtension(host) {
171
246
  },
172
247
  abort: (_anchor, runtime, context) => runtime.commit(() => ({ status: "terminal", outcome: { status: "aborted" } }), context),
173
248
  });
174
- /** Keep an answer of the child, once: several messages can end in one answer. */
175
- const keepAnswer = (record, answer, now) => {
176
- if (record.reported.includes(answer))
177
- return;
178
- record.reported.push(answer);
179
- record.result = { at: now };
180
- };
181
- /** The reporter ends: it is no longer live, and its child waits for a message once no other reporter is live. */
182
- 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) => {
183
254
  const id = state.live[reporter];
184
255
  delete state.live[reporter];
185
256
  const child = id === undefined ? undefined : state.children[id];
@@ -188,10 +259,22 @@ export function childrenExtension(host) {
188
259
  if (child.since !== undefined && child.stoppedAt === undefined)
189
260
  child.endedAt = now;
190
261
  delete child.since;
262
+ await endWaits(tx, [child]);
191
263
  };
192
- // Delivers one message to a child, waits for its answer and keeps how it ended; that wakes no one. A background task
193
- // of the main conversation; each phase ends with a checkpoint, and a request ID makes a phase that runs again after a
194
- // restart find the first submission, so the child gets the message once.
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;
273
+ };
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.
195
278
  const Reporter = defineTask({
196
279
  name: "bot.child-reporter",
197
280
  version: 1,
@@ -199,11 +282,22 @@ export function childrenExtension(host) {
199
282
  phases: {
200
283
  deliver: async (reporter, runtime, context) => {
201
284
  const { conversationId, message } = reporter.input;
202
- // 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.
203
292
  const state = await runtime.snapshot(Children, runtime.conversationId, context);
204
- if (state?.children[reporter.input.child]?.stoppedAt !== undefined) {
205
- await runtime.commit(() => ({ status: "running", checkpoint: { phase: "report" } }), context);
206
- 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);
207
301
  }
208
302
  const child = (await runtime.conversation(conversationId, context));
209
303
  const submission = await child.submit({ type: "input", content: message, whenBusy: "steer", requestId: `child:${reporter.id}`, entry: { kind: "bot.brief" } }, context);
@@ -222,8 +316,15 @@ export function childrenExtension(host) {
222
316
  if (settled.reason === "aborted" || record.stoppedAt !== undefined)
223
317
  return next;
224
318
  const detail = settled.detail === undefined ? "" : `: ${typeof settled.detail === "string" ? settled.detail : JSON.stringify(settled.detail)}`;
225
- record.result = { at: runtime.now(), failed: `${settled.reason}${detail}` };
226
- return next;
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 } } };
227
328
  }
228
329
  // An answer is kept also when a stop came after it.
229
330
  if (settled.type === "input")
@@ -232,14 +333,43 @@ export function childrenExtension(host) {
232
333
  }, context);
233
334
  },
234
335
  report: async (reporter, runtime, context) => {
336
+ const end = reporter.state.checkpoint.end;
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
+ }
359
+ }
235
360
  await runtime.commit(async (tx) => {
236
361
  const state = await tx.doc(Children, runtime.conversationId);
237
- // An end that an earlier version had not handed to the main agent yet: kept, as now.
238
- const end = reporter.state.checkpoint.end;
362
+ // An end that 0.8.8 had not kept yet: kept, as now.
239
363
  const record = state.children[reporter.input.child];
240
364
  if (end && record && (end.status === "answered" || record.stoppedAt === undefined))
241
365
  record.result = end.status === "failed" ? { at: runtime.now(), failed: end.text } : { at: runtime.now() };
242
- finish(state, String(reporter.id), 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
+ }
243
373
  return { status: "terminal", outcome: { status: "completed", result: null } };
244
374
  }, context);
245
375
  },
@@ -251,12 +381,11 @@ export function childrenExtension(host) {
251
381
  const submission = await tx.submissionByRequest(reporter.input.conversationId, `child:${reporter.id}`);
252
382
  if (record && submission?.type === "input" && submission.status === "done")
253
383
  keepAnswer(record, submission.answer, runtime.now());
254
- finish(state, String(reporter.id), runtime.now());
384
+ await finish(tx, state, String(reporter.id), runtime.now());
255
385
  return { status: "terminal", outcome: { status: "aborted" } };
256
386
  }, context),
257
387
  });
258
388
  const text = (value) => ({ output: [{ type: "text", text: value }] });
259
- const isWorking = (child) => child.since !== undefined && child.stoppedAt === undefined;
260
389
  /** At the cap, the children that work; checked in the commit that would make one more child work. */
261
390
  const atCap = (state) => {
262
391
  const working = Object.values(state.children).filter(isWorking);
@@ -272,7 +401,41 @@ export function childrenExtension(host) {
272
401
  /** What the model learns at the cap instead. */
273
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` +
274
403
  (await Promise.all(working.map(withActivity))).map((child) => describeChild(child, at)).join("\n");
275
- 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
+ };
276
439
  /**
277
440
  * A new child, in a commit of the main conversation; none at the cap, or for a routine while its earlier child works,
278
441
  * which the routine looked at before, but a message may have made that child work again since. Its first message says
@@ -283,6 +446,9 @@ export function childrenExtension(host) {
283
446
  const earlier = input.routine === undefined ? undefined : Object.values(state.children).find((child) => child.routine === input.routine && isWorking(child));
284
447
  if (earlier)
285
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 };
286
452
  const full = atCap(state);
287
453
  if (full !== undefined)
288
454
  return { full };
@@ -299,6 +465,7 @@ export function childrenExtension(host) {
299
465
  conversationId: conversation.id,
300
466
  ...(input.place ? { place: input.place } : {}),
301
467
  ...(input.routine === undefined ? {} : { routine: input.routine }),
468
+ ...(input.parent === undefined ? {} : { parent: input.parent }),
302
469
  ...(input.chosen === undefined ? {} : { model: input.chosen }),
303
470
  thinking: input.thinking,
304
471
  startedAt: now,
@@ -309,47 +476,79 @@ export function childrenExtension(host) {
309
476
  state.live[String(reporter)] = id;
310
477
  return { id };
311
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
+ };
312
494
  const task = defineTool({
313
495
  name: "task",
314
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 " +
315
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; " +
316
- "thinking: its thinking level, which it keeps, by default xhigh); it starts with an empty conversation and the brief. " +
317
- "list: your children, and what each one that works does now. result: a child's last final message (child: its ID). " +
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. " +
318
502
  "send: a message to a child; a child that waits starts on it " +
319
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 " +
320
504
  "that hangs; the child goes on, sees that they were aborted, and takes the messages that wait for it. " +
321
- "stop: stops a child and what it runs. A child's end does not wake you; a child can wake you itself.",
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.",
322
508
  parameters: obj({
323
- action: StringEnum(["start", "list", "result", "send", "interrupt", "stop"]),
509
+ action: StringEnum(["start", "list", "result", "wait", "send", "interrupt", "stop"]),
324
510
  title: opt(str()),
325
511
  brief: opt(str()),
326
512
  place: opt(str()),
327
513
  model: opt(str()),
328
514
  thinking: opt(StringEnum(["off", "minimal", "low", "medium", "high", "xhigh", "max"])),
329
515
  child: opt(str()),
516
+ children: opt(arr(str())),
517
+ any: opt(bool()),
518
+ seconds: opt(num()),
330
519
  message: opt(str()),
331
520
  }, { open: true }),
332
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
333
- // 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.
334
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
+ },
335
530
  execute: async (args, api, call) => {
336
- 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;
337
536
  const all = Object.values(state.children).map(childInfo);
338
- const working = all.filter(isWorking);
339
537
  if (args.action === "list") {
340
- 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)
341
542
  return text("No children.");
342
- const others = all.filter((child) => !working.includes(child)).slice(-20);
343
- const described = [...(await Promise.all(working.map(withActivity))), ...others];
344
- 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()));
345
544
  }
346
545
  if (args.action === "start") {
347
546
  if (!args.title?.trim() || !args.brief?.trim())
348
547
  return text("start needs a title and a brief.");
349
- const place = args.place?.trim() || host.place();
548
+ const place = args.place?.trim() || (caller ? caller.place : host.place());
350
549
  // A model of its own is checked now, so a child never starts with a model it cannot use. Without one, the
351
- // child has the main model, also when bot.json changes it later.
352
- 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;
353
552
  const found = chosen === undefined ? { model: host.mainModel() } : await host.childModel(chosen);
354
553
  if ("refused" in found)
355
554
  return text(`Not started: ${found.refused}`);
@@ -357,30 +556,92 @@ export function childrenExtension(host) {
357
556
  // As pi does, a level the model does not have becomes the nearest one it has, at each request (pi-ai).
358
557
  const thinkingLevel = args.thinking ?? DEFAULT_CHILD_THINKING;
359
558
  const title = args.title.trim();
360
- const started = await api.commit((tx) => start(tx, { title, brief: args.brief, from: "the main agent", ...(place ? { place } : {}), ...(chosen === undefined ? {} : { chosen }), model, thinking: thinkingLevel }, api.now()), call);
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.");
361
573
  if (!("id" in started))
362
574
  return text("full" in started ? await capText("Not started", started.full, api.now()) : "Not started.");
363
- return text(`Started ${started.id} ("${title}")${place ? ` for ${place}` : ""}, model ${model.provider}/${model.modelId}${chosen === undefined ? " (yours)" : ""}, ` +
575
+ return text(`Started ${started.id} ("${title}")${place ? ` for ${place}` : ""}, model ${model.provider}/${model.modelId}${args.model?.trim() ? "" : " (yours)"}, ` +
364
576
  `thinking ${thinkingLevel}.`);
365
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 { kind: "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;
625
+ }, call);
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"));
635
+ }
366
636
  if (!args.child)
367
637
  return text(`${args.action} needs a child ID.`);
368
- 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;
369
639
  if (!child)
370
- return text(`No child ${args.child}.`);
640
+ return text(`No child ${args.child}${caller ? " of yours" : ""}.`);
371
641
  if (args.action === "stop")
372
642
  return text(await host.stop(child.id));
373
- if (args.action === "result") {
374
- const result = await api.commit((tx) => childResult(tx, child), call);
375
- const now = describeChild(childInfo(child), api.now());
376
- if (result === undefined)
377
- return text(`${now}\nNo final message yet.`);
378
- // Tool output is cut at 2,000 lines or 50 KB: a longer result goes to a file, whole.
379
- if (result.length <= RESULT_CHARS && result.split("\n").length <= RESULT_LINES)
380
- return text(`${now}\nIts last final message:\n${result}`);
381
- const file = await host.saveResult(child.id, result);
382
- return text(`${now}\nIts last final message is ${result.length} characters; all of it is in ${file}. Its start:\n${result.split("\n").slice(0, 100).join("\n").slice(0, 4_000)}`);
383
- }
643
+ if (args.action === "result")
644
+ return text(await api.commit((tx) => resultText(tx, child, api.now()), call));
384
645
  if (child.stoppedAt !== undefined)
385
646
  return text(`${child.id} was stopped; start a new child.`);
386
647
  if (args.action === "interrupt") {
@@ -391,7 +652,7 @@ export function childrenExtension(host) {
391
652
  if (!args.message?.trim())
392
653
  return text("send needs a message.");
393
654
  const sent = await api.commit(async (tx) => {
394
- const state = await tx.doc(Children, api.conversationId);
655
+ const state = await tx.doc(Children, ROOT_CONVERSATION_ID);
395
656
  const record = state.children[child.id];
396
657
  // Again in the commit: a stop or other children may have come since the look above.
397
658
  if (record.stoppedAt !== undefined)
@@ -402,10 +663,7 @@ export function childrenExtension(host) {
402
663
  if (full !== undefined)
403
664
  return { full };
404
665
  }
405
- const reporter = await tx.createTask(Reporter, { child: child.id, conversationId: record.conversationId, message: `[message from the main agent]\n${args.message}` }, background);
406
- record.reporters.push(String(reporter));
407
- record.since ??= api.now();
408
- state.live[String(reporter)] = child.id;
666
+ await deliver(tx, state, record, `[message from ${from}]\n${args.message}`, api.now());
409
667
  return { busy, info: childInfo(record) };
410
668
  }, call);
411
669
  if ("refused" in sent)
@@ -424,4 +682,8 @@ export function childrenExtension(host) {
424
682
  });
425
683
  return { extension: defineExtension({ name: "tasks", tasks: [Anchor, Reporter], tools: [task] }), start };
426
684
  }
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) {
687
+ return `child-end:${String(reporter)}`;
688
+ }
427
689
  //# sourceMappingURL=children.js.map