@centralu/host-win32-x64 0.1.0-beta.60 → 0.1.0-beta.62

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.
package/host/main.mjs CHANGED
@@ -43046,7 +43046,7 @@ import { dirname as dirname27, join as join58 } from "node:path";
43046
43046
  import { mkdirSync as mkdirSync21, readFileSync as readFileSync27, writeSync as writeSync4 } from "node:fs";
43047
43047
 
43048
43048
  // packages/protocol/src/version.generated.ts
43049
- var APP_VERSION = "0.1.0-beta.60";
43049
+ var APP_VERSION = "0.1.0-beta.62";
43050
43050
 
43051
43051
  // packages/protocol/src/brand.ts
43052
43052
  var APP_NAME = "Centralu";
@@ -57798,7 +57798,8 @@ function applyBackgroundTasks(prev, e) {
57798
57798
  const liveIds = new Set(live2.map((t) => t.id));
57799
57799
  const fresh = (e.ended ?? []).filter((t) => !liveIds.has(t.id) && t.status !== "running");
57800
57800
  const freshIds = new Set(fresh.map((t) => t.id));
57801
- const kept = e.clearEnded ? [] : prev.filter((t) => t.status !== "running" && !liveIds.has(t.id) && !freshIds.has(t.id));
57801
+ const newBurst = liveBackgroundTasks(live2).length > 0 && liveBackgroundTasks(prev).length === 0;
57802
+ const kept = e.clearEnded || newBurst ? [] : prev.filter((t) => t.status !== "running" && !liveIds.has(t.id) && !freshIds.has(t.id));
57802
57803
  return [...live2, ...[...kept, ...fresh].slice(-BACKGROUND_ENDED_KEPT)];
57803
57804
  }
