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

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.61";
43050
43050
 
43051
43051
  // packages/protocol/src/brand.ts
43052
43052
  var APP_NAME = "Centralu";
@@ -108187,7 +108187,7 @@ function presetWithin(child, parent) {
108187
108187
  function aboveCallerError(name, child, caller) {
108188
108188
  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
108189
  }
108190
- var PARENT_MAIL = 'To write to it before you finish, call mail with `to: "parent"`. ';
108190
+ var PARENT_MAIL = 'No progress reports needed. To ask it something before you finish, call mail with `to: "parent"` ("assistant" is someone else). ';
108191
108191
  function canMailParent(child, senderId) {
108192
108192
  return child.askedBy === senderId && !!child.projectId;
108193
108193
  }
@@ -108218,7 +108218,7 @@ function agentChoice(asked, remembered, byDifficulty) {
108218
108218
  }
108219
108219
  function remoteAgentFrame(parentName, task, instructions = "", mail = false) {
108220
108220
  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"`. ' : (
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 ? PARENT_MAIL : (
108222
108222
  // #1987: this machine's Centralu takes no mail from that computer, so the answer is the only way it hears from the child
108223
108223
  "Mail does not reach it from here yet: the answer is how it hears from you. "
108224
108224
  )) + "Wait for your own background work that ends (a test run, a build) inside your turn before you answer.]",
@@ -108228,8 +108228,8 @@ function remoteAgentFrame(parentName, task, instructions = "", mail = false) {
108228
108228
  ...projectInstructions(instructions)
108229
108229
  ].join("\n");
108230
108230
  }
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"`.' : ""}]
108231
+ function agentNoteFrame(parentName, text3) {
108232
+ return `[A note from the parent session "${frameField(parentName)}" through Centralu's mail. These are the parent's words about your ongoing work.]
108233
108233
 
108234
108234
  ${text3}`;
108235
108235
  }
@@ -108471,7 +108471,7 @@ ${cardsText(r.cards)}
108471
108471
  agent_session(sessionId="${r.sessionId}", action="answer", card=\u2026, text=\u2026) answers it. ${ANSWER_FORM}`
108472
108472
  };
108473
108473
  case "mailed":
108474
- return { text: `${mailedText(r, "agent_session")} agent_session(sessionId="${r.sessionId}", action="stop") withdraws it until it is delivered.` };
108474
+ return { text: `${mailedText(r, "mail")} agent_session(sessionId="${r.sessionId}", action="stop") withdraws it until it is delivered.` };
108475
108475
  case "queued":
108476
108476
  return { text: `${queuedText(r)} agent_session(sessionId="${r.sessionId}", action="stop") withdraws it.` };
108477
108477
  case "answered":
@@ -108490,7 +108490,7 @@ agent_session(sessionId="${r.sessionId}", action="answer", card=\u2026, text=\u2
108490
108490
  text: `${who} is not working on anything you gave it (${r.sessionState}${r.interruption ? `, ${interruptionWords(r.interruption)}` : ""}). Its last answer, as JSON:
108491
108491
  ${trustedJsonText(r.answer || "(no final text)")}
108492
108492
  ` + (r.notice ? `${r.notice}
108493
- ` : "") + `agent_session(sessionId="${r.sessionId}", action="send", text=\u2026) gives it more. ${NEW_ROLE_NEW_AGENT}` + (r.cleanUp ? `
108493
+ ` : "") + `mail(action="send", to="${r.sessionId}", text=\u2026) gives it more. ${NEW_ROLE_NEW_AGENT}` + (r.cleanUp ? `
108494
108494
  ${cleanUpLine(r.sessionId)}` : "")
108495
108495
  };
108496
108496
  case "done": {
@@ -108498,7 +108498,7 @@ ${cleanUpLine(r.sessionId)}` : "")
108498
108498
  if (r.notice) lines.push(r.notice);
108499
108499
  if (r.readable.length) lines.push(`You can read these now: ${r.readable.join(", ")}`);
108500
108500
  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}`);
108501
+ lines.push(`mail(action="send", to="${r.sessionId}", text=\u2026) continues with it. ${NEW_ROLE_NEW_AGENT}`);
108502
108502
  if (r.cleanUp) lines.push(cleanUpLine(r.sessionId));
108503
108503
  return { text: lines.join("\n") };
108504
108504
  }
@@ -109458,7 +109458,6 @@ var HANDS_ON = /* @__PURE__ */ new Set(["create_session", "send_to_session", "st
109458
109458
  function stepKind(name, args) {
109459
109459
  if (UNDOABLE.has(name)) return "undoable";
109460
109460
  if (HANDS_ON.has(name)) return "handsOn";
109461
- if (name === "agent_session") return args.action === "send" ? "handsOn" : "asks";
109462
109461
  if (name === "mail") return args.action === "send" ? "handsOn" : "asks";
109463
109462
  return "asks";
109464
109463
  }
@@ -110428,6 +110427,7 @@ ${section(near)}` };
110428
110427
  // packages/agent-host/src/sessions/tool-definitions.ts
110429
110428
  var READ_TOOLS = external_exports.union([external_exports.enum(["none", "titles", "full"]), external_exports.boolean()]);
110430
110429
  var IF_BUSY = external_exports.enum(["fork", "fork_read"]);
110430
+ var SEND_IS_MAIL = 'agent_session has no "send": more work for a session you started is a mail send to its id';
110431
110431
  var UPDATE_ACTION = external_exports.enum(["check", "install", "apply"]);
110432
110432
  var CENTRALU_TOOLS = [
110433
110433
  {
@@ -111022,28 +111022,28 @@ var AGENT_TOOLS = [
111022
111022
  * "answer" (#676): a card of the turn the caller gave, which status shows; `card` only when more than one stands.
111023
111023
  * Not in the description: the answer that shows a card names the call, and the description rides in every request.
111024
111024
  */
111025
- description: "Lists, checks, messages, waits for, stops or archives sessions start_agent started.",
111025
+ // 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)
111026
+ description: "Lists, checks, waits for, stops or archives sessions start_agent started.",
111026
111027
  schema: external_exports.object({
111027
111028
  // Not needed for "list" (#690): the caller's own children, so a parent that forgot one finds it in one call
111028
111029
  sessionId: external_exports.string().optional(),
111029
- action: external_exports.enum(["status", "send", "wait", "stop", "delete", "answer", "list"]),
111030
+ // The refusal of the old `send` names the call that replaced it: words in an error ride in no request
111031
+ action: external_exports.enum(["status", "wait", "stop", "delete", "answer", "list"], { error: (i) => i.input === "send" ? SEND_IS_MAIL : void 0 }),
111030
111032
  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()
111033
+ card: external_exports.string().optional()
111034
111034
  }),
111035
111035
  deferred: true
111036
111036
  }
111037
111037
  ];
111038
- var AGENT_BUDGET_CHARS = 1400;
111038
+ var AGENT_BUDGET_CHARS = 1330;
111039
111039
  var MAIL_TOOLS = [
111040
111040
  {
111041
111041
  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".`,
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". In a report, say what each claim was checked against, and what was not.`,
111043
111043
  schema: external_exports.object({
111044
111044
  action: external_exports.enum(["inbox", "read", "handled", "send", "reply", "update", "close", "find"]),
111045
111045
  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'),
111046
+ 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
111047
  kind: external_exports.string().optional(),
111048
111048
  subject: external_exports.string().optional(),
111049
111049
  text: external_exports.string().optional(),
@@ -111055,12 +111055,14 @@ var MAIL_TOOLS = [
111055
111055
  urgent: external_exports.boolean().optional(),
111056
111056
  follows: external_exports.array(external_exports.string()).optional(),
111057
111057
  cite: external_exports.boolean().optional(),
111058
- choices: external_exports.array(external_exports.string()).optional()
111058
+ choices: external_exports.array(external_exports.string()).optional(),
111059
+ // A fork instead of a mail task, for a busy session the caller started (#1948); the mailed answer names it
111060
+ ifBusy: IF_BUSY.optional()
111059
111061
  }),
111060
111062
  deferred: true
111061
111063
  }
111062
111064
  ];
111063
- var MAIL_BUDGET_CHARS = 1240;
111065
+ var MAIL_BUDGET_CHARS = 1355;
111064
111066
  var COMPACT_TOOLS = [
111065
111067
  {
111066
111068
  name: "compact_self",
@@ -111586,7 +111588,7 @@ function movedChildrenNote(moved, commands = "") {
111586
111588
  "",
111587
111589
  ...moved.filter((c) => !c.folded).map((c) => `- ${movedLabel(c)} \u2014 ${c.state} \u2014 handle: ${c.handle}. ${c.can}`),
111588
111590
  ...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"}.` : "")
111591
+ `- ${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
111592
  ] : [],
111591
111593
  "",
111592
111594
  "---",
@@ -111688,7 +111690,7 @@ var HandoffChildren = class {
111688
111690
  sessions.push(id3);
111689
111691
  const project2 = s.projectId !== original.projectId ? projects.get(s.projectId ?? "") ?? s.projectId ?? "" : void 0;
111690
111692
  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.`;
111693
+ 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
111694
  const folded = state === SETTLED_CHILD && project2 === void 0 && s.askedBy === from;
111693
111695
  moved.push({ handle: id3, name: this.host.nameOf(id3), state, can, ...project2 !== void 0 ? { project: project2 } : {}, ...folded ? { folded: true } : {} });
111694
111696
  }
@@ -113033,8 +113035,8 @@ var HANDLERS = {
113033
113035
  compact_self({ focus, then: then2 }, { tools }) {
113034
113036
  return tools.compactSelf ? tools.compactSelf(focus, then2) : { text: "Compacting is not available in this session.", isError: true };
113035
113037
  },
113036
- mail(args, { tools }) {
113037
- return tools.mail ? tools.mail(args) : { text: "The mailbox is not available in this session.", isError: true };
113038
+ mail(args, { tools, signal }) {
113039
+ return tools.mail ? tools.mail(args, signal) : { text: "The mailbox is not available in this session.", isError: true };
113038
113040
  },
113039
113041
  async update_centralu({ action }, { tools, caller, signal }) {
113040
113042
  const r = tools.updateCentralu ? await tools.updateCentralu(action, signal) : { ok: false, error: "Update checks are unavailable" };
@@ -113086,7 +113088,7 @@ var HANDLERS = {
113086
113088
  const branch = trimmed(args.branch);
113087
113089
  const name = trimmed(args.name);
113088
113090
  const machine = trimmed(args.machine);
113089
- return agentCallsFor(caller, agentRunText(
113091
+ return agentCallsFor(caller.profile, agentRunText(
113090
113092
  await tools.startAgent(
113091
113093
  {
113092
113094
  task,
@@ -113107,14 +113109,13 @@ var HANDLERS = {
113107
113109
  },
113108
113110
  async agent_session(args, { tools, signal, caller }) {
113109
113111
  const sessionId = trimmed(args.sessionId);
113110
- const { action, ifBusy } = args;
113111
- if (action === "list") return agentCallsFor(caller, agentListText(await tools.listAgents()));
113112
+ const { action } = args;
113113
+ if (action === "list") return agentCallsFor(caller.profile, agentListText(await tools.listAgents()));
113112
113114
  if (!sessionId) return { text: "Give the sessionId start_agent returned.", isError: true };
113113
113115
  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
113116
  if (action === "answer" && !text3) return { text: "Give text: the answer.", isError: true };
113116
113117
  const card = trimmed(args.card);
113117
- return agentCallsFor(caller, agentRunText(await tools.agentSession({ sessionId, action, ...text3 ? { text: text3 } : {}, ...card ? { card } : {}, ...ifBusy ? { ifBusy } : {} }, signal)));
113118
+ return agentCallsFor(caller.profile, agentRunText(await tools.agentSession({ sessionId, action, ...text3 ? { text: text3 } : {}, ...card ? { card } : {} }, signal)));
113118
113119
  },
113119
113120
  async recall({ query, limit }, { tools }) {
113120
113121
  const r = await tools.recall(query, limit);
@@ -113384,10 +113385,13 @@ When you no longer need it, call ${namedCall(caller.profile, "detach_app", { app
113384
113385
  };
113385
113386
  }
113386
113387
  };
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 };
113388
+ function agentCallsFor(profile, out) {
113389
+ const commands = commandsFor(profile);
113390
+ const text3 = out.text.replace(
113391
+ /"(?:[^"\\\n]|\\.)*"|\b(agent_session|mail)\(([^)]*)\)/g,
113392
+ (call2, tool, inner) => tool && commands.includes(tool) ? `centralu_run(command="${tool}", args={${(inner ?? "").replace(/\b(\w+)=/g, "$1: ")}})` : call2
113393
+ );
113394
+ return text3 === out.text ? out : { ...out, text: text3 };
113391
113395
  }
113392
113396
  function commandLine(description) {
113393
113397
  const plain2 = description.replace(/\*\*/g, "").replace(/ \((?:#\d+|M4)\)/g, "");
@@ -114269,19 +114273,13 @@ var AgentStartFlow = class {
114269
114273
  progress.childId = child.id;
114270
114274
  if (name) this.host.rename(child.id, name);
114271
114275
  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);
114276
+ const instructions = project2.id === ASSISTANT_PLACE ? "" : this.host.store.projects.agentInstructions(project2.id);
114277
+ const frame = agentFrame(labelOf(this.host.store.messages, caller), choice.task, setupProblems, instructions, canMailParent(child, callerId));
114278
+ 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
114279
  release();
114274
114280
  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
- }
114281
+ const failed4 = await delivered;
114282
+ if (failed4) return done2({ ok: false, error: `Could not give the task to the new session: ${failed4}` });
114285
114283
  const notice = this.host.handles.get(child.id)?.delegationNotice?.();
114286
114284
  return { key, d: d2, notice: [unchecked, forkNote, notice].filter(Boolean).join("; ") || void 0 };
114287
114285
  }
@@ -114729,17 +114727,11 @@ var DelegationForks = class {
114729
114727
  if (late) return this.flow.starts.abandonChild(child, late, worktree ? void 0 : `Fork of ${target.name}`.slice(0, 48));
114730
114728
  if (!worktree) this.host.rename(child.id, `Fork of ${target.name}`.slice(0, 48));
114731
114729
  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);
114730
+ const frame = agentFrame(labelOf(this.host.store.messages, caller), text3, [], "", canMailParent(child, callerId));
114731
+ 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
114732
  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 };
114733
+ const failed4 = await delivered;
114734
+ 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
114735
  } finally {
114744
114736
  place.release();
114745
114737
  }
@@ -114830,22 +114822,15 @@ var AgentSessionActions = class {
114830
114822
  *
114831
114823
  * status where it stands, without waiting (the answer, once the turn the caller gave it has ended)
114832
114824
  * 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
114825
  * stop stops the turn the caller gave it; a turn the person started there is theirs
114836
114826
  * delete trashes a child without a worktree, stopping it first; worktree cleanup requires an idle child (#608)
114837
114827
  */
114838
114828
  async agentSession(callerId, opts, signal) {
114839
114829
  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." };
114830
+ return { ok: false, error: "agent_session cannot wait on, stop or delete its own calling session." };
114841
114831
  }
114842
114832
  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
- }
114833
+ if (remote) return this.flow.remote.agentSession(callerId, remote, opts, signal);
114849
114834
  const gone2 = this.flow.handedOverAnswer(callerId, opts.sessionId);
114850
114835
  if (gone2) return gone2;
114851
114836
  const request = this.host.children.agentStarts.get(opts.sessionId);
@@ -114868,11 +114853,9 @@ var AgentSessionActions = class {
114868
114853
  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
114854
  }
114870
114855
  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))}` };
114856
+ const mayWork = (c, ch2) => ownChild(c, ch2) || !!c.projectId && ch2.projectId === c.projectId && (deletingWithoutWorktree ? ch2.parentSessionId === callerId : this.host.autoBoundaryOpen(callerId, "session ownership"));
114857
+ if (!caller || !child || !mayWork(caller, child)) {
114858
+ 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
114859
  }
114877
114860
  if (opts.sessionId === callerId) return this.flow.agentAtRest(child);
114878
114861
  if (opts.action === "answer") return this.host.answerRoutedCard(callerId, child.id, opts.card, opts.text ?? "");
@@ -114932,41 +114915,6 @@ var AgentSessionActions = class {
114932
114915
  const note = [r.note, timers.length ? `Its timers ended with its process: ${taskList(timers)}.` : ""].filter(Boolean).join(" ");
114933
114916
  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
114917
  }
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
114918
  default:
114971
114919
  return { ok: false, error: "Unknown agent_session action." };
114972
114920
  }
@@ -114974,9 +114922,59 @@ var AgentSessionActions = class {
114974
114922
  releaseObservation?.();
114975
114923
  }
114976
114924
  }
114925
+ /**
114926
+ * `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
114927
+ * (docs/plans/mailbox.md §10.6.6). Null for any other target: the send is plain mail
114928
+ */
114929
+ async sendWork(callerId, target, text3, ifBusy, signal) {
114930
+ const remote = target.includes(".") ? this.flow.remote.of(target) : void 0;
114931
+ if (remote) {
114932
+ if (remote.callerId !== callerId) return null;
114933
+ const machine = this.host.linkedReader?.machineOf(target);
114934
+ const refused3 = this.host.refusesDelegation(callerId, { sessionId: target, linked: true }, { tool: "mail", target: `a session on ${machine ?? "a linked machine"}`, text: text3 });
114935
+ return refused3 ? { ok: false, error: refused3 } : this.flow.remote.send(callerId, remote, text3);
114936
+ }
114937
+ const gone2 = this.flow.handedOverAnswer(callerId, target);
114938
+ if (gone2) return gone2;
114939
+ const request = this.host.children.agentStarts.get(target);
114940
+ if (request?.req.callerId === callerId) {
114941
+ const ended2 = request.ended;
114942
+ 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.` };
114943
+ if ("error" in ended2) return { ok: false, error: `Request ${target} started no session: ${ended2.error}` };
114944
+ target = ended2.childId;
114945
+ }
114946
+ const caller = this.host.meta.get(callerId);
114947
+ const child = this.host.meta.get(target);
114948
+ if (!caller || !child || !ownChild(caller, child)) return null;
114949
+ const above = aboveCallerError(child.name, child.permissionPreset, caller.permissionPreset);
114950
+ if (above) return { ok: false, error: above };
114951
+ const refused2 = this.host.refusesDelegation(callerId, { sessionId: child.id, projectId: child.projectId }, { tool: "mail", target: child.name || child.id, text: text3 });
114952
+ if (refused2) return { ok: false, error: refused2 };
114953
+ if (!this.host.takesSendNow(child.id)) {
114954
+ if (!ifBusy) {
114955
+ const mailed = this.host.mailTask(callerId, child, "agent_session", text3);
114956
+ return "error" in mailed ? { ok: false, error: mailed.error } : { ok: true, tool: child.tool, ...mailed };
114957
+ }
114958
+ const f = await this.flow.forkFor(callerId, child, text3, ifBusy === "fork_read", "agent_session", signal);
114959
+ if (!f.ok) return f;
114960
+ if ("mailed" in f) return { ok: true, tool: child.tool, ...f.mailed };
114961
+ const working = this.flow.agentWorking(f.d);
114962
+ return working.ok ? { ...working, via: "fork", forkedFrom: child.id } : working;
114963
+ }
114964
+ const key = `${callerId}>${child.id}`;
114965
+ if (this.host.children.delegations.has(key)) this.host.children.dropDelegation(key);
114966
+ const full = this.flow.starts.agentCeilingError(callerId, child.projectId ?? "");
114967
+ if (full) return { ok: false, error: full };
114968
+ const project2 = this.host.store.projects.listProjects().find((p) => p.id === child.projectId);
114969
+ const cwd = this.host.store.sessions.sessionCwd(child.id) ?? child.worktree?.path ?? project2?.path ?? "";
114970
+ const frame = agentFrame(labelOf(this.host.store.messages, caller), text3, [], "", canMailParent(child, callerId));
114971
+ 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 });
114972
+ const failed4 = await delivered;
114973
+ return failed4 ? { ok: false, error: `Could not send it: ${failed4}` } : this.flow.agentWorking(d2);
114974
+ }
114977
114975
  /**
114978
114976
  * 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
114977
+ * person's answer up to the bound, stop (or delete) withdraws the card. Once the child started, the
114980
114978
  * call goes on to that session (a wait that saw it start answers its status, so the call stays inside its bound);
114981
114979
  * once it ended without one, the reason.
114982
114980
  */
@@ -114987,10 +114985,6 @@ var AgentSessionActions = class {
114987
114985
  this.flow.starts.withdrawAgentStart(id3, "The session that asked withdrew the request.", agentStartPersonText(rec.req, "stopped"));
114988
114986
  return { ok: true, state: "stopped", sessionId: id3, sessionName: "", tool: rec.req.detail.tool };
114989
114987
  }
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
114988
  if (action === "wait") {
114995
114989
  const owner = rec.req.callerId;
114996
114990
  const leaving = this.flow.untilHandedOver(rec);
@@ -115007,6 +115001,9 @@ var AgentSessionActions = class {
115007
115001
  return { childId: ended2.childId, action };
115008
115002
  }
115009
115003
  };
115004
+ function ownChild(caller, child) {
115005
+ return child.askedBy === caller.id && child.projectId === caller.projectId && (!!caller.projectId || isAssistantKind(caller.kind));
115006
+ }
115010
115007
 
115011
115008
  // packages/agent-host/src/sessions/remote-agents.ts
115012
115009
  import { randomUUID as randomUUID16 } from "node:crypto";
@@ -115375,7 +115372,7 @@ var RemoteAgents = class {
115375
115372
  if (!sent.ok) {
115376
115373
  if (waiting && this.waits.get(rec.sessionId) === waiting) this.dropWait(rec.sessionId);
115377
115374
  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.` };
115375
+ 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
115376
  }
115380
115377
  const notTaken = this.unclaimed(rec, waiting);
115381
115378
  if (notTaken) return notTaken;
@@ -115404,7 +115401,7 @@ var RemoteAgents = class {
115404
115401
  const now = await raceTimeout(reader.agentInstructions(target).catch(() => null), INSTRUCTIONS_WAIT_MS, null);
115405
115402
  return now?.ok ? now.text : listed2;
115406
115403
  }
115407
- /** agent_session on a child of a linked machine (#1038): status, wait, send, stop, delete, through the link */
115404
+ /** agent_session on a child of a linked machine (#1038): status, wait, stop, delete, through the link */
115408
115405
  async agentSession(callerId, rec, opts, signal) {
115409
115406
  if (opts.action !== "delete") return this.act(callerId, rec, opts, signal);
115410
115407
  this.deleting.add(rec.sessionId);
@@ -115415,6 +115412,10 @@ var RemoteAgents = class {
115415
115412
  if (this.of(rec.sessionId)?.queued?.length) this.scheduleDrain(rec.sessionId);
115416
115413
  }
115417
115414
  }
115415
+ /** New work for a child of a linked machine (`AgentSessionActions.sendWork`, the caller's `mail` to it), through the link */
115416
+ send(callerId, rec, text3) {
115417
+ return this.act(callerId, rec, { sessionId: rec.sessionId, action: "send", text: text3 });
115418
+ }
115418
115419
  async act(callerId, rec, opts, signal) {
115419
115420
  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
115421
  const reader = this.host.linkedReader;
@@ -115452,8 +115453,7 @@ var RemoteAgents = class {
115452
115453
  return now.running ? this.awaitTurn(rec, signal, ASK_WAIT_MS) : this.atRest(rec, now.state, reader);
115453
115454
  }
115454
115455
  case "send": {
115455
- const text3 = opts.text?.trim();
115456
- if (!text3) return { ok: false, error: "Give the text to send." };
115456
+ const { text: text3 } = opts;
115457
115457
  if (this.deleting.has(rec.sessionId)) return this.hold(rec, text3);
115458
115458
  const above = aboveCallerError(rec.name, rec.preset ?? "normal", this.callerPreset(callerId));
115459
115459
  if (above) return { ok: false, error: above };
@@ -116271,7 +116271,31 @@ var DelegationFlow = class {
116271
116271
  return answer;
116272
116272
  };
116273
116273
  }
116274
- /** Registers the wait on the delegated session's turn (the same watcher an app's agent uses, `AgentRunWait`) */
116274
+ /**
116275
+ * 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
116276
+ * 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
116277
+ * 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
116278
+ * error text when they did not go in
116279
+ */
116280
+ delegate(w) {
116281
+ const d2 = this.startDelegation(w.key, w.callerId, w.sessionId, w.target, w.agent);
116282
+ const withdraw = this.host.children.delegated(w.callerId, w.sessionId, w.via, w.task);
116283
+ const caller = this.host.meta.get(w.callerId);
116284
+ const delivered = (async () => {
116285
+ try {
116286
+ 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);
116287
+ return null;
116288
+ } catch (e) {
116289
+ withdraw();
116290
+ d2.wait.fail(e instanceof Error ? e : new Error(errorMessage(e)));
116291
+ this.host.children.dropDelegation(w.key, d2);
116292
+ if (this.host.agentRuns.get(w.sessionId) === d2.wait) this.host.agentRuns.delete(w.sessionId);
116293
+ return errorMessage(e);
116294
+ }
116295
+ })();
116296
+ return { d: d2, delivered };
116297
+ }
116298
+ /** 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
116299
  startDelegation(key, callerId, sessionId, target, agent = false) {
116276
116300
  let notice;
116277
116301
  const wait = new AgentRunWait((message) => notice = message, () => this.host.meta.get(sessionId)?.name ?? "the session", void 0, this.answerReader(sessionId));
@@ -120615,7 +120639,7 @@ var SessionTools = class {
120615
120639
  findApps: async (query) => this.host.apps.requireAppAccess().find(sessionId, query),
120616
120640
  attachApp: async (app2) => this.host.apps.requireAppAccess().attach(sessionId, app2),
120617
120641
  detachApp: async (app2) => this.host.apps.requireAppAccess().detach(sessionId, app2),
120618
- mail: (args) => this.host.mailTool(sessionId, args),
120642
+ mail: (args, signal) => this.host.mailTool(sessionId, args, signal),
120619
120643
  compactSelf: (focus, then2) => this.host.selfCompaction.request(sessionId, focus, then2)
120620
120644
  };
120621
120645
  }
@@ -121314,8 +121338,8 @@ var MailboxRecords = class {
121314
121338
  rootId = target.root_id;
121315
121339
  }
121316
121340
  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)`
121341
+ `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)
121342
+ VALUES (@id, @sender, @senderProject, @kind, @needsReply, @replyTo, @rootId, @causeId, @depth, @urgent, @body, @facts, @choices, @subject, @dedupeKey, @origin, @legacyThread, @createdAt)`
121319
121343
  ).run({
121320
121344
  id: mail.id,
121321
121345
  sender: mail.sender,
@@ -121330,6 +121354,7 @@ var MailboxRecords = class {
121330
121354
  body: mail.body,
121331
121355
  facts: JSON.stringify(mail.facts),
121332
121356
  choices: mail.choices ? JSON.stringify(mail.choices) : null,
121357
+ subject: mail.subject,
121333
121358
  dedupeKey: mail.dedupeKey,
121334
121359
  origin: mail.origin,
121335
121360
  legacyThread: mail.legacyThread,
@@ -122007,6 +122032,7 @@ var MailboxRecords = class {
122007
122032
  body: r.body,
122008
122033
  facts: this.readFacts(r.id, r.facts),
122009
122034
  choices: choicesFrom(r.choices),
122035
+ subject: r.subject,
122010
122036
  dedupeKey: r.dedupe_key,
122011
122037
  origin: r.origin,
122012
122038
  legacyThread: r.legacy_thread,
@@ -123819,6 +123845,11 @@ var MailSessionsView = class {
123819
123845
  const run2 = this.host.agentRuns.get(id3);
123820
123846
  return this.takesTurn(id3) && !(run2 && !run2.finished) && this.hooks?.waiting?.(id3) !== true;
123821
123847
  }
123848
+ /** `MailToolHost.work` (#1948): the answer worded as agent_session's are for the caller's seat, or null for plain mail */
123849
+ async work(callerId, target, text3, ifBusy, signal) {
123850
+ const r = await this.host.delegationFlow.actions.sendWork(callerId, target, text3, ifBusy, signal);
123851
+ return r && agentCallsFor(this.host.tools.toolProfileOf(callerId) ?? "human", agentRunText(r));
123852
+ }
123822
123853
  /** 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
123854
  mailTask(callerId, target, origin, text3) {
123824
123855
  const hooks = this.hooks;
@@ -126804,6 +126835,7 @@ function stepLine(s) {
126804
126835
  }
126805
126836
  var AGENT_ACTIONS = {
126806
126837
  status: "Checked on an agent",
126838
+ // A recorded call from before #1948 moved more work to mail still reads as it did
126807
126839
  send: "Sent more to an agent",
126808
126840
  wait: "Waited for an agent",
126809
126841
  stop: "Stopped an agent",
@@ -126811,6 +126843,8 @@ var AGENT_ACTIONS = {
126811
126843
  answer: "Answered an agent's card",
126812
126844
  list: "Listed its agents"
126813
126845
  };
126846
+ var MAIL_ACTIONS = { send: "Sent mail", reply: "Replied" };
126847
+ var sessionAddressed = (to) => to && isUuid(to.slice(to.lastIndexOf(".") + 1)) ? to : void 0;
126814
126848
  var CENTRALU_LABELS = {
126815
126849
  start_agent: "Started an agent",
126816
126850
  ask_project: "Asked a project",
@@ -126872,15 +126906,15 @@ var CENTRALU_LABELS = {
126872
126906
  function centraluMark(server2, tool, args) {
126873
126907
  const origin = centraluServer(server2);
126874
126908
  if (!origin) return null;
126875
- const sessionId = trimmed(args.sessionId);
126909
+ const action = trimmed(args.action);
126910
+ const sessionId = tool === "mail" ? action === "send" ? sessionAddressed(trimmed(args.to)) : void 0 : trimmed(args.sessionId);
126876
126911
  const base2 = { tool, ...origin, ...sessionId ? { sessionId } : {} };
126877
126912
  if (origin.app) return { centralu: base2 };
126878
126913
  const text3 = (v) => {
126879
126914
  const t = trimmed(v);
126880
126915
  return t ? firstLine2(t, 160) : void 0;
126881
126916
  };
126882
- const action = trimmed(args.action);
126883
- let label = tool === "agent_session" ? action && AGENT_ACTIONS[action] : CENTRALU_LABELS[tool];
126917
+ let label = tool === "agent_session" ? action && AGENT_ACTIONS[action] : tool === "mail" ? action && MAIL_ACTIONS[action] : CENTRALU_LABELS[tool];
126884
126918
  let title;
126885
126919
  switch (tool) {
126886
126920
  case "start_agent": {
@@ -126894,6 +126928,9 @@ function centraluMark(server2, tool, args) {
126894
126928
  case "answer_question":
126895
126929
  title = text3(args.text);
126896
126930
  break;
126931
+ case "mail":
126932
+ if (label) title = text3(args.subject) ?? text3(args.text);
126933
+ break;
126897
126934
  case "read_session":
126898
126935
  if (!sessionId) label = "Listed sessions";
126899
126936
  break;
@@ -143241,6 +143278,21 @@ var StepsV65 = class extends MigrationRange {
143241
143278
  run: () => {
143242
143279
  this.addColumn("mail", "choices", "TEXT");
143243
143280
  }
143281
+ },
143282
+ {
143283
+ to: 71,
143284
+ breaksOlderReaders: false,
143285
+ /**
143286
+ * The subject a session's `mail` send gives the chain it starts (#2229): `mail.subject`, one line of at most 80 characters, NULL on
143287
+ * 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
143288
+ * names the chain by it instead of its first message's words.
143289
+ *
143290
+ * **Expand only (#292's rule).** One nullable column. An older build names its columns in every read and insert of `mail`, so it
143291
+ * never sees it: it opens the store and names the chain by its words, as before. Nothing is backfilled: no build kept a subject.
143292
+ */
143293
+ run: () => {
143294
+ this.addColumn("mail", "subject", "TEXT");
143295
+ }
143244
143296
  }
143245
143297
  ];
143246
143298
  }
@@ -144879,23 +144931,13 @@ var AskProjectFlow = class {
144879
144931
  return "error" in mailed ? { ok: false, error: mailed.error } : { ok: true, project: target.name, ...mailed };
144880
144932
  }
144881
144933
  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
144934
  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);
144935
+ const logged = !this.host.projectTrusted(callerProjectId);
144936
+ const stillAllowed = () => this.askGateError(callerId, logged) ?? this.projectGoneError(target);
144937
+ const frame = askFrame(callerProject, opts.task, { name: labelOf(this.host.store.messages, caller), sessionId: callerId });
144938
+ const { d: d2, delivered } = this.host.delegationFlow.delegate({ key, callerId, sessionId: chosen.id, target, agent: false, via: "ask_project", task: opts.task, frame, stillAllowed });
144939
+ const failed4 = await delivered;
144940
+ return failed4 ? { ok: false, error: `Could not hand the task to ${target.name}: ${failed4}` } : this.awaitDelegation(key, d2, signal);
144899
144941
  }
144900
144942
  /**
144901
144943
  * 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 +148051,7 @@ var SessionManager = class {
148009
148051
  return self2.adapters;
148010
148052
  },
148011
148053
  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 },
148054
+ mailTool: async (id3, args, signal) => await self2.mail.hooks?.tool?.(id3, args, signal) ?? { text: "The mailbox is not available.", isError: true },
148013
148055
  refusesDelegation: (callerId, target, call2) => self2.mail.hooks?.refusesDelegation?.(callerId, target, call2) ?? null,
148014
148056
  roleMoved: (toId) => self2.mail.hooks?.roleMoved?.(toId),
148015
148057
  whenAsked: (id3, call2, signal, run2, refused2) => self2.askedGate.when(id3, call2, signal, run2, refused2),
@@ -148517,743 +148559,231 @@ var SessionManager = class {
148517
148559
  }
148518
148560
  };
148519
148561
 
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);
148562
+ // packages/agent-host/src/mail/last-response.ts
148563
+ function tasksAtRest(records, recipient, last) {
148564
+ return records.watchedTo(recipient).flatMap((row) => {
148565
+ if (row.deliveredAt === null || row.held !== null && row.held !== "released" || !last.released && row.releasedAt !== null || last.queued?.has(row.messageId)) return [];
148566
+ const task = records.message(row.messageId);
148567
+ if (task?.kind !== "task" || task.sender === recipient || !last.answers(task.sender)) return [];
148568
+ return records.handedOn(task.id).length > 0 ? [] : [{ row, sender: task.sender }];
148569
+ });
148531
148570
  }
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
- });
148571
+ function answerAtRest(records, recipient, last, report, personAt) {
148572
+ return tasksAtRest(records, recipient, last).map(({ row, sender }) => {
148573
+ const given = row.deliveredAt ?? 0;
148574
+ const personSince = parseAddress(sender)?.kind === "session" && personAt !== void 0 && personAt > given;
148575
+ const after = last.writtenAt !== void 0 && last.writtenAt < given;
148576
+ const lines = [last.body(sender), ...personSince ? [PERSON_SINCE] : [], ...after ? [AFTER2] : []];
148577
+ report(row.messageId, {
148578
+ outcome: "finished",
148579
+ body: lines.join("\n"),
148580
+ ...last.answer ? { answer: last.answer } : {},
148581
+ ...personSince ? { personSince: true } : {},
148582
+ ...after ? { after: true } : {}
148583
+ });
148584
+ return row.messageId;
148585
+ });
148586
+ }
148587
+ 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.";
148588
+ var AFTER2 = "Your task arrived after this response was written.";
148589
+
148590
+ // packages/agent-host/src/mail/reach.ts
148591
+ function mailReach(host) {
148592
+ const sessionOf = (address) => {
148593
+ const party = parseAddress(address);
148594
+ if (party?.kind !== "session") return void 0;
148595
+ if (party.host === host.hostId) return { id: party.sessionId, info: host.session(party.sessionId) };
148596
+ const far = host.foreign?.(address);
148597
+ return far ? { id: party.sessionId, info: { projectId: null, askedBy: null, here: true, canReadMail: false, host: "elsewhere", name: far.name } } : void 0;
148598
+ };
148599
+ const untrusted = (projectId) => projectId === null ? false : !(host.project(projectId)?.trusted ?? false);
148600
+ const leaves = (senderProject, recipientProject) => HOLD_UNTRUSTED_OUT && untrusted(senderProject) && recipientProject !== senderProject;
148601
+ return {
148602
+ untrusted,
148603
+ isAssistant: (address) => {
148604
+ const s = sessionOf(address);
148605
+ return s !== void 0 && host.assistantId() === s.id;
148606
+ },
148607
+ askGroupMembers: (address) => host.askGroupMembers(address),
148608
+ projectOf: (address) => sessionOf(address)?.info?.projectId ?? null,
148609
+ parentOf: (address) => {
148610
+ const parent = sessionOf(address)?.info?.askedBy;
148611
+ const party = parseAddress(address);
148612
+ return parent && party?.kind === "session" ? sessionAddress(party.host, parent) : null;
148613
+ },
148614
+ labelOf: (address) => sessionOf(address)?.info?.name ?? address,
148615
+ elsewhere: (address) => sessionOf(address)?.info?.host === "elsewhere",
148616
+ projectLabel: (projectId) => host.project(projectId)?.name ?? projectId,
148617
+ mayWrite(from, to, asRequest = true) {
148618
+ const f = parseAddress(from);
148619
+ const t = parseAddress(to);
148620
+ if (!f || !t) return "bad_address";
148621
+ if (t.kind === "centralu" || t.kind === "app") return "not_allowed";
148622
+ if (t.kind === "session" && t.host !== host.hostId) return "elsewhere";
148623
+ const receiver = sessionOf(to);
148624
+ if (receiver) {
148625
+ if (!receiver.info?.here) return "gone";
148626
+ if (receiver.info.host === "elsewhere") return "elsewhere";
148627
+ if (!receiver.info.canReadMail) return "no_mailbox";
148628
+ }
148629
+ if (f.kind === "centralu" || f.kind === "person") return null;
148630
+ if (f.kind === "app") return receiver && host.appCalledBy(from, receiver.id) ? null : "not_allowed";
148631
+ if (!sessionOf(from)?.info?.here) return "gone";
148632
+ if (!receiver) return null;
148633
+ const assistant = host.assistantId();
148634
+ return asRequest && receiver.id === assistant && f.sessionId !== assistant && !host.assistantAsks() ? "assistant_asks" : null;
148635
+ },
148636
+ holdFor(m, recipient) {
148637
+ if (m.kind !== "message") return null;
148638
+ const receiver = sessionOf(recipient);
148639
+ return receiver?.info && leaves(m.senderProject, receiver.info.projectId) ? "policy" : null;
148640
+ },
148641
+ refusesDelegation(callerId, target) {
148642
+ const project2 = host.session(callerId)?.projectId ?? null;
148643
+ if (project2 === null) return null;
148644
+ const targetProject = target.linked || target.assistant ? null : target.sessionId !== void 0 ? host.session(target.sessionId)?.projectId ?? null : target.projectId ?? null;
148645
+ return leaves(project2, targetProject) ? project2 : null;
148562
148646
  }
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;
148647
+ };
148648
+ }
148649
+ function droppedText(ids, project2) {
148650
+ const shown3 = ids.slice(0, 10).join(", ") + (ids.length > 10 ? `, and ${ids.length - 10} more` : "");
148651
+ 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.`;
148652
+ }
148653
+ function trustedText(project2, calls) {
148654
+ 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` : ""}`;
148655
+ }
148656
+
148657
+ // packages/agent-host/src/mail/send-guards.ts
148658
+ function sendGuards(d2, { sender, cls, to, text: text3, requests: requests2 }, now) {
148659
+ const label = (a) => d2.reach.labelOf(a);
148660
+ for (const r of to) {
148661
+ if ((cls === "session" || cls === "app") && d2.records.sameBody(sender, r, text3, now - REPEAT_WINDOW_MS)) {
148662
+ throw guardRefused(d2, sender, "repeat", WARNING_TEXT.repeat(label(sender), r === PERSON ? "you" : label(r)), REFUSAL_TEXT.repeat(label(r)), now);
148567
148663
  }
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
148664
  }
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
- };
148665
+ const limit = postsPerMinute(cls);
148666
+ if (limit !== Infinity && d2.records.postsSince(sender, now - MINUTE_MS) >= limit) {
148667
+ 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);
148598
148668
  }
148599
- /**
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
148603
- */
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 });
148669
+ for (const [i, r] of to.entries()) {
148670
+ if (requests2[i] && d2.records.requestsSince(d2.reach.askGroupMembers(sender), r, now - HOUR_MS) >= ASKS_PER_HOUR) {
148671
+ throw guardRefused(d2, sender, "ask_rate", WARNING_TEXT.ask_rate(label(sender)), REFUSAL_TEXT.ask_rate(), now);
148672
+ }
148673
+ }
148674
+ }
148675
+ function guardRefused(d2, sender, reason, toPerson, toSender, now) {
148676
+ d2.notice(PERSON, { body: toPerson, facts: { guardRefused: { sender, reason } }, dedupeKey: hourlyKey(`guard:${reason}:${sender}`, now) });
148677
+ return refuse4(reason, toSender);
148678
+ }
148679
+
148680
+ // packages/agent-host/src/mail/stop-notices.ts
148681
+ var StopNotices = class {
148682
+ constructor(d2) {
148683
+ this.d = d2;
148612
148684
  }
148685
+ d;
148613
148686
  /**
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
148687
+ * 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
148688
+ * 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
148689
+ * 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
148616
148690
  */
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");
148691
+ partyGone(address) {
148692
+ this.releaseAndTell((now, senders) => {
148693
+ for (const { row, message } of this.owedBy(address, "gone", null)) if (this.d.records.markReleased(row.messageId, address, now, "gone")) senders.add(message.sender);
148694
+ for (const row of this.d.records.watchedTo(address)) if (!isRoleVia(row.via)) this.d.records.settle(row.messageId, address, "gone", now);
148695
+ for (const row of this.d.records.watchedFrom(address)) this.d.records.settle(row.messageId, row.recipient, "withdrawn", now);
148626
148696
  });
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 };
148633
148697
  }
148634
148698
  /**
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)
148699
+ * 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
148700
+ * 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
148701
+ * 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
148702
+ * 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
148703
+ * 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
148704
+ * 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
148705
+ * 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.
148706
+ *
148707
+ * 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
148708
+ * itself), whose rows are released and marked told. Returns how many rows were released
148637
148709
  */
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] };
148645
- }
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;
148710
+ sessionStopped(address, why2, opts = {}) {
148711
+ return this.sessionsStopped([{ ...opts, address, why: why2, turnSeq: opts.turnSeq ?? null }]);
148650
148712
  }