57804
57805
  function liveBackgroundTasks(tasks) {
@@ -59581,6 +59582,16 @@ var MailParty = external_exports.object({
59581
59582
  state: external_exports.string().nullable().default(null)
59582
59583
  });
59583
59584
  var MailChoices = external_exports.array(external_exports.string()).min(2).max(6);
59585
+ var MailAsk = external_exports.object({
59586
+ /** The message waiting for the answer: the one a pick or words answer (`mail.reply` `answers`) */
59587
+ id: external_exports.string(),
59588
+ sender: MailParty,
59589
+ /** Its first lines, as plain words */
59590
+ text: external_exports.string(),
59591
+ choices: MailChoices.optional().catch(void 0),
59592
+ /** Every message to the person that waits for an answer in this thread, oldest first, `id` being the last: the host's one rule for an open question, which a window reads and never works out (#2233). */
59593
+ open: external_exports.array(external_exports.string())
59594
+ });
59584
59595
  var MailThreadRow = external_exports.object({
59585
59596
  id: external_exports.string(),
59586
59597
  subject: external_exports.string(),
@@ -59592,6 +59603,8 @@ var MailThreadRow = external_exports.object({
59592
59603
  assignee: MailParty.nullable().default(null),
59593
59604
  /** Messages to the person in this thread that the person has not read */
59594
59605
  unread: external_exports.number().default(0),
59606
+ /** What the thread waits on the person to answer; null when nothing does. Absent from a host of an older build */
59607
+ ask: MailAsk.nullable().default(null),
59595
59608
  /** Mail in the thread held for the person to act on (a loop, a spent budget, a policy, a delivery that failed), for any receiver */
59596
59609
  held: external_exports.number().default(0),
59597
59610
  /** Standing blockers: none since blockers went with threads (§12.2); kept for a window of an older build, which reads it */
@@ -62048,7 +62061,7 @@ var mailParams = {
62048
62061
  threadId: external_exports.string(),
62049
62062
  text: external_exports.string().min(1).max(16e3),
62050
62063
  kind: external_exports.enum(["note", "answer", "question"]).optional(),
62051
- /** A pick (#1630): the id of the question in this thread whose choice `text` is. The answer goes to that question, not to the newest open one, and a question already answered refuses it (`answered`). An older host ignores it */
62064
+ /** The id of the question in this thread that `text` answers (#1630, #2191): a pick of one of its choices, or the person's own words. The answer goes to that question, not to the newest open one, and a question already answered refuses it (`answered`). An older host takes only a choice of the question, and refuses other words */
62052
62065
  answers: external_exports.string().optional()
62053
62066
  }),
62054
62067
  /** The person closes a thread */
@@ -64092,6 +64105,26 @@ function builderErrorFrame(app2, report) {
64092
64105
  ` + body;
64093
64106
  }
64094
64107
 
64108
+ // packages/protocol/src/plain-line.ts
64109
+ var LINE_MARKS = /^\s*(?:`{3,}|~{3,}|#{1,6}\s+|>\s?|(?:[-*+]|\d{1,9}[.)])\s+(?:\[[ xX]\]\s+)?)+/;
64110
+ function plainLine(body, max) {
64111
+ return oneLineText(plainText(body), max);
64112
+ }
64113
+ function plainLines(body, lines, max) {
64114
+ const text3 = plainText(body).split("\n").map((l) => oneLineText(l)).filter((l) => l !== "").slice(0, lines).join("\n");
64115
+ return text3.length > max ? `${text3.slice(0, max)}\u2026` : text3;
64116
+ }
64117
+ function plainText(body) {
64118
+ return body.split("\n").map((line) => line.replace(LINE_MARKS, "")).join("\n").replace(/!?\[([^\]\n]*)\]\([^)\n]*\)/g, "$1").replace(/`+([^`\n]+?)`+/g, "$1").replace(/(\*\*|__|~~)(?=\S)(.+?)(?<=\S)\1/g, "$2").replace(/(?<![\w*])\*(?=\S)([^*\n]+?)(?<=\S)\*(?![\w*])/g, "$1").replace(/(?<![\w_])_(?=\S)([^_\n]+?)(?<=\S)_(?![\w_])/g, "$1");
64119
+ }
64120
+
64121
+ // packages/protocol/src/mail-ask.ts
64122
+ var ASK_LINES = 4;
64123
+ var ASK_CHARS = 320;
64124
+ function mailAsk(newest, sender, open6) {
64125
+ return { id: newest.id, sender, text: plainLines(newest.body, ASK_LINES, ASK_CHARS), ...newest.choices ? { choices: newest.choices } : {}, open: [...open6] };
64126
+ }
64127
+
64095
64128
  // packages/protocol/src/centralu-calls.ts
64096
64129
  function mcpNameParts(name) {
64097
64130
  const m = /^mcp__([^_]+(?:_(?!_)[^_]*)*)__(.+)$/.exec(name);
@@ -108187,7 +108220,7 @@ function presetWithin(child, parent) {
108187
108220
  function aboveCallerError(name, child, caller) {
108188
108221
  return presetWithin(child, caller) ? null : `"${name}" now has more permissions (${child}) than this session (${caller}), so this session cannot give it work. Tell the person.`;
108189
108222
  }
108190
- var PARENT_MAIL = 'To write to it before you finish, call mail with `to: "parent"`. ';
108223
+ var PARENT_MAIL = 'No progress reports needed. To ask it something before you finish, call mail with `to: "parent"` ("assistant" is someone else). ';
108191
108224
  function canMailParent(child, senderId) {
108192
108225
  return child.askedBy === senderId && !!child.projectId;
108193
108226
  }
@@ -108218,7 +108251,7 @@ function agentChoice(asked, remembered, byDifficulty) {
108218
108251
  }
108219
108252
  function remoteAgentFrame(parentName, task, instructions = "", mail = false) {
108220
108253
  return [
108221
- `[A session working on this repository on another computer, "${frameField(parentName)}", gives you this task through Centralu's start_agent. Your final message goes back to it as the answer: keep it short. It cannot read this computer's files, so put what it needs in the answer itself, and commit and push what it should get. ${ANSWER_GROUNDS} ` + (mail ? 'To write to it before you answer (a question, a checkpoint), call mail with `to: "parent"`. ' : (
108254
+ `[A session working on this repository on another computer, "${frameField(parentName)}", gives you this task through Centralu's start_agent. Your final message goes back to it as the answer: keep it short. It cannot read this computer's files, so put what it needs in the answer itself, and commit and push what it should get. ${ANSWER_GROUNDS} ` + (mail ? PARENT_MAIL : (
108222
108255
  // #1987: this machine's Centralu takes no mail from that computer, so the answer is the only way it hears from the child
108223
108256
  "Mail does not reach it from here yet: the answer is how it hears from you. "
108224
108257
  )) + "Wait for your own background work that ends (a test run, a build) inside your turn before you answer.]",
@@ -108228,8 +108261,8 @@ function remoteAgentFrame(parentName, task, instructions = "", mail = false) {
108228
108261
  ...projectInstructions(instructions)
108229
108262
  ].join("\n");
108230
108263
  }
108231
- function agentNoteFrame(parentName, text3, mailParent = false) {
108232
- return `[A note from the parent session "${frameField(parentName)}" through Centralu's agent_session. These are the parent's words about your ongoing work.${mailParent ? ' To write to it, call mail with `to: "parent"`.' : ""}]
108264
+ function agentNoteFrame(parentName, text3) {
108265
+ return `[A note from the parent session "${frameField(parentName)}" through Centralu's mail. These are the parent's words about your ongoing work.]
108233
108266
 
108234
108267
  ${text3}`;
108235
108268
  }
@@ -108471,7 +108504,7 @@ ${cardsText(r.cards)}
108471
108504
  agent_session(sessionId="${r.sessionId}", action="answer", card=\u2026, text=\u2026) answers it. ${ANSWER_FORM}`
108472
108505
  };
108473
108506
  case "mailed":
108474
- return { text: `${mailedText(r, "agent_session")} agent_session(sessionId="${r.sessionId}", action="stop") withdraws it until it is delivered.` };
108507
+ return { text: `${mailedText(r, "mail")} agent_session(sessionId="${r.sessionId}", action="stop") withdraws it until it is delivered.` };
108475
108508
  case "queued":
108476
108509
  return { text: `${queuedText(r)} agent_session(sessionId="${r.sessionId}", action="stop") withdraws it.` };
108477
108510
  case "answered":
@@ -108490,7 +108523,7 @@ agent_session(sessionId="${r.sessionId}", action="answer", card=\u2026, text=\u2
108490
108523
  text: `${who} is not working on anything you gave it (${r.sessionState}${r.interruption ? `, ${interruptionWords(r.interruption)}` : ""}). Its last answer, as JSON:
108491
108524
  ${trustedJsonText(r.answer || "(no final text)")}
108492
108525
  ` + (r.notice ? `${r.notice}
108493
- ` : "") + `agent_session(sessionId="${r.sessionId}", action="send", text=\u2026) gives it more. ${NEW_ROLE_NEW_AGENT}` + (r.cleanUp ? `
108526
+ ` : "") + `mail(action="send", to="${r.sessionId}", text=\u2026) gives it more. ${NEW_ROLE_NEW_AGENT}` + (r.cleanUp ? `
108494
108527
  ${cleanUpLine(r.sessionId)}` : "")
108495
108528
  };
108496
108529
  case "done": {
@@ -108498,7 +108531,7 @@ ${cleanUpLine(r.sessionId)}` : "")
108498
108531
  if (r.notice) lines.push(r.notice);
108499
108532
  if (r.readable.length) lines.push(`You can read these now: ${r.readable.join(", ")}`);
108500
108533
  if (r.outside.length) lines.push(`Named outside its folder (not opened for you): ${r.outside.join(", ")}`);
108501
- lines.push(`agent_session(sessionId="${r.sessionId}", action="send", text=\u2026) continues with it. ${NEW_ROLE_NEW_AGENT}`);
108534
+ lines.push(`mail(action="send", to="${r.sessionId}", text=\u2026) continues with it. ${NEW_ROLE_NEW_AGENT}`);
108502
108535
  if (r.cleanUp) lines.push(cleanUpLine(r.sessionId));
108503
108536
  return { text: lines.join("\n") };
108504
108537
  }
@@ -109458,7 +109491,6 @@ var HANDS_ON = /* @__PURE__ */ new Set(["create_session", "send_to_session", "st
109458
109491
  function stepKind(name, args) {
109459
109492
  if (UNDOABLE.has(name)) return "undoable";
109460
109493
  if (HANDS_ON.has(name)) return "handsOn";
109461
- if (name === "agent_session") return args.action === "send" ? "handsOn" : "asks";
109462
109494
  if (name === "mail") return args.action === "send" ? "handsOn" : "asks";
109463
109495
  return "asks";
109464
109496
  }
@@ -110428,6 +110460,7 @@ ${section(near)}` };
110428
110460
  // packages/agent-host/src/sessions/tool-definitions.ts
110429
110461
  var READ_TOOLS = external_exports.union([external_exports.enum(["none", "titles", "full"]), external_exports.boolean()]);
110430
110462
  var IF_BUSY = external_exports.enum(["fork", "fork_read"]);
110463
+ var SEND_IS_MAIL = 'agent_session has no "send": more work for a session you started is a mail send to its id';
110431
110464
  var UPDATE_ACTION = external_exports.enum(["check", "install", "apply"]);
110432
110465
  var CENTRALU_TOOLS = [
110433
110466
  {
@@ -111022,28 +111055,28 @@ var AGENT_TOOLS = [
111022
111055
  * "answer" (#676): a card of the turn the caller gave, which status shows; `card` only when more than one stands.
111023
111056
  * Not in the description: the answer that shows a card names the call, and the description rides in every request.
111024
111057
  */
111025
- description: "Lists, checks, messages, waits for, stops or archives sessions start_agent started.",
111058
+ // No `send` (#1948, owner 2026-11-12): words to a session are `mail`, which gives a child of the caller's its next work (MAIL_TOOLS)
111059
+ description: "Lists, checks, waits for, stops or archives sessions start_agent started.",
111026
111060
  schema: external_exports.object({
111027
111061
  // Not needed for "list" (#690): the caller's own children, so a parent that forgot one finds it in one call
111028
111062
  sessionId: external_exports.string().optional(),
111029
- action: external_exports.enum(["status", "send", "wait", "stop", "delete", "answer", "list"]),
111063
+ // The refusal of the old `send` names the call that replaced it: words in an error ride in no request
111064
+ action: external_exports.enum(["status", "wait", "stop", "delete", "answer", "list"], { error: (i) => i.input === "send" ? SEND_IS_MAIL : void 0 }),
111030
111065
  text: external_exports.string().optional(),
111031
- card: external_exports.string().optional(),
111032
- // A fork instead of mail to a busy session; the mailed answer names it
111033
- ifBusy: IF_BUSY.optional()
111066
+ card: external_exports.string().optional()
111034
111067
  }),
111035
111068
  deferred: true
111036
111069
  }
111037
111070
  ];
111038
- var AGENT_BUDGET_CHARS = 1400;
111071
+ var AGENT_BUDGET_CHARS = 1330;
111039
111072
  var MAIL_TOOLS = [
111040
111073
  {
111041
111074
  name: "mail",
111042
- description: `Work and messages with sessions, apps and the person; cite=true (to "assistant") only when the person's last message here asked for it. Ask the person with kind "question".`,
111075
+ description: `Work and messages with sessions, apps and the person; cite=true (to "assistant") only when the person's last message here asked for it. Ask the person with kind "question". In a report, say what each claim was checked against, and what was not.`,
111043
111076
  schema: external_exports.object({
111044
111077
  action: external_exports.enum(["inbox", "read", "handled", "send", "reply", "update", "close", "find"]),
111045
111078
  thread: external_exports.string().optional(),
111046
- to: external_exports.string().optional().describe('"parent": the session that started you, for a question or checkpoint; "assistant": the Centralu Assistant, for what only it can decide; "person": the human; or a session by name or id. For find: words (name, project, machine, role) to search every computer'),
111079
+ to: external_exports.string().optional().describe('"parent": the session that started you, for a question; "assistant": the Centralu Assistant, for what only it can decide; "person": the human; or a session by name or id. For find: words (name, project, machine, role) to search every computer'),
111047
111080
  kind: external_exports.string().optional(),
111048
111081
  subject: external_exports.string().optional(),
111049
111082
  text: external_exports.string().optional(),
@@ -111055,12 +111088,14 @@ var MAIL_TOOLS = [
111055
111088
  urgent: external_exports.boolean().optional(),
111056
111089
  follows: external_exports.array(external_exports.string()).optional(),
111057
111090
  cite: external_exports.boolean().optional(),
111058
- choices: external_exports.array(external_exports.string()).optional()
111091
+ choices: external_exports.array(external_exports.string()).optional(),
111092
+ // A fork instead of a mail task, for a busy session the caller started (#1948); the mailed answer names it
111093
+ ifBusy: IF_BUSY.optional()
111059
111094
  }),
111060
111095
  deferred: true
111061
111096
  }
111062
111097
  ];
111063
- var MAIL_BUDGET_CHARS = 1240;
111098
+ var MAIL_BUDGET_CHARS = 1355;
111064
111099
  var COMPACT_TOOLS = [
111065
111100
  {
111066
111101
  name: "compact_self",
@@ -111586,7 +111621,7 @@ function movedChildrenNote(moved, commands = "") {
111586
111621
  "",
111587
111622
  ...moved.filter((c) => !c.folded).map((c) => `- ${movedLabel(c)} \u2014 ${c.state} \u2014 handle: ${c.handle}. ${c.can}`),
111588
111623
  ...folded > 0 ? [
111589
- `- ${folded} finished session${folded === 1 ? "" : "s"} \u2014 ${SETTLED_CHILD}. agent_session(action="list") lists ${folded === 1 ? "it" : "them"} with ${folded === 1 ? "its" : "their"} names, handles and states. ${folded === 1 ? "It answers" : "They answer"} to you as ${folded === 1 ? "a session" : "sessions"} you started: agent_session works on ${folded === 1 ? "it" : "each"} (status, wait, send, stop, delete), and a send gives more work, whose report comes to you.` + (reports > 0 ? ` ${reports === 1 ? "A report" : `${reports} reports`} the previous session had not read came with ${folded === 1 ? "it" : "them"} as mail: the mail tool's inbox lists ${reports === 1 ? "it" : "them"}.` : "")
111624
+ `- ${folded} finished session${folded === 1 ? "" : "s"} \u2014 ${SETTLED_CHILD}. agent_session(action="list") lists ${folded === 1 ? "it" : "them"} with ${folded === 1 ? "its" : "their"} names, handles and states. ${folded === 1 ? "It answers" : "They answer"} to you as ${folded === 1 ? "a session" : "sessions"} you started: agent_session works on ${folded === 1 ? "it" : "each"} (status, wait, stop, delete), and mail to ${folded === 1 ? "it" : "one"} gives more work, whose report comes to you.` + (reports > 0 ? ` ${reports === 1 ? "A report" : `${reports} reports`} the previous session had not read came with ${folded === 1 ? "it" : "them"} as mail: the mail tool's inbox lists ${reports === 1 ? "it" : "them"}.` : "")
111590
111625
  ] : [],
111591
111626
  "",
111592
111627
  "---",
@@ -111688,7 +111723,7 @@ var HandoffChildren = class {
111688
111723
  sessions.push(id3);
111689
111724
  const project2 = s.projectId !== original.projectId ? projects.get(s.projectId ?? "") ?? s.projectId ?? "" : void 0;
111690
111725
  const told = owing.has(id3);
111691
- const can = project2 !== void 0 ? `Call ask_project with project "${project2}" and no task to wait for its answer${told ? "; you are told of its cards and answer them with agent_session (answer) as far as you may" : ""}. It is that project's session: agent_session does nothing else with it.` : s.askedBy === from ? `${told ? "Its report comes to you. " : state === SETTLED_CHILD ? "Give it more work with agent_session (send) and its report comes to you. " : ""}agent_session works on it as on a session you started (status, wait, send, stop, delete).` : `${told ? "Its report and its cards come to you" : "Nothing about it comes to you unless you ask"}. You did not start it, so agent_session works on it only with the auto preset.`;
111726
+ const can = project2 !== void 0 ? `Call ask_project with project "${project2}" and no task to wait for its answer${told ? "; you are told of its cards and answer them with agent_session (answer) as far as you may" : ""}. It is that project's session: agent_session does nothing else with it.` : s.askedBy === from ? `${told ? "Its report comes to you. " : state === SETTLED_CHILD ? "Give it more work by mail and its report comes to you. " : ""}agent_session works on it as on a session you started (status, wait, stop, delete).` : `${told ? "Its report and its cards come to you" : "Nothing about it comes to you unless you ask"}. You did not start it, so agent_session works on it only with the auto preset.`;
111692
111727
  const folded = state === SETTLED_CHILD && project2 === void 0 && s.askedBy === from;
111693
111728
  moved.push({ handle: id3, name: this.host.nameOf(id3), state, can, ...project2 !== void 0 ? { project: project2 } : {}, ...folded ? { folded: true } : {} });
111694
111729
  }
@@ -113033,8 +113068,8 @@ var HANDLERS = {
113033
113068
  compact_self({ focus, then: then2 }, { tools }) {
113034
113069
  return tools.compactSelf ? tools.compactSelf(focus, then2) : { text: "Compacting is not available in this session.", isError: true };
113035
113070
  },
113036
- mail(args, { tools }) {
113037
- return tools.mail ? tools.mail(args) : { text: "The mailbox is not available in this session.", isError: true };
113071
+ mail(args, { tools, signal }) {
113072
+ return tools.mail ? tools.mail(args, signal) : { text: "The mailbox is not available in this session.", isError: true };
113038
113073
  },
113039
113074
  async update_centralu({ action }, { tools, caller, signal }) {
113040
113075
  const r = tools.updateCentralu ? await tools.updateCentralu(action, signal) : { ok: false, error: "Update checks are unavailable" };
@@ -113086,7 +113121,7 @@ var HANDLERS = {
113086
113121
  const branch = trimmed(args.branch);
113087
113122
  const name = trimmed(args.name);
113088
113123
  const machine = trimmed(args.machine);
113089
- return agentCallsFor(caller, agentRunText(
113124
+ return agentCallsFor(caller.profile, agentRunText(
113090
113125
  await tools.startAgent(
113091
113126
  {
113092
113127
  task,
@@ -113107,14 +113142,13 @@ var HANDLERS = {
113107
113142
  },
113108
113143
  async agent_session(args, { tools, signal, caller }) {
113109
113144
  const sessionId = trimmed(args.sessionId);
113110
- const { action, ifBusy } = args;
113111
- if (action === "list") return agentCallsFor(caller, agentListText(await tools.listAgents()));
113145
+ const { action } = args;
113146
+ if (action === "list") return agentCallsFor(caller.profile, agentListText(await tools.listAgents()));
113112
113147
  if (!sessionId) return { text: "Give the sessionId start_agent returned.", isError: true };
113113
113148
  const text3 = args.text?.trim() ? args.text : void 0;
113114
- if (action === "send" && !text3) return { text: "Give text: what to send it.", isError: true };
113115
113149
  if (action === "answer" && !text3) return { text: "Give text: the answer.", isError: true };
113116
113150
  const card = trimmed(args.card);
113117
- return agentCallsFor(caller, agentRunText(await tools.agentSession({ sessionId, action, ...text3 ? { text: text3 } : {}, ...card ? { card } : {}, ...ifBusy ? { ifBusy } : {} }, signal)));
113151
+ return agentCallsFor(caller.profile, agentRunText(await tools.agentSession({ sessionId, action, ...text3 ? { text: text3 } : {}, ...card ? { card } : {} }, signal)));
113118
113152
  },
113119
113153
  async recall({ query, limit }, { tools }) {
113120
113154
  const r = await tools.recall(query, limit);
@@ -113384,10 +113418,13 @@ When you no longer need it, call ${namedCall(caller.profile, "detach_app", { app
113384
113418
  };
113385
113419
  }
113386
113420
  };
113387
- function agentCallsFor(caller, out) {
113388
- if (!commandsFor(caller.profile).includes("agent_session")) return out;
113389
- const text3 = out.text.replace(/\bagent_session\(([^)]*)\)/g, (_, inner) => `centralu_run(command="agent_session", args={${inner.replace(/\b(\w+)=/g, "$1: ")}})`);
113390
- return { ...out, text: text3 };
113421
+ function agentCallsFor(profile, out) {
113422
+ const commands = commandsFor(profile);
113423
+ const text3 = out.text.replace(
113424
+ /"(?:[^"\\\n]|\\.)*"|\b(agent_session|mail)\(([^)]*)\)/g,
113425
+ (call2, tool, inner) => tool && commands.includes(tool) ? `centralu_run(command="${tool}", args={${(inner ?? "").replace(/\b(\w+)=/g, "$1: ")}})` : call2
113426
+ );
113427
+ return text3 === out.text ? out : { ...out, text: text3 };
113391
113428
  }
113392
113429
  function commandLine(description) {
113393
113430
  const plain2 = description.replace(/\*\*/g, "").replace(/ \((?:#\d+|M4)\)/g, "");
@@ -114269,19 +114306,13 @@ var AgentStartFlow = class {
114269
114306
  progress.childId = child.id;
114270
114307
  if (name) this.host.rename(child.id, name);
114271
114308
  const key = `${callerId}>${child.id}`;
114272
- const d2 = this.flow.startDelegation(key, callerId, child.id, { id: project2.id, name: project2.name, path: child.worktree?.path ?? cwd }, true);
114309
+ const instructions = project2.id === ASSISTANT_PLACE ? "" : this.host.store.projects.agentInstructions(project2.id);
114310
+ const frame = agentFrame(labelOf(this.host.store.messages, caller), choice.task, setupProblems, instructions, canMailParent(child, callerId));
114311
+ const { d: d2, delivered } = this.flow.delegate({ key, callerId, sessionId: child.id, target: { id: project2.id, name: project2.name, path: child.worktree?.path ?? cwd }, agent: true, via: "start_agent", task: choice.task, frame });
114273
114312
  release();
114274
114313
  progress.d = d2;
114275
- const withdraw = this.host.children.delegated(callerId, child.id, "start_agent", choice.task);
114276
- try {
114277
- const instructions = project2.id === ASSISTANT_PLACE ? "" : this.host.store.projects.agentInstructions(project2.id);
114278
- await this.host.deliver(child.id, agentFrame(labelOf(this.host.store.messages, caller), choice.task, setupProblems, instructions, canMailParent(child, callerId)), void 0, { sessionId: callerId, name: labelOf(this.host.store.messages, caller) }, false);
114279
- } catch (e) {
114280
- withdraw();
114281
- this.host.children.dropDelegation(key, d2);
114282
- if (this.host.agentRuns.get(child.id) === d2.wait) this.host.agentRuns.delete(child.id);
114283
- return done2({ ok: false, error: `Could not give the task to the new session: ${e.message}` });
114284
- }
114314
+ const failed4 = await delivered;
114315
+ if (failed4) return done2({ ok: false, error: `Could not give the task to the new session: ${failed4}` });
114285
114316
  const notice = this.host.handles.get(child.id)?.delegationNotice?.();
114286
114317
  return { key, d: d2, notice: [unchecked, forkNote, notice].filter(Boolean).join("; ") || void 0 };
114287
114318
  }
@@ -114729,17 +114760,11 @@ var DelegationForks = class {
114729
114760
  if (late) return this.flow.starts.abandonChild(child, late, worktree ? void 0 : `Fork of ${target.name}`.slice(0, 48));
114730
114761
  if (!worktree) this.host.rename(child.id, `Fork of ${target.name}`.slice(0, 48));
114731
114762
  const key = `${callerId}>${child.id}`;
114732
- const d2 = this.flow.startDelegation(key, callerId, child.id, { id: project2.id, name: project2.name, path: child.worktree?.path ?? this.host.cwdFor(child) }, true);
114763
+ const frame = agentFrame(labelOf(this.host.store.messages, caller), text3, [], "", canMailParent(child, callerId));
114764
+ const { d: d2, delivered } = this.flow.delegate({ key, callerId, sessionId: child.id, target: { id: project2.id, name: project2.name, path: child.worktree?.path ?? this.host.cwdFor(child) }, agent: true, via, task: text3, frame });
114733
114765
  place.release();
114734
- try {
114735
- await this.host.deliver(child.id, agentFrame(labelOf(this.host.store.messages, caller), text3, [], "", canMailParent(child, callerId)), void 0, { sessionId: callerId, name: labelOf(this.host.store.messages, caller) }, false);
114736
- } catch (e) {
114737
- d2.wait.fail(e);
114738
- this.host.children.dropDelegation(key, d2);
114739
- return { ok: false, error: `The fork "${child.name}" [${child.id}] was made but did not take the request: ${e.message}` };
114740
- }
114741
- this.host.children.delegated(callerId, child.id, via, text3);
114742
- return { ok: true, key, d: d2, fork: child };
114766
+ const failed4 = await delivered;
114767
+ return failed4 ? { ok: false, error: `The fork "${child.name}" [${child.id}] was made but did not take the request: ${failed4}` } : { ok: true, key, d: d2, fork: child };
114743
114768
  } finally {
114744
114769
  place.release();
114745
114770
  }
@@ -114830,22 +114855,15 @@ var AgentSessionActions = class {
114830
114855
  *
114831
114856
  * status where it stands, without waiting (the answer, once the turn the caller gave it has ended)
114832
114857
  * wait waits on that turn up to the bound, as start_agent does
114833
- * send gives it more, including during the caller's turn on adapters that accept mid-turn input; refused
114834
- * while it works on the person's own message or has a higher preset than the caller
114835
114858
  * stop stops the turn the caller gave it; a turn the person started there is theirs
114836
114859
  * delete trashes a child without a worktree, stopping it first; worktree cleanup requires an idle child (#608)
114837
114860
  */
114838
114861
  async agentSession(callerId, opts, signal) {
114839
114862
  if (opts.sessionId === callerId && opts.action !== "status") {
114840
- return { ok: false, error: "agent_session cannot wait on, stop, delete or send to its own calling session." };
114863
+ return { ok: false, error: "agent_session cannot wait on, stop or delete its own calling session." };
114841
114864
  }
114842
114865
  const remote = opts.sessionId.includes(".") ? this.flow.remote.of(opts.sessionId) : void 0;
114843
- if (remote) {
114844
- const machine = opts.action === "send" ? this.host.linkedReader?.machineOf(opts.sessionId) : void 0;
114845
- const refused2 = opts.action === "send" ? this.host.refusesDelegation(callerId, { sessionId: opts.sessionId, linked: true }, { tool: "agent_session", target: `a session on ${machine ?? "a linked machine"}`, text: opts.text ?? "" }) : null;
114846
- if (refused2) return { ok: false, error: refused2 };
114847
- return this.flow.remote.agentSession(callerId, remote, opts, signal);
114848
- }
114866
+ if (remote) return this.flow.remote.agentSession(callerId, remote, opts, signal);
114849
114867
  const gone2 = this.flow.handedOverAnswer(callerId, opts.sessionId);
114850
114868
  if (gone2) return gone2;
114851
114869
  const request = this.host.children.agentStarts.get(opts.sessionId);
@@ -114868,11 +114886,9 @@ var AgentSessionActions = class {
114868
114886
  return cards2.length ? { ok: true, state: "asking", sessionId: child.id, sessionName: child.name, tool: child.tool, cards: cards2 } : { ok: true, state: "working", sessionId: child.id, sessionName: child.name, tool: child.tool, reported: false };
114869
114887
  }
114870
114888
  const deletingWithoutWorktree = opts.action === "delete" && !child?.worktree;
114871
- const startedHere = child?.askedBy === callerId || deletingWithoutWorktree && child?.parentSessionId === callerId;
114872
- const seat = caller?.projectId ? "project" : isAssistantKind(caller?.kind) ? "assistant" : null;
114873
- const owns = seat === "assistant" ? child?.askedBy === callerId : startedHere || !deletingWithoutWorktree && this.host.autoBoundaryOpen(callerId, "session ownership");
114874
- if (!caller || !seat || !child || !owns || child.projectId !== caller.projectId) {
114875
- return { ok: false, error: `${opts.sessionId} is not a session this session started. agent_session works only on sessions start_agent started from here.${child ? "" : staleSessionHint(this.host, opts.sessionId, (s) => s.projectId === caller?.projectId && s.id !== callerId && (seat !== "assistant" || s.askedBy === callerId))}` };
114889
+ const mayWork = (c, ch2) => ownChild(c, ch2) || !!c.projectId && ch2.projectId === c.projectId && (deletingWithoutWorktree ? ch2.parentSessionId === callerId : this.host.autoBoundaryOpen(callerId, "session ownership"));
114890
+ if (!caller || !child || !mayWork(caller, child)) {
114891
+ return { ok: false, error: `${opts.sessionId} is not a session this session started. agent_session works only on sessions start_agent started from here.${child ? "" : staleSessionHint(this.host, opts.sessionId, (s) => s.projectId === caller?.projectId && s.id !== callerId && (!!caller?.projectId || s.askedBy === callerId))}` };
114876
114892
  }
114877
114893
  if (opts.sessionId === callerId) return this.flow.agentAtRest(child);
114878
114894
  if (opts.action === "answer") return this.host.answerRoutedCard(callerId, child.id, opts.card, opts.text ?? "");
@@ -114932,41 +114948,6 @@ var AgentSessionActions = class {
114932
114948
  const note = [r.note, timers.length ? `Its timers ended with its process: ${taskList(timers)}.` : ""].filter(Boolean).join(" ");
114933
114949
  return { ok: true, state: "deleted", sessionId: child.id, sessionName: child.name, tool: child.tool, branch: r.branch, setAside: r.setAside, ...r.warning ? { warning: r.warning } : {}, ...note ? { note } : {} };
114934
114950
  }
114935
- case "send": {
114936
- const above = aboveCallerError(child.name, child.permissionPreset, caller.permissionPreset);
114937
- if (above) return { ok: false, error: above };
114938
- const refused2 = this.host.refusesDelegation(callerId, { sessionId: child.id, projectId: child.projectId }, { tool: "agent_session", target: child.name || child.id, text: opts.text ?? "" });
114939
- if (refused2) return { ok: false, error: refused2 };
114940
- const from = { sessionId: callerId, name: labelOf(this.host.store.messages, caller) };
114941
- if (!this.host.takesSendNow(child.id)) {
114942
- if (opts.ifBusy) {
114943
- const f = await this.flow.forkFor(callerId, child, opts.text ?? "", opts.ifBusy === "fork_read", "agent_session", signal);
114944
- if (!f.ok) return f;
114945
- if ("mailed" in f) return { ok: true, tool: child.tool, ...f.mailed };
114946
- const r = await this.flow.awaitAgent(f.key, f.d, signal);
114947
- return r.ok ? { ...r, via: "fork", forkedFrom: child.id } : r;
114948
- }
114949
- const mailed = this.host.mailTask(callerId, child, "agent_session", opts.text ?? "");
114950
- return "error" in mailed ? { ok: false, error: mailed.error } : { ok: true, tool: child.tool, ...mailed };
114951
- }
114952
- if (d2) this.host.children.dropDelegation(key);
114953
- const full = this.flow.starts.agentCeilingError(callerId, child.projectId ?? "");
114954
- if (full) return { ok: false, error: full };
114955
- const project2 = this.host.store.projects.listProjects().find((p) => p.id === child.projectId);
114956
- const cwd = this.host.store.sessions.sessionCwd(child.id) ?? child.worktree?.path ?? project2?.path ?? "";
114957
- const next = this.flow.startDelegation(key, callerId, child.id, { id: child.projectId ?? "", name: project2?.name ?? "", path: cwd }, true);
114958
- const withdraw = this.host.children.delegated(callerId, child.id, "agent_session", opts.text ?? "");
114959
- try {
114960
- await this.host.deliver(child.id, agentFrame(from.name, opts.text ?? "", [], "", canMailParent(child, callerId)), void 0, from, false);
114961
- } catch (e) {
114962
- withdraw();
114963
- next.wait.fail(e);
114964
- this.host.children.dropDelegation(key, next);
114965
- if (this.host.agentRuns.get(child.id) === next.wait) this.host.agentRuns.delete(child.id);
114966
- return { ok: false, error: `Could not send it: ${e.message}` };
114967
- }
114968
- return this.flow.awaitAgent(key, next, signal);
114969
- }
114970
114951
  default:
114971
114952
  return { ok: false, error: "Unknown agent_session action." };
114972
114953
  }
@@ -114974,9 +114955,59 @@ var AgentSessionActions = class {
114974
114955
  releaseObservation?.();
114975
114956
  }
114976
114957
  }
114958
+ /**
114959
+ * `mail` to a session agent_session works on for the caller, its start request or its linked child: new work, answered at once, its end told
114960
+ * (docs/plans/mailbox.md §10.6.6). Null for any other target: the send is plain mail
114961
+ */
114962
+ async sendWork(callerId, target, text3, ifBusy, signal) {
114963
+ const remote = target.includes(".") ? this.flow.remote.of(target) : void 0;
114964
+ if (remote) {
114965
+ if (remote.callerId !== callerId) return null;
114966
+ const machine = this.host.linkedReader?.machineOf(target);
114967
+ const refused3 = this.host.refusesDelegation(callerId, { sessionId: target, linked: true }, { tool: "mail", target: `a session on ${machine ?? "a linked machine"}`, text: text3 });
114968
+ return refused3 ? { ok: false, error: refused3 } : this.flow.remote.send(callerId, remote, text3);
114969
+ }
114970
+ const gone2 = this.flow.handedOverAnswer(callerId, target);
114971
+ if (gone2) return gone2;
114972
+ const request = this.host.children.agentStarts.get(target);
114973
+ if (request?.req.callerId === callerId) {
114974
+ const ended2 = request.ended;
114975
+ if (!ended2) return { ok: false, error: `No session yet: request ${target} is still waiting for ${request.lowMemory ? "memory to start" : "the person's answer"}. Send once it has started.` };
114976
+ if ("error" in ended2) return { ok: false, error: `Request ${target} started no session: ${ended2.error}` };
114977
+ target = ended2.childId;
114978
+ }
114979
+ const caller = this.host.meta.get(callerId);
114980
+ const child = this.host.meta.get(target);
114981
+ if (!caller || !child || !ownChild(caller, child)) return null;
114982
+ const above = aboveCallerError(child.name, child.permissionPreset, caller.permissionPreset);
114983
+ if (above) return { ok: false, error: above };
114984
+ const refused2 = this.host.refusesDelegation(callerId, { sessionId: child.id, projectId: child.projectId }, { tool: "mail", target: child.name || child.id, text: text3 });
114985
+ if (refused2) return { ok: false, error: refused2 };
114986
+ if (!this.host.takesSendNow(child.id)) {
114987
+ if (!ifBusy) {
114988
+ const mailed = this.host.mailTask(callerId, child, "agent_session", text3);
114989
+ return "error" in mailed ? { ok: false, error: mailed.error } : { ok: true, tool: child.tool, ...mailed };
114990
+ }
114991
+ const f = await this.flow.forkFor(callerId, child, text3, ifBusy === "fork_read", "agent_session", signal);
114992
+ if (!f.ok) return f;
114993
+ if ("mailed" in f) return { ok: true, tool: child.tool, ...f.mailed };
114994
+ const working = this.flow.agentWorking(f.d);
114995
+ return working.ok ? { ...working, via: "fork", forkedFrom: child.id } : working;
114996
+ }
114997
+ const key = `${callerId}>${child.id}`;
114998
+ if (this.host.children.delegations.has(key)) this.host.children.dropDelegation(key);
114999
+ const full = this.flow.starts.agentCeilingError(callerId, child.projectId ?? "");
115000
+ if (full) return { ok: false, error: full };
115001
+ const project2 = this.host.store.projects.listProjects().find((p) => p.id === child.projectId);
115002
+ const cwd = this.host.store.sessions.sessionCwd(child.id) ?? child.worktree?.path ?? project2?.path ?? "";
115003
+ const frame = agentFrame(labelOf(this.host.store.messages, caller), text3, [], "", canMailParent(child, callerId));
115004
+ const { d: d2, delivered } = this.flow.delegate({ key, callerId, sessionId: child.id, target: { id: child.projectId ?? "", name: project2?.name ?? "", path: cwd }, agent: true, via: "agent_session", task: text3, frame });
115005
+ const failed4 = await delivered;
115006
+ return failed4 ? { ok: false, error: `Could not send it: ${failed4}` } : this.flow.agentWorking(d2);
115007
+ }
114977
115008
  /**
114978
115009
  * agent_session on a start_agent request's handle (#673). While the card stands: status says so, wait waits for the
114979
- * person's answer up to the bound, stop (or delete) withdraws the card, send is refused. Once the child started, the
115010
+ * person's answer up to the bound, stop (or delete) withdraws the card. Once the child started, the
114980
115011
  * call goes on to that session (a wait that saw it start answers its status, so the call stays inside its bound);
114981
115012
  * once it ended without one, the reason.
114982
115013
  */
@@ -114987,10 +115018,6 @@ var AgentSessionActions = class {
114987
115018
  this.flow.starts.withdrawAgentStart(id3, "The session that asked withdrew the request.", agentStartPersonText(rec.req, "stopped"));
114988
115019
  return { ok: true, state: "stopped", sessionId: id3, sessionName: "", tool: rec.req.detail.tool };
114989
115020
  }
114990
- if (action === "send") {
114991
- const on2 = rec.lowMemory ? "memory to start" : "the person's answer";
114992
- return { ok: false, error: `No session yet: request ${id3} is still waiting for ${on2}. Send once it has started.` };
114993
- }
114994
115021
  if (action === "wait") {
114995
115022
  const owner = rec.req.callerId;
114996
115023
  const leaving = this.flow.untilHandedOver(rec);
@@ -115007,6 +115034,9 @@ var AgentSessionActions = class {
115007
115034
  return { childId: ended2.childId, action };
115008
115035
  }
115009
115036
  };
115037
+ function ownChild(caller, child) {
115038
+ return child.askedBy === caller.id && child.projectId === caller.projectId && (!!caller.projectId || isAssistantKind(caller.kind));
115039
+ }
115010
115040
 
115011
115041
  // packages/agent-host/src/sessions/remote-agents.ts
115012
115042
  import { randomUUID as randomUUID16 } from "node:crypto";
@@ -115375,7 +115405,7 @@ var RemoteAgents = class {
115375
115405
  if (!sent.ok) {
115376
115406
  if (waiting && this.waits.get(rec.sessionId) === waiting) this.dropWait(rec.sessionId);
115377
115407
  if (this.host.children.linkedReports.get(rec.sessionId)?.assistantId === callerId) this.host.children.dropLinkedReport(rec.sessionId);
115378
- return { ok: false, error: `The session "${rec.name}" [${rec.sessionId}] was made on ${machine.name} but did not take the task: ${bare(sent.error)}. Send it again with agent_session, or delete it.` };
115408
+ return { ok: false, error: `The session "${rec.name}" [${rec.sessionId}] was made on ${machine.name} but did not take the task: ${bare(sent.error)}. Send it again by mail, or delete it with agent_session.` };
115379
115409
  }
115380
115410
  const notTaken = this.unclaimed(rec, waiting);
115381
115411
  if (notTaken) return notTaken;
@@ -115404,7 +115434,7 @@ var RemoteAgents = class {
115404
115434
  const now = await raceTimeout(reader.agentInstructions(target).catch(() => null), INSTRUCTIONS_WAIT_MS, null);
115405
115435
  return now?.ok ? now.text : listed2;
115406
115436
  }
115407
- /** agent_session on a child of a linked machine (#1038): status, wait, send, stop, delete, through the link */
115437
+ /** agent_session on a child of a linked machine (#1038): status, wait, stop, delete, through the link */
115408
115438
  async agentSession(callerId, rec, opts, signal) {
115409
115439
  if (opts.action !== "delete") return this.act(callerId, rec, opts, signal);
115410
115440
  this.deleting.add(rec.sessionId);
@@ -115415,6 +115445,10 @@ var RemoteAgents = class {
115415
115445
  if (this.of(rec.sessionId)?.queued?.length) this.scheduleDrain(rec.sessionId);
115416
115446
  }
115417
115447
  }
115448
+ /** New work for a child of a linked machine (`AgentSessionActions.sendWork`, the caller's `mail` to it), through the link */
115449
+ send(callerId, rec, text3) {
115450
+ return this.act(callerId, rec, { sessionId: rec.sessionId, action: "send", text: text3 });
115451
+ }
115418
115452
  async act(callerId, rec, opts, signal) {
115419
115453
  if (rec.callerId !== callerId) return { ok: false, error: `${rec.sessionId} is not a session this session started. agent_session works only on sessions start_agent started from here.` };
115420
115454
  const reader = this.host.linkedReader;
@@ -115452,8 +115486,7 @@ var RemoteAgents = class {
115452
115486
  return now.running ? this.awaitTurn(rec, signal, ASK_WAIT_MS) : this.atRest(rec, now.state, reader);
115453
115487
  }
115454
115488
  case "send": {
115455
- const text3 = opts.text?.trim();
115456
- if (!text3) return { ok: false, error: "Give the text to send." };
115489
+ const { text: text3 } = opts;
115457
115490
  if (this.deleting.has(rec.sessionId)) return this.hold(rec, text3);
115458
115491
  const above = aboveCallerError(rec.name, rec.preset ?? "normal", this.callerPreset(callerId));
115459
115492
  if (above) return { ok: false, error: above };
@@ -116271,7 +116304,31 @@ var DelegationFlow = class {
116271
116304
  return answer;
116272
116305
  };
116273
116306
  }
116274
- /** Registers the wait on the delegated session's turn (the same watcher an app's agent uses, `AgentRunWait`) */
116307
+ /**
116308
+ * Gives a session the caller's work, the one way start_agent, ask_project, a fork and a mail send do: the wait on its turn, the caller's thread
116309
+ * written before the words go in so a card the turn raises at once finds the work open (docs/plans/mailbox.md §10.6.4), and all of it undone
116310
+ * when they do not go in, the wait failed too (#839: a wait of the caller's may have joined it while the session woke). `delivered` is the
116311
+ * error text when they did not go in
116312
+ */
116313
+ delegate(w) {
116314
+ const d2 = this.startDelegation(w.key, w.callerId, w.sessionId, w.target, w.agent);
116315
+ const withdraw = this.host.children.delegated(w.callerId, w.sessionId, w.via, w.task);
116316
+ const caller = this.host.meta.get(w.callerId);
116317
+ const delivered = (async () => {
116318
+ try {
116319
+ await this.host.deliver(w.sessionId, w.frame, void 0, { sessionId: w.callerId, name: caller ? labelOf(this.host.store.messages, caller) : w.callerId }, false, void 0, "inline", void 0, w.stillAllowed);
116320
+ return null;
116321
+ } catch (e) {
116322
+ withdraw();
116323
+ d2.wait.fail(e instanceof Error ? e : new Error(errorMessage(e)));
116324
+ this.host.children.dropDelegation(w.key, d2);
116325
+ if (this.host.agentRuns.get(w.sessionId) === d2.wait) this.host.agentRuns.delete(w.sessionId);
116326
+ return errorMessage(e);
116327
+ }
116328
+ })();
116329
+ return { d: d2, delivered };
116330
+ }
116331
+ /** Registers the wait on the delegated session's turn (the same watcher an app's agent uses, `AgentRunWait`); only `delegate` calls it, tests aside */
116275
116332
  startDelegation(key, callerId, sessionId, target, agent = false) {
116276
116333
  let notice;
116277
116334
  const wait = new AgentRunWait((message) => notice = message, () => this.host.meta.get(sessionId)?.name ?? "the session", void 0, this.answerReader(sessionId));
@@ -120615,7 +120672,7 @@ var SessionTools = class {
120615
120672
  findApps: async (query) => this.host.apps.requireAppAccess().find(sessionId, query),
120616
120673
  attachApp: async (app2) => this.host.apps.requireAppAccess().attach(sessionId, app2),
120617
120674
  detachApp: async (app2) => this.host.apps.requireAppAccess().detach(sessionId, app2),
120618
- mail: (args) => this.host.mailTool(sessionId, args),
120675
+ mail: (args, signal) => this.host.mailTool(sessionId, args, signal),
120619
120676
  compactSelf: (focus, then2) => this.host.selfCompaction.request(sessionId, focus, then2)
120620
120677
  };
120621
120678
  }
@@ -121314,8 +121371,8 @@ var MailboxRecords = class {
121314
121371
  rootId = target.root_id;
121315
121372
  }
121316
121373
  this.db.prepare(
121317
- `INSERT INTO mail (id, sender, sender_project, kind, needs_reply, reply_to, root_id, cause_id, depth, urgent, body, facts, choices, dedupe_key, origin, legacy_thread, created_at)
121318
- VALUES (@id, @sender, @senderProject, @kind, @needsReply, @replyTo, @rootId, @causeId, @depth, @urgent, @body, @facts, @choices, @dedupeKey, @origin, @legacyThread, @createdAt)`
121374
+ `INSERT INTO mail (id, sender, sender_project, kind, needs_reply, reply_to, root_id, cause_id, depth, urgent, body, facts, choices, subject, dedupe_key, origin, legacy_thread, created_at)
121375
+ VALUES (@id, @sender, @senderProject, @kind, @needsReply, @replyTo, @rootId, @causeId, @depth, @urgent, @body, @facts, @choices, @subject, @dedupeKey, @origin, @legacyThread, @createdAt)`
121319
121376
  ).run({
121320
121377
  id: mail.id,
121321
121378
  sender: mail.sender,
@@ -121330,6 +121387,7 @@ var MailboxRecords = class {
121330
121387
  body: mail.body,
121331
121388
  facts: JSON.stringify(mail.facts),
121332
121389
  choices: mail.choices ? JSON.stringify(mail.choices) : null,
121390
+ subject: mail.subject,
121333
121391
  dedupeKey: mail.dedupeKey,
121334
121392
  origin: mail.origin,
121335
121393
  legacyThread: mail.legacyThread,
@@ -122007,6 +122065,7 @@ var MailboxRecords = class {
122007
122065
  body: r.body,
122008
122066
  facts: this.readFacts(r.id, r.facts),
122009
122067
  choices: choicesFrom(r.choices),
122068
+ subject: r.subject,
122010
122069
  dedupeKey: r.dedupe_key,
122011
122070
  origin: r.origin,
122012
122071
  legacyThread: r.legacy_thread,
@@ -123819,6 +123878,11 @@ var MailSessionsView = class {
123819
123878
  const run2 = this.host.agentRuns.get(id3);
123820
123879
  return this.takesTurn(id3) && !(run2 && !run2.finished) && this.hooks?.waiting?.(id3) !== true;
123821
123880
  }
123881
+ /** `MailToolHost.work` (#1948): the answer worded as agent_session's are for the caller's seat, or null for plain mail */
123882
+ async work(callerId, target, text3, ifBusy, signal) {
123883
+ const r = await this.host.delegationFlow.actions.sendWork(callerId, target, text3, ifBusy, signal);
123884
+ return r && agentCallsFor(this.host.tools.toolProfileOf(callerId) ?? "human", agentRunText(r));
123885
+ }
123822
123886
  /** A send to a session that cannot take it now: a task from the caller, which the delivery gives it as a turn of its own once it is free (§10.6.2) */
123823
123887
  mailTask(callerId, target, origin, text3) {
123824
123888
  const hooks = this.hooks;
@@ -126804,6 +126868,7 @@ function stepLine(s) {
126804
126868
  }
126805
126869
  var AGENT_ACTIONS = {
126806
126870
  status: "Checked on an agent",
126871
+ // A recorded call from before #1948 moved more work to mail still reads as it did
126807
126872
  send: "Sent more to an agent",
126808
126873
  wait: "Waited for an agent",
126809
126874
  stop: "Stopped an agent",
@@ -126811,6 +126876,8 @@ var AGENT_ACTIONS = {
126811
126876
  answer: "Answered an agent's card",
126812
126877
  list: "Listed its agents"
126813
126878
  };
126879
+ var MAIL_ACTIONS = { send: "Sent mail", reply: "Replied" };
126880
+ var sessionAddressed = (to) => to && isUuid(to.slice(to.lastIndexOf(".") + 1)) ? to : void 0;
126814
126881
  var CENTRALU_LABELS = {
126815
126882
  start_agent: "Started an agent",
126816
126883
  ask_project: "Asked a project",
@@ -126872,15 +126939,15 @@ var CENTRALU_LABELS = {
126872
126939
  function centraluMark(server2, tool, args) {
126873
126940
  const origin = centraluServer(server2);
126874
126941
  if (!origin) return null;
126875
- const sessionId = trimmed(args.sessionId);
126942
+ const action = trimmed(args.action);
126943
+ const sessionId = tool === "mail" ? action === "send" ? sessionAddressed(trimmed(args.to)) : void 0 : trimmed(args.sessionId);
126876
126944
  const base2 = { tool, ...origin, ...sessionId ? { sessionId } : {} };
126877
126945
  if (origin.app) return { centralu: base2 };
126878
126946
  const text3 = (v) => {
126879
126947
  const t = trimmed(v);
126880
126948
  return t ? firstLine2(t, 160) : void 0;
126881
126949
  };
126882
- const action = trimmed(args.action);
126883
- let label = tool === "agent_session" ? action && AGENT_ACTIONS[action] : CENTRALU_LABELS[tool];
126950
+ let label = tool === "agent_session" ? action && AGENT_ACTIONS[action] : tool === "mail" ? action && MAIL_ACTIONS[action] : CENTRALU_LABELS[tool];
126884
126951
  let title;
126885
126952
  switch (tool) {
126886
126953
  case "start_agent": {
@@ -126894,6 +126961,9 @@ function centraluMark(server2, tool, args) {
126894
126961
  case "answer_question":
126895
126962
  title = text3(args.text);
126896
126963
  break;
126964
+ case "mail":
126965
+ if (label) title = text3(args.subject) ?? text3(args.text);
126966
+ break;
126897
126967
  case "read_session":
126898
126968
  if (!sessionId) label = "Listed sessions";
126899
126969
  break;
@@ -130537,13 +130607,33 @@ function endedSummary(text3) {
130537
130607
  const summary = (text3 ?? "").slice(0, BACKGROUND_SUMMARY_CHARS);
130538
130608
  return summary ? { summary } : {};
130539
130609
  }
130610
+ var NONE = /* @__PURE__ */ new Set();
130611
+ var KIND_WORDS = { agent: "agent", shell: "shell", mcp: "MCP task", other: "task" };
130612
+ function endedNotice(sessionId, t) {
130613
+ if (t.status !== "failed" && t.status !== "stopped") return [];
130614
+ const why2 = t.summary ? `: ${oneLineText(t.summary, BACKGROUND_SUMMARY_CHARS)}` : "";
130615
+ return [
130616
+ {
130617
+ type: "notice",
130618
+ sessionId,
130619
+ level: t.status === "failed" ? "warning" : "info",
130620
+ text: `Background ${KIND_WORDS[t.kind]} "${oneLineText(t.description, 80)}" ${t.status}${why2}`,
130621
+ from: "Centralu",
130622
+ label: "background task"
130623
+ }
130624
+ ];
130625
+ }
130540
130626
  var BackgroundEvents = class {
130541
130627
  constructor(sessionId) {
130542
130628
  this.sessionId = sessionId;
130543
130629
  }
130544
130630
  sessionId;
130545
130631
  last = "[]";
130546
- event(live2, ended2 = [], snapshot2 = false) {
130632
+ /**
130633
+ * `carded`: the launch cards that carry the ending of their own task as they close with it (a background agent's card marked failed with the reason when the process
130634
+ * goes away). A task whose card is one of them leaves no line of its own: its ending is said once
130635
+ */
130636
+ event(live2, ended2 = [], snapshot2 = false, carded = NONE) {
130547
130637
  const key = JSON.stringify(live2);
130548
130638
  if (key === this.last && ended2.length === 0 && !snapshot2) return [];
130549
130639
  this.last = key;
@@ -130554,7 +130644,8 @@ var BackgroundEvents = class {
130554
130644
  sessionId: this.sessionId,
130555
130645
  live: live2,
130556
130646
  ...ended2.length ? { ended: ended2 } : {}
130557
- }
130647
+ },
130648
+ ...ended2.flatMap((t) => t.parentCallId !== void 0 && carded.has(t.parentCallId) ? [] : endedNotice(this.sessionId, t))
130558
130649
  ];
130559
130650
  }
130560
130651
  };
@@ -130617,7 +130708,8 @@ var ClaudeBackgroundTracker = class {
130617
130708
  tick() {
130618
130709
  return this.schedules.prune() ? this.event() : [];
130619
130710
  }
130620
- push(m) {
130711
+ /** `cards`: the launch cards still open, which an ending closes with it (`BackgroundEvents.event`) */
130712
+ push(m, cards) {
130621
130713
  if (str(m.type) === "assistant" || str(m.type) === "user") {
130622
130714
  const changed = this.schedules.push(m);
130623
130715
  return changed ? this.event() : [];
@@ -130673,7 +130765,7 @@ var ClaudeBackgroundTracker = class {
130673
130765
  this.live = this.live.filter((x) => x !== id3);
130674
130766
  const raw = str(m.status);
130675
130767
  const status = raw === "failed" || raw === "stopped" ? raw : "completed";
130676
- return this.event([{ ...this.entry(id3, known), status, ...endedSummary(str(m.summary)) }]);
130768
+ return this.event([{ ...this.entry(id3, known), status, ...endedSummary(str(m.summary)) }], void 0, cards);
130677
130769
  }
130678
130770
  return [];
130679
130771
  }
@@ -130681,8 +130773,8 @@ var ClaudeBackgroundTracker = class {
130681
130773
  get running() {
130682
130774
  return this.live.length > 0;
130683
130775
  }
130684
- /** The process went away and took its tasks with it — each live one ends as stopped, with the reason. */
130685
- release(why2) {
130776
+ /** The process went away and took its tasks with it — each live one ends as stopped, with the reason. `cards`: the launch cards that close with it */
130777
+ release(why2, cards) {
130686
130778
  const timers = this.schedules.release().map((t) => ({ ...t, status: "stopped", summary: why2 }));
130687
130779
  if (this.live.length === 0 && timers.length === 0) {
130688
130780
  this.info.clear();
@@ -130693,7 +130785,7 @@ var ClaudeBackgroundTracker = class {
130693
130785
  this.live = [];
130694
130786
  this.info.clear();
130695
130787
  this.seen.clear();
130696
- return this.event(ended2);
130788
+ return this.event(ended2, void 0, cards);
130697
130789
  }
130698
130790
  entry(id3, i) {
130699
130791
  const kind = i?.kind ?? "other";
@@ -130709,8 +130801,8 @@ var ClaudeBackgroundTracker = class {
130709
130801
  status: "running"
130710
130802
  };
130711
130803
  }
130712
- event(ended2, snapshot2) {
130713
- return this.events.event([...this.live.map((id3) => this.entry(id3, this.info.get(id3))), ...this.schedules.live()], ended2, snapshot2);
130804
+ event(ended2, snapshot2, cards) {
130805
+ return this.events.event([...this.live.map((id3) => this.entry(id3, this.info.get(id3))), ...this.schedules.live()], ended2, snapshot2, cards);
130714
130806
  }
130715
130807
  };
130716
130808
 
@@ -131300,7 +131392,7 @@ var ClaudeStreamNormalizer = class {
131300
131392
  const type = msg.type;
131301
131393
  const subagent = "parent_tool_use_id" in msg && str(msg.parent_tool_use_id) !== "";
131302
131394
  this.unmapped.note(msg.type === "system" ? `system/${str(msg.subtype)}` : type);
131303
- const tasks = this.tasks.push(msg);
131395
+ const tasks = this.tasks.push(msg, this.background);
131304
131396
  if (msg.type === "system" && msg.subtype === "task_notification") {
131305
131397
  const callId = str(msg.tool_use_id);
131306
131398
  if (!this.background.delete(callId)) return tasks;
@@ -131399,8 +131491,8 @@ var ClaudeStreamNormalizer = class {
131399
131491
  const out = [...this.releaseRequest(), ...this.deferred.splice(0)];
131400
131492
  this.held = null;
131401
131493
  for (const callId of this.background) out.push({ type: "tool_result", sessionId: this.sessionId, callId, ok: false, summary: why2 });
131494
+ out.push(...this.tasks.release("Ended with the session process", this.background));
131402
131495
  this.background.clear();
131403
- out.push(...this.tasks.release("Ended with the session process"));
131404
131496
  return out;
131405
131497
  }
131406
131498
  };
@@ -135093,9 +135185,10 @@ var CodexChildTracker = class {
135093
135185
  t.turnId = null;
135094
135186
  }
135095
135187
  const held3 = [...this.held.keys()].map((callId) => ({ type: "tool_result", sessionId: this.sessionId, callId, ok: false, summary: why2 }));
135188
+ const carded = new Set(this.held.keys());
135096
135189
  this.held.clear();
135097
135190
  if (live2.length === 0) return held3;
135098
- return [...this.changed(live2.map((task) => ({ ...task, status: "stopped", summary: why2 }))), ...held3];
135191
+ return [...this.changed(live2.map((task) => ({ ...task, status: "stopped", summary: why2 })), carded), ...held3];
135099
135192
  }
135100
135193
  ended(thread, status, summary) {
135101
135194
  const task = this.task(thread);
@@ -135124,10 +135217,12 @@ var CodexChildTracker = class {
135124
135217
  return out;
135125
135218
  }
135126
135219
  /** The event when the live set or an ending moved; nothing when neither did. */
135127
- changed(ended2 = []) {
135220
+ changed(ended2 = [], carded) {
135128
135221
  return this.events.event(
135129
135222
  this.live(),
135130
- ended2.filter((t) => t !== null)
135223
+ ended2.filter((t) => t !== null),
135224
+ false,
135225
+ carded
135131
135226
  );
135132
135227
  }
135133
135228
  };
@@ -143241,6 +143336,21 @@ var StepsV65 = class extends MigrationRange {
143241
143336
  run: () => {
143242
143337
  this.addColumn("mail", "choices", "TEXT");
143243
143338
  }
143339
+ },
143340
+ {
143341
+ to: 71,
143342
+ breaksOlderReaders: false,
143343
+ /**
143344
+ * The subject a session's `mail` send gives the chain it starts (#2229): `mail.subject`, one line of at most 80 characters, NULL on
143345
+ * every other message. The sender's words, so a column of its own as v70's choices: `facts` is Centralu's record. The person's Inbox
143346
+ * names the chain by it instead of its first message's words.
143347
+ *
143348
+ * **Expand only (#292's rule).** One nullable column. An older build names its columns in every read and insert of `mail`, so it
143349
+ * never sees it: it opens the store and names the chain by its words, as before. Nothing is backfilled: no build kept a subject.
143350
+ */
143351
+ run: () => {
143352
+ this.addColumn("mail", "subject", "TEXT");
143353
+ }
143244
143354
  }
143245
143355
  ];
143246
143356
  }
@@ -144879,23 +144989,13 @@ var AskProjectFlow = class {
144879
144989
  return "error" in mailed ? { ok: false, error: mailed.error } : { ok: true, project: target.name, ...mailed };
144880
144990
  }
144881
144991
  if (pending) this.host.children.dropDelegation(key);
144882
- const delegatedId = chosen.id;
144883
- const d2 = this.host.delegationFlow.startDelegation(key, callerId, delegatedId, target, false);
144884
144992
  const callerProject = projects.find((p) => p.id === caller.projectId)?.name ?? "another project";
144885
- const withdraw = this.host.children.delegated(callerId, delegatedId, "ask_project", opts.task);
144886
- try {
144887
- const from = { sessionId: callerId, name: labelOf(this.host.store.messages, caller) };
144888
- const logged = !this.host.projectTrusted(callerProjectId);
144889
- const stillAllowed = () => this.askGateError(callerId, logged) ?? this.projectGoneError(target);
144890
- await this.host.deliver(delegatedId, askFrame(callerProject, opts.task, { name: from.name, sessionId: callerId }), void 0, from, false, void 0, "inline", void 0, stillAllowed);
144891
- } catch (e) {
144892
- withdraw();
144893
- d2.wait.fail(e);
144894
- this.host.children.dropDelegation(key, d2);
144895
- if (this.host.agentRuns.get(delegatedId) === d2.wait) this.host.agentRuns.delete(delegatedId);
144896
- return { ok: false, error: `Could not hand the task to ${target.name}: ${e.message}` };
144897
- }
144898
- return this.awaitDelegation(key, d2, signal);
144993
+ const logged = !this.host.projectTrusted(callerProjectId);
144994
+ const stillAllowed = () => this.askGateError(callerId, logged) ?? this.projectGoneError(target);
144995
+ const frame = askFrame(callerProject, opts.task, { name: labelOf(this.host.store.messages, caller), sessionId: callerId });
144996
+ const { d: d2, delivered } = this.host.delegationFlow.delegate({ key, callerId, sessionId: chosen.id, target, agent: false, via: "ask_project", task: opts.task, frame, stillAllowed });
144997
+ const failed4 = await delivered;
144998
+ return failed4 ? { ok: false, error: `Could not hand the task to ${target.name}: ${failed4}` } : this.awaitDelegation(key, d2, signal);
144899
144999
  }
144900
145000
  /**
144901
145001
  * ask_project to a project on a linked machine (#700, docs/plans/remote-hub.md §12.2 step 3). The same call as for a
@@ -148009,7 +148109,7 @@ var SessionManager = class {
148009
148109
  return self2.adapters;
148010
148110
  },
148011
148111
  agentSession: (...a) => self2.agentSession(...a),
148012
- mailTool: async (id3, args) => await self2.mail.hooks?.tool?.(id3, args) ?? { text: "The mailbox is not available.", isError: true },
148112
+ mailTool: async (id3, args, signal) => await self2.mail.hooks?.tool?.(id3, args, signal) ?? { text: "The mailbox is not available.", isError: true },
148013
148113
  refusesDelegation: (callerId, target, call2) => self2.mail.hooks?.refusesDelegation?.(callerId, target, call2) ?? null,
148014
148114
  roleMoved: (toId) => self2.mail.hooks?.roleMoved?.(toId),
148015
148115
  whenAsked: (id3, call2, signal, run2, refused2) => self2.askedGate.when(id3, call2, signal, run2, refused2),
@@ -148517,794 +148617,282 @@ var SessionManager = class {
148517
148617
  }
148518
148618
  };
148519
148619
 
148520
- // packages/agent-host/src/mail/person.ts
148521
- var THREAD_PAGE = 100;
148522
- var LIST_CHAINS = 100;
148523
- var LIST_SCAN = 1e3;
148524
- var CHAIN_CAP = 1e3;
148525
- var PREVIEW_CHARS2 = 140;
148526
- var SUBJECT_CHARS = 80;
148527
- var PERSON_HOLDS = ["uncertain", "failed", "loop", "budget", "policy"];
148528
- function subjectLine(m) {
148529
- const script = m.facts.fromScript?.credential;
148530
- return oneLineText(script === void 0 ? m.body : `The script "${script}": ${m.body}`, SUBJECT_CHARS);
148620
+ // packages/agent-host/src/mail/last-response.ts
148621
+ function tasksAtRest(records, recipient, last) {
148622
+ return records.watchedTo(recipient).flatMap((row) => {
148623
+ if (row.deliveredAt === null || row.held !== null && row.held !== "released" || !last.released && row.releasedAt !== null || last.queued?.has(row.messageId)) return [];
148624
+ const task = records.message(row.messageId);
148625
+ if (task?.kind !== "task" || task.sender === recipient || !last.answers(task.sender)) return [];
148626
+ return records.handedOn(task.id).length > 0 ? [] : [{ row, sender: task.sender }];
148627
+ });
148531
148628
  }
148532
- var MailPerson = class {
148533
- constructor(service, records, delivery, host) {
148534
- this.service = service;
148535
- this.records = records;
148536
- this.delivery = delivery;
148537
- this.host = host;
148538
- }
148539
- service;
148540
- records;
148541
- delivery;
148542
- host;
148543
- list() {
148544
- const heldRows = this.records.heldRows();
148545
- const heldBy = /* @__PURE__ */ new Map();
148546
- const held3 = [];
148547
- for (const r of heldRows) {
148548
- const m = this.records.message(r.messageId);
148549
- if (!m || r.held === null) continue;
148550
- heldBy.set(m.rootId, (heldBy.get(m.rootId) ?? 0) + 1);
148551
- held3.push({
148552
- messageId: m.id,
148553
- threadId: m.rootId,
148554
- subject: this.subjectOf(m.rootId),
148555
- sender: this.party(m.sender),
148556
- recipient: this.party(r.recipient),
148557
- kind: windowKind(m),
148558
- reason: r.held,
148559
- preview: oneLineText(m.body, PREVIEW_CHARS2),
148560
- since: m.createdAt
148561
- });
148629
+ function answerAtRest(records, recipient, last, report, personAt) {
148630
+ return tasksAtRest(records, recipient, last).map(({ row, sender }) => {
148631
+ const given = row.deliveredAt ?? 0;
148632
+ const personSince = parseAddress(sender)?.kind === "session" && personAt !== void 0 && personAt > given;
148633
+ const after = last.writtenAt !== void 0 && last.writtenAt < given;
148634
+ const lines = [last.body(sender), ...personSince ? [PERSON_SINCE] : [], ...after ? [AFTER2] : []];
148635
+ report(row.messageId, {
148636
+ outcome: "finished",
148637
+ body: lines.join("\n"),
148638
+ ...last.answer ? { answer: last.answer } : {},
148639
+ ...personSince ? { personSince: true } : {},
148640
+ ...after ? { after: true } : {}
148641
+ });
148642
+ return row.messageId;
148643
+ });
148644
+ }
148645
+ var PERSON_SINCE = "The person also wrote in this session after your task was given, so this last response may be an answer to them.";
148646
+ var AFTER2 = "Your task arrived after this response was written.";
148647
+
148648
+ // packages/agent-host/src/mail/reach.ts
148649
+ function mailReach(host) {
148650
+ const sessionOf = (address) => {
148651
+ const party = parseAddress(address);
148652
+ if (party?.kind !== "session") return void 0;
148653
+ if (party.host === host.hostId) return { id: party.sessionId, info: host.session(party.sessionId) };
148654
+ const far = host.foreign?.(address);
148655
+ return far ? { id: party.sessionId, info: { projectId: null, askedBy: null, here: true, canReadMail: false, host: "elsewhere", name: far.name } } : void 0;
148656
+ };
148657
+ const untrusted = (projectId) => projectId === null ? false : !(host.project(projectId)?.trusted ?? false);
148658
+ const leaves = (senderProject, recipientProject) => HOLD_UNTRUSTED_OUT && untrusted(senderProject) && recipientProject !== senderProject;
148659
+ return {
148660
+ untrusted,
148661
+ isAssistant: (address) => {
148662
+ const s = sessionOf(address);
148663
+ return s !== void 0 && host.assistantId() === s.id;
148664
+ },
148665
+ askGroupMembers: (address) => host.askGroupMembers(address),
148666
+ projectOf: (address) => sessionOf(address)?.info?.projectId ?? null,
148667
+ parentOf: (address) => {
148668
+ const parent = sessionOf(address)?.info?.askedBy;
148669
+ const party = parseAddress(address);
148670
+ return parent && party?.kind === "session" ? sessionAddress(party.host, parent) : null;
148671
+ },
148672
+ labelOf: (address) => sessionOf(address)?.info?.name ?? address,
148673
+ elsewhere: (address) => sessionOf(address)?.info?.host === "elsewhere",
148674
+ projectLabel: (projectId) => host.project(projectId)?.name ?? projectId,
148675
+ mayWrite(from, to, asRequest = true) {
148676
+ const f = parseAddress(from);
148677
+ const t = parseAddress(to);
148678
+ if (!f || !t) return "bad_address";
148679
+ if (t.kind === "centralu" || t.kind === "app") return "not_allowed";
148680
+ if (t.kind === "session" && t.host !== host.hostId) return "elsewhere";
148681
+ const receiver = sessionOf(to);
148682
+ if (receiver) {
148683
+ if (!receiver.info?.here) return "gone";
148684
+ if (receiver.info.host === "elsewhere") return "elsewhere";
148685
+ if (!receiver.info.canReadMail) return "no_mailbox";
148686
+ }
148687
+ if (f.kind === "centralu" || f.kind === "person") return null;
148688
+ if (f.kind === "app") return receiver && host.appCalledBy(from, receiver.id) ? null : "not_allowed";
148689
+ if (!sessionOf(from)?.info?.here) return "gone";
148690
+ if (!receiver) return null;
148691
+ const assistant = host.assistantId();
148692
+ return asRequest && receiver.id === assistant && f.sessionId !== assistant && !host.assistantAsks() ? "assistant_asks" : null;
148693
+ },
148694
+ holdFor(m, recipient) {
148695
+ if (m.kind !== "message") return null;
148696
+ const receiver = sessionOf(recipient);
148697
+ return receiver?.info && leaves(m.senderProject, receiver.info.projectId) ? "policy" : null;
148698
+ },
148699
+ refusesDelegation(callerId, target) {
148700
+ const project2 = host.session(callerId)?.projectId ?? null;
148701
+ if (project2 === null) return null;
148702
+ const targetProject = target.linked || target.assistant ? null : target.sessionId !== void 0 ? host.session(target.sessionId)?.projectId ?? null : target.projectId ?? null;
148703
+ return leaves(project2, targetProject) ? project2 : null;
148562
148704
  }
148563
- const roots = [];
148564
- for (const m of this.records.feedOf(PERSON, { limit: LIST_SCAN })) {
148565
- if (!roots.includes(m.rootId)) roots.push(m.rootId);
148566
- if (roots.length >= LIST_CHAINS) break;
148705
+ };
148706
+ }
148707
+ function droppedText(ids, project2) {
148708
+ const shown3 = ids.slice(0, 10).join(", ") + (ids.length > 10 ? `, and ${ids.length - 10} more` : "");
148709
+ return `The person dismissed ${ids.length} of your messages that were waiting for project ${project2} to be trusted (${shown3}). They were not delivered and will not be.`;
148710
+ }
148711
+ function trustedText(project2, calls) {
148712
+ return `${project2} is trusted now. The calls refused for it can be given again: ${calls.slice(0, 10).join(", ")}${calls.length > 10 ? `, and ${calls.length - 10} more` : ""}`;
148713
+ }
148714
+
148715
+ // packages/agent-host/src/mail/send-guards.ts
148716
+ function sendGuards(d2, { sender, cls, to, text: text3, requests: requests2 }, now) {
148717
+ const label = (a) => d2.reach.labelOf(a);
148718
+ for (const r of to) {
148719
+ if ((cls === "session" || cls === "app") && d2.records.sameBody(sender, r, text3, now - REPEAT_WINDOW_MS)) {
148720
+ throw guardRefused(d2, sender, "repeat", WARNING_TEXT.repeat(label(sender), r === PERSON ? "you" : label(r)), REFUSAL_TEXT.repeat(label(r)), now);
148567
148721
  }
148568
- const threads = roots.map((root3) => this.row(root3, heldBy.get(root3) ?? 0)).flatMap((r) => r ?? []).sort((a, b2) => Number(b2.unread > 0) - Number(a.unread > 0) || b2.updatedAt - a.updatedAt);
148569
- return { threads, held: held3, waiting: this.delivery.crowdWaiting() };
148570
148722
  }
148571
- /** A chain with its messages, which the person reads: what is returned is read for them. An old thread's id names the chain moved from it */
148572
- thread(threadId, opts = {}) {
148573
- const root3 = this.rootsOf(threadId)[0];
148574
- if (root3 === void 0) throw refuse4("unknown_message", `There is no mail ${threadId} kept.`);
148575
- const all = this.shown(root3);
148576
- let page;
148577
- if (opts.after !== void 0) page = all.filter((s) => s.seq > (opts.after ?? 0)).slice(0, opts.all ? void 0 : THREAD_PAGE);
148578
- else if (opts.tail !== void 0 || !opts.all) {
148579
- const upTo = opts.before === void 0 ? all : all.filter((s) => s.seq < (opts.before ?? 0));
148580
- page = upTo.slice(-Math.min(opts.tail ?? THREAD_PAGE, THREAD_PAGE));
148581
- } else page = all;
148582
- if (this.records.markRead(PERSON, page.flatMap((s) => this.records.recipient(s.m.id, PERSON)?.readAt === null ? [s.m.id] : []), Date.now()) > 0) this.service.announce();
148583
- const first = page[0]?.seq;
148584
- const last = page.at(-1)?.seq;
148585
- const legacy = this.legacyOf(all[0]?.m);
148586
- const fromStart = first === void 0 || first === all[0]?.seq;
148587
- const messages2 = [...(fromStart ? legacy : []).map((m, i) => legacyMessage(m, i - legacy.length + 1, (a) => this.party(a))), ...page.map((s) => this.message(s))];
148588
- return {
148589
- thread: this.row(root3, this.heldIn(root3)) ?? this.emptyRow(root3),
148590
- parties: this.partiesOf(all.map((s) => s.m)),
148591
- blockers: [],
148592
- messages: messages2,
148593
- more: last !== void 0 && all.some((s) => s.seq > last),
148594
- older: first !== void 0 && all.some((s) => s.seq < first),
148595
- follows: [],
148596
- canReply: this.replyTarget([root3]) !== void 0
148597
- };
148723
+ const limit = postsPerMinute(cls);
148724
+ if (limit !== Infinity && d2.records.postsSince(sender, now - MINUTE_MS) >= limit) {
148725
+ throw guardRefused(d2, sender, "rate_limited", WARNING_TEXT.rate_limited(label(sender), limit), `at most ${limit} posts a minute from ${cls === "app" ? "an app" : "a session"}: wait a minute`, now);
148726
+ }
148727
+ for (const [i, r] of to.entries()) {
148728
+ if (requests2[i] && d2.records.requestsSince(d2.reach.askGroupMembers(sender), r, now - HOUR_MS) >= ASKS_PER_HOUR) {
148729
+ throw guardRefused(d2, sender, "ask_rate", WARNING_TEXT.ask_rate(label(sender)), REFUSAL_TEXT.ask_rate(), now);
148730
+ }
148731
+ }
148732
+ }
148733
+ function guardRefused(d2, sender, reason, toPerson, toSender, now) {
148734
+ d2.notice(PERSON, { body: toPerson, facts: { guardRefused: { sender, reason } }, dedupeKey: hourlyKey(`guard:${reason}:${sender}`, now) });
148735
+ return refuse4(reason, toSender);
148736
+ }
148737
+
148738
+ // packages/agent-host/src/mail/stop-notices.ts
148739
+ var StopNotices = class {
148740
+ constructor(d2) {
148741
+ this.d = d2;
148598
148742
  }
148743
+ d;
148599
148744
  /**
148600
- * The person writes in a chain (every chain an old thread's id names): an answer to the newest question to them that waits for their answer, else to
148601
- * the newest message sent to them, to its sender; else a word more to the ones the person's own newest message went to. A sender that is gone, and a
148602
- * message hidden from the person, are passed over. A question waits for an answer (D3); an answer or a note does not
148745
+ * A session went to the trash or was deleted: it can answer nothing any more. What it owes (`owedBy`: its questions, whichever turn, and every task a
148746
+ * session gave it) is released `gone` and each sender told once, as for a stop (mailbox.md §10.6.1); then its watched rows are settled `gone` and its
148747
+ * own watched messages `withdrawn`. Mail sent to the Assistant's role follows the role, not the session that held it (D15): `roleMoved` gives it on
148603
148748
  */
148604
- reply(threadId, text3, kind = "note", answers2) {
148605
- const roots = this.rootsOf(threadId);
148606
- const found = answers2 === void 0 ? this.replyTarget(roots) : this.pickTarget(roots, answers2, text3);
148607
- if (!found) throw refuse4("unknown_message", `There is no message in ${threadId} to answer.`);
148608
- const { target, to } = found;
148609
- const sent = this.service.send(PERSON, { to, text: text3, replyTo: target.id, needsReply: kind === "question", ...answers2 === void 0 ? {} : { picked: true } });
148610
- const at2 = this.shown(target.rootId).find((s) => s.m.id === sent.message.id)?.seq ?? 1;
148611
- return this.thread(target.rootId, { after: at2 - 1 });
148749
+ partyGone(address) {
148750
+ this.releaseAndTell((now, senders) => {
148751
+ for (const { row, message } of this.owedBy(address, "gone", null)) if (this.d.records.markReleased(row.messageId, address, now, "gone")) senders.add(message.sender);
148752
+ for (const row of this.d.records.watchedTo(address)) if (!isRoleVia(row.via)) this.d.records.settle(row.messageId, address, "gone", now);
148753
+ for (const row of this.d.records.watchedFrom(address)) this.d.records.settle(row.messageId, row.recipient, "withdrawn", now);
148754
+ });
148612
148755
  }
148613
148756
  /**
148614
- * The message the person's word in these chains answers, and whom it goes to: the one `reply` writes to, and so what the window's reply box (`canReply`) is
148615
- * offered for. Undefined when the chains hold nothing of the person's to answer: only mail between sessions held for them, or to sessions that are gone
148757
+ * A session stopped without answering (mailbox.md "The stop notice"): an error, a usage limit, the network, its tool's interrupt, a Stop, a quit
148758
+ * or shutdown of Centralu, or a cut turn Centralu could not continue. What it owes an answer is released with the cause: each question delivered
148759
+ * into the cut turn `turnSeq` and not answered (a `needsReply` message, the person's too; none without a turn), and every open task a session or the
148760
+ * person gave it. Each sender is told once, in one notice, and woken: it is owed a reply (`standing`: in a turn it reads it when that turn ends; one a quit
148761
+ * cut reads it at its next turn). `starter`, the session that started the stopped one, is told too when it is owed nothing and the turn was not
148762
+ * the person's, woken only from a turn. The rows stay open, so a reply or a last response after the person continues the session still answers
148763
+ * them. A question delivered in an earlier turn is not this stop's: it was read, and the session may have answered it in conversation.
148764
+ *
148765
+ * The person's notice goes to the Inbox and wakes nothing. `told`: the senders a call still waiting on the session already told (it read the stop
148766
+ * itself), whose rows are released and marked told. Returns how many rows were released
148616
148767
  */
148617
- replyTarget(roots) {
148618
- const chain = roots.flatMap((root3) => this.shown(root3).map((s) => s.m)).sort((a, b2) => a.createdAt - b2.createdAt || (a.id < b2.id ? -1 : a.id > b2.id ? 1 : 0));
148619
- const toPerson = chain.filter((m) => {
148620
- const row = this.records.recipient(m.id, PERSON);
148621
- return m.sender !== PERSON && parseAddress(m.sender)?.kind !== "centralu" && row !== void 0 && !hiddenFromPerson(row) && this.here(m.sender);
148622
- });
148623
- const open6 = toPerson.findLast((m) => {
148624
- const row = this.records.recipient(m.id, PERSON);
148625
- return m.needsReply && row !== void 0 && row.answerId === null && (row.settled === null || row.settled === "legacy");
148768
+ sessionStopped(address, why2, opts = {}) {
148769
+ return this.sessionsStopped([{ ...opts, address, why: why2, turnSeq: opts.turnSeq ?? null }]);
148770
+ }
148771
+ /** Several sessions stopped at once (a quit found at the start): in one write, so a sender of questions to many of them is told once, in one notice */
148772
+ sessionsStopped(stops) {
148773
+ return this.d.run(() => {
148774
+ const now = this.d.now();
148775
+ const senders = /* @__PURE__ */ new Set();
148776
+ let released = 0;
148777
+ for (const { address, why: why2, turnSeq, told, starter } of stops) {
148778
+ const owed = /* @__PURE__ */ new Set();
148779
+ for (const { row, message: m } of this.owedBy(address, why2, turnSeq)) {
148780
+ if (!this.d.records.markReleased(row.messageId, address, now, why2)) continue;
148781
+ released++;
148782
+ owed.add(m.sender);
148783
+ if (told?.includes(m.sender)) this.d.records.markTold([{ messageId: row.messageId, recipient: address }], now);
148784
+ else senders.add(m.sender);
148785
+ }
148786
+ const party = parseAddress(address);
148787
+ const persons = party?.kind === "session" && turnSeq !== null && this.d.records.turn(party.sessionId, turnSeq)?.startedBy === "person";
148788
+ if (starter && starter !== address && !persons && !owed.has(starter) && !told?.includes(starter)) this.tellStarter(starter, address, why2, turnSeq);
148789
+ }
148790
+ for (const sender of senders) this.tellUnanswered(sender, now);
148791
+ return released;
148626
148792
  });
148627
- const theirs = open6 ?? toPerson.at(-1);
148628
- const mine = chain.findLast((m) => m.sender === PERSON && this.records.recipients(m.id).some((r) => this.here(r.recipient)));
148629
- const target = theirs ?? mine;
148630
- if (!target) return void 0;
148631
- const to = target === theirs ? [target.sender] : this.records.recipients(target.id).flatMap((r) => this.here(r.recipient) ? [r.recipient] : []);
148632
- return { target, to };
148793
+ }
148794
+ /** The latest turn the mailbox recorded of a session address, 0 when none */
148795
+ latestTurnSeq(address) {
148796
+ const party = parseAddress(address);
148797
+ return party?.kind === "session" ? this.d.records.nextTurnSeq(party.sessionId) - 1 : 0;
148798
+ }
148799
+ /** What `stopped`'s stop notice to `sender` quotes of its cut turn `turnSeq` (owner, #1948): its words when `quotes` allows it, else null */
148800
+ quoteFor(stopped, sender, turnSeq) {
148801
+ return turnSeq !== null && this.quotes(stopped, sender, turnSeq) ? this.d.stoppedWords?.(stopped) ?? null : null;
148633
148802
  }
148634
148803
  /**
148635
- * The question a pick answers (#1630): the one the window names, which must be a question in these chains sent to the person by a session that is still
148636
- * here, whose choices include `text`, and not answered already (a question is answered once, whichever window gives the answer first)
148804
+ * Whether a stop notice to `sender` may quote the words of `stopped`'s turn `turnSeq` (its latest when absent): the one rule every stop notice
148805
+ * to a session quotes by (security-boundaries/inter-agent-content.md). `sender` is a session that can read `stopped` with read_session
148806
+ * (`mayRead`, that tool's own rule), and the turn is `sender`'s alone (`alone`)
148637
148807
  */
148638
- pickTarget(roots, id3, text3) {
148639
- const target = roots.flatMap((root3) => this.shown(root3).map((s) => s.m)).find((m) => m.id === id3);
148640
- const row = target && this.records.recipient(target.id, PERSON);
148641
- if (!target || !row || hiddenFromPerson(row) || !this.here(target.sender)) return void 0;
148642
- if (!target.choices?.includes(text3)) throw refuse4("bad_value", `${id3} does not offer that choice.`);
148643
- if (row.answerId !== null || row.settled !== null && row.settled !== "legacy") throw refuse4("answered", REFUSAL_TEXT.answered(id3));
148644
- return { target, to: [target.sender] };
148808
+ quotes(stopped, sender, turnSeq) {
148809
+ return this.d.mayRead?.(sender, stopped) === true && this.alone(stopped, sender, { turnSeq });
148645
148810
  }
148646
- /** Whether mail to `address` can still reach it: a session this host keeps (trashed or deleted ones are gone), or any other party */
148647
- here(address) {
148648
- const party = parseAddress(address);
148649
- return party?.kind !== "session" || this.host.session(party.sessionId) !== void 0;
148811
+ /**
148812
+ * Whether `session`'s turn `turnSeq` (its latest when absent) is `sender`'s alone: what a stop notice may quote to it (`quotes`), and whether it may
148813
+ * answer the session's cards as its work's giver (docs/plans/mailbox.md §10.6.4). All of it must hold:
148814
+ * - the turn is the session's latest (no turn since), and `sender`'s own message started it: a mail the mailbox delivered, or work `sender`
148815
+ * gave it (a start_agent task, mail to its child: a `caller` turn whose starter is that work's task row, sent by `sender`). A turn the
148816
+ * CLI started by itself (`cli`), or the person's, is never `sender`'s alone, even when it goes on with a task's work;
148817
+ * - every message the mailbox gave into it is from `sender`;
148818
+ * - everything else that may have entered it (`turnInputs`: each user row stored since the turn before began, and a question card answered
148819
+ * since) was sent by `sender`: none from the person, an app, a script, a relayed report or another session.
148820
+ * A turn anyone else had a part in, or one these records cannot tell, is no one's alone. `gaveIt`: only work `sender` gave it started the turn (a
148821
+ * `caller` turn), not a mail the mailbox delivered
148822
+ */
148823
+ alone(session2, sender, { turnSeq, gaveIt = false } = {}) {
148824
+ const [party, from] = [parseAddress(session2), parseAddress(sender)];
148825
+ if (party?.kind !== "session" || from?.kind !== "session") return false;
148826
+ const seq = turnSeq ?? this.d.records.nextTurnSeq(party.sessionId) - 1;
148827
+ if (this.d.records.nextTurnSeq(party.sessionId) !== seq + 1) return false;
148828
+ const turn = this.d.records.turn(party.sessionId, seq);
148829
+ if (!turn || turn.startedBy !== "caller" && (gaveIt || turn.startedBy !== "mail") || turn.starterId === null || this.d.records.message(turn.starterId)?.sender !== sender) return false;
148830
+ if (this.d.records.inTurn(session2, seq).some((r) => r.message.sender !== sender)) return false;
148831
+ const given = this.d.turnInputs?.(party.sessionId);
148832
+ return given !== void 0 && given.every((id3) => id3 === from.sessionId);
148650
148833
  }
148651
148834
  /**
148652
- * The person's Mark done (`finished`) or Drop (`dropped`), at once, on the whole chain and on every chain an old thread's id names (plan C12): nothing
148653
- * in it waits for them any more, and what they asked in it is withdrawn (their tasks and the questions they put that are still open, settled `withdrawn`:
148654
- * undelivered ones are never delivered, and no report of them is written). Nothing is stopped: the turn may carry other requests, and the
148655
- * person's Stop is the way to stop one. The session whose turn is on the chain, and each one that was asked something there and was delivered it, is told
148656
- * once, in a notice from Centralu that wakes nobody (`closedWords`), so it can stop that work itself; it reads it in the turn it is in when its tool takes
148657
- * input there, else with its next mail. What it sends in the chain after that is mail to the person like any: it reaches them in the same chain, which
148658
- * is listed again as open and unread
148835
+ * Turns the last host left that nothing continues, closed `lost` at this start (#1916): a crash or a plain restart cut them, or a kept process's
148836
+ * turn ended while no host was there to record it. The questions delivered in them that were not answered were read, so no delivery gives them
148837
+ * again: each is released `lost`, and each sender is told once for all of them (D25), so it can ask again. A task is not: it stays open, and the
148838
+ * session's next last response or reply answers it. `close` closes them and returns them, in the same write as the release: if the release fails, the turns
148839
+ * stay open and the next start finds them again
148659
148840
  */
148660
- close(threadId, outcome = "finished") {
148661
- const roots = this.rootsOf(threadId);
148662
- const root3 = roots[0];
148663
- if (root3 === void 0) throw refuse4("unknown_message", `There is no mail ${threadId} kept.`);
148664
- const now = Date.now();
148665
- const tell = /* @__PURE__ */ new Map();
148666
- this.records.transaction(() => {
148667
- for (const r of roots) {
148668
- const chain = this.chainOf(r);
148669
- const asked = [];
148670
- for (const m of chain) {
148671
- if (m.sender !== PERSON || !(m.needsReply || m.kind === "task")) continue;
148672
- for (const row of this.records.recipients(m.id)) if (row.settled === null) asked.push({ id: m.id, recipient: row.recipient, seen: row.deliveredAt !== null || row.attemptAt !== null || row.held === "uncertain" });
148673
- }
148674
- const working = this.workers(chain);
148675
- this.records.closeFor(
148676
- PERSON,
148677
- this.shown(r).map((s) => s.m.id),
148678
- now
148679
- );
148680
- const withdrawn = asked.filter((a) => this.records.settle(a.id, a.recipient, "withdrawn", now) > 0);
148681
- for (const m of chain) {
148682
- if (m.sender === PERSON && (m.needsReply || m.kind === "task")) for (const row of this.records.recipients(m.id)) this.records.settle(m.id, row.recipient, "done", now);
148683
- }
148684
- this.records.markClosed(r, outcome, now);
148685
- const end = chain.at(-1)?.id ?? r;
148686
- const add2 = (sessionId, address, id3) => {
148687
- const kept = tell.get(sessionId) ?? { address, root: r, ids: [], ends: [] };
148688
- if (id3 !== void 0 && !kept.ids.includes(id3)) kept.ids.push(id3);
148689
- if (!kept.ends.includes(end)) kept.ends.push(end);
148690
- tell.set(sessionId, kept);
148691
- };
148692
- for (const w of working) add2(w.sessionId, w.address);
148693
- for (const a of withdrawn) {
148694
- const party = parseAddress(a.recipient);
148695
- if (party?.kind !== "session" || !a.seen || !this.here(a.recipient)) continue;
148696
- add2(party.sessionId, a.recipient, a.id);
148697
- }
148841
+ turnsLost(close) {
148842
+ this.releaseAndTell((now, senders) => {
148843
+ for (const { address, turnSeq } of close()) {
148844
+ for (const { row, message } of this.cutQuestions(address, turnSeq)) if (this.d.records.markReleased(row.messageId, address, now, "lost")) senders.add(message.sender);
148698
148845
  }
148699
148846
  });
148700
- for (const r of roots) this.service.announce(r);
148701
- for (const [sessionId, t] of tell) this.tellClosed(outcome, sessionId, t);
148702
- return this.row(root3, this.heldIn(root3)) ?? this.emptyRow(root3);
148703
148847
  }
148704
148848
  /**
148705
- * One notice to a session about the chain it worked on being closed: its key names the session and the last message of each chain, so a second close of
148706
- * the same chain tells nothing again, and one after the chain went on (a reply, a new request) does. In the process now when it takes it there, else as
148707
- * mail. A process that fails to take it leaves the notice as undelivered mail, which goes again with the session's next mail
148849
+ * The questions `address` left unanswered in its turn `turnSeq` (in any turn when null), the rows a stop (`owedBy`) or a lost turn (`turnsLost`) releases: each
148850
+ * `needsReply` message delivered into that turn and not answered, settled or released, a request to the Assistant included. Not a task (a stop
148851
+ * releases those by its own rule, `owedBy`), nor a message the session sent itself (a handoff to the very session that asked leaves such a row)
148708
148852
  */
148709
- tellClosed(outcome, sessionId, t) {
148710
- const text3 = closedWords(t.root, outcome, t.ids);
148711
- const now = this.host.tellsNow(sessionId);
148712
- const stored = this.service.notice(t.address, {
148713
- body: text3,
148714
- facts: { quiet: true, chainClosed: { root: t.root, outcome, withdrawn: t.ids.slice(0, 10) } },
148715
- dedupeKey: `closed:${t.address}:${t.ends.join(",")}`,
148716
- delivered: now
148717
- });
148718
- if (!stored || !now) return;
148719
- const at2 = this.records.recipient(stored.id, t.address)?.deliveredAt;
148720
- this.host.tell(sessionId, text3).catch(() => {
148721
- if (at2 != null) this.service.deliveryFailedLate(t.address, [stored.id], at2);
148853
+ cutQuestions(address, turnSeq) {
148854
+ return this.d.records.unansweredTo(address).flatMap((row) => {
148855
+ if (turnSeq !== null && row.turnSeq !== turnSeq || row.settled !== null || row.releasedAt !== null) return [];
148856
+ const message = this.d.records.message(row.messageId);
148857
+ return message && message.kind !== "task" && message.sender !== address ? [{ row, message }] : [];
148722
148858
  });
148723
148859
  }
148724
148860
  /**
148725
- * The person's Release (Send again, Retry) or Dismiss of held rows. A row an earlier build held for a session's budget goes as the mail it is. A
148726
- * row held for its project's trust goes when the person trusts the project (§7.4): its Release says so. A dismissed answer leaves its question open (D8)
148861
+ * What a stopped session owes and its stop releases (mailbox.md §10.6.1), the one definition for a stop (`sessionsStopped`) and a deletion
148862
+ * (`partyGone`, `gone`):
148863
+ * - the questions of the cut turn `turnSeq` (`cutQuestions`; none without a turn), or, deleted, every one it has not answered;
148864
+ * - the open tasks a session or the person gave it (the person's own work is a request like any other, §10.6.3). Delivered ones only (one still
148865
+ * queued was never its work), except when it is deleted: then nothing of it will run. A stop that leaves it unable to answer (an error, a limit, the network,
148866
+ * a quit) releases them all; the person's Stop only those of the turn it stopped (delivered into it, or the work it was for): the session can
148867
+ * still answer the rest.
148868
+ * A deleted session leaves out mail to the Assistant's role, which follows the role (D15)
148727
148869
  */
148728
- held(action, recipient, messageIds) {
148729
- if (action === "dismiss") return { changed: this.service.dismissHeld(recipient, messageIds, PERSON_HOLDS) };
148730
- const projects = new Set(messageIds.flatMap((id3) => this.records.recipient(id3, recipient)?.held === "policy" ? this.records.message(id3)?.senderProject ?? [] : []));
148731
- const still = [...projects].find((p) => this.host.untrusted(p));
148732
- if (still !== void 0) throw refuse4("untrusted_project", `${this.host.projectLabel(still)} is not trusted: what its sessions send out of it waits until you trust the project, and then goes in order.`);
148733
- const policy = messageIds.filter((id3) => this.records.recipient(id3, recipient)?.held === "policy");
148734
- for (const p of projects) this.trusted(p);
148735
- const letGo = policy.filter((id3) => this.records.recipient(id3, recipient)?.held !== "policy").length;
148736
- return { changed: letGo + this.service.resendHeld(recipient, messageIds, ["uncertain", "failed", "budget"]) };
148870
+ owedBy(address, why2, turnSeq) {
148871
+ const party = parseAddress(address);
148872
+ const turn = why2 === "stopped" && turnSeq !== null && party?.kind === "session" ? this.d.records.turn(party.sessionId, turnSeq) : void 0;
148873
+ const stopped = (row) => why2 !== "stopped" || turnSeq !== null && (row.turnSeq === turnSeq || turn?.starterId === row.messageId);
148874
+ const questions = why2 === "gone" ? this.cutQuestions(address, null) : turnSeq === null ? [] : this.cutQuestions(address, turnSeq);
148875
+ const tasks = this.d.records.watchedTo(address).flatMap((row) => {
148876
+ const message = row.releasedAt === null && (why2 === "gone" || row.deliveredAt !== null) && stopped(row) ? this.d.records.message(row.messageId) : void 0;
148877
+ const by = message?.kind === "task" ? parseAddress(message.sender)?.kind : void 0;
148878
+ return message && (by === "session" || by === "person") && message.sender !== address ? [{ row, message }] : [];
148879
+ });
148880
+ return why2 === "gone" ? [...questions, ...tasks].filter(({ row }) => !isRoleVia(row.via)) : [...questions, ...tasks];
148881
+ }
148882
+ /** One write: `release` releases rows and adds each released question's sender to `senders`; then each sender is told once, in one notice (D25) */
148883
+ releaseAndTell(release) {
148884
+ this.d.run(() => {
148885
+ const senders = /* @__PURE__ */ new Set();
148886
+ const now = this.d.now();
148887
+ release(now, senders);
148888
+ for (const sender of senders) this.tellUnanswered(sender, now);
148889
+ });
148737
148890
  }
148738
148891
  /**
148739
- * Resume on what an earlier build paused (#2014: nothing pauses mail now): a session's rows held `budget`, or a chain's held `loop` (an old thread's id
148740
- * names the chains moved from it). They go as the mail they are, and a previous build still serving during a swap does not hold them again
148741
- */
148742
- resume(target) {
148743
- const rows3 = this.records.heldRows();
148744
- if (target.sessionId !== void 0) {
148745
- const recipient = this.service.sessionAddress(target.sessionId);
148746
- const ids = rows3.flatMap((r) => r.recipient === recipient && r.held === "budget" ? [r.messageId] : []);
148747
- if (ids.length > 0) this.service.resendHeld(recipient, ids, ["budget"]);
148748
- } else if (target.threadId !== void 0) {
148749
- const roots = new Set(this.rootsOf(target.threadId));
148750
- const ids = new Set(rows3.flatMap((r) => r.held === "loop" && roots.has(this.records.message(r.messageId)?.rootId ?? "") ? [r.messageId] : []));
148751
- for (const id3 of ids) this.service.resumeHeld(id3);
148752
- }
148753
- }
148754
- /** The person trusted a project (§7.4): what its sessions sent that was held for it goes, in order, and the callers refused are told */
148755
- trusted(projectId) {
148756
- for (const address of this.service.trustChanged(projectId)) {
148757
- const party = parseAddress(address);
148758
- if (party?.kind === "session") this.delivery.poke(party.sessionId);
148759
- }
148760
- this.service.announce();
148761
- }
148762
- /** A project was deleted: the mail held for its trust is dropped and its senders are told, naming it as it was named (§7.4) */
148763
- projectDeleted(projectId, name) {
148764
- this.service.dismissProject(projectId, name);
148765
- this.service.announce();
148766
- }
148767
- /** The project's name now, for `projectDeleted` once it is gone */
148768
- projectName(projectId) {
148769
- return this.host.projectLabel(projectId);
148770
- }
148771
- /**
148772
- * The answer is taken at once: waking a crowd resumes the sessions two at a time and takes as long as that takes, longer than a
148773
- * window waits for an answer. The list shows who is still waiting as it goes
148774
- */
148775
- wake(wake) {
148776
- this.delivery.answerCrowd(wake).catch((e) => console.error(`[mail] waking the sessions failed: ${errorMessage(e)}`));
148777
- }
148778
- // ── Chains ──
148779
- /** Every message of the chain, readable by the person or not: what a turn's work may be */
148780
- chainOf(root3) {
148781
- return this.records.numbered(root3, CHAIN_CAP).map(({ m }) => m);
148782
- }
148783
- /** The sessions of the chain whose turn going now is on it: the turn records name a message of the chain as that turn's work (or its starter) */
148784
- workers(chain) {
148785
- const ids = new Set(chain.map((m) => m.id));
148786
- const sessions = /* @__PURE__ */ new Map();
148787
- for (const m of chain) {
148788
- for (const address of [m.sender, ...this.records.recipients(m.id).map((r) => r.recipient)]) {
148789
- const party = parseAddress(address);
148790
- if (party?.kind === "session") sessions.set(party.sessionId, address);
148791
- }
148792
- }
148793
- return [...sessions].flatMap(([sessionId, address]) => {
148794
- const turn = this.host.turnOn(sessionId);
148795
- return turn && turn.work !== null && ids.has(turn.work) ? [{ sessionId, address }] : [];
148796
- });
148797
- }
148798
- /** Every chain an id names: a message's root, or each chain moved from an old thread, newest first */
148799
- rootsOf(id3) {
148800
- const m = this.records.message(id3);
148801
- return m ? [m.rootId] : this.records.movedFrom(id3);
148802
- }
148803
- /**
148804
- * The chain's messages the person may read, in the order they were stored, each numbered for the window by its own row number: a message that comes,
148805
- * goes or stops being readable leaves the others' numbers as they were, so the window's `after` misses nothing
148806
- */
148807
- shown(root3) {
148808
- return this.records.numbered(root3, CHAIN_CAP).map(({ m, n }) => ({ m, seq: n })).filter((s) => this.readable(s.m));
148809
- }
148810
- /** The person reads what they sent, what was sent to them, and what is held for them to act on (§5.5, §7.4) */
148811
- readable(m) {
148812
- if (m.sender === PERSON) return true;
148813
- return this.records.recipients(m.id).some((r) => r.recipient === PERSON && !hiddenFromPerson(r) || isPersonHold(r.held));
148814
- }
148815
- /** An old thread's messages before the first one moved from it: the chain's history, read-only (§6.3) */
148816
- legacyOf(first) {
148817
- if (!first?.legacyThread) return [];
148818
- const moved = new Set(this.records.byRoot(first.rootId, { limit: CHAIN_CAP }).map((m) => m.id));
148819
- const earlier = [];
148820
- for (const m of this.host.legacyChain(first.legacyThread)) {
148821
- if (m.id === first.id || moved.has(m.id)) break;
148822
- earlier.push(m);
148823
- }
148824
- return earlier;
148825
- }
148826
- heldIn(root3) {
148827
- return this.records.heldRows().filter((r) => this.records.message(r.messageId)?.rootId === root3).length;
148828
- }
148829
- subjectOf(root3) {
148830
- const first = this.shown(root3)[0]?.m ?? this.records.message(root3);
148831
- return first ? subjectLine(first) : root3;
148832
- }
148833
- /**
148834
- * A chain as the window's list row. Done when the person closed it (`facts.closed` on its root, or an older close: a row to them settled `done`) and
148835
- * nothing in it waits for them or for an answer to them, with how they closed it. Otherwise running while a session's turn is on it or a task the person gave in it is
148836
- * neither reported nor released by a stop, in review once such a task is reported, and open for the rest; the person may always write in a chain that is not done. The session
148837
- * named on it is the one whose turn is on it, else the first one the person's first message went to
148838
- */
148839
- row(root3, held3) {
148840
- const all = this.shown(root3).map((s) => s.m);
148841
- const first = all[0];
148842
- const last = all.at(-1);
148843
- if (!first || !last) return null;
148844
- const toPerson = all.flatMap((m) => this.records.recipient(m.id, PERSON) ?? []);
148845
- const tasks = all.filter((m) => m.sender === PERSON && m.kind === "task").flatMap((m) => this.records.recipients(m.id).filter((r) => parseAddress(r.recipient)?.kind === "session"));
148846
- const waits = toPerson.some((r) => r.settled === null) || all.some((m) => m.sender === PERSON && (m.needsReply || m.kind === "task") && this.records.recipients(m.id).some((r) => r.settled === null));
148847
- const closedAs = this.records.message(root3)?.facts.closed?.outcome;
148848
- const done2 = (closedAs !== void 0 || toPerson.some((r) => r.settled === "done") || tasks.some((r) => r.settled === "done")) && !waits;
148849
- const working = done2 ? [] : this.workers(this.chainOf(root3));
148850
- const state = done2 ? "done" : working.length > 0 || tasks.some((r) => r.settled === null && r.releasedAt === null) ? "running" : tasks.some((r) => r.settled === "reported") ? "review" : "open";
148851
- const assignee = working[0]?.address ?? (first.sender === PERSON ? this.records.recipients(first.id)[0]?.recipient : void 0);
148852
- return {
148853
- id: root3,
148854
- subject: subjectLine(first),
148855
- state,
148856
- outcome: done2 ? closedAs ?? "finished" : null,
148857
- next: null,
148858
- projectId: first.senderProject,
148859
- owner: this.party(first.sender),
148860
- assignee: assignee === void 0 ? null : this.party(assignee),
148861
- unread: toPerson.filter((r) => r.readAt === null && !hiddenFromPerson(r)).length,
148862
- held: held3,
148863
- blocked: 0,
148864
- working: working.length > 0,
148865
- createdAt: first.createdAt,
148866
- updatedAt: last.createdAt,
148867
- last: { sender: this.party(last.sender), kind: windowKind(last), preview: oneLineText(last.body, PREVIEW_CHARS2), at: last.createdAt }
148868
- };
148869
- }
148870
- /** A chain whose every message the person may not read (held for them, then let go): a row with nothing in it */
148871
- emptyRow(root3) {
148872
- const m = this.records.message(root3);
148873
- const at2 = m?.createdAt ?? 0;
148874
- return { id: root3, subject: m ? subjectLine(m) : root3, state: "open", outcome: null, next: null, projectId: null, owner: this.party(m?.sender ?? PERSON), assignee: null, unread: 0, held: 0, blocked: 0, working: false, createdAt: at2, updatedAt: at2, last: null };
148875
- }
148876
- // ── Shapes ──
148877
- /** The windows' `mail_changed` for a change to the mail (main.ts): a new message the person can read also names itself, for the OS notification (#1630) */
148878
- changeEvent(c) {
148879
- const toPerson = c.recipients.includes(PERSON);
148880
- const arrived = c.arrived && toPerson ? this.arrival(c.messageId) : void 0;
148881
- return { type: "mail_changed", threadId: c.rootId, toPerson, ...arrived ? { arrived } : {} };
148882
- }
148883
- /** A new message as the person's notification names it (`mail_changed.arrived`): one they can read, not their own */
148884
- arrival(messageId) {
148885
- const m = this.records.message(messageId);
148886
- const row = this.records.recipient(messageId, PERSON);
148887
- if (!m || !row || m.sender === PERSON || hiddenFromPerson(row) || row.held !== null) return void 0;
148888
- return { messageId, from: this.party(m.sender), kind: windowKind(m), preview: oneLineText(m.body, PREVIEW_CHARS2) };
148889
- }
148890
- party(address) {
148891
- const p = parseAddress(address);
148892
- if (p?.kind === "session") {
148893
- const s = this.host.session(p.sessionId);
148894
- return { address, kind: "session", sessionId: p.sessionId, name: s?.name ?? null, state: s?.state ?? null };
148895
- }
148896
- if (p?.kind === "app") return { address, kind: "app", sessionId: null, name: p.appId, state: null };
148897
- return { address, kind: p?.kind ?? "unknown", sessionId: null, name: null, state: null };
148898
- }
148899
- partiesOf(chain) {
148900
- const addresses = /* @__PURE__ */ new Set();
148901
- for (const m of chain) {
148902
- addresses.add(m.sender);
148903
- for (const r of this.records.recipients(m.id)) addresses.add(r.recipient);
148904
- }
148905
- return [...addresses].filter((a) => parseAddress(a)?.kind === "session" || parseAddress(a)?.kind === "app").map((a) => ({ party: this.party(a), role: "member" }));
148906
- }
148907
- message({ m, seq }) {
148908
- return {
148909
- id: m.id,
148910
- seq,
148911
- sender: this.party(m.sender),
148912
- kind: windowKind(m),
148913
- urgent: m.urgent,
148914
- body: m.body,
148915
- facts: { ...m.facts },
148916
- ...m.choices ? { choices: m.choices } : {},
148917
- ...m.replyTo !== null ? { replyTo: m.replyTo } : {},
148918
- createdAt: m.createdAt,
148919
- ...m.sender === PERSON ? { receipts: this.records.recipients(m.id).map((r) => ({ recipient: this.party(r.recipient), delivered: r.deliveredAt !== null, read: r.readAt !== null, handled: r.settled !== null })) } : {}
148920
- };
148921
- }
148922
- };
148923
- function closedWords(root3, outcome, ids) {
148924
- const what = outcome === "dropped" ? "dropped" : outcome === "finished" ? "marked done" : "closed";
148925
- const shown3 = ids.slice(0, 10).join(", ") + (ids.length > 10 ? `, and ${ids.length - 10} more` : "");
148926
- const withdrew = ids.length === 0 ? "" : ` and withdrew what they asked of you in it (${shown3})`;
148927
- return `The person ${what} the mail that began with ${root3}${withdrew}. Do not continue that work. Centralu did not stop your turn: if you are still working on it, stop it yourself. What you send in it still reaches the person.`;
148928
- }
148929
- function windowKind(m) {
148930
- if (typeof m.facts.legacyKind === "string") return m.facts.legacyKind;
148931
- if (m.kind === "task") return "assign";
148932
- if (m.kind === "message") return m.needsReply ? "question" : m.replyTo === null ? "note" : "answer";
148933
- return m.kind;
148934
- }
148935
- function legacyMessage(m, seq, party) {
148936
- return { id: m.id, seq, sender: party(m.sender), kind: m.kind, urgent: m.urgent, body: m.body, facts: { ...m.facts }, createdAt: m.createdAt };
148937
- }
148938
- function isPersonHold(held3) {
148939
- return PERSON_HOLDS.some((h) => h === held3);
148940
- }
148941
- function hiddenFromPerson(r) {
148942
- return r.held === "policy" || r.held === "loop" || r.held === "dismissed" || r.settled === "withdrawn" || r.settled === "gone";
148943
- }
148944
-
148945
- // packages/agent-host/src/mail/adoption.ts
148946
- var RETIRED_SESSION_KEYS = ["turn_inputs", "report_turn", "input_origins", "report_paused", "person_report_paused"];
148947
- function takeOverFromEarlierBuild(mail, store2, sessions) {
148948
- let queued2 = 0;
148949
- for (const r of store2.children.listQueuedRequests()) {
148950
- if (!SEND_ORIGINS.has(r.via)) continue;
148951
- try {
148952
- store2.mailbox.transaction(() => {
148953
- if (sessions.info(r.sessionId) && sessions.info(r.callerSessionId)) {
148954
- mail.task(mail.sessionAddress(r.callerSessionId), mail.sessionAddress(r.sessionId), { text: r.text, origin: r.via, delivered: false });
148955
- queued2++;
148956
- }
148957
- store2.children.removeQueuedRequest(r.id);
148958
- });
148959
- } catch (e) {
148960
- console.error(`[mail] could not take the request an earlier build queued for ${r.sessionId.slice(0, 8)} (${errorMessage(e)})`);
148961
- }
148962
- }
148963
- let adopted = 0;
148964
- for (const mark of store2.children.listReportMarks()) {
148965
- const child = sessions.info(mark.sessionId);
148966
- const owner = mail.sessionAddress(mark.callerSessionId);
148967
- const childAddress = mail.sessionAddress(mark.sessionId);
148968
- try {
148969
- store2.mailbox.transaction(() => {
148970
- if (mark.sessionId !== mark.callerSessionId && child && sessions.info(mark.callerSessionId) && !store2.mailbox.newestTask(owner, childAddress)) {
148971
- mail.task(owner, childAddress, { text: ADOPTED_TASK, origin: child.askedBy === mark.callerSessionId ? "start_agent" : "send_to_session", delivered: true });
148972
- adopted++;
148973
- }
148974
- store2.children.clearReportMark(mark.sessionId);
148975
- });
148976
- } catch (e) {
148977
- console.error(`[mail] could not adopt the report mark of ${mark.sessionId.slice(0, 8)} (${errorMessage(e)})`);
148978
- }
148979
- }
148980
- store2.settings.deleteSessionSettings(RETIRED_SESSION_KEYS);
148981
- return { queued: queued2, adopted };
148982
- }
148983
- function leaveForEarlierBuild(mail, store2, inTurnNow) {
148984
- const work = new Map(store2.mailbox.openTurns().map((t) => [t.sessionId, t.messageId]));
148985
- for (const id3 of inTurnNow) {
148986
- const address = mail.sessionAddress(id3);
148987
- const open6 = store2.mailbox.watchedTo(address).map((r) => store2.mailbox.message(r.messageId)).filter((m) => m?.kind === "task" && parseAddress(m.sender)?.kind === "session");
148988
- const task = open6.find((m) => m?.id === work.get(id3)) ?? open6.at(-1);
148989
- const caller = task ? parseAddress(task.sender) : null;
148990
- if (caller?.kind === "session") store2.children.setReportMark(id3, caller.sessionId);
148991
- }
148992
- }
148993
-
148994
- // packages/agent-host/src/mail/asked-by.ts
148995
- function askerFacts(host, sessionId) {
148996
- const session2 = host.session(sessionId);
148997
- const projectId = session2 ? session2.projectId : "gone";
148998
- const project2 = projectId ? host.project(projectId) : void 0;
148999
- return { name: session2?.name ?? sessionId.slice(0, 8), project: project2?.name ?? null, trusted: !host.untrusted(projectId) };
149000
- }
149001
- function askedBy(host, assistantId) {
149002
- const inTurn2 = host.requestsInTurn(assistantId);
149003
- const [first, ...rest] = inTurn2?.requests ?? [];
149004
- if (!inTurn2 || !first) return null;
149005
- return {
149006
- messageId: first.messageId,
149007
- sessionId: first.sessionId,
149008
- turn: inTurn2.turnSeq,
149009
- ...askerFacts(host, first.sessionId),
149010
- cites: host.cites(first.messageId),
149011
- ...rest.length > 0 ? { also: rest.map((r) => ({ sessionId: r.sessionId, ...askerFacts(host, r.sessionId) })) } : {}
149012
- };
149013
- }
149014
-
149015
- // packages/agent-host/src/mail/card-notices.ts
149016
- function cardGivers(records, address, alone) {
149017
- const givers = openTaskParties(records, address, "to");
149018
- const [only] = givers.length === 1 ? givers : [];
149019
- return { givers, answerer: only !== void 0 && alone(only) ? only : null };
149020
- }
149021
- function tellCard(service, giver, card, body, delivered) {
149022
- const written = service.notice(giver, { body, facts: { card, about: { session: card.session } }, dedupeKey: `card:${giver}:${card.session}:${card.handle}`, delivered });
149023
- return written?.id ?? null;
149024
- }
149025
- function withdrawEndedCards(records, session2, stands2) {
149026
- records.transaction(() => {
149027
- const gone2 = records.undeliveredCardNotices(session2).filter(({ message: { facts } }) => facts.card && !stands2(facts.card.session, facts.card.requestId));
149028
- if (gone2.length) records.deleteRows(gone2.map(({ row }) => ({ messageId: row.messageId, recipient: row.recipient })));
149029
- });
149030
- }
149031
-
149032
- // packages/agent-host/src/mail/last-response.ts
149033
- function tasksAtRest(records, recipient, last) {
149034
- return records.watchedTo(recipient).flatMap((row) => {
149035
- if (row.deliveredAt === null || row.held !== null && row.held !== "released" || !last.released && row.releasedAt !== null || last.queued?.has(row.messageId)) return [];
149036
- const task = records.message(row.messageId);
149037
- if (task?.kind !== "task" || task.sender === recipient || !last.answers(task.sender)) return [];
149038
- return records.handedOn(task.id).length > 0 ? [] : [{ row, sender: task.sender }];
149039
- });
149040
- }
149041
- function answerAtRest(records, recipient, last, report, personAt) {
149042
- return tasksAtRest(records, recipient, last).map(({ row, sender }) => {
149043
- const given = row.deliveredAt ?? 0;
149044
- const personSince = parseAddress(sender)?.kind === "session" && personAt !== void 0 && personAt > given;
149045
- const after = last.writtenAt !== void 0 && last.writtenAt < given;
149046
- const lines = [last.body(sender), ...personSince ? [PERSON_SINCE] : [], ...after ? [AFTER2] : []];
149047
- report(row.messageId, {
149048
- outcome: "finished",
149049
- body: lines.join("\n"),
149050
- ...last.answer ? { answer: last.answer } : {},
149051
- ...personSince ? { personSince: true } : {},
149052
- ...after ? { after: true } : {}
149053
- });
149054
- return row.messageId;
149055
- });
149056
- }
149057
- var PERSON_SINCE = "The person also wrote in this session after your task was given, so this last response may be an answer to them.";
149058
- var AFTER2 = "Your task arrived after this response was written.";
149059
-
149060
- // packages/agent-host/src/mail/reach.ts
149061
- function mailReach(host) {
149062
- const sessionOf = (address) => {
149063
- const party = parseAddress(address);
149064
- if (party?.kind !== "session") return void 0;
149065
- if (party.host === host.hostId) return { id: party.sessionId, info: host.session(party.sessionId) };
149066
- const far = host.foreign?.(address);
149067
- return far ? { id: party.sessionId, info: { projectId: null, askedBy: null, here: true, canReadMail: false, host: "elsewhere", name: far.name } } : void 0;
149068
- };
149069
- const untrusted = (projectId) => projectId === null ? false : !(host.project(projectId)?.trusted ?? false);
149070
- const leaves = (senderProject, recipientProject) => HOLD_UNTRUSTED_OUT && untrusted(senderProject) && recipientProject !== senderProject;
149071
- return {
149072
- untrusted,
149073
- isAssistant: (address) => {
149074
- const s = sessionOf(address);
149075
- return s !== void 0 && host.assistantId() === s.id;
149076
- },
149077
- askGroupMembers: (address) => host.askGroupMembers(address),
149078
- projectOf: (address) => sessionOf(address)?.info?.projectId ?? null,
149079
- parentOf: (address) => {
149080
- const parent = sessionOf(address)?.info?.askedBy;
149081
- const party = parseAddress(address);
149082
- return parent && party?.kind === "session" ? sessionAddress(party.host, parent) : null;
149083
- },
149084
- labelOf: (address) => sessionOf(address)?.info?.name ?? address,
149085
- elsewhere: (address) => sessionOf(address)?.info?.host === "elsewhere",
149086
- projectLabel: (projectId) => host.project(projectId)?.name ?? projectId,
149087
- mayWrite(from, to, asRequest = true) {
149088
- const f = parseAddress(from);
149089
- const t = parseAddress(to);
149090
- if (!f || !t) return "bad_address";
149091
- if (t.kind === "centralu" || t.kind === "app") return "not_allowed";
149092
- if (t.kind === "session" && t.host !== host.hostId) return "elsewhere";
149093
- const receiver = sessionOf(to);
149094
- if (receiver) {
149095
- if (!receiver.info?.here) return "gone";
149096
- if (receiver.info.host === "elsewhere") return "elsewhere";
149097
- if (!receiver.info.canReadMail) return "no_mailbox";
149098
- }
149099
- if (f.kind === "centralu" || f.kind === "person") return null;
149100
- if (f.kind === "app") return receiver && host.appCalledBy(from, receiver.id) ? null : "not_allowed";
149101
- if (!sessionOf(from)?.info?.here) return "gone";
149102
- if (!receiver) return null;
149103
- const assistant = host.assistantId();
149104
- return asRequest && receiver.id === assistant && f.sessionId !== assistant && !host.assistantAsks() ? "assistant_asks" : null;
149105
- },
149106
- holdFor(m, recipient) {
149107
- if (m.kind !== "message") return null;
149108
- const receiver = sessionOf(recipient);
149109
- return receiver?.info && leaves(m.senderProject, receiver.info.projectId) ? "policy" : null;
149110
- },
149111
- refusesDelegation(callerId, target) {
149112
- const project2 = host.session(callerId)?.projectId ?? null;
149113
- if (project2 === null) return null;
149114
- const targetProject = target.linked || target.assistant ? null : target.sessionId !== void 0 ? host.session(target.sessionId)?.projectId ?? null : target.projectId ?? null;
149115
- return leaves(project2, targetProject) ? project2 : null;
149116
- }
149117
- };
149118
- }
149119
- function droppedText(ids, project2) {
149120
- const shown3 = ids.slice(0, 10).join(", ") + (ids.length > 10 ? `, and ${ids.length - 10} more` : "");
149121
- return `The person dismissed ${ids.length} of your messages that were waiting for project ${project2} to be trusted (${shown3}). They were not delivered and will not be.`;
149122
- }
149123
- function trustedText(project2, calls) {
149124
- return `${project2} is trusted now. The calls refused for it can be given again: ${calls.slice(0, 10).join(", ")}${calls.length > 10 ? `, and ${calls.length - 10} more` : ""}`;
149125
- }
149126
-
149127
- // packages/agent-host/src/mail/send-guards.ts
149128
- function sendGuards(d2, { sender, cls, to, text: text3, requests: requests2 }, now) {
149129
- const label = (a) => d2.reach.labelOf(a);
149130
- for (const r of to) {
149131
- if ((cls === "session" || cls === "app") && d2.records.sameBody(sender, r, text3, now - REPEAT_WINDOW_MS)) {
149132
- throw guardRefused(d2, sender, "repeat", WARNING_TEXT.repeat(label(sender), r === PERSON ? "you" : label(r)), REFUSAL_TEXT.repeat(label(r)), now);
149133
- }
149134
- }
149135
- const limit = postsPerMinute(cls);
149136
- if (limit !== Infinity && d2.records.postsSince(sender, now - MINUTE_MS) >= limit) {
149137
- throw guardRefused(d2, sender, "rate_limited", WARNING_TEXT.rate_limited(label(sender), limit), `at most ${limit} posts a minute from ${cls === "app" ? "an app" : "a session"}: wait a minute`, now);
149138
- }
149139
- for (const [i, r] of to.entries()) {
149140
- if (requests2[i] && d2.records.requestsSince(d2.reach.askGroupMembers(sender), r, now - HOUR_MS) >= ASKS_PER_HOUR) {
149141
- throw guardRefused(d2, sender, "ask_rate", WARNING_TEXT.ask_rate(label(sender)), REFUSAL_TEXT.ask_rate(), now);
149142
- }
149143
- }
149144
- }
149145
- function guardRefused(d2, sender, reason, toPerson, toSender, now) {
149146
- d2.notice(PERSON, { body: toPerson, facts: { guardRefused: { sender, reason } }, dedupeKey: hourlyKey(`guard:${reason}:${sender}`, now) });
149147
- return refuse4(reason, toSender);
149148
- }
149149
-
149150
- // packages/agent-host/src/mail/stop-notices.ts
149151
- var StopNotices = class {
149152
- constructor(d2) {
149153
- this.d = d2;
149154
- }
149155
- d;
149156
- /**
149157
- * A session went to the trash or was deleted: it can answer nothing any more. What it owes (`owedBy`: its questions, whichever turn, and every task a
149158
- * session gave it) is released `gone` and each sender told once, as for a stop (mailbox.md §10.6.1); then its watched rows are settled `gone` and its
149159
- * own watched messages `withdrawn`. Mail sent to the Assistant's role follows the role, not the session that held it (D15): `roleMoved` gives it on
149160
- */
149161
- partyGone(address) {
149162
- this.releaseAndTell((now, senders) => {
149163
- for (const { row, message } of this.owedBy(address, "gone", null)) if (this.d.records.markReleased(row.messageId, address, now, "gone")) senders.add(message.sender);
149164
- for (const row of this.d.records.watchedTo(address)) if (!isRoleVia(row.via)) this.d.records.settle(row.messageId, address, "gone", now);
149165
- for (const row of this.d.records.watchedFrom(address)) this.d.records.settle(row.messageId, row.recipient, "withdrawn", now);
149166
- });
149167
- }
149168
- /**
149169
- * A session stopped without answering (mailbox.md "The stop notice"): an error, a usage limit, the network, its tool's interrupt, a Stop, a quit
149170
- * or shutdown of Centralu, or a cut turn Centralu could not continue. What it owes an answer is released with the cause: each question delivered
149171
- * into the cut turn `turnSeq` and not answered (a `needsReply` message, the person's too; none without a turn), and every open task a session or the
149172
- * person gave it. Each sender is told once, in one notice, and woken: it is owed a reply (`standing`: in a turn it reads it when that turn ends; one a quit
149173
- * cut reads it at its next turn). `starter`, the session that started the stopped one, is told too when it is owed nothing and the turn was not
149174
- * the person's, woken only from a turn. The rows stay open, so a reply or a last response after the person continues the session still answers
149175
- * them. A question delivered in an earlier turn is not this stop's: it was read, and the session may have answered it in conversation.
149176
- *
149177
- * The person's notice goes to the Inbox and wakes nothing. `told`: the senders a call still waiting on the session already told (it read the stop
149178
- * itself), whose rows are released and marked told. Returns how many rows were released
149179
- */
149180
- sessionStopped(address, why2, opts = {}) {
149181
- return this.sessionsStopped([{ ...opts, address, why: why2, turnSeq: opts.turnSeq ?? null }]);
149182
- }
149183
- /** Several sessions stopped at once (a quit found at the start): in one write, so a sender of questions to many of them is told once, in one notice */
149184
- sessionsStopped(stops) {
149185
- return this.d.run(() => {
149186
- const now = this.d.now();
149187
- const senders = /* @__PURE__ */ new Set();
149188
- let released = 0;
149189
- for (const { address, why: why2, turnSeq, told, starter } of stops) {
149190
- const owed = /* @__PURE__ */ new Set();
149191
- for (const { row, message: m } of this.owedBy(address, why2, turnSeq)) {
149192
- if (!this.d.records.markReleased(row.messageId, address, now, why2)) continue;
149193
- released++;
149194
- owed.add(m.sender);
149195
- if (told?.includes(m.sender)) this.d.records.markTold([{ messageId: row.messageId, recipient: address }], now);
149196
- else senders.add(m.sender);
149197
- }
149198
- const party = parseAddress(address);
149199
- const persons = party?.kind === "session" && turnSeq !== null && this.d.records.turn(party.sessionId, turnSeq)?.startedBy === "person";
149200
- if (starter && starter !== address && !persons && !owed.has(starter) && !told?.includes(starter)) this.tellStarter(starter, address, why2, turnSeq);
149201
- }
149202
- for (const sender of senders) this.tellUnanswered(sender, now);
149203
- return released;
149204
- });
149205
- }
149206
- /** The latest turn the mailbox recorded of a session address, 0 when none */
149207
- latestTurnSeq(address) {
149208
- const party = parseAddress(address);
149209
- return party?.kind === "session" ? this.d.records.nextTurnSeq(party.sessionId) - 1 : 0;
149210
- }
149211
- /** What `stopped`'s stop notice to `sender` quotes of its cut turn `turnSeq` (owner, #1948): its words when `quotes` allows it, else null */
149212
- quoteFor(stopped, sender, turnSeq) {
149213
- return turnSeq !== null && this.quotes(stopped, sender, turnSeq) ? this.d.stoppedWords?.(stopped) ?? null : null;
149214
- }
149215
- /**
149216
- * Whether a stop notice to `sender` may quote the words of `stopped`'s turn `turnSeq` (its latest when absent): the one rule every stop notice
149217
- * to a session quotes by (security-boundaries/inter-agent-content.md). `sender` is a session that can read `stopped` with read_session
149218
- * (`mayRead`, that tool's own rule), and the turn is `sender`'s alone (`alone`)
149219
- */
149220
- quotes(stopped, sender, turnSeq) {
149221
- return this.d.mayRead?.(sender, stopped) === true && this.alone(stopped, sender, { turnSeq });
149222
- }
149223
- /**
149224
- * Whether `session`'s turn `turnSeq` (its latest when absent) is `sender`'s alone: what a stop notice may quote to it (`quotes`), and whether it may
149225
- * answer the session's cards as its work's giver (docs/plans/mailbox.md §10.6.4). All of it must hold:
149226
- * - the turn is the session's latest (no turn since), and `sender`'s own message started it: a mail the mailbox delivered, or work `sender`
149227
- * gave it (a start_agent task, an agent_session send: a `caller` turn whose starter is that work's task row, sent by `sender`). A turn the
149228
- * CLI started by itself (`cli`), or the person's, is never `sender`'s alone, even when it goes on with a task's work;
149229
- * - every message the mailbox gave into it is from `sender`;
149230
- * - everything else that may have entered it (`turnInputs`: each user row stored since the turn before began, and a question card answered
149231
- * since) was sent by `sender`: none from the person, an app, a script, a relayed report or another session.
149232
- * A turn anyone else had a part in, or one these records cannot tell, is no one's alone. `gaveIt`: only work `sender` gave it started the turn (a
149233
- * `caller` turn), not a mail the mailbox delivered
149234
- */
149235
- alone(session2, sender, { turnSeq, gaveIt = false } = {}) {
149236
- const [party, from] = [parseAddress(session2), parseAddress(sender)];
149237
- if (party?.kind !== "session" || from?.kind !== "session") return false;
149238
- const seq = turnSeq ?? this.d.records.nextTurnSeq(party.sessionId) - 1;
149239
- if (this.d.records.nextTurnSeq(party.sessionId) !== seq + 1) return false;
149240
- const turn = this.d.records.turn(party.sessionId, seq);
149241
- if (!turn || turn.startedBy !== "caller" && (gaveIt || turn.startedBy !== "mail") || turn.starterId === null || this.d.records.message(turn.starterId)?.sender !== sender) return false;
149242
- if (this.d.records.inTurn(session2, seq).some((r) => r.message.sender !== sender)) return false;
149243
- const given = this.d.turnInputs?.(party.sessionId);
149244
- return given !== void 0 && given.every((id3) => id3 === from.sessionId);
149245
- }
149246
- /**
149247
- * Turns the last host left that nothing continues, closed `lost` at this start (#1916): a crash or a plain restart cut them, or a kept process's
149248
- * turn ended while no host was there to record it. The questions delivered in them that were not answered were read, so no delivery gives them
149249
- * again: each is released `lost`, and each sender is told once for all of them (D25), so it can ask again. A task is not: it stays open, and the
149250
- * session's next last response or reply answers it. `close` closes them and returns them, in the same write as the release: if the release fails, the turns
149251
- * stay open and the next start finds them again
149252
- */
149253
- turnsLost(close) {
149254
- this.releaseAndTell((now, senders) => {
149255
- for (const { address, turnSeq } of close()) {
149256
- for (const { row, message } of this.cutQuestions(address, turnSeq)) if (this.d.records.markReleased(row.messageId, address, now, "lost")) senders.add(message.sender);
149257
- }
149258
- });
149259
- }
149260
- /**
149261
- * The questions `address` left unanswered in its turn `turnSeq` (in any turn when null), the rows a stop (`owedBy`) or a lost turn (`turnsLost`) releases: each
149262
- * `needsReply` message delivered into that turn and not answered, settled or released, a request to the Assistant included. Not a task (a stop
149263
- * releases those by its own rule, `owedBy`), nor a message the session sent itself (a handoff to the very session that asked leaves such a row)
149264
- */
149265
- cutQuestions(address, turnSeq) {
149266
- return this.d.records.unansweredTo(address).flatMap((row) => {
149267
- if (turnSeq !== null && row.turnSeq !== turnSeq || row.settled !== null || row.releasedAt !== null) return [];
149268
- const message = this.d.records.message(row.messageId);
149269
- return message && message.kind !== "task" && message.sender !== address ? [{ row, message }] : [];
149270
- });
149271
- }
149272
- /**
149273
- * What a stopped session owes and its stop releases (mailbox.md §10.6.1), the one definition for a stop (`sessionsStopped`) and a deletion
149274
- * (`partyGone`, `gone`):
149275
- * - the questions of the cut turn `turnSeq` (`cutQuestions`; none without a turn), or, deleted, every one it has not answered;
149276
- * - the open tasks a session or the person gave it (the person's own work is a request like any other, §10.6.3). Delivered ones only (one still
149277
- * queued was never its work), except when it is deleted: then nothing of it will run. A stop that leaves it unable to answer (an error, a limit, the network,
149278
- * a quit) releases them all; the person's Stop only those of the turn it stopped (delivered into it, or the work it was for): the session can
149279
- * still answer the rest.
149280
- * A deleted session leaves out mail to the Assistant's role, which follows the role (D15)
149281
- */
149282
- owedBy(address, why2, turnSeq) {
149283
- const party = parseAddress(address);
149284
- const turn = why2 === "stopped" && turnSeq !== null && party?.kind === "session" ? this.d.records.turn(party.sessionId, turnSeq) : void 0;
149285
- const stopped = (row) => why2 !== "stopped" || turnSeq !== null && (row.turnSeq === turnSeq || turn?.starterId === row.messageId);
149286
- const questions = why2 === "gone" ? this.cutQuestions(address, null) : turnSeq === null ? [] : this.cutQuestions(address, turnSeq);
149287
- const tasks = this.d.records.watchedTo(address).flatMap((row) => {
149288
- const message = row.releasedAt === null && (why2 === "gone" || row.deliveredAt !== null) && stopped(row) ? this.d.records.message(row.messageId) : void 0;
149289
- const by = message?.kind === "task" ? parseAddress(message.sender)?.kind : void 0;
149290
- return message && (by === "session" || by === "person") && message.sender !== address ? [{ row, message }] : [];
149291
- });
149292
- return why2 === "gone" ? [...questions, ...tasks].filter(({ row }) => !isRoleVia(row.via)) : [...questions, ...tasks];
149293
- }
149294
- /** One write: `release` releases rows and adds each released question's sender to `senders`; then each sender is told once, in one notice (D25) */
149295
- releaseAndTell(release) {
149296
- this.d.run(() => {
149297
- const senders = /* @__PURE__ */ new Set();
149298
- const now = this.d.now();
149299
- release(now, senders);
149300
- for (const sender of senders) this.tellUnanswered(sender, now);
149301
- });
149302
- }
149303
- /**
149304
- * The sender's released and untold rows, gathered in one notice (D25, S3); the row's `told_at` is set so it is listed once. The person is told in
149305
- * the Inbox, in plain words with no ids, and only for what was released at `since` and was not their own doing: the rows older builds released
149306
- * without telling the person are not listed all at once.
149307
- * It wakes a session, unless a quit cut it (`wakes`)
148892
+ * The sender's released and untold rows, gathered in one notice (D25, S3); the row's `told_at` is set so it is listed once. The person is told in
148893
+ * the Inbox, in plain words with no ids, and only for what was released at `since` and was not their own doing: the rows older builds released
148894
+ * without telling the person are not listed all at once.
148895
+ * It wakes a session, unless a quit cut it (`wakes`)
149308
148896
  */
149309
148897
  tellUnanswered(sender, since) {
149310
148898
  const kind = parseAddress(sender)?.kind;
@@ -149461,6 +149049,7 @@ function checkedChoices(c, cls, to, question) {
149461
149049
  return choices;
149462
149050
  }
149463
149051
  var CHOICE_CHARS = 80;
149052
+ var SUBJECT_CHARS = 80;
149464
149053
  var MessageService = class {
149465
149054
  constructor(records, reach, opts) {
149466
149055
  this.records = records;
@@ -149561,7 +149150,7 @@ var MessageService = class {
149561
149150
  const facts = { ...clarifies !== void 0 ? { clarifies } : {}, ...quiet ? { quiet: true } : {}, ...cited ? { cites: cited } : {}, ...input.picked && cls === "person" ? { picked: true } : {} };
149562
149151
  const stored = this.put(
149563
149152
  // The citation's one use: `UNIQUE(sender, dedupe_key)` (`personWord` looked first, in this transaction)
149564
- { ...input.id ? { id: input.id } : {}, sender, kind, body: text3, needsReply, replyTo: target?.id ?? null, causeId, depth: 0, urgent, facts, choices: choices ?? null, origin: cls === "person" ? "person" : cls === "app" ? "app" : "mail", ...cited ? { dedupeKey: citeKey(cited.seq) } : {} },
149153
+ { ...input.id ? { id: input.id } : {}, sender, kind, body: text3, needsReply, replyTo: target?.id ?? null, causeId, depth: 0, urgent, facts, choices: choices ?? null, subject: !target && input.subject && oneLineText(input.subject, SUBJECT_CHARS) || null, origin: cls === "person" ? "person" : cls === "app" ? "app" : "mail", ...cited ? { dedupeKey: citeKey(cited.seq) } : {} },
149565
149154
  to.map((r, i) => this.row(r, { dueAt: dueAt(now, urgent, cls === "person"), via: input.to.length > 0 ? input.via?.[input.to.indexOf(r)] ?? null : null, held: holds[i] ?? null }))
149566
149155
  );
149567
149156
  const held3 = to.flatMap((recipient, i) => holds[i] ? [{ recipient, why: holds[i] }] : []);
@@ -150012,237 +149601,767 @@ var MessageService = class {
150012
149601
  this.records.letGo(r.recipient, [messageId]);
150013
149602
  this.records.hold(r.recipient, [messageId], "released");
150014
149603
  }
150015
- if (m?.replyTo && rows3.length > 0) this.records.settle(m.replyTo, m.sender, "answered", this.now(), m.id);
150016
- if (m && rows3.length > 0) this.changed(m, [...rows3.map((r) => r.recipient), PERSON]);
150017
- return rows3.length;
149604
+ if (m?.replyTo && rows3.length > 0) this.records.settle(m.replyTo, m.sender, "answered", this.now(), m.id);
149605
+ if (m && rows3.length > 0) this.changed(m, [...rows3.map((r) => r.recipient), PERSON]);
149606
+ return rows3.length;
149607
+ });
149608
+ }
149609
+ // ── Parties that go, parties that take over (§7.7) ──
149610
+ /**
149611
+ * The handoff (§7.7, §10.6.5), its one move: `from`'s unsettled watched rows and unread mail move to `to`, and the tasks `from` gave the sessions that
149612
+ * move (`children`) become `to`'s; the successor is told of each message. Called inside the children's move
149613
+ */
149614
+ handOver(from, to, scope, children = scope === "all" ? [] : scope.senders) {
149615
+ return this.run(() => {
149616
+ const plan = this.handOverPreview(from, to, scope);
149617
+ const fresh = plan.filter((p) => this.records.recipient(p.messageId, to) === void 0);
149618
+ this.records.moveRows(from, to, scope);
149619
+ for (const row of this.records.watchedFrom(from)) {
149620
+ const m = children.includes(row.recipient) ? this.records.message(row.messageId) : void 0;
149621
+ if (m?.kind !== "task") continue;
149622
+ this.records.settle(m.id, row.recipient, "withdrawn", this.now());
149623
+ const again = this.put({ sender: to, kind: "task", body: m.body, causeId: m.causeId, origin: m.origin, facts: m.facts }, [this.row(row.recipient, { dueAt: row.dueAt, deliveredAt: row.deliveredAt, readAt: row.readAt })]);
149624
+ if (row.releasedAt !== null && row.releasedWhy !== null) this.records.markReleased(again.id, row.recipient, row.releasedAt, row.releasedWhy);
149625
+ }
149626
+ this.movedNotice(to, fresh.map((p) => p.messageId));
149627
+ return plan;
149628
+ });
149629
+ }
149630
+ /** What `handOver` would move, read only: each message by id and the first line of its words, for the handoff note to quote */
149631
+ handOverPreview(from, to, scope = "all") {
149632
+ return this.records.movable(from, to, scope).flatMap((id3) => {
149633
+ const m = this.records.message(id3);
149634
+ return m ? [{ messageId: id3, firstLine: firstLineOf(m.body, 160), kind: m.kind, unread: this.records.recipient(id3, from)?.readAt === null, ...m.facts.about ? { about: m.facts.about.session } : {} }] : [];
149635
+ });
149636
+ }
149637
+ /** The Assistant's role is `to`'s (D15): rows sent to the role that another session held are delivered afresh, read or not, and the new Assistant is told of each. Returns how many */
149638
+ roleMoved(to) {
149639
+ return this.run(() => {
149640
+ const ids = this.records.moveRole(to);
149641
+ this.movedNotice(to, ids);
149642
+ return ids.length;
149643
+ });
149644
+ }
149645
+ sweep() {
149646
+ return this.records.sweep(this.now());
149647
+ }
149648
+ // ── Inside ──
149649
+ /** A message stored for its recipients; the change is queued for the listeners. A missing reply target is the sender's `unknown_message` */
149650
+ put(mail, rows3) {
149651
+ const now = this.now();
149652
+ let stored;
149653
+ try {
149654
+ stored = this.records.insert(
149655
+ { id: messageIdOf(this.opts.hostId, this.ulids.next(now)), senderProject: this.reach.projectOf(mail.sender), needsReply: false, replyTo: null, causeId: null, depth: 0, urgent: false, facts: {}, choices: null, subject: null, dedupeKey: null, legacyThread: null, createdAt: now, ...mail },
149656
+ rows3
149657
+ );
149658
+ } catch (e) {
149659
+ if (e instanceof MailTargetMissing) throw refuse4("unknown_message", REFUSAL_TEXT.unknown_message(e.replyTo));
149660
+ throw e;
149661
+ }
149662
+ if (!stored.duplicate) this.queued.push({ messageId: stored.id, rootId: stored.rootId, recipients: rows3.map((r) => r.recipient), arrived: true });
149663
+ return stored;
149664
+ }
149665
+ changed(m, recipients) {
149666
+ this.queued.push({ messageId: m.id, rootId: m.rootId, recipients: [...recipients] });
149667
+ }
149668
+ row(recipient, over) {
149669
+ return { recipient, recipientProject: this.reach.projectOf(recipient), ...over };
149670
+ }
149671
+ /** A message from Centralu to `recipient`: not a sender's, so no guard applies. `delivered` writes it already delivered and read */
149672
+ centralu(recipient, m) {
149673
+ const now = this.now();
149674
+ return this.put(
149675
+ { sender: CENTRALU, kind: m.kind, body: this.checkText("centralu", m.body), facts: m.facts, dedupeKey: m.dedupeKey, replyTo: m.replyTo ?? null, origin: "centralu" },
149676
+ [this.row(recipient, { dueAt: dueAt(now, false, false), ...m.delivered ? { deliveredAt: now, readAt: now } : {} })]
149677
+ );
149678
+ }
149679
+ checkText(cls, text3) {
149680
+ if (typeof text3 !== "string") throw refuse4("bad_value", "a body is text");
149681
+ if (text3.trim() === "") throw refuse4("empty", "a post says something");
149682
+ if (text3.length > bodyLimit(cls)) throw refuse4("too_long", tooLongText(cls));
149683
+ return text3;
149684
+ }
149685
+ refusalText(why2, to) {
149686
+ const text3 = {
149687
+ gone: REFUSAL_TEXT.gone(to),
149688
+ no_mailbox: REFUSAL_TEXT.no_mailbox(),
149689
+ elsewhere: REFUSAL_TEXT.elsewhere(to),
149690
+ assistant_asks: REFUSAL_TEXT.assistant_asks(),
149691
+ not_allowed: REFUSAL_TEXT.not_allowed()
149692
+ };
149693
+ return text3[why2] ?? why2;
149694
+ }
149695
+ /** The message `id` as `reader` may read it (§5.5): one it sent, or one it is a recipient of and is not held from it. Anything else is not there for it */
149696
+ readable(reader, id3) {
149697
+ const m = this.records.message(id3);
149698
+ const row = m && m.sender !== reader ? this.records.recipient(id3, reader) : void 0;
149699
+ if (!m || m.sender !== reader && (!row || isHidden(row))) throw refuse4("unknown_message", REFUSAL_TEXT.unknown_message(id3));
149700
+ return m;
149701
+ }
149702
+ /** Whether `target` is a clarification of a task `owner` gave, and the answer goes to the one who asked (§9.7) */
149703
+ answersClarification(owner, target, to) {
149704
+ const task = typeof target.facts.clarifies === "string" ? this.records.message(target.facts.clarifies) : void 0;
149705
+ return task?.kind === "task" && task.sender === owner && to.length === 1 && to[0] === target.sender;
149706
+ }
149707
+ /**
149708
+ * Whether a message is a request to the Assistant (§7.6): from a session to the Assistant, unless it answers a `needsReply` message or a task the
149709
+ * assistant sent that session, or is a clarification. Only requests are counted by `ask_rate` and raise the person's cards
149710
+ */
149711
+ isRequest(m, recipient) {
149712
+ if (m.kind !== "message" && m.kind !== "task" || m.sender === recipient || !this.reach.isAssistant(recipient)) return false;
149713
+ if (parseAddress(m.sender)?.kind !== "session" || typeof m.facts.clarifies === "string") return false;
149714
+ const target = m.replyTo === null ? void 0 : this.records.message(m.replyTo);
149715
+ return !(target && target.sender === recipient && (target.needsReply || target.kind === "task"));
149716
+ }
149717
+ /**
149718
+ * Whether a message was given in the recipient's open turn (§4.2): its row names the turn, or it is the work message of a turn the delivery began,
149719
+ * whose rows are marked once the tool took them. Not another row held from the recipient: what it was not woken for has not joined the turn
149720
+ */
149721
+ inOpenTurn(m, row, turn) {
149722
+ if (!turn || !row) return false;
149723
+ if (turn.by === "mail" && turn.messageId === m.id) return true;
149724
+ return row.turnSeq === turn.turnSeq && (row.held === null || row.held === "released");
149725
+ }
149726
+ /** The message that started `sender`'s turn, when a message did (not the person, not the session itself): what a send in that turn is caused by (§8.2 step 6) */
149727
+ causeOf(sender) {
149728
+ const turn = this.opts.turn?.(sender) ?? null;
149729
+ return turn !== null && turn.by !== "person" && turn.by !== "cli" ? turn.starter : null;
149730
+ }
149731
+ /** The answer `answer` to `question` is held for the person: the question stays open (it keeps the answer's id) and its asker is told once, quietly (S14) */
149732
+ answerHeld(question, answer) {
149733
+ this.records.answerHeld(question.id, answer.sender, answer.id);
149734
+ if (parseAddress(question.sender)?.kind !== "session") return;
149735
+ const reason = `${this.reach.projectLabel(answer.senderProject ?? "")} is not trusted`;
149736
+ this.centralu(question.sender, {
149737
+ kind: "notice",
149738
+ body: `${this.reach.labelOf(answer.sender)} answered your ${question.id} with ${answer.id}, and the answer is held for the person (${reason}). It reaches you if the person lets it through; until then Centralu does not remind ${this.reach.labelOf(answer.sender)} of it.`,
149739
+ facts: { quiet: true, answerHeld: { question: question.id, answer: answer.id } },
149740
+ dedupeKey: `answer_held:${question.sender}:${answer.id}:policy`
149741
+ });
149742
+ }
149743
+ /** Rows came to `to` from another holder (a handoff, the role's move): one quiet notice for the move, so it knows why the messages are there (key `handover:`) */
149744
+ movedNotice(to, messageIds) {
149745
+ if (messageIds.length === 0 || parseAddress(to)?.kind !== "session") return;
149746
+ this.centralu(to, {
149747
+ kind: "notice",
149748
+ body: messageIds.length === 1 ? "A message addressed to the previous holder was moved to you." : `${messageIds.length} messages addressed to the previous holder were moved to you.`,
149749
+ facts: { quiet: true, handedOver: true },
149750
+ dedupeKey: `handover:${to}:${hash16(messageIds)}`
149751
+ });
149752
+ }
149753
+ /** A reminder whose messages are all settled (or gone) has nothing to say (§8.2 step 1) */
149754
+ reminderSettled(m, recipient) {
149755
+ return m.kind === "notice" && m.facts.reminder !== void 0 && (m.facts.of ?? []).every((id3) => {
149756
+ const row = this.records.recipient(id3, recipient);
149757
+ return row === void 0 || row.settled !== null;
149758
+ });
149759
+ }
149760
+ /** The task this delivery's report hands on from (§8.2 step 3): the report is of a task the recipient gave while it worked on one still open */
149761
+ handedOnFrom(m, recipient) {
149762
+ const task = m.kind === "report" && m.replyTo !== null ? this.records.message(m.replyTo) : void 0;
149763
+ const cause2 = task?.causeId ? this.records.message(task.causeId) : void 0;
149764
+ return cause2?.kind === "task" && this.records.recipient(cause2.id, recipient)?.settled === null ? cause2.id : void 0;
149765
+ }
149766
+ /** Mail whose delivery may or may not have gone: news and Centralu's own words go again, the rest is held `uncertain` for the person */
149767
+ settleUncertain(recipient, ids) {
149768
+ const messages2 = ids.flatMap((id3) => this.records.message(id3) ?? []);
149769
+ const again = messages2.filter((m) => m.kind === "notice" || m.sender === CENTRALU).map((m) => m.id);
149770
+ const unsure = messages2.filter((m) => !again.includes(m.id)).map((m) => m.id);
149771
+ if (again.length > 0) this.records.markMaybeRepeated(recipient, again, this.now());
149772
+ if (unsure.length > 0) this.records.markUncertain(recipient, unsure);
149773
+ for (const m of messages2) this.changed(m, again.includes(m.id) ? [recipient, PERSON] : [PERSON]);
149774
+ return { resent: again.length, held: unsure.length };
149775
+ }
149776
+ /** The ids of those of `ids` that `recipient`'s rows hold for one of `why` */
149777
+ heldBy(recipient, ids, why2) {
149778
+ return ids.filter((id3) => why2.includes(this.records.recipient(id3, recipient)?.held ?? ""));
149779
+ }
149780
+ // ── What the reader sees ──
149781
+ /** Centralu's word for how the sender stands to the receiver (§8.3). Never a name another party wrote */
149782
+ relation(recipient, m) {
149783
+ const kind = parseAddress(m.sender)?.kind;
149784
+ if (kind === "centralu") return "Centralu";
149785
+ if (kind === "person") return "the person";
149786
+ if (kind === "app") return "an app you called";
149787
+ if (this.isRequest(m, recipient)) return "a session asking you for something";
149788
+ if (this.reach.parentOf(recipient) === m.sender) return "your parent session";
149789
+ if (this.reach.parentOf(m.sender) === recipient) return "your child session";
149790
+ const target = m.replyTo === null ? void 0 : this.records.message(m.replyTo);
149791
+ if (target?.kind === "task" && target.sender === recipient) return "the session you gave this work to";
149792
+ if (this.reach.isAssistant(m.sender)) return "the Assistant";
149793
+ const mine = this.reach.projectOf(recipient);
149794
+ return mine !== null && mine === this.reach.projectOf(m.sender) ? "a session of your project" : "a session of another project";
149795
+ }
149796
+ /** A message as `reader` sees it: whole, or a phantom without its words (§5.5), or a request whose words are for the turn it is in only (§7.6) */
149797
+ item(m, reader, turn) {
149798
+ const row = this.records.recipient(m.id, reader) ?? null;
149799
+ const relation = this.relation(reader, m);
149800
+ if (m.sender !== reader && (!row || isHidden(row))) return { message: { ...m, body: "", facts: {} }, row: null, relation, phantom: row ? "held" : "not_sent" };
149801
+ if (this.isRequest(m, reader) && !this.inOpenTurn(m, row ?? void 0, turn)) return { message: { ...m, body: "" }, row, relation, withheld: true };
149802
+ return { message: m, row, relation };
149803
+ }
149804
+ /** The line for an earlier message that is no longer kept (S5) */
149805
+ gone(id3) {
149806
+ const stub = { id: id3, sender: "", senderProject: null, kind: "notice", needsReply: false, replyTo: null, rootId: id3, causeId: null, depth: 0, urgent: false, body: "", facts: {}, choices: null, subject: null, dedupeKey: null, origin: null, legacyThread: null, createdAt: 0 };
149807
+ return { message: stub, row: null, relation: "", phantom: "gone" };
149808
+ }
149809
+ frameItem(recipient, m, relation, inline, maybeRepeated) {
149810
+ const about = asObj(m.facts.about).session;
149811
+ const answered = m.replyTo === null ? void 0 : this.records.message(m.replyTo);
149812
+ return {
149813
+ messageId: m.id,
149814
+ kind: m.kind,
149815
+ from: m.sender,
149816
+ relation,
149817
+ ...m.kind === "message" ? { needsReply: m.needsReply } : {},
149818
+ ...answered?.sender === recipient ? { answers: answered.id } : {},
149819
+ ...typeof m.facts.clarifies === "string" ? { clarifies: m.facts.clarifies } : {},
149820
+ ...typeof about === "string" && parseAddress(about) ? { about } : {},
149821
+ // The stored word `finished` is the host's knowledge that a turn ended, not that the work is done (#1902): the model reads it as that
149822
+ ...m.facts.outcome ? { outcome: m.facts.outcome === "finished" ? "turn_ended" : m.facts.outcome } : {},
149823
+ ...m.facts.error ? { error: m.facts.error } : {},
149824
+ ...m.facts.reason ? { reason: m.facts.reason } : {},
149825
+ ...m.facts.paused !== void 0 ? { paused: m.facts.paused } : {},
149826
+ ...m.facts.waitingOn !== void 0 && m.facts.waitingOn > 0 ? { waitingOn: m.facts.waitingOn } : {},
149827
+ ...m.facts.personNote === true ? { personNote: true } : {},
149828
+ ...maybeRepeated ? { maybeRepeated: true } : {},
149829
+ ...inline ? { inline: m.body } : {}
149830
+ };
149831
+ }
149832
+ };
149833
+ var citeKey = (seq) => `cite:${seq}`;
149834
+ var isHidden = (row) => HIDDEN_HOLDS.includes(row.held ?? "");
149835
+
149836
+ // packages/agent-host/src/mail/person.ts
149837
+ var THREAD_PAGE = 100;
149838
+ var LIST_CHAINS = 100;
149839
+ var LIST_SCAN = 1e3;
149840
+ var CHAIN_CAP = 1e3;
149841
+ var PREVIEW_CHARS2 = 140;
149842
+ var PERSON_HOLDS = ["uncertain", "failed", "loop", "budget", "policy"];
149843
+ function subjectLine(m) {
149844
+ const script = m.facts.fromScript?.credential;
149845
+ return plainLine(m.subject ?? (script === void 0 ? m.body : `The script "${script}": ${m.body}`), SUBJECT_CHARS);
149846
+ }
149847
+ var MailPerson = class {
149848
+ constructor(service, records, delivery, host) {
149849
+ this.service = service;
149850
+ this.records = records;
149851
+ this.delivery = delivery;
149852
+ this.host = host;
149853
+ }
149854
+ service;
149855
+ records;
149856
+ delivery;
149857
+ host;
149858
+ list() {
149859
+ const heldRows = this.records.heldRows();
149860
+ const heldBy = /* @__PURE__ */ new Map();
149861
+ const held3 = [];
149862
+ for (const r of heldRows) {
149863
+ const m = this.records.message(r.messageId);
149864
+ if (!m || r.held === null) continue;
149865
+ heldBy.set(m.rootId, (heldBy.get(m.rootId) ?? 0) + 1);
149866
+ held3.push({
149867
+ messageId: m.id,
149868
+ threadId: m.rootId,
149869
+ subject: this.subjectOf(m.rootId),
149870
+ sender: this.party(m.sender),
149871
+ recipient: this.party(r.recipient),
149872
+ kind: windowKind(m),
149873
+ reason: r.held,
149874
+ preview: plainLine(m.body, PREVIEW_CHARS2),
149875
+ since: m.createdAt
149876
+ });
149877
+ }
149878
+ const roots = [];
149879
+ for (const m of this.records.feedOf(PERSON, { limit: LIST_SCAN })) {
149880
+ if (!roots.includes(m.rootId)) roots.push(m.rootId);
149881
+ if (roots.length >= LIST_CHAINS) break;
149882
+ }
149883
+ const threads = roots.map((root3) => this.row(root3, heldBy.get(root3) ?? 0)).flatMap((r) => r ?? []).sort((a, b2) => Number(b2.unread > 0) - Number(a.unread > 0) || b2.updatedAt - a.updatedAt);
149884
+ return { threads, held: held3, waiting: this.delivery.crowdWaiting() };
149885
+ }
149886
+ /** A chain with its messages, which the person reads: what is returned is read for them. An old thread's id names the chain moved from it */
149887
+ thread(threadId, opts = {}) {
149888
+ const root3 = this.rootsOf(threadId)[0];
149889
+ if (root3 === void 0) throw refuse4("unknown_message", `There is no mail ${threadId} kept.`);
149890
+ const all = this.shown(root3);
149891
+ let page;
149892
+ if (opts.after !== void 0) page = all.filter((s) => s.seq > (opts.after ?? 0)).slice(0, opts.all ? void 0 : THREAD_PAGE);
149893
+ else if (opts.tail !== void 0 || !opts.all) {
149894
+ const upTo = opts.before === void 0 ? all : all.filter((s) => s.seq < (opts.before ?? 0));
149895
+ page = upTo.slice(-Math.min(opts.tail ?? THREAD_PAGE, THREAD_PAGE));
149896
+ } else page = all;
149897
+ this.readFor(page);
149898
+ const first = page[0]?.seq;
149899
+ const last = page.at(-1)?.seq;
149900
+ const legacy = this.legacyOf(all[0]?.m);
149901
+ const fromStart = first === void 0 || first === all[0]?.seq;
149902
+ const messages2 = [...(fromStart ? legacy : []).map((m, i) => legacyMessage(m, i - legacy.length + 1, (a) => this.party(a))), ...page.map((s) => this.message(s))];
149903
+ return {
149904
+ thread: this.row(root3, this.heldIn(root3)) ?? this.emptyRow(root3),
149905
+ parties: this.partiesOf(all.map((s) => s.m)),
149906
+ blockers: [],
149907
+ messages: messages2,
149908
+ more: last !== void 0 && all.some((s) => s.seq > last),
149909
+ older: first !== void 0 && all.some((s) => s.seq < first),
149910
+ follows: [],
149911
+ canReply: this.replyTarget([root3]) !== void 0
149912
+ };
149913
+ }
149914
+ /**
149915
+ * The person writes in a chain (every chain an old thread's id names): an answer to the newest question to them that waits for their answer, else to
149916
+ * the newest message sent to them, to its sender; else a word more to the ones the person's own newest message went to. A sender that is gone, and a
149917
+ * message hidden from the person, are passed over. A question waits for an answer (D3); an answer or a note does not
149918
+ */
149919
+ reply(threadId, text3, kind = "note", answers2) {
149920
+ const roots = this.rootsOf(threadId);
149921
+ const found = answers2 === void 0 ? this.replyTarget(roots) : this.pickTarget(roots, answers2);
149922
+ if (!found) throw refuse4("unknown_message", `There is no message in ${threadId} to answer.`);
149923
+ const { target, to } = found;
149924
+ const sent = this.service.send(PERSON, { to, text: text3, replyTo: target.id, needsReply: kind === "question", ...answers2 !== void 0 && target.choices?.includes(text3) ? { picked: true } : {} });
149925
+ const shown3 = this.shown(target.rootId);
149926
+ const answered = shown3.find((s) => s.m.id === target.id)?.seq ?? 0;
149927
+ this.readFor(shown3.filter((s) => s.seq <= answered));
149928
+ const at2 = shown3.find((s) => s.m.id === sent.message.id)?.seq ?? 1;
149929
+ return this.thread(target.rootId, { after: at2 - 1 });
149930
+ }
149931
+ /** What was shown the person is read for them, and every window's list hears it */
149932
+ readFor(shown3) {
149933
+ if (this.records.markRead(PERSON, shown3.flatMap((s) => this.records.recipient(s.m.id, PERSON)?.readAt === null ? [s.m.id] : []), Date.now()) > 0) this.service.announce();
149934
+ }
149935
+ /**
149936
+ * The message the person's word in these chains answers, and whom it goes to: the one `reply` writes to, and so what the window's reply box (`canReply`) is
149937
+ * offered for. Undefined when the chains hold nothing of the person's to answer: only mail between sessions held for them, or to sessions that are gone
149938
+ */
149939
+ replyTarget(roots) {
149940
+ const chain = roots.flatMap((root3) => this.shown(root3).map((s) => s.m)).sort((a, b2) => a.createdAt - b2.createdAt || (a.id < b2.id ? -1 : a.id > b2.id ? 1 : 0));
149941
+ const toPerson = this.toPerson(chain);
149942
+ const open6 = this.asking(chain).at(-1);
149943
+ const theirs = open6 ?? toPerson.at(-1);
149944
+ const mine = chain.findLast((m) => m.sender === PERSON && this.records.recipients(m.id).some((r) => this.here(r.recipient)));
149945
+ const target = theirs ?? mine;
149946
+ if (!target) return void 0;
149947
+ const to = target === theirs ? [target.sender] : this.records.recipients(target.id).flatMap((r) => this.here(r.recipient) ? [r.recipient] : []);
149948
+ return { target, to };
149949
+ }
149950
+ /**
149951
+ * The question a pick or the person's own words answer (#1630, #2191): the one the window names, which must be a question in these chains sent to the person
149952
+ * by a session that is still here, and not answered already (a question is answered once, whichever window gives the answer first)
149953
+ */
149954
+ pickTarget(roots, id3) {
149955
+ const target = roots.flatMap((root3) => this.shown(root3).map((s) => s.m)).find((m) => m.id === id3);
149956
+ const row = target && this.records.recipient(target.id, PERSON);
149957
+ if (!target || !row || hiddenFromPerson(row) || !this.here(target.sender)) return void 0;
149958
+ if (row.answerId !== null || row.settled !== null && row.settled !== "legacy") throw refuse4("answered", REFUSAL_TEXT.answered(id3));
149959
+ return { target, to: [target.sender] };
149960
+ }
149961
+ /** Whether mail to `address` can still reach it: a session this host keeps (trashed or deleted ones are gone), or any other party */
149962
+ here(address) {
149963
+ const party = parseAddress(address);
149964
+ return party?.kind !== "session" || this.host.session(party.sessionId) !== void 0;
149965
+ }
149966
+ /**
149967
+ * The person's Mark done (`finished`) or Drop (`dropped`), at once, on the whole chain and on every chain an old thread's id names (plan C12): nothing
149968
+ * in it waits for them any more, and what they asked in it is withdrawn (their tasks and the questions they put that are still open, settled `withdrawn`:
149969
+ * undelivered ones are never delivered, and no report of them is written). Nothing is stopped: the turn may carry other requests, and the
149970
+ * person's Stop is the way to stop one. The session whose turn is on the chain, and each one that was asked something there and was delivered it, is told
149971
+ * once, in a notice from Centralu that wakes nobody (`closedWords`), so it can stop that work itself; it reads it in the turn it is in when its tool takes
149972
+ * input there, else with its next mail. What it sends in the chain after that is mail to the person like any: it reaches them in the same chain, which
149973
+ * is listed again as open and unread
149974
+ */
149975
+ close(threadId, outcome = "finished") {
149976
+ const roots = this.rootsOf(threadId);
149977
+ const root3 = roots[0];
149978
+ if (root3 === void 0) throw refuse4("unknown_message", `There is no mail ${threadId} kept.`);
149979
+ const now = Date.now();
149980
+ const tell = /* @__PURE__ */ new Map();
149981
+ this.records.transaction(() => {
149982
+ for (const r of roots) {
149983
+ const chain = this.chainOf(r);
149984
+ const asked = [];
149985
+ for (const m of chain) {
149986
+ if (m.sender !== PERSON || !(m.needsReply || m.kind === "task")) continue;
149987
+ for (const row of this.records.recipients(m.id)) if (row.settled === null) asked.push({ id: m.id, recipient: row.recipient, seen: row.deliveredAt !== null || row.attemptAt !== null || row.held === "uncertain" });
149988
+ }
149989
+ const working = this.workers(chain);
149990
+ const readable = this.shown(r).map((s) => s.m.id);
149991
+ this.records.closeFor(PERSON, readable, now);
149992
+ this.records.markRead(PERSON, readable, now);
149993
+ const withdrawn = asked.filter((a) => this.records.settle(a.id, a.recipient, "withdrawn", now) > 0);
149994
+ for (const m of chain) {
149995
+ if (m.sender === PERSON && (m.needsReply || m.kind === "task")) for (const row of this.records.recipients(m.id)) this.records.settle(m.id, row.recipient, "done", now);
149996
+ }
149997
+ this.records.markClosed(r, outcome, now);
149998
+ const end = chain.at(-1)?.id ?? r;
149999
+ const add2 = (sessionId, address, id3) => {
150000
+ const kept = tell.get(sessionId) ?? { address, root: r, ids: [], ends: [] };
150001
+ if (id3 !== void 0 && !kept.ids.includes(id3)) kept.ids.push(id3);
150002
+ if (!kept.ends.includes(end)) kept.ends.push(end);
150003
+ tell.set(sessionId, kept);
150004
+ };
150005
+ for (const w of working) add2(w.sessionId, w.address);
150006
+ for (const a of withdrawn) {
150007
+ const party = parseAddress(a.recipient);
150008
+ if (party?.kind !== "session" || !a.seen || !this.here(a.recipient)) continue;
150009
+ add2(party.sessionId, a.recipient, a.id);
150010
+ }
150011
+ }
150018
150012
  });
150013
+ for (const r of roots) this.service.announce(r);
150014
+ for (const [sessionId, t] of tell) this.tellClosed(outcome, sessionId, t);
150015
+ return this.row(root3, this.heldIn(root3)) ?? this.emptyRow(root3);
150019
150016
  }
150020
- // ── Parties that go, parties that take over (§7.7) ──
150021
150017
  /**
150022
- * The handoff (§7.7, §10.6.5), its one move: `from`'s unsettled watched rows and unread mail move to `to`, and the tasks `from` gave the sessions that
150023
- * move (`children`) become `to`'s; the successor is told of each message. Called inside the children's move
150018
+ * One notice to a session about the chain it worked on being closed: its key names the session and the last message of each chain, so a second close of
150019
+ * the same chain tells nothing again, and one after the chain went on (a reply, a new request) does. In the process now when it takes it there, else as
150020
+ * mail. A process that fails to take it leaves the notice as undelivered mail, which goes again with the session's next mail
150024
150021
  */
150025
- handOver(from, to, scope, children = scope === "all" ? [] : scope.senders) {
150026
- return this.run(() => {
150027
- const plan = this.handOverPreview(from, to, scope);
150028
- const fresh = plan.filter((p) => this.records.recipient(p.messageId, to) === void 0);
150029
- this.records.moveRows(from, to, scope);
150030
- for (const row of this.records.watchedFrom(from)) {
150031
- const m = children.includes(row.recipient) ? this.records.message(row.messageId) : void 0;
150032
- if (m?.kind !== "task") continue;
150033
- this.records.settle(m.id, row.recipient, "withdrawn", this.now());
150034
- const again = this.put({ sender: to, kind: "task", body: m.body, causeId: m.causeId, origin: m.origin, facts: m.facts }, [this.row(row.recipient, { dueAt: row.dueAt, deliveredAt: row.deliveredAt, readAt: row.readAt })]);
150035
- if (row.releasedAt !== null && row.releasedWhy !== null) this.records.markReleased(again.id, row.recipient, row.releasedAt, row.releasedWhy);
150036
- }
150037
- this.movedNotice(to, fresh.map((p) => p.messageId));
150038
- return plan;
150022
+ tellClosed(outcome, sessionId, t) {
150023
+ const text3 = closedWords(t.root, outcome, t.ids);
150024
+ const now = this.host.tellsNow(sessionId);
150025
+ const stored = this.service.notice(t.address, {
150026
+ body: text3,
150027
+ facts: { quiet: true, chainClosed: { root: t.root, outcome, withdrawn: t.ids.slice(0, 10) } },
150028
+ dedupeKey: `closed:${t.address}:${t.ends.join(",")}`,
150029
+ delivered: now
150039
150030
  });
150040
- }
150041
- /** What `handOver` would move, read only: each message by id and the first line of its words, for the handoff note to quote */
150042
- handOverPreview(from, to, scope = "all") {
150043
- return this.records.movable(from, to, scope).flatMap((id3) => {
150044
- const m = this.records.message(id3);
150045
- return m ? [{ messageId: id3, firstLine: firstLineOf(m.body, 160), kind: m.kind, unread: this.records.recipient(id3, from)?.readAt === null, ...m.facts.about ? { about: m.facts.about.session } : {} }] : [];
150031
+ if (!stored || !now) return;
150032
+ const at2 = this.records.recipient(stored.id, t.address)?.deliveredAt;
150033
+ this.host.tell(sessionId, text3).catch(() => {
150034
+ if (at2 != null) this.service.deliveryFailedLate(t.address, [stored.id], at2);
150046
150035
  });
150047
150036
  }
150048
- /** The Assistant's role is `to`'s (D15): rows sent to the role that another session held are delivered afresh, read or not, and the new Assistant is told of each. Returns how many */
150049
- roleMoved(to) {
150050
- return this.run(() => {
150051
- const ids = this.records.moveRole(to);
150052
- this.movedNotice(to, ids);
150053
- return ids.length;
150054
- });
150037
+ /**
150038
+ * The person's Release (Send again, Retry) or Dismiss of held rows. A row an earlier build held for a session's budget goes as the mail it is. A
150039
+ * row held for its project's trust goes when the person trusts the project (§7.4): its Release says so. A dismissed answer leaves its question open (D8)
150040
+ */
150041
+ held(action, recipient, messageIds) {
150042
+ if (action === "dismiss") return { changed: this.service.dismissHeld(recipient, messageIds, PERSON_HOLDS) };
150043
+ const projects = new Set(messageIds.flatMap((id3) => this.records.recipient(id3, recipient)?.held === "policy" ? this.records.message(id3)?.senderProject ?? [] : []));
150044
+ const still = [...projects].find((p) => this.host.untrusted(p));
150045
+ if (still !== void 0) throw refuse4("untrusted_project", `${this.host.projectLabel(still)} is not trusted: what its sessions send out of it waits until you trust the project, and then goes in order.`);
150046
+ const policy = messageIds.filter((id3) => this.records.recipient(id3, recipient)?.held === "policy");
150047
+ for (const p of projects) this.trusted(p);
150048
+ const letGo = policy.filter((id3) => this.records.recipient(id3, recipient)?.held !== "policy").length;
150049
+ return { changed: letGo + this.service.resendHeld(recipient, messageIds, ["uncertain", "failed", "budget"]) };
150055
150050
  }
150056
- sweep() {
150057
- return this.records.sweep(this.now());
150051
+ /**
150052
+ * Resume on what an earlier build paused (#2014: nothing pauses mail now): a session's rows held `budget`, or a chain's held `loop` (an old thread's id
150053
+ * names the chains moved from it). They go as the mail they are, and a previous build still serving during a swap does not hold them again
150054
+ */
150055
+ resume(target) {
150056
+ const rows3 = this.records.heldRows();
150057
+ if (target.sessionId !== void 0) {
150058
+ const recipient = this.service.sessionAddress(target.sessionId);
150059
+ const ids = rows3.flatMap((r) => r.recipient === recipient && r.held === "budget" ? [r.messageId] : []);
150060
+ if (ids.length > 0) this.service.resendHeld(recipient, ids, ["budget"]);
150061
+ } else if (target.threadId !== void 0) {
150062
+ const roots = new Set(this.rootsOf(target.threadId));
150063
+ const ids = new Set(rows3.flatMap((r) => r.held === "loop" && roots.has(this.records.message(r.messageId)?.rootId ?? "") ? [r.messageId] : []));
150064
+ for (const id3 of ids) this.service.resumeHeld(id3);
150065
+ }
150058
150066
  }
150059
- // ── Inside ──
150060
- /** A message stored for its recipients; the change is queued for the listeners. A missing reply target is the sender's `unknown_message` */
150061
- put(mail, rows3) {
150062
- const now = this.now();
150063
- let stored;
150064
- try {
150065
- stored = this.records.insert(
150066
- { id: messageIdOf(this.opts.hostId, this.ulids.next(now)), senderProject: this.reach.projectOf(mail.sender), needsReply: false, replyTo: null, causeId: null, depth: 0, urgent: false, facts: {}, choices: null, dedupeKey: null, legacyThread: null, createdAt: now, ...mail },
150067
- rows3
150068
- );
150069
- } catch (e) {
150070
- if (e instanceof MailTargetMissing) throw refuse4("unknown_message", REFUSAL_TEXT.unknown_message(e.replyTo));
150071
- throw e;
150067
+ /** The person trusted a project (§7.4): what its sessions sent that was held for it goes, in order, and the callers refused are told */
150068
+ trusted(projectId) {
150069
+ for (const address of this.service.trustChanged(projectId)) {
150070
+ const party = parseAddress(address);
150071
+ if (party?.kind === "session") this.delivery.poke(party.sessionId);
150072
150072
  }
150073
- if (!stored.duplicate) this.queued.push({ messageId: stored.id, rootId: stored.rootId, recipients: rows3.map((r) => r.recipient), arrived: true });
150074
- return stored;
150073
+ this.service.announce();
150075
150074
  }
150076
- changed(m, recipients) {
150077
- this.queued.push({ messageId: m.id, rootId: m.rootId, recipients: [...recipients] });
150075
+ /** A project was deleted: the mail held for its trust is dropped and its senders are told, naming it as it was named (§7.4) */
150076
+ projectDeleted(projectId, name) {
150077
+ this.service.dismissProject(projectId, name);
150078
+ this.service.announce();
150078
150079
  }
150079
- row(recipient, over) {
150080
- return { recipient, recipientProject: this.reach.projectOf(recipient), ...over };
150080
+ /** The project's name now, for `projectDeleted` once it is gone */
150081
+ projectName(projectId) {
150082
+ return this.host.projectLabel(projectId);
150081
150083
  }
150082
- /** A message from Centralu to `recipient`: not a sender's, so no guard applies. `delivered` writes it already delivered and read */
150083
- centralu(recipient, m) {
150084
- const now = this.now();
150085
- return this.put(
150086
- { sender: CENTRALU, kind: m.kind, body: this.checkText("centralu", m.body), facts: m.facts, dedupeKey: m.dedupeKey, replyTo: m.replyTo ?? null, origin: "centralu" },
150087
- [this.row(recipient, { dueAt: dueAt(now, false, false), ...m.delivered ? { deliveredAt: now, readAt: now } : {} })]
150088
- );
150084
+ /**
150085
+ * The answer is taken at once: waking a crowd resumes the sessions two at a time and takes as long as that takes, longer than a
150086
+ * window waits for an answer. The list shows who is still waiting as it goes
150087
+ */
150088
+ wake(wake) {
150089
+ this.delivery.answerCrowd(wake).catch((e) => console.error(`[mail] waking the sessions failed: ${errorMessage(e)}`));
150089
150090
  }
150090
- checkText(cls, text3) {
150091
- if (typeof text3 !== "string") throw refuse4("bad_value", "a body is text");
150092
- if (text3.trim() === "") throw refuse4("empty", "a post says something");
150093
- if (text3.length > bodyLimit(cls)) throw refuse4("too_long", tooLongText(cls));
150094
- return text3;
150091
+ // ── Chains ──
150092
+ /** Every message of the chain, readable by the person or not: what a turn's work may be */
150093
+ chainOf(root3) {
150094
+ return this.records.numbered(root3, CHAIN_CAP).map(({ m }) => m);
150095
150095
  }
150096
- refusalText(why2, to) {
150097
- const text3 = {
150098
- gone: REFUSAL_TEXT.gone(to),
150099
- no_mailbox: REFUSAL_TEXT.no_mailbox(),
150100
- elsewhere: REFUSAL_TEXT.elsewhere(to),
150101
- assistant_asks: REFUSAL_TEXT.assistant_asks(),
150102
- not_allowed: REFUSAL_TEXT.not_allowed()
150103
- };
150104
- return text3[why2] ?? why2;
150096
+ /** The sessions of the chain whose turn going now is on it: the turn records name a message of the chain as that turn's work (or its starter) */
150097
+ workers(chain) {
150098
+ const ids = new Set(chain.map((m) => m.id));
150099
+ const sessions = /* @__PURE__ */ new Map();
150100
+ for (const m of chain) {
150101
+ for (const address of [m.sender, ...this.records.recipients(m.id).map((r) => r.recipient)]) {
150102
+ const party = parseAddress(address);
150103
+ if (party?.kind === "session") sessions.set(party.sessionId, address);
150104
+ }
150105
+ }
150106
+ return [...sessions].flatMap(([sessionId, address]) => {
150107
+ const turn = this.host.turnOn(sessionId);
150108
+ return turn && turn.work !== null && ids.has(turn.work) ? [{ sessionId, address }] : [];
150109
+ });
150105
150110
  }
150106
- /** The message `id` as `reader` may read it (§5.5): one it sent, or one it is a recipient of and is not held from it. Anything else is not there for it */
150107
- readable(reader, id3) {
150111
+ /** Every chain an id names: a message's root, or each chain moved from an old thread, newest first */
150112
+ rootsOf(id3) {
150108
150113
  const m = this.records.message(id3);
150109
- const row = m && m.sender !== reader ? this.records.recipient(id3, reader) : void 0;
150110
- if (!m || m.sender !== reader && (!row || isHidden(row))) throw refuse4("unknown_message", REFUSAL_TEXT.unknown_message(id3));
150111
- return m;
150112
- }
150113
- /** Whether `target` is a clarification of a task `owner` gave, and the answer goes to the one who asked (§9.7) */
150114
- answersClarification(owner, target, to) {
150115
- const task = typeof target.facts.clarifies === "string" ? this.records.message(target.facts.clarifies) : void 0;
150116
- return task?.kind === "task" && task.sender === owner && to.length === 1 && to[0] === target.sender;
150114
+ return m ? [m.rootId] : this.records.movedFrom(id3);
150117
150115
  }
150118
150116
  /**
150119
- * Whether a message is a request to the Assistant (§7.6): from a session to the Assistant, unless it answers a `needsReply` message or a task the
150120
- * assistant sent that session, or is a clarification. Only requests are counted by `ask_rate` and raise the person's cards
150117
+ * The chain's messages the person may read, in the order they were stored, each numbered for the window by its own row number: a message that comes,
150118
+ * goes or stops being readable leaves the others' numbers as they were, so the window's `after` misses nothing
150121
150119
  */
150122
- isRequest(m, recipient) {
150123
- if (m.kind !== "message" && m.kind !== "task" || m.sender === recipient || !this.reach.isAssistant(recipient)) return false;
150124
- if (parseAddress(m.sender)?.kind !== "session" || typeof m.facts.clarifies === "string") return false;
150125
- const target = m.replyTo === null ? void 0 : this.records.message(m.replyTo);
150126
- return !(target && target.sender === recipient && (target.needsReply || target.kind === "task"));
150120
+ shown(root3) {
150121
+ return this.records.numbered(root3, CHAIN_CAP).map(({ m, n }) => ({ m, seq: n })).filter((s) => this.readable(s.m));
150127
150122
  }
150128
- /**
150129
- * Whether a message was given in the recipient's open turn (§4.2): its row names the turn, or it is the work message of a turn the delivery began,
150130
- * whose rows are marked once the tool took them. Not another row held from the recipient: what it was not woken for has not joined the turn
150131
- */
150132
- inOpenTurn(m, row, turn) {
150133
- if (!turn || !row) return false;
150134
- if (turn.by === "mail" && turn.messageId === m.id) return true;
150135
- return row.turnSeq === turn.turnSeq && (row.held === null || row.held === "released");
150123
+ /** The person reads what they sent, what was sent to them, and what is held for them to act on (§5.5, §7.4) */
150124
+ readable(m) {
150125
+ if (m.sender === PERSON) return true;
150126
+ return this.records.recipients(m.id).some((r) => r.recipient === PERSON && !hiddenFromPerson(r) || isPersonHold(r.held));
150136
150127
  }
150137
- /** The message that started `sender`'s turn, when a message did (not the person, not the session itself): what a send in that turn is caused by (§8.2 step 6) */
150138
- causeOf(sender) {
150139
- const turn = this.opts.turn?.(sender) ?? null;
150140
- return turn !== null && turn.by !== "person" && turn.by !== "cli" ? turn.starter : null;
150128
+ /** An old thread's messages before the first one moved from it: the chain's history, read-only (§6.3) */
150129
+ legacyOf(first) {
150130
+ if (!first?.legacyThread) return [];
150131
+ const moved = new Set(this.records.byRoot(first.rootId, { limit: CHAIN_CAP }).map((m) => m.id));
150132
+ const earlier = [];
150133
+ for (const m of this.host.legacyChain(first.legacyThread)) {
150134
+ if (m.id === first.id || moved.has(m.id)) break;
150135
+ earlier.push(m);
150136
+ }
150137
+ return earlier;
150141
150138
  }
150142
- /** The answer `answer` to `question` is held for the person: the question stays open (it keeps the answer's id) and its asker is told once, quietly (S14) */
150143
- answerHeld(question, answer) {
150144
- this.records.answerHeld(question.id, answer.sender, answer.id);
150145
- if (parseAddress(question.sender)?.kind !== "session") return;
150146
- const reason = `${this.reach.projectLabel(answer.senderProject ?? "")} is not trusted`;
150147
- this.centralu(question.sender, {
150148
- kind: "notice",
150149
- body: `${this.reach.labelOf(answer.sender)} answered your ${question.id} with ${answer.id}, and the answer is held for the person (${reason}). It reaches you if the person lets it through; until then Centralu does not remind ${this.reach.labelOf(answer.sender)} of it.`,
150150
- facts: { quiet: true, answerHeld: { question: question.id, answer: answer.id } },
150151
- dedupeKey: `answer_held:${question.sender}:${answer.id}:policy`
150152
- });
150139
+ heldIn(root3) {
150140
+ return this.records.heldRows().filter((r) => this.records.message(r.messageId)?.rootId === root3).length;
150153
150141
  }
150154
- /** Rows came to `to` from another holder (a handoff, the role's move): one quiet notice for the move, so it knows why the messages are there (key `handover:`) */
150155
- movedNotice(to, messageIds) {
150156
- if (messageIds.length === 0 || parseAddress(to)?.kind !== "session") return;
150157
- this.centralu(to, {
150158
- kind: "notice",
150159
- body: messageIds.length === 1 ? "A message addressed to the previous holder was moved to you." : `${messageIds.length} messages addressed to the previous holder were moved to you.`,
150160
- facts: { quiet: true, handedOver: true },
150161
- dedupeKey: `handover:${to}:${hash16(messageIds)}`
150162
- });
150142
+ subjectOf(root3) {
150143
+ const first = this.shown(root3)[0]?.m ?? this.records.message(root3);
150144
+ return first ? subjectLine(first) : root3;
150163
150145
  }
150164
- /** A reminder whose messages are all settled (or gone) has nothing to say (§8.2 step 1) */
150165
- reminderSettled(m, recipient) {
150166
- return m.kind === "notice" && m.facts.reminder !== void 0 && (m.facts.of ?? []).every((id3) => {
150167
- const row = this.records.recipient(id3, recipient);
150168
- return row === void 0 || row.settled !== null;
150146
+ /**
150147
+ * A chain as the window's list row. Done when the person closed it (`facts.closed` on its root, or an older close: a row to them settled `done`) and
150148
+ * nothing in it waits for them or for an answer to them, with how they closed it. Otherwise running while a session's turn is on it or a task the person gave in it is
150149
+ * neither reported nor released by a stop, in review once such a task is reported, and open for the rest; the person may always write in a chain that is not done. The session
150150
+ * named on it is the one whose turn is on it, else the first one the person's first message went to
150151
+ */
150152
+ row(root3, held3) {
150153
+ const all = this.shown(root3).map((s) => s.m);
150154
+ const first = all[0];
150155
+ const last = all.at(-1);
150156
+ if (!first || !last) return null;
150157
+ const toPerson = all.flatMap((m) => this.records.recipient(m.id, PERSON) ?? []);
150158
+ const tasks = all.filter((m) => m.sender === PERSON && m.kind === "task").flatMap((m) => this.records.recipients(m.id).filter((r) => parseAddress(r.recipient)?.kind === "session"));
150159
+ const waits = toPerson.some((r) => r.settled === null) || all.some((m) => m.sender === PERSON && (m.needsReply || m.kind === "task") && this.records.recipients(m.id).some((r) => r.settled === null));
150160
+ const closedAs = this.records.message(root3)?.facts.closed?.outcome;
150161
+ const done2 = (closedAs !== void 0 || toPerson.some((r) => r.settled === "done") || tasks.some((r) => r.settled === "done")) && !waits;
150162
+ const working = done2 ? [] : this.workers(this.chainOf(root3));
150163
+ const state = done2 ? "done" : working.length > 0 || tasks.some((r) => r.settled === null && r.releasedAt === null) ? "running" : tasks.some((r) => r.settled === "reported") ? "review" : "open";
150164
+ const asking = done2 ? [] : this.asking(all);
150165
+ const asked = asking.at(-1);
150166
+ const assignee = working[0]?.address ?? (first.sender === PERSON ? this.records.recipients(first.id)[0]?.recipient : void 0);
150167
+ return {
150168
+ id: root3,
150169
+ subject: subjectLine(first),
150170
+ state,
150171
+ outcome: done2 ? closedAs ?? "finished" : null,
150172
+ next: null,
150173
+ projectId: first.senderProject,
150174
+ owner: this.party(first.sender),
150175
+ assignee: assignee === void 0 ? null : this.party(assignee),
150176
+ ask: asked ? mailAsk(asked, this.party(asked.sender), asking.map((m) => m.id)) : null,
150177
+ unread: toPerson.filter((r) => r.readAt === null && !hiddenFromPerson(r)).length,
150178
+ held: held3,
150179
+ blocked: 0,
150180
+ working: working.length > 0,
150181
+ createdAt: first.createdAt,
150182
+ updatedAt: last.createdAt,
150183
+ last: { sender: this.party(last.sender), kind: windowKind(last), preview: plainLine(last.body, PREVIEW_CHARS2), at: last.createdAt }
150184
+ };
150185
+ }
150186
+ /** The messages in a chain sent to the person, in its order: not by Centralu, from a sender that is still here (one that is gone cannot be answered), and that they may read */
150187
+ toPerson(chain) {
150188
+ return chain.filter((m) => {
150189
+ const row = this.records.recipient(m.id, PERSON);
150190
+ return m.sender !== PERSON && parseAddress(m.sender)?.kind !== "centralu" && row !== void 0 && !hiddenFromPerson(row) && this.here(m.sender);
150169
150191
  });
150170
150192
  }
150171
- /** The task this delivery's report hands on from (§8.2 step 3): the report is of a task the recipient gave while it worked on one still open */
150172
- handedOnFrom(m, recipient) {
150173
- const task = m.kind === "report" && m.replyTo !== null ? this.records.message(m.replyTo) : void 0;
150174
- const cause2 = task?.causeId ? this.records.message(task.causeId) : void 0;
150175
- return cause2?.kind === "task" && this.records.recipient(cause2.id, recipient)?.settled === null ? cause2.id : void 0;
150193
+ /**
150194
+ * The messages in a chain that wait on the person's answer, oldest first: the one definition of an open question. A message to them that asks for an
150195
+ * answer (a session's question, or one that needs a reply) and is not answered or settled yet. The row's `ask` (#2229), the reply box's target
150196
+ * (`replyTarget`) and the thread's `ask.open` all come from here; a window works nothing out of its own
150197
+ */
150198
+ asking(chain) {
150199
+ return this.toPerson(chain).filter((m) => {
150200
+ const row = this.records.recipient(m.id, PERSON);
150201
+ return m.needsReply && row !== void 0 && row.answerId === null && (row.settled === null || row.settled === "legacy");
150202
+ });
150176
150203
  }
150177
- /** Mail whose delivery may or may not have gone: news and Centralu's own words go again, the rest is held `uncertain` for the person */
150178
- settleUncertain(recipient, ids) {
150179
- const messages2 = ids.flatMap((id3) => this.records.message(id3) ?? []);
150180
- const again = messages2.filter((m) => m.kind === "notice" || m.sender === CENTRALU).map((m) => m.id);
150181
- const unsure = messages2.filter((m) => !again.includes(m.id)).map((m) => m.id);
150182
- if (again.length > 0) this.records.markMaybeRepeated(recipient, again, this.now());
150183
- if (unsure.length > 0) this.records.markUncertain(recipient, unsure);
150184
- for (const m of messages2) this.changed(m, again.includes(m.id) ? [recipient, PERSON] : [PERSON]);
150185
- return { resent: again.length, held: unsure.length };
150204
+ /** A chain whose every message the person may not read (held for them, then let go): a row with nothing in it */
150205
+ emptyRow(root3) {
150206
+ const m = this.records.message(root3);
150207
+ const at2 = m?.createdAt ?? 0;
150208
+ return { id: root3, subject: m ? subjectLine(m) : root3, state: "open", outcome: null, next: null, projectId: null, owner: this.party(m?.sender ?? PERSON), assignee: null, ask: null, unread: 0, held: 0, blocked: 0, working: false, createdAt: at2, updatedAt: at2, last: null };
150186
150209
  }
150187
- /** The ids of those of `ids` that `recipient`'s rows hold for one of `why` */
150188
- heldBy(recipient, ids, why2) {
150189
- return ids.filter((id3) => why2.includes(this.records.recipient(id3, recipient)?.held ?? ""));
150210
+ // ── Shapes ──
150211
+ /** The windows' `mail_changed` for a change to the mail (main.ts): a new message the person can read also names itself, for the OS notification (#1630) */
150212
+ changeEvent(c) {
150213
+ const toPerson = c.recipients.includes(PERSON);
150214
+ const arrived = c.arrived && toPerson ? this.arrival(c.messageId) : void 0;
150215
+ return { type: "mail_changed", threadId: c.rootId, toPerson, ...arrived ? { arrived } : {} };
150190
150216
  }
150191
- // ── What the reader sees ──
150192
- /** Centralu's word for how the sender stands to the receiver (§8.3). Never a name another party wrote */
150193
- relation(recipient, m) {
150194
- const kind = parseAddress(m.sender)?.kind;
150195
- if (kind === "centralu") return "Centralu";
150196
- if (kind === "person") return "the person";
150197
- if (kind === "app") return "an app you called";
150198
- if (this.isRequest(m, recipient)) return "a session asking you for something";
150199
- if (this.reach.parentOf(recipient) === m.sender) return "your parent session";
150200
- if (this.reach.parentOf(m.sender) === recipient) return "your child session";
150201
- const target = m.replyTo === null ? void 0 : this.records.message(m.replyTo);
150202
- if (target?.kind === "task" && target.sender === recipient) return "the session you gave this work to";
150203
- if (this.reach.isAssistant(m.sender)) return "the Assistant";
150204
- const mine = this.reach.projectOf(recipient);
150205
- return mine !== null && mine === this.reach.projectOf(m.sender) ? "a session of your project" : "a session of another project";
150217
+ /** A new message as the person's notification names it (`mail_changed.arrived`): one they can read, not their own */
150218
+ arrival(messageId) {
150219
+ const m = this.records.message(messageId);
150220
+ const row = this.records.recipient(messageId, PERSON);
150221
+ if (!m || !row || m.sender === PERSON || hiddenFromPerson(row) || row.held !== null) return void 0;
150222
+ return { messageId, from: this.party(m.sender), kind: windowKind(m), preview: plainLine(m.body, PREVIEW_CHARS2) };
150206
150223
  }
150207
- /** A message as `reader` sees it: whole, or a phantom without its words (§5.5), or a request whose words are for the turn it is in only (§7.6) */
150208
- item(m, reader, turn) {
150209
- const row = this.records.recipient(m.id, reader) ?? null;
150210
- const relation = this.relation(reader, m);
150211
- if (m.sender !== reader && (!row || isHidden(row))) return { message: { ...m, body: "", facts: {} }, row: null, relation, phantom: row ? "held" : "not_sent" };
150212
- if (this.isRequest(m, reader) && !this.inOpenTurn(m, row ?? void 0, turn)) return { message: { ...m, body: "" }, row, relation, withheld: true };
150213
- return { message: m, row, relation };
150224
+ party(address) {
150225
+ const p = parseAddress(address);
150226
+ if (p?.kind === "session") {
150227
+ const s = this.host.session(p.sessionId);
150228
+ return { address, kind: "session", sessionId: p.sessionId, name: s?.name ?? null, state: s?.state ?? null };
150229
+ }
150230
+ if (p?.kind === "app") return { address, kind: "app", sessionId: null, name: p.appId, state: null };
150231
+ return { address, kind: p?.kind ?? "unknown", sessionId: null, name: null, state: null };
150214
150232
  }
150215
- /** The line for an earlier message that is no longer kept (S5) */
150216
- gone(id3) {
150217
- const stub = { id: id3, sender: "", senderProject: null, kind: "notice", needsReply: false, replyTo: null, rootId: id3, causeId: null, depth: 0, urgent: false, body: "", facts: {}, choices: null, dedupeKey: null, origin: null, legacyThread: null, createdAt: 0 };
150218
- return { message: stub, row: null, relation: "", phantom: "gone" };
150233
+ partiesOf(chain) {
150234
+ const addresses = /* @__PURE__ */ new Set();
150235
+ for (const m of chain) {
150236
+ addresses.add(m.sender);
150237
+ for (const r of this.records.recipients(m.id)) addresses.add(r.recipient);
150238
+ }
150239
+ return [...addresses].filter((a) => parseAddress(a)?.kind === "session" || parseAddress(a)?.kind === "app").map((a) => ({ party: this.party(a), role: "member" }));
150219
150240
  }
150220
- frameItem(recipient, m, relation, inline, maybeRepeated) {
150221
- const about = asObj(m.facts.about).session;
150222
- const answered = m.replyTo === null ? void 0 : this.records.message(m.replyTo);
150241
+ message({ m, seq }) {
150223
150242
  return {
150224
- messageId: m.id,
150225
- kind: m.kind,
150226
- from: m.sender,
150227
- relation,
150228
- ...m.kind === "message" ? { needsReply: m.needsReply } : {},
150229
- ...answered?.sender === recipient ? { answers: answered.id } : {},
150230
- ...typeof m.facts.clarifies === "string" ? { clarifies: m.facts.clarifies } : {},
150231
- ...typeof about === "string" && parseAddress(about) ? { about } : {},
150232
- // The stored word `finished` is the host's knowledge that a turn ended, not that the work is done (#1902): the model reads it as that
150233
- ...m.facts.outcome ? { outcome: m.facts.outcome === "finished" ? "turn_ended" : m.facts.outcome } : {},
150234
- ...m.facts.error ? { error: m.facts.error } : {},
150235
- ...m.facts.reason ? { reason: m.facts.reason } : {},
150236
- ...m.facts.paused !== void 0 ? { paused: m.facts.paused } : {},
150237
- ...m.facts.waitingOn !== void 0 && m.facts.waitingOn > 0 ? { waitingOn: m.facts.waitingOn } : {},
150238
- ...m.facts.personNote === true ? { personNote: true } : {},
150239
- ...maybeRepeated ? { maybeRepeated: true } : {},
150240
- ...inline ? { inline: m.body } : {}
150243
+ id: m.id,
150244
+ seq,
150245
+ sender: this.party(m.sender),
150246
+ kind: windowKind(m),
150247
+ urgent: m.urgent,
150248
+ body: m.body,
150249
+ facts: { ...m.facts },
150250
+ ...m.choices ? { choices: m.choices } : {},
150251
+ ...m.replyTo !== null ? { replyTo: m.replyTo } : {},
150252
+ createdAt: m.createdAt,
150253
+ ...m.sender === PERSON ? { receipts: this.records.recipients(m.id).map((r) => ({ recipient: this.party(r.recipient), delivered: r.deliveredAt !== null, read: r.readAt !== null, handled: r.settled !== null })) } : {}
150241
150254
  };
150242
150255
  }
150243
150256
  };
150244
- var citeKey = (seq) => `cite:${seq}`;
150245
- var isHidden = (row) => HIDDEN_HOLDS.includes(row.held ?? "");
150257
+ function closedWords(root3, outcome, ids) {
150258
+ const what = outcome === "dropped" ? "dropped" : outcome === "finished" ? "marked done" : "closed";
150259
+ const shown3 = ids.slice(0, 10).join(", ") + (ids.length > 10 ? `, and ${ids.length - 10} more` : "");
150260
+ const withdrew = ids.length === 0 ? "" : ` and withdrew what they asked of you in it (${shown3})`;
150261
+ return `The person ${what} the mail that began with ${root3}${withdrew}. Do not continue that work. Centralu did not stop your turn: if you are still working on it, stop it yourself. What you send in it still reaches the person.`;
150262
+ }
150263
+ function windowKind(m) {
150264
+ if (typeof m.facts.legacyKind === "string") return m.facts.legacyKind;
150265
+ if (m.kind === "task") return "assign";
150266
+ if (m.kind === "message") return m.needsReply ? "question" : m.replyTo === null ? "note" : "answer";
150267
+ return m.kind;
150268
+ }
150269
+ function legacyMessage(m, seq, party) {
150270
+ return { id: m.id, seq, sender: party(m.sender), kind: m.kind, urgent: m.urgent, body: m.body, facts: { ...m.facts }, createdAt: m.createdAt };
150271
+ }
150272
+ function isPersonHold(held3) {
150273
+ return PERSON_HOLDS.some((h) => h === held3);
150274
+ }
150275
+ function hiddenFromPerson(r) {
150276
+ return r.held === "policy" || r.held === "loop" || r.held === "dismissed" || r.settled === "withdrawn" || r.settled === "gone";
150277
+ }
150278
+
150279
+ // packages/agent-host/src/mail/adoption.ts
150280
+ var RETIRED_SESSION_KEYS = ["turn_inputs", "report_turn", "input_origins", "report_paused", "person_report_paused"];
150281
+ function takeOverFromEarlierBuild(mail, store2, sessions) {
150282
+ let queued2 = 0;
150283
+ for (const r of store2.children.listQueuedRequests()) {
150284
+ if (!SEND_ORIGINS.has(r.via)) continue;
150285
+ try {
150286
+ store2.mailbox.transaction(() => {
150287
+ if (sessions.info(r.sessionId) && sessions.info(r.callerSessionId)) {
150288
+ mail.task(mail.sessionAddress(r.callerSessionId), mail.sessionAddress(r.sessionId), { text: r.text, origin: r.via, delivered: false });
150289
+ queued2++;
150290
+ }
150291
+ store2.children.removeQueuedRequest(r.id);
150292
+ });
150293
+ } catch (e) {
150294
+ console.error(`[mail] could not take the request an earlier build queued for ${r.sessionId.slice(0, 8)} (${errorMessage(e)})`);
150295
+ }
150296
+ }
150297
+ let adopted = 0;
150298
+ for (const mark of store2.children.listReportMarks()) {
150299
+ const child = sessions.info(mark.sessionId);
150300
+ const owner = mail.sessionAddress(mark.callerSessionId);
150301
+ const childAddress = mail.sessionAddress(mark.sessionId);
150302
+ try {
150303
+ store2.mailbox.transaction(() => {
150304
+ if (mark.sessionId !== mark.callerSessionId && child && sessions.info(mark.callerSessionId) && !store2.mailbox.newestTask(owner, childAddress)) {
150305
+ mail.task(owner, childAddress, { text: ADOPTED_TASK, origin: child.askedBy === mark.callerSessionId ? "start_agent" : "send_to_session", delivered: true });
150306
+ adopted++;
150307
+ }
150308
+ store2.children.clearReportMark(mark.sessionId);
150309
+ });
150310
+ } catch (e) {
150311
+ console.error(`[mail] could not adopt the report mark of ${mark.sessionId.slice(0, 8)} (${errorMessage(e)})`);
150312
+ }
150313
+ }
150314
+ store2.settings.deleteSessionSettings(RETIRED_SESSION_KEYS);
150315
+ return { queued: queued2, adopted };
150316
+ }
150317
+ function leaveForEarlierBuild(mail, store2, inTurnNow) {
150318
+ const work = new Map(store2.mailbox.openTurns().map((t) => [t.sessionId, t.messageId]));
150319
+ for (const id3 of inTurnNow) {
150320
+ const address = mail.sessionAddress(id3);
150321
+ const open6 = store2.mailbox.watchedTo(address).map((r) => store2.mailbox.message(r.messageId)).filter((m) => m?.kind === "task" && parseAddress(m.sender)?.kind === "session");
150322
+ const task = open6.find((m) => m?.id === work.get(id3)) ?? open6.at(-1);
150323
+ const caller = task ? parseAddress(task.sender) : null;
150324
+ if (caller?.kind === "session") store2.children.setReportMark(id3, caller.sessionId);
150325
+ }
150326
+ }
150327
+
150328
+ // packages/agent-host/src/mail/asked-by.ts
150329
+ function askerFacts(host, sessionId) {
150330
+ const session2 = host.session(sessionId);
150331
+ const projectId = session2 ? session2.projectId : "gone";
150332
+ const project2 = projectId ? host.project(projectId) : void 0;
150333
+ return { name: session2?.name ?? sessionId.slice(0, 8), project: project2?.name ?? null, trusted: !host.untrusted(projectId) };
150334
+ }
150335
+ function askedBy(host, assistantId) {
150336
+ const inTurn2 = host.requestsInTurn(assistantId);
150337
+ const [first, ...rest] = inTurn2?.requests ?? [];
150338
+ if (!inTurn2 || !first) return null;
150339
+ return {
150340
+ messageId: first.messageId,
150341
+ sessionId: first.sessionId,
150342
+ turn: inTurn2.turnSeq,
150343
+ ...askerFacts(host, first.sessionId),
150344
+ cites: host.cites(first.messageId),
150345
+ ...rest.length > 0 ? { also: rest.map((r) => ({ sessionId: r.sessionId, ...askerFacts(host, r.sessionId) })) } : {}
150346
+ };
150347
+ }
150348
+
150349
+ // packages/agent-host/src/mail/card-notices.ts
150350
+ function cardGivers(records, address, alone) {
150351
+ const givers = openTaskParties(records, address, "to");
150352
+ const [only] = givers.length === 1 ? givers : [];
150353
+ return { givers, answerer: only !== void 0 && alone(only) ? only : null };
150354
+ }
150355
+ function tellCard(service, giver, card, body, delivered) {
150356
+ const written = service.notice(giver, { body, facts: { card, about: { session: card.session } }, dedupeKey: `card:${giver}:${card.session}:${card.handle}`, delivered });
150357
+ return written?.id ?? null;
150358
+ }
150359
+ function withdrawEndedCards(records, session2, stands2) {
150360
+ records.transaction(() => {
150361
+ const gone2 = records.undeliveredCardNotices(session2).filter(({ message: { facts } }) => facts.card && !stands2(facts.card.session, facts.card.requestId));
150362
+ if (gone2.length) records.deleteRows(gone2.map(({ row }) => ({ messageId: row.messageId, recipient: row.recipient })));
150363
+ });
150364
+ }
150246
150365
 
150247
150366
  // packages/agent-host/src/mail/tool.ts
150248
150367
  var MailTool = class {
@@ -150258,8 +150377,6 @@ var MailTool = class {
150258
150377
  reach;
150259
150378
  host;
150260
150379
  now;
150261
- /** The sessions told once that `assistant` is not their parent (#1984) */
150262
- hinted = /* @__PURE__ */ new Set();
150263
150380
  run(sessionId, args) {
150264
150381
  try {
150265
150382
  const me2 = this.host.caller(sessionId);
@@ -150274,7 +150391,7 @@ var MailTool = class {
150274
150391
  * session on another computer goes to that computer, which writes it or refuses it (#2067 items 2 and 3,
150275
150392
  * docs/plans/linked-mail.md §6 to §8). Nothing is written here unless it took the message
150276
150393
  */
150277
- async call(sessionId, args) {
150394
+ async call(sessionId, args, signal) {
150278
150395
  const me2 = this.host.caller(sessionId);
150279
150396
  const across = this.host.across;
150280
150397
  if (!me2) return this.run(sessionId, args);
@@ -150283,6 +150400,8 @@ var MailTool = class {
150283
150400
  if (!across) return { text: "Finding sessions is not available here.", isError: true };
150284
150401
  return { text: await across.find((args.to ?? args.text ?? "").trim(), me2.address) };
150285
150402
  }
150403
+ const work = await this.work(sessionId, me2, args, signal);
150404
+ if (work) return work;
150286
150405
  const far = across ? await this.acrossTarget(sessionId, me2, args, across) : null;
150287
150406
  if (!far || !across) return this.run(sessionId, args);
150288
150407
  if (args.cite) {
@@ -150340,6 +150459,28 @@ var MailTool = class {
150340
150459
  const n = shown3.length;
150341
150460
  throw refuse4("ambiguous", `${n} sessions are named ${JSON.stringify(t)}: ${shown3.slice(0, 8).join(", ")}${n > 8 ? ", and more" : ""}. Send to one of them by its address.`);
150342
150461
  }
150462
+ /**
150463
+ * `MailToolHost.work` for the one session `to` names here, else for the word itself (a start request's handle, a linked child's id); a role is
150464
+ * never work. The subject leads the words, so the child reads what the card shows, and the answer says it went as work
150465
+ */
150466
+ async work(sessionId, me2, a, signal) {
150467
+ const t = a.to?.trim() ?? "";
150468
+ if (a.action !== "send" || !this.host.work || !t || [PERSON, "assistant", "parent"].includes(t.toLowerCase()) || !a.text?.trim()) return null;
150469
+ const own = me2.address.slice(0, me2.address.lastIndexOf("/") + 1);
150470
+ const word = t.startsWith(own) ? t.slice(own.length) : t;
150471
+ const [only, other] = this.sessionsNamed(sessionId, word);
150472
+ const subject = a.subject?.trim() ? `${oneLineText(a.subject, SUBJECT_CHARS)}
150473
+
150474
+ ` : "";
150475
+ const r = await this.host.work(sessionId, only && !other ? only.id : word, subject + a.text.trim(), a.ifBusy, signal);
150476
+ return r && !r.isError ? { ...r, text: `Sent as work for a session you started${a.kind ? ` (kind "${a.kind}" is for other mail)` : ""}. ${r.text}` } : r;
150477
+ }
150478
+ /** The sessions here a word names: the one with that id, else those of that name but the caller (after a handoff the heir has the name of the session it replaced, and writes to that one) */
150479
+ sessionsNamed(sessionId, word) {
150480
+ const here = this.host.sessions();
150481
+ const exact = here.find((s) => s.id === word);
150482
+ return exact ? [exact] : here.filter((s) => s.id !== sessionId && s.name.trim().toLowerCase() === word.toLowerCase());
150483
+ }
150343
150484
  dispatch(sessionId, me2, a, calls) {
150344
150485
  switch (a.action) {
150345
150486
  case "inbox":
@@ -150350,8 +150491,8 @@ var MailTool = class {
150350
150491
  return this.handled(me2.address, this.target(me2.address, this.need(a.thread, "thread")));
150351
150492
  case "send": {
150352
150493
  const to = this.party(sessionId, me2, this.need(a.to, "to"));
150353
- const sent = this.service.send(me2.address, { to: [to.address], text: this.need(a.text, "text"), needsReply: a.kind !== "note", ...a.urgent ? { urgent: true } : {}, ...to.via ? { via: [to.via] } : {}, ...a.cite ? { cite: true } : {}, ...a.choices ? { choices: a.choices } : {} });
150354
- return this.sent(sent) + this.parentHint(sessionId, me2, to);
150494
+ const sent = this.service.send(me2.address, { to: [to.address], text: this.need(a.text, "text"), needsReply: a.kind !== "note", ...a.urgent ? { urgent: true } : {}, ...to.via ? { via: [to.via] } : {}, ...a.cite ? { cite: true } : {}, ...a.choices ? { choices: a.choices } : {}, ...a.subject ? { subject: a.subject } : {} });
150495
+ return this.sent(sent);
150355
150496
  }
150356
150497
  case "reply": {
150357
150498
  const id3 = this.target(me2.address, this.need(a.thread, "thread"));
@@ -150407,10 +150548,7 @@ var MailTool = class {
150407
150548
  if (absolute && !(absolute.kind === "session" && t.startsWith(own))) return { address: t };
150408
150549
  const word = t.startsWith(own) ? t.slice(own.length) : t;
150409
150550
  if (word === sessionId) throw refuse4("bad_value", "a message is for someone else");
150410
- const here = this.host.sessions();
150411
- const exact = here.find((s) => s.id === word);
150412
- if (exact) return { address: this.service.sessionAddress(exact.id) };
150413
- const named3 = here.filter((s) => s.id !== sessionId && s.name.trim().toLowerCase() === word.toLowerCase());
150551
+ const named3 = this.sessionsNamed(sessionId, word);
150414
150552
  const [only] = named3;
150415
150553
  if (only && named3.length === 1) return { address: this.service.sessionAddress(only.id) };
150416
150554
  if (!only && parseAddress(own + word) && this.reach.elsewhere(own + word)) return { address: own + word };
@@ -150423,15 +150561,6 @@ var MailTool = class {
150423
150561
  `no session on this computer has the id or name ${JSON.stringify(oneLineText(word, 80))} (a session in the archive or deleted cannot be written to). Write to a session by its exact name, its id or session:<host>/<id>, or to "assistant", "parent" or "person". Find one on any computer with mail(action="find", to="<words>").`
150424
150562
  );
150425
150563
  }
150426
- /**
150427
- * #1984: a session that has a parent and mails `assistant` may have meant the parent, which nothing it sees named. The answer says so once per session
150428
- * (the mail still goes where it was addressed: nothing is rerouted). Silent when the parent is the Assistant itself.
150429
- */
150430
- parentHint(sessionId, me2, to) {
150431
- if (!isRoleVia(to.via) || !me2.askedBy || me2.askedBy === this.host.assistantId() || this.hinted.has(sessionId)) return "";
150432
- this.hinted.add(sessionId);
150433
- return ` It went to the Assistant, not to your parent ${JSON.stringify(oneLineText(this.reach.labelOf(this.service.sessionAddress(me2.askedBy)), 80))}. If you meant your parent, use to: "parent".`;
150434
- }
150435
150564
  /** `send`'s and `reply`'s answer (S4's lines, in this tool's calls) */
150436
150565
  sent(r) {
150437
150566
  const m = r.message;
@@ -151317,6 +151446,7 @@ function mailSessionsOf(mgr2, assistantHasMailCommand) {
151317
151446
  readsSession: (readerId, targetId) => mgr2.mail.readsSession(readerId, targetId),
151318
151447
  turnInputs: (id3) => mgr2.mail.turnInputs(id3),
151319
151448
  onLinkedMachine: (id3) => mgr2.mail.onLinkedMachine(id3),
151449
+ work: (...a) => mgr2.mail.work(...a),
151320
151450
  settleAtRest: (id3) => mgr2.mail.settleAtRest(id3),
151321
151451
  relayStop: (receiverId, stoppedId, why2, told) => mgr2.mail.relayStop(receiverId, stoppedId, why2, told)
151322
151452
  };
@@ -151455,7 +151585,8 @@ function hostMail(store2, sessions, opts) {
151455
151585
  form: (id3) => sessions.mailCommand(id3) ? "command" : "plain",
151456
151586
  askerOf: (id3) => askerFacts(askedByHost, id3),
151457
151587
  legacyChain: (threadId, messageId, reader) => store2.legacyChainFor(threadId, messageId, reader, 9),
151458
- across
151588
+ across,
151589
+ ...sessions.work ? { work: sessions.work } : {}
151459
151590
  });
151460
151591
  const cardStands = (session2, requestId) => {
151461
151592
  const party = parseAddress(session2);
@@ -151477,7 +151608,7 @@ function hostMail(store2, sessions, opts) {
151477
151608
  // The person's warning, written as the mailbox writes its own (delivery.ts `warnIfRunning`): one a clock hour for the session, and nothing waits for it
151478
151609
  compactCycles: (id3, count) => service.notice(PERSON, { body: WARNING_TEXT.compactCycles(service.labelOf(addressOf(id3)), count), facts: { compactCycles: { session: addressOf(id3), count } }, dedupeKey: hourlyKey(`compactcycles:${addressOf(id3)}`, now()) }),
151479
151610
  sessionEvent: (e, ended2) => mailTurns.observe(e, ended2),
151480
- tool: (id3, args) => tool.call(id3, args),
151611
+ tool: (id3, args, signal) => tool.call(id3, args, signal),
151481
151612
  // Work a session gave another is a task, beside the old path that delivered it (§9.1)
151482
151613
  delegated: delegationRecorder(service, mailTurns),
151483
151614
  sendTask: taskSender(service),
@@ -161727,7 +161858,7 @@ var handedToken = launch.tokenOnStdin ? await readHandedToken(process.stdin).cat
161727
161858
  console.error(`[agent-host] the launcher did not hand over the token: ${e.message}`);
161728
161859
  process.exit(1);
161729
161860
  }) : launch.token;
161730
- var BUILD = true ? "6299d64" : "dev";
161861
+ var BUILD = true ? "4b3be7a" : "dev";
161731
161862
  var { values } = parseArgs({
161732
161863
  options: {
161733
161864
  port: { type: "string", default: "5175" },