148651
- /**
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
148659
- */
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);
148713
+ /** 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 */
148714
+ sessionsStopped(stops) {
148715
+ return this.d.run(() => {
148716
+ const now = this.d.now();
148717
+ const senders = /* @__PURE__ */ new Set();
148718
+ let released = 0;
148719
+ for (const { address, why: why2, turnSeq, told, starter } of stops) {
148720
+ const owed = /* @__PURE__ */ new Set();
148721
+ for (const { row, message: m } of this.owedBy(address, why2, turnSeq)) {
148722
+ if (!this.d.records.markReleased(row.messageId, address, now, why2)) continue;
148723
+ released++;
148724
+ owed.add(m.sender);
148725
+ if (told?.includes(m.sender)) this.d.records.markTold([{ messageId: row.messageId, recipient: address }], now);
148726
+ else senders.add(m.sender);
148697
148727
  }
148728
+ const party = parseAddress(address);
148729
+ const persons = party?.kind === "session" && turnSeq !== null && this.d.records.turn(party.sessionId, turnSeq)?.startedBy === "person";
148730
+ if (starter && starter !== address && !persons && !owed.has(starter) && !told?.includes(starter)) this.tellStarter(starter, address, why2, turnSeq);
148698
148731
  }
148732
+ for (const sender of senders) this.tellUnanswered(sender, now);
148733
+ return released;
148699
148734
  });
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
148735
  }
148704
- /**
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
148708
- */
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);
148722
- });
148736
+ /** The latest turn the mailbox recorded of a session address, 0 when none */
148737
+ latestTurnSeq(address) {
148738
+ const party = parseAddress(address);
148739
+ return party?.kind === "session" ? this.d.records.nextTurnSeq(party.sessionId) - 1 : 0;
148740
+ }
148741
+ /** What `stopped`'s stop notice to `sender` quotes of its cut turn `turnSeq` (owner, #1948): its words when `quotes` allows it, else null */
148742
+ quoteFor(stopped, sender, turnSeq) {
148743
+ return turnSeq !== null && this.quotes(stopped, sender, turnSeq) ? this.d.stoppedWords?.(stopped) ?? null : null;
148723
148744
  }
148724
148745
  /**
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)
148746
+ * 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
148747
+ * to a session quotes by (security-boundaries/inter-agent-content.md). `sender` is a session that can read `stopped` with read_session
148748
+ * (`mayRead`, that tool's own rule), and the turn is `sender`'s alone (`alone`)
148727
148749
  */
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"]) };
148750
+ quotes(stopped, sender, turnSeq) {
148751
+ return this.d.mayRead?.(sender, stopped) === true && this.alone(stopped, sender, { turnSeq });
148737
148752
  }
148738
148753
  /**
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
148754
+ * 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
148755
+ * answer the session's cards as its work's giver (docs/plans/mailbox.md §10.6.4). All of it must hold:
148756
+ * - 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`
148757
+ * 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
148758
+ * CLI started by itself (`cli`), or the person's, is never `sender`'s alone, even when it goes on with a task's work;
148759
+ * - every message the mailbox gave into it is from `sender`;
148760
+ * - everything else that may have entered it (`turnInputs`: each user row stored since the turn before began, and a question card answered
148761
+ * since) was sent by `sender`: none from the person, an app, a script, a relayed report or another session.
148762
+ * 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
148763
+ * `caller` turn), not a mail the mailbox delivered
148741
148764
  */
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);
148765
+ alone(session2, sender, { turnSeq, gaveIt = false } = {}) {
148766
+ const [party, from] = [parseAddress(session2), parseAddress(sender)];
148767
+ if (party?.kind !== "session" || from?.kind !== "session") return false;
148768
+ const seq = turnSeq ?? this.d.records.nextTurnSeq(party.sessionId) - 1;
148769
+ if (this.d.records.nextTurnSeq(party.sessionId) !== seq + 1) return false;
148770
+ const turn = this.d.records.turn(party.sessionId, seq);
148771
+ if (!turn || turn.startedBy !== "caller" && (gaveIt || turn.startedBy !== "mail") || turn.starterId === null || this.d.records.message(turn.starterId)?.sender !== sender) return false;
148772
+ if (this.d.records.inTurn(session2, seq).some((r) => r.message.sender !== sender)) return false;
148773
+ const given = this.d.turnInputs?.(party.sessionId);
148774
+ return given !== void 0 && given.every((id3) => id3 === from.sessionId);
148770
148775
  }
148771
148776
  /**
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
148777
+ * 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
148778
+ * 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
148779
+ * 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
148780
+ * 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
148781
+ * stay open and the next start finds them again
148774
148782
  */
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);
148783
+ turnsLost(close) {
148784
+ this.releaseAndTell((now, senders) => {
148785
+ for (const { address, turnSeq } of close()) {
148786
+ for (const { row, message } of this.cutQuestions(address, turnSeq)) if (this.d.records.markReleased(row.messageId, address, now, "lost")) senders.add(message.sender);
149257
148787
  }
149258
148788
  });
149259
148789
  }
@@ -149461,6 +148991,7 @@ function checkedChoices(c, cls, to, question) {
149461
148991
  return choices;
149462
148992
  }
149463
148993
  var CHOICE_CHARS = 80;
148994
+ var SUBJECT_CHARS = 80;
149464
148995
  var MessageService = class {
149465
148996
  constructor(records, reach, opts) {
149466
148997
  this.records = records;
@@ -149561,7 +149092,7 @@ var MessageService = class {
149561
149092
  const facts = { ...clarifies !== void 0 ? { clarifies } : {}, ...quiet ? { quiet: true } : {}, ...cited ? { cites: cited } : {}, ...input.picked && cls === "person" ? { picked: true } : {} };
149562
149093
  const stored = this.put(
149563
149094
  // 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) } : {} },
149095
+ { ...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
149096
  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
149097
  );
149567
149098
  const held3 = to.flatMap((recipient, i) => holds[i] ? [{ recipient, why: holds[i] }] : []);
@@ -150063,7 +149594,7 @@ var MessageService = class {
150063
149594
  let stored;
150064
149595
  try {
150065
149596
  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 },
149597
+ { 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 },
150067
149598
  rows3
150068
149599
  );
150069
149600
  } catch (e) {
@@ -150214,7 +149745,7 @@ var MessageService = class {
150214
149745
  }
150215
149746
  /** The line for an earlier message that is no longer kept (S5) */
150216
149747
  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 };
149748
+ 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 };
150218
149749
  return { message: stub, row: null, relation: "", phantom: "gone" };
150219
149750
  }
150220
149751
  frameItem(recipient, m, relation, inline, maybeRepeated) {
@@ -150244,6 +149775,517 @@ var MessageService = class {
150244
149775
  var citeKey = (seq) => `cite:${seq}`;
150245
149776
  var isHidden = (row) => HIDDEN_HOLDS.includes(row.held ?? "");
150246
149777
 
149778
+ // packages/agent-host/src/mail/person.ts
149779
+ var THREAD_PAGE = 100;
149780
+ var LIST_CHAINS = 100;
149781
+ var LIST_SCAN = 1e3;
149782
+ var CHAIN_CAP = 1e3;
149783
+ var PREVIEW_CHARS2 = 140;
149784
+ var PERSON_HOLDS = ["uncertain", "failed", "loop", "budget", "policy"];
149785
+ function subjectLine(m) {
149786
+ const script = m.facts.fromScript?.credential;
149787
+ return m.subject ?? oneLineText(script === void 0 ? m.body : `The script "${script}": ${m.body}`, SUBJECT_CHARS);
149788
+ }
149789
+ var MailPerson = class {
149790
+ constructor(service, records, delivery, host) {
149791
+ this.service = service;
149792
+ this.records = records;
149793
+ this.delivery = delivery;
149794
+ this.host = host;
149795
+ }
149796
+ service;
149797
+ records;
149798
+ delivery;
149799
+ host;
149800
+ list() {
149801
+ const heldRows = this.records.heldRows();
149802
+ const heldBy = /* @__PURE__ */ new Map();
149803
+ const held3 = [];
149804
+ for (const r of heldRows) {
149805
+ const m = this.records.message(r.messageId);
149806
+ if (!m || r.held === null) continue;
149807
+ heldBy.set(m.rootId, (heldBy.get(m.rootId) ?? 0) + 1);
149808
+ held3.push({
149809
+ messageId: m.id,
149810
+ threadId: m.rootId,
149811
+ subject: this.subjectOf(m.rootId),
149812
+ sender: this.party(m.sender),
149813
+ recipient: this.party(r.recipient),
149814
+ kind: windowKind(m),
149815
+ reason: r.held,
149816
+ preview: oneLineText(m.body, PREVIEW_CHARS2),
149817
+ since: m.createdAt
149818
+ });
149819
+ }
149820
+ const roots = [];
149821
+ for (const m of this.records.feedOf(PERSON, { limit: LIST_SCAN })) {
149822
+ if (!roots.includes(m.rootId)) roots.push(m.rootId);
149823
+ if (roots.length >= LIST_CHAINS) break;
149824
+ }
149825
+ 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);
149826
+ return { threads, held: held3, waiting: this.delivery.crowdWaiting() };
149827
+ }
149828
+ /** 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 */
149829
+ thread(threadId, opts = {}) {
149830
+ const root3 = this.rootsOf(threadId)[0];
149831
+ if (root3 === void 0) throw refuse4("unknown_message", `There is no mail ${threadId} kept.`);
149832
+ const all = this.shown(root3);
149833
+ let page;
149834
+ if (opts.after !== void 0) page = all.filter((s) => s.seq > (opts.after ?? 0)).slice(0, opts.all ? void 0 : THREAD_PAGE);
149835
+ else if (opts.tail !== void 0 || !opts.all) {
149836
+ const upTo = opts.before === void 0 ? all : all.filter((s) => s.seq < (opts.before ?? 0));
149837
+ page = upTo.slice(-Math.min(opts.tail ?? THREAD_PAGE, THREAD_PAGE));
149838
+ } else page = all;
149839
+ 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();
149840
+ const first = page[0]?.seq;
149841
+ const last = page.at(-1)?.seq;
149842
+ const legacy = this.legacyOf(all[0]?.m);
149843
+ const fromStart = first === void 0 || first === all[0]?.seq;
149844
+ const messages2 = [...(fromStart ? legacy : []).map((m, i) => legacyMessage(m, i - legacy.length + 1, (a) => this.party(a))), ...page.map((s) => this.message(s))];
149845
+ return {
149846
+ thread: this.row(root3, this.heldIn(root3)) ?? this.emptyRow(root3),
149847
+ parties: this.partiesOf(all.map((s) => s.m)),
149848
+ blockers: [],
149849
+ messages: messages2,
149850
+ more: last !== void 0 && all.some((s) => s.seq > last),
149851
+ older: first !== void 0 && all.some((s) => s.seq < first),
149852
+ follows: [],
149853
+ canReply: this.replyTarget([root3]) !== void 0
149854
+ };
149855
+ }
149856
+ /**
149857
+ * 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
149858
+ * 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
149859
+ * message hidden from the person, are passed over. A question waits for an answer (D3); an answer or a note does not
149860
+ */
149861
+ reply(threadId, text3, kind = "note", answers2) {
149862
+ const roots = this.rootsOf(threadId);
149863
+ const found = answers2 === void 0 ? this.replyTarget(roots) : this.pickTarget(roots, answers2, text3);
149864
+ if (!found) throw refuse4("unknown_message", `There is no message in ${threadId} to answer.`);
149865
+ const { target, to } = found;
149866
+ const sent = this.service.send(PERSON, { to, text: text3, replyTo: target.id, needsReply: kind === "question", ...answers2 === void 0 ? {} : { picked: true } });
149867
+ const at2 = this.shown(target.rootId).find((s) => s.m.id === sent.message.id)?.seq ?? 1;
149868
+ return this.thread(target.rootId, { after: at2 - 1 });
149869
+ }
149870
+ /**
149871
+ * 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
149872
+ * 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
149873
+ */
149874
+ replyTarget(roots) {
149875
+ 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));
149876
+ const toPerson = chain.filter((m) => {
149877
+ const row = this.records.recipient(m.id, PERSON);
149878
+ return m.sender !== PERSON && parseAddress(m.sender)?.kind !== "centralu" && row !== void 0 && !hiddenFromPerson(row) && this.here(m.sender);
149879
+ });
149880
+ const open6 = toPerson.findLast((m) => {
149881
+ const row = this.records.recipient(m.id, PERSON);
149882
+ return m.needsReply && row !== void 0 && row.answerId === null && (row.settled === null || row.settled === "legacy");
149883
+ });
149884
+ const theirs = open6 ?? toPerson.at(-1);
149885
+ const mine = chain.findLast((m) => m.sender === PERSON && this.records.recipients(m.id).some((r) => this.here(r.recipient)));
149886
+ const target = theirs ?? mine;
149887
+ if (!target) return void 0;
149888
+ const to = target === theirs ? [target.sender] : this.records.recipients(target.id).flatMap((r) => this.here(r.recipient) ? [r.recipient] : []);
149889
+ return { target, to };
149890
+ }
149891
+ /**
149892
+ * 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
149893
+ * here, whose choices include `text`, and not answered already (a question is answered once, whichever window gives the answer first)
149894
+ */
149895
+ pickTarget(roots, id3, text3) {
149896
+ const target = roots.flatMap((root3) => this.shown(root3).map((s) => s.m)).find((m) => m.id === id3);
149897
+ const row = target && this.records.recipient(target.id, PERSON);
149898
+ if (!target || !row || hiddenFromPerson(row) || !this.here(target.sender)) return void 0;
149899
+ if (!target.choices?.includes(text3)) throw refuse4("bad_value", `${id3} does not offer that choice.`);
149900
+ if (row.answerId !== null || row.settled !== null && row.settled !== "legacy") throw refuse4("answered", REFUSAL_TEXT.answered(id3));
149901
+ return { target, to: [target.sender] };
149902
+ }
149903
+ /** Whether mail to `address` can still reach it: a session this host keeps (trashed or deleted ones are gone), or any other party */
149904
+ here(address) {
149905
+ const party = parseAddress(address);
149906
+ return party?.kind !== "session" || this.host.session(party.sessionId) !== void 0;
149907
+ }
149908
+ /**
149909
+ * 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
149910
+ * 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`:
149911
+ * undelivered ones are never delivered, and no report of them is written). Nothing is stopped: the turn may carry other requests, and the
149912
+ * 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
149913
+ * 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
149914
+ * 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
149915
+ * is listed again as open and unread
149916
+ */
149917
+ close(threadId, outcome = "finished") {
149918
+ const roots = this.rootsOf(threadId);
149919
+ const root3 = roots[0];
149920
+ if (root3 === void 0) throw refuse4("unknown_message", `There is no mail ${threadId} kept.`);
149921
+ const now = Date.now();
149922
+ const tell = /* @__PURE__ */ new Map();
149923
+ this.records.transaction(() => {
149924
+ for (const r of roots) {
149925
+ const chain = this.chainOf(r);
149926
+ const asked = [];
149927
+ for (const m of chain) {
149928
+ if (m.sender !== PERSON || !(m.needsReply || m.kind === "task")) continue;
149929
+ 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" });
149930
+ }
149931
+ const working = this.workers(chain);
149932
+ this.records.closeFor(
149933
+ PERSON,
149934
+ this.shown(r).map((s) => s.m.id),
149935
+ now
149936
+ );
149937
+ const withdrawn = asked.filter((a) => this.records.settle(a.id, a.recipient, "withdrawn", now) > 0);
149938
+ for (const m of chain) {
149939
+ 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);
149940
+ }
149941
+ this.records.markClosed(r, outcome, now);
149942
+ const end = chain.at(-1)?.id ?? r;
149943
+ const add2 = (sessionId, address, id3) => {
149944
+ const kept = tell.get(sessionId) ?? { address, root: r, ids: [], ends: [] };
149945
+ if (id3 !== void 0 && !kept.ids.includes(id3)) kept.ids.push(id3);
149946
+ if (!kept.ends.includes(end)) kept.ends.push(end);
149947
+ tell.set(sessionId, kept);
149948
+ };
149949
+ for (const w of working) add2(w.sessionId, w.address);
149950
+ for (const a of withdrawn) {
149951
+ const party = parseAddress(a.recipient);
149952
+ if (party?.kind !== "session" || !a.seen || !this.here(a.recipient)) continue;
149953
+ add2(party.sessionId, a.recipient, a.id);
149954
+ }
149955
+ }
149956
+ });
149957
+ for (const r of roots) this.service.announce(r);
149958
+ for (const [sessionId, t] of tell) this.tellClosed(outcome, sessionId, t);
149959
+ return this.row(root3, this.heldIn(root3)) ?? this.emptyRow(root3);
149960
+ }
149961
+ /**
149962
+ * 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
149963
+ * 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
149964
+ * mail. A process that fails to take it leaves the notice as undelivered mail, which goes again with the session's next mail
149965
+ */
149966
+ tellClosed(outcome, sessionId, t) {
149967
+ const text3 = closedWords(t.root, outcome, t.ids);
149968
+ const now = this.host.tellsNow(sessionId);
149969
+ const stored = this.service.notice(t.address, {
149970
+ body: text3,
149971
+ facts: { quiet: true, chainClosed: { root: t.root, outcome, withdrawn: t.ids.slice(0, 10) } },
149972
+ dedupeKey: `closed:${t.address}:${t.ends.join(",")}`,
149973
+ delivered: now
149974
+ });
149975
+ if (!stored || !now) return;
149976
+ const at2 = this.records.recipient(stored.id, t.address)?.deliveredAt;
149977
+ this.host.tell(sessionId, text3).catch(() => {
149978
+ if (at2 != null) this.service.deliveryFailedLate(t.address, [stored.id], at2);
149979
+ });
149980
+ }
149981
+ /**
149982
+ * 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
149983
+ * 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)
149984
+ */
149985
+ held(action, recipient, messageIds) {
149986
+ if (action === "dismiss") return { changed: this.service.dismissHeld(recipient, messageIds, PERSON_HOLDS) };
149987
+ const projects = new Set(messageIds.flatMap((id3) => this.records.recipient(id3, recipient)?.held === "policy" ? this.records.message(id3)?.senderProject ?? [] : []));
149988
+ const still = [...projects].find((p) => this.host.untrusted(p));
149989
+ 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.`);
149990
+ const policy = messageIds.filter((id3) => this.records.recipient(id3, recipient)?.held === "policy");
149991
+ for (const p of projects) this.trusted(p);
149992
+ const letGo = policy.filter((id3) => this.records.recipient(id3, recipient)?.held !== "policy").length;
149993
+ return { changed: letGo + this.service.resendHeld(recipient, messageIds, ["uncertain", "failed", "budget"]) };
149994
+ }
149995
+ /**
149996
+ * 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
149997
+ * 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
149998
+ */
149999
+ resume(target) {
150000
+ const rows3 = this.records.heldRows();
150001
+ if (target.sessionId !== void 0) {
150002
+ const recipient = this.service.sessionAddress(target.sessionId);
150003
+ const ids = rows3.flatMap((r) => r.recipient === recipient && r.held === "budget" ? [r.messageId] : []);
150004
+ if (ids.length > 0) this.service.resendHeld(recipient, ids, ["budget"]);
150005
+ } else if (target.threadId !== void 0) {
150006
+ const roots = new Set(this.rootsOf(target.threadId));
150007
+ const ids = new Set(rows3.flatMap((r) => r.held === "loop" && roots.has(this.records.message(r.messageId)?.rootId ?? "") ? [r.messageId] : []));
150008
+ for (const id3 of ids) this.service.resumeHeld(id3);
150009
+ }
150010
+ }
150011
+ /** 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 */
150012
+ trusted(projectId) {
150013
+ for (const address of this.service.trustChanged(projectId)) {
150014
+ const party = parseAddress(address);
150015
+ if (party?.kind === "session") this.delivery.poke(party.sessionId);
150016
+ }
150017
+ this.service.announce();
150018
+ }
150019
+ /** 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) */
150020
+ projectDeleted(projectId, name) {
150021
+ this.service.dismissProject(projectId, name);
150022
+ this.service.announce();
150023
+ }
150024
+ /** The project's name now, for `projectDeleted` once it is gone */
150025
+ projectName(projectId) {
150026
+ return this.host.projectLabel(projectId);
150027
+ }
150028
+ /**
150029
+ * 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
150030
+ * window waits for an answer. The list shows who is still waiting as it goes
150031
+ */
150032
+ wake(wake) {
150033
+ this.delivery.answerCrowd(wake).catch((e) => console.error(`[mail] waking the sessions failed: ${errorMessage(e)}`));
150034
+ }
150035
+ // ── Chains ──
150036
+ /** Every message of the chain, readable by the person or not: what a turn's work may be */
150037
+ chainOf(root3) {
150038
+ return this.records.numbered(root3, CHAIN_CAP).map(({ m }) => m);
150039
+ }
150040
+ /** 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) */
150041
+ workers(chain) {
150042
+ const ids = new Set(chain.map((m) => m.id));
150043
+ const sessions = /* @__PURE__ */ new Map();
150044
+ for (const m of chain) {
150045
+ for (const address of [m.sender, ...this.records.recipients(m.id).map((r) => r.recipient)]) {
150046
+ const party = parseAddress(address);
150047
+ if (party?.kind === "session") sessions.set(party.sessionId, address);
150048
+ }
150049
+ }
150050
+ return [...sessions].flatMap(([sessionId, address]) => {
150051
+ const turn = this.host.turnOn(sessionId);
150052
+ return turn && turn.work !== null && ids.has(turn.work) ? [{ sessionId, address }] : [];
150053
+ });
150054
+ }
150055
+ /** Every chain an id names: a message's root, or each chain moved from an old thread, newest first */
150056
+ rootsOf(id3) {
150057
+ const m = this.records.message(id3);
150058
+ return m ? [m.rootId] : this.records.movedFrom(id3);
150059
+ }
150060
+ /**
150061
+ * 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,
150062
+ * goes or stops being readable leaves the others' numbers as they were, so the window's `after` misses nothing
150063
+ */
150064
+ shown(root3) {
150065
+ return this.records.numbered(root3, CHAIN_CAP).map(({ m, n }) => ({ m, seq: n })).filter((s) => this.readable(s.m));
150066
+ }
150067
+ /** The person reads what they sent, what was sent to them, and what is held for them to act on (§5.5, §7.4) */
150068
+ readable(m) {
150069
+ if (m.sender === PERSON) return true;
150070
+ return this.records.recipients(m.id).some((r) => r.recipient === PERSON && !hiddenFromPerson(r) || isPersonHold(r.held));
150071
+ }
150072
+ /** An old thread's messages before the first one moved from it: the chain's history, read-only (§6.3) */
150073
+ legacyOf(first) {
150074
+ if (!first?.legacyThread) return [];
150075
+ const moved = new Set(this.records.byRoot(first.rootId, { limit: CHAIN_CAP }).map((m) => m.id));
150076
+ const earlier = [];
150077
+ for (const m of this.host.legacyChain(first.legacyThread)) {
150078
+ if (m.id === first.id || moved.has(m.id)) break;
150079
+ earlier.push(m);
150080
+ }
150081
+ return earlier;
150082
+ }
150083
+ heldIn(root3) {
150084
+ return this.records.heldRows().filter((r) => this.records.message(r.messageId)?.rootId === root3).length;
150085
+ }
150086
+ subjectOf(root3) {
150087
+ const first = this.shown(root3)[0]?.m ?? this.records.message(root3);
150088
+ return first ? subjectLine(first) : root3;
150089
+ }
150090
+ /**
150091
+ * 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
150092
+ * 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
150093
+ * 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
150094
+ * named on it is the one whose turn is on it, else the first one the person's first message went to
150095
+ */
150096
+ row(root3, held3) {
150097
+ const all = this.shown(root3).map((s) => s.m);
150098
+ const first = all[0];
150099
+ const last = all.at(-1);
150100
+ if (!first || !last) return null;
150101
+ const toPerson = all.flatMap((m) => this.records.recipient(m.id, PERSON) ?? []);
150102
+ 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"));
150103
+ 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));
150104
+ const closedAs = this.records.message(root3)?.facts.closed?.outcome;
150105
+ const done2 = (closedAs !== void 0 || toPerson.some((r) => r.settled === "done") || tasks.some((r) => r.settled === "done")) && !waits;
150106
+ const working = done2 ? [] : this.workers(this.chainOf(root3));
150107
+ 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";
150108
+ const assignee = working[0]?.address ?? (first.sender === PERSON ? this.records.recipients(first.id)[0]?.recipient : void 0);
150109
+ return {
150110
+ id: root3,
150111
+ subject: subjectLine(first),
150112
+ state,
150113
+ outcome: done2 ? closedAs ?? "finished" : null,
150114
+ next: null,
150115
+ projectId: first.senderProject,
150116
+ owner: this.party(first.sender),
150117
+ assignee: assignee === void 0 ? null : this.party(assignee),
150118
+ unread: toPerson.filter((r) => r.readAt === null && !hiddenFromPerson(r)).length,
150119
+ held: held3,
150120
+ blocked: 0,
150121
+ working: working.length > 0,
150122
+ createdAt: first.createdAt,
150123
+ updatedAt: last.createdAt,
150124
+ last: { sender: this.party(last.sender), kind: windowKind(last), preview: oneLineText(last.body, PREVIEW_CHARS2), at: last.createdAt }
150125
+ };
150126
+ }
150127
+ /** A chain whose every message the person may not read (held for them, then let go): a row with nothing in it */
150128
+ emptyRow(root3) {
150129
+ const m = this.records.message(root3);
150130
+ const at2 = m?.createdAt ?? 0;
150131
+ 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 };
150132
+ }
150133
+ // ── Shapes ──
150134
+ /** 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) */
150135
+ changeEvent(c) {
150136
+ const toPerson = c.recipients.includes(PERSON);
150137
+ const arrived = c.arrived && toPerson ? this.arrival(c.messageId) : void 0;
150138
+ return { type: "mail_changed", threadId: c.rootId, toPerson, ...arrived ? { arrived } : {} };
150139
+ }
150140
+ /** A new message as the person's notification names it (`mail_changed.arrived`): one they can read, not their own */
150141
+ arrival(messageId) {
150142
+ const m = this.records.message(messageId);
150143
+ const row = this.records.recipient(messageId, PERSON);
150144
+ if (!m || !row || m.sender === PERSON || hiddenFromPerson(row) || row.held !== null) return void 0;
150145
+ return { messageId, from: this.party(m.sender), kind: windowKind(m), preview: oneLineText(m.body, PREVIEW_CHARS2) };
150146
+ }
150147
+ party(address) {
150148
+ const p = parseAddress(address);
150149
+ if (p?.kind === "session") {
150150
+ const s = this.host.session(p.sessionId);
150151
+ return { address, kind: "session", sessionId: p.sessionId, name: s?.name ?? null, state: s?.state ?? null };
150152
+ }
150153
+ if (p?.kind === "app") return { address, kind: "app", sessionId: null, name: p.appId, state: null };
150154
+ return { address, kind: p?.kind ?? "unknown", sessionId: null, name: null, state: null };
150155
+ }
150156
+ partiesOf(chain) {
150157
+ const addresses = /* @__PURE__ */ new Set();
150158
+ for (const m of chain) {
150159
+ addresses.add(m.sender);
150160
+ for (const r of this.records.recipients(m.id)) addresses.add(r.recipient);
150161
+ }
150162
+ return [...addresses].filter((a) => parseAddress(a)?.kind === "session" || parseAddress(a)?.kind === "app").map((a) => ({ party: this.party(a), role: "member" }));
150163
+ }
150164
+ message({ m, seq }) {
150165
+ return {
150166
+ id: m.id,
150167
+ seq,
150168
+ sender: this.party(m.sender),
150169
+ kind: windowKind(m),
150170
+ urgent: m.urgent,
150171
+ body: m.body,
150172
+ facts: { ...m.facts },
150173
+ ...m.choices ? { choices: m.choices } : {},
150174
+ ...m.replyTo !== null ? { replyTo: m.replyTo } : {},
150175
+ createdAt: m.createdAt,
150176
+ ...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 })) } : {}
150177
+ };
150178
+ }
150179
+ };
150180
+ function closedWords(root3, outcome, ids) {
150181
+ const what = outcome === "dropped" ? "dropped" : outcome === "finished" ? "marked done" : "closed";
150182
+ const shown3 = ids.slice(0, 10).join(", ") + (ids.length > 10 ? `, and ${ids.length - 10} more` : "");
150183
+ const withdrew = ids.length === 0 ? "" : ` and withdrew what they asked of you in it (${shown3})`;
150184
+ 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.`;
150185
+ }
150186
+ function windowKind(m) {
150187
+ if (typeof m.facts.legacyKind === "string") return m.facts.legacyKind;
150188
+ if (m.kind === "task") return "assign";
150189
+ if (m.kind === "message") return m.needsReply ? "question" : m.replyTo === null ? "note" : "answer";
150190
+ return m.kind;
150191
+ }
150192
+ function legacyMessage(m, seq, party) {
150193
+ return { id: m.id, seq, sender: party(m.sender), kind: m.kind, urgent: m.urgent, body: m.body, facts: { ...m.facts }, createdAt: m.createdAt };
150194
+ }
150195
+ function isPersonHold(held3) {
150196
+ return PERSON_HOLDS.some((h) => h === held3);
150197
+ }
150198
+ function hiddenFromPerson(r) {
150199
+ return r.held === "policy" || r.held === "loop" || r.held === "dismissed" || r.settled === "withdrawn" || r.settled === "gone";
150200
+ }
150201
+
150202
+ // packages/agent-host/src/mail/adoption.ts
150203
+ var RETIRED_SESSION_KEYS = ["turn_inputs", "report_turn", "input_origins", "report_paused", "person_report_paused"];
150204
+ function takeOverFromEarlierBuild(mail, store2, sessions) {
150205
+ let queued2 = 0;
150206
+ for (const r of store2.children.listQueuedRequests()) {
150207
+ if (!SEND_ORIGINS.has(r.via)) continue;
150208
+ try {
150209
+ store2.mailbox.transaction(() => {
150210
+ if (sessions.info(r.sessionId) && sessions.info(r.callerSessionId)) {
150211
+ mail.task(mail.sessionAddress(r.callerSessionId), mail.sessionAddress(r.sessionId), { text: r.text, origin: r.via, delivered: false });
150212
+ queued2++;
150213
+ }
150214
+ store2.children.removeQueuedRequest(r.id);
150215
+ });
150216
+ } catch (e) {
150217
+ console.error(`[mail] could not take the request an earlier build queued for ${r.sessionId.slice(0, 8)} (${errorMessage(e)})`);
150218
+ }
150219
+ }
150220
+ let adopted = 0;
150221
+ for (const mark of store2.children.listReportMarks()) {
150222
+ const child = sessions.info(mark.sessionId);
150223
+ const owner = mail.sessionAddress(mark.callerSessionId);
150224
+ const childAddress = mail.sessionAddress(mark.sessionId);
150225
+ try {
150226
+ store2.mailbox.transaction(() => {
150227
+ if (mark.sessionId !== mark.callerSessionId && child && sessions.info(mark.callerSessionId) && !store2.mailbox.newestTask(owner, childAddress)) {
150228
+ mail.task(owner, childAddress, { text: ADOPTED_TASK, origin: child.askedBy === mark.callerSessionId ? "start_agent" : "send_to_session", delivered: true });
150229
+ adopted++;
150230
+ }
150231
+ store2.children.clearReportMark(mark.sessionId);
150232
+ });
150233
+ } catch (e) {
150234
+ console.error(`[mail] could not adopt the report mark of ${mark.sessionId.slice(0, 8)} (${errorMessage(e)})`);
150235
+ }
150236
+ }
150237
+ store2.settings.deleteSessionSettings(RETIRED_SESSION_KEYS);
150238
+ return { queued: queued2, adopted };
150239
+ }
150240
+ function leaveForEarlierBuild(mail, store2, inTurnNow) {
150241
+ const work = new Map(store2.mailbox.openTurns().map((t) => [t.sessionId, t.messageId]));
150242
+ for (const id3 of inTurnNow) {
150243
+ const address = mail.sessionAddress(id3);
150244
+ const open6 = store2.mailbox.watchedTo(address).map((r) => store2.mailbox.message(r.messageId)).filter((m) => m?.kind === "task" && parseAddress(m.sender)?.kind === "session");
150245
+ const task = open6.find((m) => m?.id === work.get(id3)) ?? open6.at(-1);
150246
+ const caller = task ? parseAddress(task.sender) : null;
150247
+ if (caller?.kind === "session") store2.children.setReportMark(id3, caller.sessionId);
150248
+ }
150249
+ }
150250
+
150251
+ // packages/agent-host/src/mail/asked-by.ts
150252
+ function askerFacts(host, sessionId) {
150253
+ const session2 = host.session(sessionId);
150254
+ const projectId = session2 ? session2.projectId : "gone";
150255
+ const project2 = projectId ? host.project(projectId) : void 0;
150256
+ return { name: session2?.name ?? sessionId.slice(0, 8), project: project2?.name ?? null, trusted: !host.untrusted(projectId) };
150257
+ }
150258
+ function askedBy(host, assistantId) {
150259
+ const inTurn2 = host.requestsInTurn(assistantId);
150260
+ const [first, ...rest] = inTurn2?.requests ?? [];
150261
+ if (!inTurn2 || !first) return null;
150262
+ return {
150263
+ messageId: first.messageId,
150264
+ sessionId: first.sessionId,
150265
+ turn: inTurn2.turnSeq,
150266
+ ...askerFacts(host, first.sessionId),
150267
+ cites: host.cites(first.messageId),
150268
+ ...rest.length > 0 ? { also: rest.map((r) => ({ sessionId: r.sessionId, ...askerFacts(host, r.sessionId) })) } : {}
150269
+ };
150270
+ }
150271
+
150272
+ // packages/agent-host/src/mail/card-notices.ts
150273
+ function cardGivers(records, address, alone) {
150274
+ const givers = openTaskParties(records, address, "to");
150275
+ const [only] = givers.length === 1 ? givers : [];
150276
+ return { givers, answerer: only !== void 0 && alone(only) ? only : null };
150277
+ }
150278
+ function tellCard(service, giver, card, body, delivered) {
150279
+ const written = service.notice(giver, { body, facts: { card, about: { session: card.session } }, dedupeKey: `card:${giver}:${card.session}:${card.handle}`, delivered });
150280
+ return written?.id ?? null;
150281
+ }
150282
+ function withdrawEndedCards(records, session2, stands2) {
150283
+ records.transaction(() => {
150284
+ const gone2 = records.undeliveredCardNotices(session2).filter(({ message: { facts } }) => facts.card && !stands2(facts.card.session, facts.card.requestId));
150285
+ if (gone2.length) records.deleteRows(gone2.map(({ row }) => ({ messageId: row.messageId, recipient: row.recipient })));
150286
+ });
150287
+ }
150288
+
150247
150289
  // packages/agent-host/src/mail/tool.ts
150248
150290
  var MailTool = class {
150249
150291
  constructor(service, records, reach, host) {
@@ -150258,8 +150300,6 @@ var MailTool = class {
150258
150300
  reach;
150259
150301
  host;
150260
150302
  now;
150261
- /** The sessions told once that `assistant` is not their parent (#1984) */
150262
- hinted = /* @__PURE__ */ new Set();
150263
150303
  run(sessionId, args) {
150264
150304
  try {
150265
150305
  const me2 = this.host.caller(sessionId);
@@ -150274,7 +150314,7 @@ var MailTool = class {
150274
150314
  * session on another computer goes to that computer, which writes it or refuses it (#2067 items 2 and 3,
150275
150315
  * docs/plans/linked-mail.md §6 to §8). Nothing is written here unless it took the message
150276
150316
  */
150277
- async call(sessionId, args) {
150317
+ async call(sessionId, args, signal) {
150278
150318
  const me2 = this.host.caller(sessionId);
150279
150319
  const across = this.host.across;
150280
150320
  if (!me2) return this.run(sessionId, args);
@@ -150283,6 +150323,8 @@ var MailTool = class {
150283
150323
  if (!across) return { text: "Finding sessions is not available here.", isError: true };
150284
150324
  return { text: await across.find((args.to ?? args.text ?? "").trim(), me2.address) };
150285
150325
  }
150326
+ const work = await this.work(sessionId, me2, args, signal);
150327
+ if (work) return work;
150286
150328
  const far = across ? await this.acrossTarget(sessionId, me2, args, across) : null;
150287
150329
  if (!far || !across) return this.run(sessionId, args);
150288
150330
  if (args.cite) {
@@ -150340,6 +150382,28 @@ var MailTool = class {
150340
150382
  const n = shown3.length;
150341
150383
  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
150384
  }
150385
+ /**
150386
+ * `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
150387
+ * never work. The subject leads the words, so the child reads what the card shows, and the answer says it went as work
150388
+ */
150389
+ async work(sessionId, me2, a, signal) {
150390
+ const t = a.to?.trim() ?? "";
150391
+ if (a.action !== "send" || !this.host.work || !t || [PERSON, "assistant", "parent"].includes(t.toLowerCase()) || !a.text?.trim()) return null;
150392
+ const own = me2.address.slice(0, me2.address.lastIndexOf("/") + 1);
150393
+ const word = t.startsWith(own) ? t.slice(own.length) : t;
150394
+ const [only, other] = this.sessionsNamed(sessionId, word);
150395
+ const subject = a.subject?.trim() ? `${oneLineText(a.subject, SUBJECT_CHARS)}
150396
+
150397
+ ` : "";
150398
+ const r = await this.host.work(sessionId, only && !other ? only.id : word, subject + a.text.trim(), a.ifBusy, signal);
150399
+ 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;
150400
+ }
150401
+ /** 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) */
150402
+ sessionsNamed(sessionId, word) {
150403
+ const here = this.host.sessions();
150404
+ const exact = here.find((s) => s.id === word);
150405
+ return exact ? [exact] : here.filter((s) => s.id !== sessionId && s.name.trim().toLowerCase() === word.toLowerCase());
150406
+ }
150343
150407
  dispatch(sessionId, me2, a, calls) {
150344
150408
  switch (a.action) {
150345
150409
  case "inbox":
@@ -150350,8 +150414,8 @@ var MailTool = class {
150350
150414
  return this.handled(me2.address, this.target(me2.address, this.need(a.thread, "thread")));
150351
150415
  case "send": {
150352
150416
  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);
150417
+ 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 } : {} });
150418
+ return this.sent(sent);
150355
150419
  }
150356
150420
  case "reply": {
150357
150421
  const id3 = this.target(me2.address, this.need(a.thread, "thread"));
@@ -150407,10 +150471,7 @@ var MailTool = class {
150407
150471
  if (absolute && !(absolute.kind === "session" && t.startsWith(own))) return { address: t };
150408
150472
  const word = t.startsWith(own) ? t.slice(own.length) : t;
150409
150473
  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());
150474
+ const named3 = this.sessionsNamed(sessionId, word);
150414
150475
  const [only] = named3;
150415
150476
  if (only && named3.length === 1) return { address: this.service.sessionAddress(only.id) };
150416
150477
  if (!only && parseAddress(own + word) && this.reach.elsewhere(own + word)) return { address: own + word };
@@ -150423,15 +150484,6 @@ var MailTool = class {
150423
150484
  `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
150485
  );
150425
150486
  }
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
150487
  /** `send`'s and `reply`'s answer (S4's lines, in this tool's calls) */
150436
150488
  sent(r) {
150437
150489
  const m = r.message;
@@ -151317,6 +151369,7 @@ function mailSessionsOf(mgr2, assistantHasMailCommand) {
151317
151369
  readsSession: (readerId, targetId) => mgr2.mail.readsSession(readerId, targetId),
151318
151370
  turnInputs: (id3) => mgr2.mail.turnInputs(id3),
151319
151371
  onLinkedMachine: (id3) => mgr2.mail.onLinkedMachine(id3),
151372
+ work: (...a) => mgr2.mail.work(...a),
151320
151373
  settleAtRest: (id3) => mgr2.mail.settleAtRest(id3),
151321
151374
  relayStop: (receiverId, stoppedId, why2, told) => mgr2.mail.relayStop(receiverId, stoppedId, why2, told)
151322
151375
  };
@@ -151455,7 +151508,8 @@ function hostMail(store2, sessions, opts) {
151455
151508
  form: (id3) => sessions.mailCommand(id3) ? "command" : "plain",
151456
151509
  askerOf: (id3) => askerFacts(askedByHost, id3),
151457
151510
  legacyChain: (threadId, messageId, reader) => store2.legacyChainFor(threadId, messageId, reader, 9),
151458
- across
151511
+ across,
151512
+ ...sessions.work ? { work: sessions.work } : {}
151459
151513
  });
151460
151514
  const cardStands = (session2, requestId) => {
151461
151515
  const party = parseAddress(session2);
@@ -151477,7 +151531,7 @@ function hostMail(store2, sessions, opts) {
151477
151531
  // 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
151532
  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
151533
  sessionEvent: (e, ended2) => mailTurns.observe(e, ended2),
151480
- tool: (id3, args) => tool.call(id3, args),
151534
+ tool: (id3, args, signal) => tool.call(id3, args, signal),
151481
151535
  // Work a session gave another is a task, beside the old path that delivered it (§9.1)
151482
151536
  delegated: delegationRecorder(service, mailTurns),
151483
151537
  sendTask: taskSender(service),
@@ -161727,7 +161781,7 @@ var handedToken = launch.tokenOnStdin ? await readHandedToken(process.stdin).cat
161727
161781
  console.error(`[agent-host] the launcher did not hand over the token: ${e.message}`);
161728
161782
  process.exit(1);
161729
161783
  }) : launch.token;
161730
- var BUILD = true ? "6299d64" : "dev";
161784
+ var BUILD = true ? "3c2c2cd" : "dev";
161731
161785
  var { values } = parseArgs({
161732
161786
  options: {
161733
161787
  port: { type: "string", default: "5175" },