@centralu/host-win32-x64 0.1.0-beta.71 → 0.1.0-beta.73

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.71";
43049
+ var APP_VERSION = "0.1.0-beta.73";
43050
43050
 
43051
43051
  // packages/protocol/src/brand.ts
43052
43052
  var APP_NAME = "Centralu";
@@ -57893,6 +57893,7 @@ var HostHandover = external_exports.object({ state: external_exports.enum(["wait
57893
57893
  // packages/protocol/src/machines.ts
57894
57894
  var MACHINE_ID_RE = /^[a-z][a-z0-9-]{0,31}$/;
57895
57895
  var MachineId = external_exports.string().regex(MACHINE_ID_RE, "Not a machine id");
57896
+ var UnreachedMachine = external_exports.object({ machineId: external_exports.string(), name: external_exports.string() });
57896
57897
  var MachineStatus = external_exports.enum([
57897
57898
  "connecting",
57898
57899
  "connected",
@@ -61346,6 +61347,7 @@ var SessionInfo = external_exports.object({
61346
61347
  compactAt: external_exports.number().optional()
61347
61348
  }).nullable().default(null)
61348
61349
  });
61350
+ var LiveStateFields = SessionInfo.pick({ state: true, waitingSince: true, pendingApproval: true, pendingQuestions: true, activity: true, limit: true });
61349
61351
  var SettingsApplied = external_exports.enum(["restarted", "after_turn", "saved"]);
61350
61352
  var UpdateSettingsResult = SessionInfo.extend({ applied: SettingsApplied.optional() });
61351
61353
  function sessionLiveDefaults() {
@@ -61597,7 +61599,13 @@ var HubOffer = external_exports.object({
61597
61599
  mail: external_exports.boolean().optional(),
61598
61600
  you: MachineId.optional(),
61599
61601
  /** The hub answers `hub.apps` and `hub.appCall` (#1938, docs/plans/remote-hub.md §13.6). Additive */
61600
- apps: external_exports.boolean().optional()
61602
+ apps: external_exports.boolean().optional(),
61603
+ /**
61604
+ * The open tasks the hub gave this machine's sessions, by id, oldest first (#2289, docs/plans/linked-mail.md §10): the machine answers which it
61605
+ * lacks (`lacks`), and the hub deletes those copies, as tasks that never arrived. Additive: a machine from before it answers no `lacks`, and the hub
61606
+ * keeps every copy
61607
+ */
61608
+ open: external_exports.array(external_exports.string().min(1).max(200)).max(500).optional()
61601
61609
  });
61602
61610
  var HubProject = external_exports.object({ id: external_exports.string().min(1).max(200), name: external_exports.string().max(500) });
61603
61611
  var HubAskParams = external_exports.object({
@@ -62219,7 +62227,16 @@ var hostResults = {
62219
62227
  // `mail`: this host takes mail from the hub's side (`host.mail`, #2067 item 2), so the hub's task for a child here says to mail
62220
62228
  // `apps`: this host answers `host.apps` and `host.appCall` from the hub (#1938)
62221
62229
  // `tasks`: this host takes the hub's tasks as mail and reports them back (`host.mail` with `task`, #1948 step 6)
62222
- "host.hubOffer": external_exports.object({ ok: external_exports.literal(true), mail: external_exports.boolean().optional(), apps: external_exports.boolean().optional(), tasks: external_exports.boolean().optional() }),
62230
+ // `lacks`: the offer's `open` tasks this host never received (#2289); absent from an older host, which the hub reads as none
62231
+ // `host`: this host's own id in mail addresses (`hubSelfId`), by which the hub reads this host's mail in its own terms (#2268)
62232
+ "host.hubOffer": external_exports.object({
62233
+ ok: external_exports.literal(true),
62234
+ mail: external_exports.boolean().optional(),
62235
+ apps: external_exports.boolean().optional(),
62236
+ tasks: external_exports.boolean().optional(),
62237
+ lacks: external_exports.array(external_exports.string().max(200)).max(500).optional(),
62238
+ host: external_exports.string().max(200).optional()
62239
+ }),
62223
62240
  // As `hub.mail` answers (machines-hub.ts `HubMailResult`, which the window's bundle leaves out, #1648)
62224
62241
  "host.mail": external_exports.union([
62225
62242
  external_exports.object({ ok: external_exports.literal(true), messageId: external_exports.string().min(1).max(200), to: external_exports.string().max(500), address: external_exports.string().max(300).optional() }),
@@ -62252,7 +62269,12 @@ var mailParams = {
62252
62269
  all: external_exports.boolean().optional(),
62253
62270
  /** The last this many messages (at most 100), and the thread is read to its end; with `before`, the last this many before that `seq`, read already */
62254
62271
  tail: external_exports.number().int().min(1).max(100).optional(),
62255
- before: external_exports.number().int().min(1).optional()
62272
+ before: external_exports.number().int().min(1).optional(),
62273
+ /**
62274
+ * Read it as a look in (#2268): nothing in it is read for anyone. A hub sends it for a linked machine's chain it opens from its Tasks, which it shows
62275
+ * read-only. Absent: false. A host from before it drops it and reads what is the person's there for them, as before
62276
+ */
62277
+ lookIn: external_exports.boolean().default(false)
62256
62278
  }),
62257
62279
  /** The person writes in a thread: their words, whatever the thread's other parties are (§7.1) */
62258
62280
  "mail.reply": external_exports.object({
@@ -62300,7 +62322,9 @@ var mailResults = {
62300
62322
  "mail.tasks": external_exports.object({
62301
62323
  tasks: external_exports.array(MailTaskRow).default([]),
62302
62324
  /** How many open tasks are listed when more are open than the host lists (the oldest left out); null when every open one is. Absent from an older host */
62303
- capped: external_exports.number().nullable().default(null)
62325
+ capped: external_exports.number().nullable().default(null),
62326
+ /** On a hub: the linked machines whose tasks are not in the list, as they could not be read just now (#2268). Absent from an older host */
62327
+ unreached: external_exports.array(UnreachedMachine).default([])
62304
62328
  }),
62305
62329
  "mail.thread": MailThreadView,
62306
62330
  "mail.reply": MailThreadView,
@@ -63536,7 +63560,7 @@ var sessionsResults = {
63536
63560
  sessions: external_exports.array(TrashedSession),
63537
63561
  runs: external_exports.array(TrashedRun).default([]),
63538
63562
  bytes: external_exports.number(),
63539
- unreached: external_exports.array(external_exports.object({ machineId: external_exports.string(), name: external_exports.string() })).optional(),
63563
+ unreached: external_exports.array(UnreachedMachine).optional(),
63540
63564
  /**
63541
63565
  * The subagent steps moved to the trash without their session (#418), most recently moved first. Their bytes
63542
63566
  * are in `bytes`. `trash.empty` leaves them: the window deletes each one it listed (`trash.purgeSubagentSteps`).
@@ -63556,7 +63580,7 @@ var sessionsResults = {
63556
63580
  "trash.purge": external_exports.object({ ok: external_exports.literal(true) }),
63557
63581
  "subagents.usage": external_exports.object({
63558
63582
  sessions: external_exports.array(SubagentStepsHeld),
63559
- unreached: external_exports.array(external_exports.object({ machineId: external_exports.string(), name: external_exports.string() })).optional()
63583
+ unreached: external_exports.array(UnreachedMachine).optional()
63560
63584
  }),
63561
63585
  "subagents.trash": external_exports.object({ steps: external_exports.number(), bytes: external_exports.number() }),
63562
63586
  "trash.restoreSubagentSteps": external_exports.object({ ok: external_exports.literal(true) }),
@@ -64138,6 +64162,9 @@ var ProofServer = external_exports.object({
64138
64162
  sig: external_exports.string().regex(base64urlShape(LINK_SIGNATURE_BYTES)).optional().catch(void 0)
64139
64163
  });
64140
64164
  var CANCEL_CALL_METHOD = "call.cancel";
64165
+ var HOLD_CALL_METHOD = "call.hold";
64166
+ var HoldCallParams = external_exports.object({ id: external_exports.string().max(200), held: external_exports.boolean() });
64167
+ var CALL_HOLD_MAX_MS = 4 * 60 * 6e4;
64141
64168
  var ServerFrame = external_exports.union([
64142
64169
  HelloServer,
64143
64170
  ProofServer,
@@ -64728,9 +64755,8 @@ function activityCounts(s) {
64728
64755
  function turnCut(s) {
64729
64756
  return inTurn(s.state);
64730
64757
  }
64731
- function cutTurns(s, woken = []) {
64732
- const inTurnNow = s.sessions.flatMap((x) => x.id !== void 0 && turnCut(x) ? [{ id: x.id }] : []);
64733
- return [...inTurnNow, ...woken.filter((id3) => !inTurnNow.some((t) => t.id === id3)).map((id3) => ({ id: id3, woken: true }))];
64758
+ function cutTurns(s) {
64759
+ return s.sessions.flatMap((x) => x.id !== void 0 && turnCut(x) ? [{ id: x.id }] : []);
64734
64760
  }
64735
64761
  function sessionIdle(s, process4) {
64736
64762
  const busy = busyWith(s);
@@ -65196,6 +65222,9 @@ function openCodeMatchesAnyCase(platform = HOST_PLATFORM) {
65196
65222
  function programFile(name, platform = HOST_PLATFORM) {
65197
65223
  return platform === "win32" ? `${name}.exe` : name;
65198
65224
  }
65225
+ function npmMachine(platform = HOST_PLATFORM, arch = process.arch) {
65226
+ return `${platform}-${arch}`;
65227
+ }
65199
65228
  function rustTarget(platform = HOST_PLATFORM, arch = process.arch) {
65200
65229
  const cpu = arch === "x64" ? "x86_64" : arch === "arm64" ? "aarch64" : null;
65201
65230
  if (!cpu) return null;
@@ -66559,7 +66588,7 @@ function raceTimeout(p, ms3, fallback) {
66559
66588
  })
66560
66589
  ]).finally(() => clearTimeout(timer));
66561
66590
  }
66562
- async function raceBound(outcome2, ms3, signal, ...wakes2) {
66591
+ async function raceBound(outcome2, ms3, signal, ...wakes) {
66563
66592
  let timer;
66564
66593
  let onAbort;
66565
66594
  const bound = new Promise((resolve21) => timer = unrefTimer(() => resolve21("bound"), ms3));
@@ -66570,7 +66599,7 @@ async function raceBound(outcome2, ms3, signal, ...wakes2) {
66570
66599
  else signal.addEventListener("abort", onAbort, { once: true });
66571
66600
  });
66572
66601
  try {
66573
- return await Promise.race([outcome2, bound, aborted2, ...wakes2]);
66602
+ return await Promise.race([outcome2, bound, aborted2, ...wakes]);
66574
66603
  } finally {
66575
66604
  clearTimeout(timer);
66576
66605
  if (onAbort) signal?.removeEventListener("abort", onAbort);
@@ -68820,6 +68849,12 @@ var HostServer = class _HostServer {
68820
68849
  if (bridgeOf2 === null && !limited) this.answered(ws2, frame.data);
68821
68850
  return;
68822
68851
  }
68852
+ if (frame.data.method === HOLD_CALL_METHOD) {
68853
+ const hold = HoldCallParams.safeParse(frame.data.params);
68854
+ if (hold.success && bridgeOf2 === null && !limited) this.calls.get(ws2)?.get(hold.data.id)?.hold(hold.data.held);
68855
+ this.sendTo(ws2, JSON.stringify({ kind: "res", id: frame.data.id, ok: true, result: { ok: true } }));
68856
+ return;
68857
+ }
68823
68858
  const { method, params, id: id3 } = frame.data;
68824
68859
  if (bridgeOf2 !== null) {
68825
68860
  const refusal2 = bridgeRefusal(bridgeOf2, method, params);
@@ -68886,6 +68921,10 @@ var HostServer = class _HostServer {
68886
68921
  * over the socket the hub opened, and nowhere else. Fails at once when that connection is gone; withdrawn with
68887
68922
  * `call.cancel` when `signal` fires, and when `timeoutMs` runs out (a call nobody answers is not held for good, and its
68888
68923
  * work on the other side, a card standing there, is not left waiting for nobody: #550 review).
68924
+ *
68925
+ * The hub may hold the limit while what the call waits on is out of the person's sight (`call.hold`, #2271): the time
68926
+ * stops while held and runs on with what was left when released. Held for `holdMaxMs` in all (`CALL_HOLD_MAX_MS`), the
68927
+ * call is withdrawn as one that ran out of time. A held call still ends when its socket goes or `signal` fires.
68889
68928
  */
68890
68929
  call(client, method, params, opts = {}) {
68891
68930
  const ws2 = this.byClient.get(client);
@@ -68908,12 +68947,29 @@ var HostServer = class _HostServer {
68908
68947
  withdraw();
68909
68948
  reject(rpcError("The call was cancelled", "internal"));
68910
68949
  };
68911
- const timer = setTimeout(() => {
68950
+ const expire = (why2) => () => {
68912
68951
  if (!calls.has(id3)) return;
68913
68952
  done2();
68914
68953
  withdraw();
68915
- reject(rpcError(`The other side did not answer ${method} in time`, "internal", { retryable: true }));
68916
- }, opts.timeoutMs ?? REVERSE_CALL_TIMEOUT_MS);
68954
+ reject(rpcError(why2, "internal", { retryable: true }));
68955
+ };
68956
+ const late = expire(`The other side did not answer ${method} in time`);
68957
+ let left = opts.timeoutMs ?? REVERSE_CALL_TIMEOUT_MS;
68958
+ let heldFor = 0;
68959
+ let held3 = false;
68960
+ let since = Date.now();
68961
+ let timer = setTimeout(late, left);
68962
+ const hold = (h) => {
68963
+ if (h === held3 || !calls.has(id3)) return;
68964
+ const now = Date.now();
68965
+ clearTimeout(timer);
68966
+ if (h) left -= now - since;
68967
+ else heldFor += now - since;
68968
+ held3 = h;
68969
+ since = now;
68970
+ const holdMax = opts.holdMaxMs ?? CALL_HOLD_MAX_MS;
68971
+ timer = h ? setTimeout(expire(`The other side held ${method} longer than ${durationText(holdMax)}`), Math.max(0, holdMax - heldFor)) : setTimeout(late, Math.max(0, left));
68972
+ };
68917
68973
  calls.set(id3, {
68918
68974
  resolve: (v) => {
68919
68975
  done2();
@@ -68922,7 +68978,8 @@ var HostServer = class _HostServer {
68922
68978
  reject: (e) => {
68923
68979
  done2();
68924
68980
  reject(e);
68925
- }
68981
+ },
68982
+ hold
68926
68983
  });
68927
68984
  opts.signal?.addEventListener("abort", onAbort, { once: true });
68928
68985
  if (!this.sendTo(ws2, JSON.stringify({ kind: "rpc", id: id3, method, params }))) {
@@ -75906,12 +75963,12 @@ var require_discriminator = /* @__PURE__ */ __commonJSMin(((exports) => {
75906
75963
  },
75907
75964
  code(cxt2) {
75908
75965
  const { gen, data, schema, parentSchema, it: it2 } = cxt2;
75909
- const { oneOf: oneOf3 } = parentSchema;
75966
+ const { oneOf: oneOf2 } = parentSchema;
75910
75967
  if (!it2.opts.discriminator) throw new Error("discriminator: requires discriminator option");
75911
75968
  const tagName = schema.propertyName;
75912
75969
  if (typeof tagName != "string") throw new Error("discriminator: requires propertyName");
75913
75970
  if (schema.mapping) throw new Error("discriminator: mapping is not supported");
75914
- if (!oneOf3) throw new Error("discriminator: requires oneOf keyword");
75971
+ if (!oneOf2) throw new Error("discriminator: requires oneOf keyword");
75915
75972
  const valid = gen.let("valid", false);
75916
75973
  const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`);
75917
75974
  gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt2.error(false, {
@@ -75949,8 +76006,8 @@ var require_discriminator = /* @__PURE__ */ __commonJSMin(((exports) => {
75949
76006
  const oneOfMapping = {};
75950
76007
  const topRequired = hasRequired(parentSchema);
75951
76008
  let tagRequired = true;
75952
- for (let i = 0; i < oneOf3.length; i++) {
75953
- let sch = oneOf3[i];
76009
+ for (let i = 0; i < oneOf2.length; i++) {
76010
+ let sch = oneOf2[i];
75954
76011
  if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it2.self.RULES)) {
75955
76012
  const ref = sch.$ref;
75956
76013
  sch = compile_1.resolveRef.call(it2.self, it2.schemaEnv.root, it2.baseId, ref);
@@ -97284,12 +97341,12 @@ var require_discriminator2 = /* @__PURE__ */ __commonJSMin2(((exports) => {
97284
97341
  },
97285
97342
  code(cxt2) {
97286
97343
  const { gen, data, schema, parentSchema, it: it2 } = cxt2;
97287
- const { oneOf: oneOf3 } = parentSchema;
97344
+ const { oneOf: oneOf2 } = parentSchema;
97288
97345
  if (!it2.opts.discriminator) throw new Error("discriminator: requires discriminator option");
97289
97346
  const tagName = schema.propertyName;
97290
97347
  if (typeof tagName != "string") throw new Error("discriminator: requires propertyName");
97291
97348
  if (schema.mapping) throw new Error("discriminator: mapping is not supported");
97292
- if (!oneOf3) throw new Error("discriminator: requires oneOf keyword");
97349
+ if (!oneOf2) throw new Error("discriminator: requires oneOf keyword");
97293
97350
  const valid = gen.let("valid", false);
97294
97351
  const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`);
97295
97352
  gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt2.error(false, {
@@ -97327,8 +97384,8 @@ var require_discriminator2 = /* @__PURE__ */ __commonJSMin2(((exports) => {
97327
97384
  const oneOfMapping = {};
97328
97385
  const topRequired = hasRequired(parentSchema);
97329
97386
  let tagRequired = true;
97330
- for (let i = 0; i < oneOf3.length; i++) {
97331
- let sch = oneOf3[i];
97387
+ for (let i = 0; i < oneOf2.length; i++) {
97388
+ let sch = oneOf2[i];
97332
97389
  if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it2.self.RULES)) {
97333
97390
  const ref = sch.$ref;
97334
97391
  sch = compile_1.resolveRef.call(it2.self, it2.schemaEnv.root, it2.baseId, ref);
@@ -109683,9 +109740,16 @@ function isPerson(address) {
109683
109740
  function senderKind(address) {
109684
109741
  return isPerson(address) ? "person" : parseAddress(address)?.kind;
109685
109742
  }
109743
+ var SESSION_ID_RE2 = new RegExp(`^${SEGMENT}$`);
109744
+ function isSessionId2(id3) {
109745
+ return typeof id3 === "string" && SESSION_ID_RE2.test(id3);
109746
+ }
109686
109747
  function sessionAddress(host, sessionId) {
109687
109748
  return checked(`session:${host}/${sessionId}`);
109688
109749
  }
109750
+ function appAddress(host, projectId, appId) {
109751
+ return checked(`app:${host}/${projectId}/${appId}`);
109752
+ }
109689
109753
  function parseAddress(address) {
109690
109754
  if (address === PERSON) return { kind: "person" };
109691
109755
  if (address === CENTRALU) return { kind: "centralu" };
@@ -109695,6 +109759,11 @@ function parseAddress(address) {
109695
109759
  if (appHost !== void 0 && projectId !== void 0 && appId !== void 0) return { kind: "app", host: appHost, projectId, appId };
109696
109760
  return null;
109697
109761
  }
109762
+ function inHubTerms(address, hub, machine) {
109763
+ if (address === sessionAddress(hub, PERSON_ID)) return PERSON;
109764
+ const p = parseAddress(address);
109765
+ return machine && p?.kind === "session" && p.host === machine.host && !p.sessionId.includes(".") ? sessionAddress(hub, `${machine.id}.${p.sessionId}`) : address;
109766
+ }
109698
109767
  function checked(address) {
109699
109768
  if (!parseAddress(address)) throw new Error(`Not a mail address: ${JSON.stringify(address)}`);
109700
109769
  return address;
@@ -109932,28 +110001,7 @@ var askersKey = (asker) => [asker.turn, asker.messageId, ...(asker.also ?? []).m
109932
110001
  import { randomUUID as randomUUID11 } from "node:crypto";
109933
110002
 
109934
110003
  // packages/agent-host/src/dev-services/store/mail-types.ts
109935
- var DELEGATION_ORIGINS = ["start_agent", "agent_session", "send_to_session", "create_session", "ask_project"];
109936
110004
  var SEND_ORIGINS = /* @__PURE__ */ new Set(["agent_session", "ask_project", "send_to_session"]);
109937
- var MESSAGE_KINDS = ["assign", "question", "answer", "report", "notice", "note", "event"];
109938
- function oneOf2(list2, value, fallback) {
109939
- return list2.find((x) => x === value) ?? fallback;
109940
- }
109941
- var toMessage = (r) => ({
109942
- id: r.id,
109943
- threadId: r.thread_id,
109944
- seq: r.seq,
109945
- homeSeq: r.home_seq,
109946
- sender: r.sender,
109947
- kind: oneOf2(MESSAGE_KINDS, r.kind, "note"),
109948
- urgent: r.urgent === 1,
109949
- needsOwner: r.needs_owner === 1,
109950
- wake: r.wake === "yes" ? "yes" : r.wake === "no" ? "no" : null,
109951
- replyTo: r.reply_to,
109952
- body: r.body,
109953
- facts: readJson(r.facts, JsonObject, {}),
109954
- dedupeKey: r.dedupe_key,
109955
- createdAt: r.created_at
109956
- });
109957
110005
 
109958
110006
  // packages/agent-host/src/mail/rules.ts
109959
110007
  import { createHash as createHash9 } from "node:crypto";
@@ -110015,14 +110063,6 @@ function postsPerMinute(sender) {
110015
110063
  }
110016
110064
  var ASKS_PER_HOUR = 5;
110017
110065
  var REPEAT_WINDOW_MS = 10 * 6e4;
110018
- function wakes(sender, m) {
110019
- if (m.kind === "event") return false;
110020
- if (sender === "centralu" && m.wake === "no") return false;
110021
- if (sender !== "app") return true;
110022
- if (m.wake === "no") return false;
110023
- if (m.kind === "notice") return m.needsOwner || m.wake === "yes";
110024
- return true;
110025
- }
110026
110066
  function needsReceiver(m) {
110027
110067
  return isPerson(m.sender) || m.kind === "task" || m.kind === "report" || m.needsReply || isSendNote(m) || m.facts.needsOwner === true;
110028
110068
  }
@@ -110098,7 +110138,7 @@ var WARNING_TEXT = {
110098
110138
  pair: (a, b2, turns) => `${a} and ${b2} started ${turns} turns of each other by mail in the last hour, with no word from you. Their mail still goes: write to either, or stop one, if they are going round in circles.`,
110099
110139
  host: (turns) => `Mail between sessions started ${turns} turns on this computer in the last hour. It still goes: look at the busy sessions if that is more than you expect.`,
110100
110140
  compactCycles: (session2, cycles) => `${session2} asked to compact its conversation and went on to its next step ${cycles} times in the last hour. It keeps working: look at it if that is more than you expect.`,
110101
- watchWakes: (session2, wakes2) => `${session2}'s watches woke it ${wakes2} times in the last hour. They keep firing: look at it if that is more than you expect.`,
110141
+ watchWakes: (session2, wakes) => `${session2}'s watches woke it ${wakes} times in the last hour. They keep firing: look at it if that is more than you expect.`,
110102
110142
  /** The three guards that refuse rather than warn (#1684, #2035): the person hears of the first refusal of each kind a clock hour */
110103
110143
  repeat: (sender, to) => `Centralu refused mail from ${sender} to ${to}: the same text again within ${durationText(REPEAT_WINDOW_MS)}. ${sender} was told; nothing else was stopped.`,
110104
110144
  rate_limited: (sender, limit) => `Centralu refused mail from ${sender}: more than ${limit} messages in a minute. ${sender} was told to wait; nothing else was stopped.`,
@@ -110523,18 +110563,18 @@ var MailDelivery = class {
110523
110563
  return;
110524
110564
  }
110525
110565
  const { drained } = plan;
110526
- const quiet = !drained.wake;
110566
+ const quiet2 = !drained.wake;
110527
110567
  const joins = state.joins === true;
110528
- const turn = quiet || joins ? void 0 : this.turns?.begin(sessionId, { workMessage: drained.workMessage, starter: this.starterOf(drained) });
110568
+ const turn = quiet2 || joins ? void 0 : this.turns?.begin(sessionId, { workMessage: drained.workMessage, starter: this.starterOf(drained) });
110529
110569
  const cancelTurn = () => {
110530
110570
  if (turn !== void 0) this.turns?.cancel(sessionId, turn);
110531
110571
  };
110532
110572
  const delivered = {};
110533
- const shown3 = quiet ? void 0 : this.shownOf(drained);
110573
+ const shown3 = quiet2 ? void 0 : this.shownOf(drained);
110534
110574
  const inputId = joins ? randomUUID11() : void 0;
110535
110575
  const depth = Math.max(0, ...drained.messageIds.map((id3) => this.records.message(id3)?.facts.agentDepth ?? 0));
110536
110576
  try {
110537
- await this.sessions.deliver(sessionId, { text: drained.text, quiet, line: drained.line, wanted: () => drained.messageIds.some((id3) => this.records.recipient(id3, recipient)?.settled !== "withdrawn"), ...joins ? { joins, id: inputId } : {}, ...shown3 ? { shown: shown3 } : {}, ...depth ? { depth } : {} }, (e) => {
110577
+ await this.sessions.deliver(sessionId, { text: drained.text, quiet: quiet2, line: drained.line, wanted: () => drained.messageIds.some((id3) => this.records.recipient(id3, recipient)?.settled !== "withdrawn"), ...joins ? { joins, id: inputId } : {}, ...shown3 ? { shown: shown3 } : {}, ...depth ? { depth } : {} }, (e) => {
110538
110578
  cancelTurn();
110539
110579
  if (delivered.at !== void 0) this.takeBack(recipient, drained.messageIds, delivered.at, e);
110540
110580
  });
@@ -110554,14 +110594,14 @@ var MailDelivery = class {
110554
110594
  this.records.markRead(recipient, drained.inline, deliveredAt);
110555
110595
  });
110556
110596
  if (inputId) this.joined.set(recipient, [...this.joined.get(recipient) ?? [], { id: inputId, ids: drained.messageIds }]);
110557
- if (!quiet && !joins) this.lastWake.set(recipient, this.now());
110597
+ if (!quiet2 && !joins) this.lastWake.set(recipient, this.now());
110558
110598
  if (waiting) {
110559
110599
  this.left.delete(recipient);
110560
110600
  this.crowd = this.crowd?.filter((r) => r !== recipient) ?? null;
110561
110601
  if (this.crowd?.length === 0) this.crowd = null;
110562
110602
  this.crowdChanged();
110563
110603
  }
110564
- if (!quiet) this.warnIfRunning(recipient, drained.messageIds, deliveredAt);
110604
+ if (!quiet2) this.warnIfRunning(recipient, drained.messageIds, deliveredAt);
110565
110605
  }
110566
110606
  /**
110567
110607
  * What the tool said of the inputs given the recipient (docs/plans/mailbox.md §10.6.3). At a turn's end, mail given into it that the turn did not take
@@ -112312,13 +112352,13 @@ function entryOf(row) {
112312
112352
  by: work ? "work" : "person",
112313
112353
  source: p.relayed === true ? "report" : p.fromApp !== void 0 ? "app" : "caller",
112314
112354
  ...hub.success && isHubSender(hub.data.from.sessionId) ? { origin: hub.data } : {},
112315
- ...typeof from === "string" ? { from } : {}
112355
+ ...isSessionId2(from) ? { from } : from !== void 0 ? { unowned: true } : {}
112316
112356
  };
112317
112357
  }
112318
112358
  function starterFor(ran) {
112319
112359
  const work = ran.find((e) => e.by === "work");
112320
112360
  if (!work) return ran.length ? { turn: { by: "person" }, cli: false, source: "caller" } : { turn: { by: "work" }, cli: true, source: "caller" };
112321
- return { turn: { by: "work", ...ran.some((e) => e.by === "person") ? { wrote: true } : {} }, cli: false, source: work.source, ...work.from ? { from: work.from } : {} };
112361
+ return { turn: { by: "work", ...ran.some((e) => e.by === "person") ? { wrote: true } : {} }, cli: false, source: work.source, ...work.from ? { from: work.from } : {}, ...work.unowned ? { unowned: true } : {} };
112322
112362
  }
112323
112363
  var turnSpanKey = (sessionId) => `turn_span:${sessionId}`;
112324
112364
  var TURN_STARTS_KEPT = 8;
@@ -112558,7 +112598,7 @@ var ChildOwnership = class {
112558
112598
  const rows3 = this.store.messages.loadUserRowsFrom(sessionId, from).map((row) => {
112559
112599
  const p = asObj(row.payload);
112560
112600
  const sender = asObj(p.from).sessionId;
112561
- return typeof sender === "string" && p.relayed !== true ? sender : null;
112601
+ return isSessionId2(sender) && p.relayed !== true ? sender : null;
112562
112602
  });
112563
112603
  return answered >= from ? [...rows3, null] : rows3;
112564
112604
  }
@@ -112611,9 +112651,16 @@ var ChildOwnership = class {
112611
112651
  if (again && was && was.turn.by === decided.turn.by && !!was.turn.wrote === !!decided.turn.wrote && was.cli === decided.cli) return;
112612
112652
  this.starters.set(sessionId, decided);
112613
112653
  if (!this.turnStartedHook) return;
112614
- const ownerId = decided.from ?? [...this.runs.values()].find((d2) => d2.sessionId === sessionId && !d2.settled)?.callerId;
112654
+ const ownerId = decided.unowned ? void 0 : decided.from ?? [...this.runs.values()].find((d2) => d2.sessionId === sessionId && !d2.settled)?.callerId;
112615
112655
  try {
112616
- this.turnStartedHook(sessionId, { by: decided.turn.by, cli: decided.cli, source: decided.source, ...ownerId ? { ownerId } : {}, ...again ? { again: true } : {} });
112656
+ this.turnStartedHook(sessionId, {
112657
+ by: decided.turn.by,
112658
+ cli: decided.cli,
112659
+ source: decided.source,
112660
+ ...ownerId ? { ownerId } : {},
112661
+ ...decided.unowned ? { unowned: true } : {},
112662
+ ...again ? { again: true } : {}
112663
+ });
112617
112664
  } catch (e) {
112618
112665
  console.error(`[mail] could not record a turn of ${sessionId.slice(0, 8)} (${errorMessage(e)})`);
112619
112666
  }
@@ -113244,7 +113291,7 @@ var CONTINUE_NOTES = {
113244
113291
  var UPDATE_WAKES_AT_ONCE = 3;
113245
113292
  var UPDATE_SLOT_MS = 12e4;
113246
113293
  var ANSWERED = /* @__PURE__ */ new Set(["message_delta", "reasoning_delta", "tool_call", "usage_update", "approval_request", "question_request", "error", "limit_reached", "session_deleted"]);
113247
- var wakeEnded = (e) => ANSWERED.has(e.type) || e.type === "state_change" && e.state !== "working" || e.type === "session_live" && !e.live;
113294
+ var wakeEnded = (e) => ANSWERED.has(e.type) || e.type === "turn_complete" || e.type === "state_change" && e.state !== "working" || e.type === "session_live" && !e.live;
113248
113295
  var RESET_MARGIN_MS = 6e4;
113249
113296
  var NO_RESET_RETRY_MS = 30 * 6e4;
113250
113297
  var PROBE_STEPS_MS = [15e3, 3e4, 6e4, 12e4, 3e5];
@@ -113338,12 +113385,27 @@ ${spentWords(tries)}` } };
113338
113385
  this.wait(m.id, { cause: i.reason, tool: m.tool, at: a.at, tries: a.tries, phase: "waiting" });
113339
113386
  }
113340
113387
  }
113388
+ /**
113389
+ * Holds `e` when it is the turn end a process resumed by an update's wake says of its own before the note's turn (`ANSWERED`), and says whether it
113390
+ * did: the first `turn_complete` once the wake is in (`waking`), nothing having answered it. It ends no turn of the session's (#2312). Read as one, it
113391
+ * answered the continued turn's tasks with the cut turn's words and left the session at rest while the note's turn ran, so the real end reported
113392
+ * nothing. A second one is the turn's end. Held, it is said after all when the slot runs out with nothing run (`slotOver`). Only for a tool that
113393
+ * says it ends such a turn (`AgentAdapter.resumeEndsOwnTurn`): another's first end is the turn's
113394
+ */
113395
+ holdOwnEnd(e) {
113396
+ const w = e.type === "turn_complete" ? this.updates.get(e.sessionId) : void 0;
113397
+ if (w?.phase !== "waking" || w.ownEnd || !this.host.resumeEndsOwnTurn(w.sessionId)) return false;
113398
+ w.ownEnd = true;
113399
+ console.error(`[agent-host] ${w.sessionId.slice(0, 8)}: held the turn end its resumed process said of its own before the update's note (#2312)`);
113400
+ return true;
113401
+ }
113341
113402
  /** Every event of a session: the ones that end a held turn take its wait away; a finished turn starts every count over and says its tool's API answers */
113342
113403
  observe(e) {
113343
113404
  const id3 = e.sessionId;
113344
113405
  if (!id3) return;
113345
113406
  const u = this.updates.get(id3);
113346
113407
  if (u?.phase === "waking" && wakeEnded(e)) this.endUpdate(id3, u, null);
113408
+ else if (u?.phase === "waking" && u.ownEnd && e.type === "activity" && e.activity !== null) u.running = true;
113347
113409
  else if (u && e.type === "session_deleted") this.endUpdate(id3, u, "dropped");
113348
113410
  if (e.type === "turn_complete" || e.type === "error" || e.type === "limit_reached" || e.type === "session_deleted" || e.type === "state_change" && e.state !== "working") this.cancelHeld(id3);
113349
113411
  if (e.type === "session_deleted") this.dropStop(id3, false);
@@ -113579,8 +113641,8 @@ Centralu was going to retry this turn, but it restarted first. Send a message to
113579
113641
  if (this.updates.size) setTimeout(() => this.pump(), 0);
113580
113642
  }
113581
113643
  /**
113582
- * The wakes whose note went in and that have not answered yet (#2264 review): a stop for an update now lists them again (`cutTurns`). Their entry
113583
- * left the list at the send, and the resumed process reads at rest until its request streams (its own turn end comes first). One silent for
113644
+ * The wakes whose note went in and that have not answered yet (#2264 review): a stop for an update now lists what else they stopped again, their
113645
+ * turn being listed as any (`cutTurns`). Their entry left the list at the send. One silent for
113584
113646
  * `UPDATE_SLOT_MS` gave its slot up and is not among them: a stop after that does not list it again (accepted, as a request that hangs that long)
113585
113647
  */
113586
113648
  unanswered() {
@@ -113595,6 +113657,18 @@ Centralu was going to retry this turn, but it restarted first. Send a message to
113595
113657
  void this.fireUpdate(id3, w);
113596
113658
  }
113597
113659
  }
113660
+ /**
113661
+ * A woken session said nothing for `UPDATE_SLOT_MS`: its slot goes to the next. One whose resumed process's turn end was held (`holdOwnEnd`), that
113662
+ * is still in its turn and whose tool said nothing of being busy since (`running`) ran nothing after it: that end was the turn's, and is said now,
113663
+ * so the session is not left working with no turn
113664
+ */
113665
+ slotOver(id3, w) {
113666
+ this.endUpdate(id3, w, null);
113667
+ const m = this.host.meta.get(id3);
113668
+ if (!w.ownEnd || w.running || !m || !inTurn(m.state) || this.host.leaving()) return;
113669
+ console.error(`[agent-host] ${id3.slice(0, 8)}: nothing ran after the turn end held for ${UPDATE_SLOT_MS / 1e3} s, so it ends the turn (#2312)`);
113670
+ this.host.note({ type: "turn_complete", sessionId: id3 });
113671
+ }
113598
113672
  /** An update's wake is over (answered, or `step`): its slot goes to the next */
113599
113673
  endUpdate(id3, w, step, err) {
113600
113674
  if (this.updates.get(id3) === w) this.updates.delete(id3);
@@ -113617,7 +113691,7 @@ Centralu was going to retry this turn, but it restarted first. Send a message to
113617
113691
  handed: () => {
113618
113692
  handed = true;
113619
113693
  w.phase = "waking";
113620
- w.slot = setTimeout(() => this.endUpdate(id3, w, null), UPDATE_SLOT_MS);
113694
+ w.slot = setTimeout(() => this.slotOver(id3, w), UPDATE_SLOT_MS);
113621
113695
  w.slot.unref?.();
113622
113696
  }
113623
113697
  });
@@ -115347,7 +115421,7 @@ var HANDLERS = {
115347
115421
  if (!s) return { text: "Centralu update is unavailable.", isError: true };
115348
115422
  const apply = callForm(caller.profile, "update_centralu", { action: "apply" });
115349
115423
  const applies = `The person applies the installed build from Centralu${apply ? `, or ${apply} does` : ""}; their automatic-update setting was not changed.`;
115350
- if (s.phase === "failed") return { text: `Centralu update failed: ${s.error}` };
115424
+ if (s.phase === "failed") return { text: `Centralu update failed: ${(s.error ?? "unknown error").replace(/\.$/, "")}. ${namedCall(caller.profile, "update_centralu", { action: "install" })} tries again.` };
115351
115425
  if (s.phase === "updating" || s.phase === "waiting_for_npm") return { text: `Installing Centralu ${s.latest ?? ""}. ${applies}` };
115352
115426
  if (action === "check") {
115353
115427
  if (s.phase === "restart_required") return { text: `Centralu ${s.latest ?? ""} is installed and waits for a restart. ${applies}` };
@@ -119579,9 +119653,6 @@ function pragmaNumber(db, name) {
119579
119653
  if (typeof v !== "number") throw new Error(`PRAGMA ${name} answered ${typeof v}, not a number`);
119580
119654
  return v;
119581
119655
  }
119582
- function updateRecipientRows(db, table, set3, setArgs, recipient, ids, also) {
119583
- return db.prepare(`UPDATE ${table} SET ${set3} WHERE recipient = ?${also ? ` AND ${also}` : ""} AND message_id IN (SELECT value FROM json_each(?))`).run(...setArgs, recipient, JSON.stringify(ids)).changes;
119584
- }
119585
119656
 
119586
119657
  // packages/agent-host/src/dev-services/store/mailbox.ts
119587
119658
  var MAIL_KINDS = ["message", "task", "report", "notice"];
@@ -119606,6 +119677,7 @@ var MailTargetMissing = class extends Error {
119606
119677
  };
119607
119678
  var DAY = 24 * 60 * 60 * 1e3;
119608
119679
  var MAILBOX_RETENTION = { waitingMs: 180 * DAY, settledMs: 30 * DAY, readNoticeMs: 14 * DAY, batch: 500 };
119680
+ var likePrefix = (prefix) => `${prefix.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
119609
119681
  var WATCHED = `(m.needs_reply = 1 OR m.kind = 'task')`;
119610
119682
  var WAITING = `r.read_at IS NULL AND (r.held IS NULL OR r.held = 'released') AND COALESCE(r.settled, '') NOT IN ('withdrawn', 'gone')`;
119611
119683
  var HELD = `r.held IS NOT NULL AND r.held NOT IN ('released', 'dismissed')`;
@@ -120047,8 +120119,18 @@ var MailboxRecords = class {
120047
120119
  // ── Across a link (#2067 item 2, docs/plans/linked-mail.md §6) ──
120048
120120
  /** Whether `sender` ever sent a message to an address that starts with `prefix` (a linked machine's sessions, `session:<hub>/<machine>.`) */
120049
120121
  sentToward(sender, prefix) {
120050
- const like = `${prefix.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
120051
- return this.db.prepare(`SELECT 1 AS one FROM mail m JOIN mail_recipients r ON r.message_id = m.id WHERE m.sender = ? AND r.recipient LIKE ? ESCAPE '\\' LIMIT 1`).get(sender, like) !== void 0;
120122
+ return this.db.prepare(`SELECT 1 AS one FROM mail m JOIN mail_recipients r ON r.message_id = m.id WHERE m.sender = ? AND r.recipient LIKE ? ESCAPE '\\' LIMIT 1`).get(sender, likePrefix(prefix)) !== void 0;
120123
+ }
120124
+ /**
120125
+ * The open tasks given after `since` to addresses that start with `prefix` (a linked machine's sessions, `session:<hub>/<machine>.`), oldest first,
120126
+ * at most `limit` (#2289)
120127
+ */
120128
+ openTasksToward(prefix, since, limit) {
120129
+ return this.db.prepare(
120130
+ `SELECT m.id FROM mail m JOIN mail_recipients r ON r.message_id = m.id
120131
+ WHERE m.kind = 'task' AND r.recipient LIKE ? ESCAPE '\\' AND r.settled IS NULL AND r.released_at IS NULL AND m.created_at > ?
120132
+ ORDER BY m.created_at, m.id LIMIT ?`
120133
+ ).all(likePrefix(prefix), since, limit).map((r) => r.id);
120052
120134
  }
120053
120135
  /**
120054
120136
  * The rows of messages that crossed a link, with each message's sender: a row whose recipient or whose message's sender is
@@ -120467,9 +120549,12 @@ var MailboxRecords = class {
120467
120549
  { key: key2, at: anchor?.createdAt ?? null, id: anchor?.id ?? "", limit: opts.limit }
120468
120550
  );
120469
120551
  }
120470
- /** `UPDATE ... SET <set> WHERE recipient = ? [AND <also>] AND message_id IN <ids>`; returns the rows changed */
120552
+ /**
120553
+ * `UPDATE mail_recipients SET <set> WHERE recipient = ? [AND <also>] AND message_id IN <ids>`, the ids passed as one JSON parameter read with
120554
+ * `json_each`; `setArgs` fill the `?` of `set`. Returns the rows changed
120555
+ */
120471
120556
  update(set3, setArgs, recipient, ids, also) {
120472
- return updateRecipientRows(this.db, "mail_recipients", set3, setArgs, recipient, ids, also);
120557
+ return this.db.prepare(`UPDATE mail_recipients SET ${set3} WHERE recipient = ?${also ? ` AND ${also}` : ""} AND message_id IN (SELECT value FROM json_each(?))`).run(...setArgs, recipient, JSON.stringify(ids)).changes;
120473
120558
  }
120474
120559
  count(sql, ...args) {
120475
120560
  return this.db.prepare(sql).get(...args)?.n ?? 0;
@@ -120583,22 +120668,20 @@ function fitFrame(items, budget, render) {
120583
120668
  }
120584
120669
  return { text: text3, shown: shown3.map((i) => i.messageId), inline: cut3 ? [] : shown3.filter((i) => i.inline !== void 0).map((i) => i.messageId) };
120585
120670
  }
120586
- function mailCalls(version2, form) {
120671
+ function mailCalls(form) {
120587
120672
  const call2 = (action, fields5 = {}) => {
120588
120673
  const entries = Object.entries(fields5);
120589
120674
  return form === "plain" ? `mail(action="${action}"${entries.map(([k2, v]) => `, ${k2}="${v}"`).join("")})` : `centralu_run(command="mail", args={action: "${action}"${entries.map(([k2, v]) => `, ${k2}: "${v}"`).join("")}})`;
120590
120675
  };
120591
- const target = version2 === 2 ? "id" : "thread";
120592
120676
  return {
120593
- read: (id3) => call2("read", id3 === void 0 ? {} : { [target]: id3 }),
120594
- answer: (id3) => call2(version2 === 2 ? "send" : "reply", { [target]: id3, text: "\u2026" }),
120595
- done: (id3) => call2(version2 === 2 ? "done" : "handled", { [target]: id3 }),
120677
+ read: (id3) => call2("read", id3 === void 0 ? {} : { thread: id3 }),
120678
+ answer: (id3) => call2("reply", { thread: id3, text: "\u2026" }),
120679
+ done: (id3) => call2("handled", { thread: id3 }),
120596
120680
  inbox: () => call2("inbox"),
120597
- sessions: () => call2("sessions"),
120598
120681
  close: (id3) => call2("close", { thread: id3 })
120599
120682
  };
120600
120683
  }
120601
- var PLAIN_MESSAGE_CALLS = mailCalls(2, "plain");
120684
+ var PLAIN_MESSAGE_CALLS = mailCalls("plain");
120602
120685
  var FOR_PERSON = {
120603
120686
  note: "from the Assistant, which acts for the person in Centralu: carry it out as the person's request. No answer is owed:",
120604
120687
  task: "from the Assistant, which acts for the person in Centralu: carry it out as the person's request. Report back when done:"
@@ -122771,7 +122854,7 @@ var DelegationForks = class {
122771
122854
  return this.forkTrustError(callerId, target, true) ?? this.flow.starts.agentCeilingError(callerId, target.projectId ?? "");
122772
122855
  }
122773
122856
  /** `forkGateError` without the ceiling: read before the card and again once it is answered (`forkFor`); `quiet` as `trustGate` */
122774
- forkTrustError(callerId, target, quiet) {
122857
+ forkTrustError(callerId, target, quiet2) {
122775
122858
  const caller = this.host.meta.get(callerId);
122776
122859
  if (!caller) return "the requesting session is gone";
122777
122860
  if (!this.host.meta.has(target.id)) return "it is no longer here";
@@ -122779,7 +122862,7 @@ var DelegationForks = class {
122779
122862
  if (deep) return deep.replace(/^This/, "this").replace(/\.$/, "");
122780
122863
  if (!target.projectId) return NO_PROJECT;
122781
122864
  if (!this.host.store.projects.listProjects().some((p) => p.id === target.projectId)) return "its project is no longer registered";
122782
- return this.host.trustGate(callerId, target.projectId, "forking a session", quiet);
122865
+ return this.host.trustGate(callerId, target.projectId, "forking a session", quiet2);
122783
122866
  }
122784
122867
  /** Why `target` cannot be forked for `callerId` now, or null. Its project is said first, whatever its CLI can do (#994 review) */
122785
122868
  forkWhy(callerId, target) {
@@ -123919,6 +124002,7 @@ var SessionEvents = class {
123919
124002
  return this.onEvent({ ...e, live: m.backgroundTasks.filter((t) => t.status === "running") });
123920
124003
  }
123921
124004
  if (e.type === "error") e = this.host.turnContinue.hold(e);
124005
+ if (this.host.turnContinue.holdOwnEnd(e)) return;
123922
124006
  if (e.sessionId) this.host.turnContinue.observe(e);
123923
124007
  const unborn = e.sessionId && !this.host.meta.has(e.sessionId) ? this.host.record.unborn.get(e.sessionId) : void 0;
123924
124008
  if (unborn) {
@@ -124079,6 +124163,7 @@ var SessionEvents = class {
124079
124163
  const from = m.state;
124080
124164
  if (applySessionState(m, e, Date.now()).illegal) console.warn(`[agent-host] ignored ${e.type} for ${m.id.slice(0, 8)}: ${from} cannot go to ${nextStateFor(e)}`);
124081
124165
  this.trackLiveFacts(e, m);
124166
+ this.host.hostCards.noteStanding(m.id);
124082
124167
  }
124083
124168
  /**
124084
124169
  * An adapter's card raised between turns closes back into that rest once answered (#428), as the host's own cards do
@@ -124500,11 +124585,11 @@ var MailSessionsView = class {
124500
124585
  if (this.host.closing) return { kind: "busy", why: "turn" };
124501
124586
  const busy = cardOrTurn(m);
124502
124587
  const live2 = this.host.handles.has(id3);
124503
- const quiet = live2 && this.host.adapters.get(m.tool)?.quietInput === true;
124504
- if (busy === "turn" && live2 && this.host.joinsRunningTurn(id3) && !this.host.selfCompaction.compacts(id3)) return { kind: "ready", live: live2, quiet, auto: m.permissionPreset === "auto", joins: true };
124588
+ const quiet2 = live2 && this.host.adapters.get(m.tool)?.quietInput === true;
124589
+ if (busy === "turn" && live2 && this.host.joinsRunningTurn(id3) && !this.host.selfCompaction.compacts(id3)) return { kind: "ready", live: live2, quiet: quiet2, auto: m.permissionPreset === "auto", joins: true };
124505
124590
  if (busy !== null) return { kind: "busy", why: busy === "turn" ? "turn" : "card" };
124506
124591
  if (m.state === "limited") return { kind: "busy", why: "limited" };
124507
- return { kind: "ready", live: live2, quiet, auto: m.permissionPreset === "auto" };
124592
+ return { kind: "ready", live: live2, quiet: quiet2, auto: m.permissionPreset === "auto" };
124508
124593
  }
124509
124594
  /** The session can be given a turn of its own now: at rest with no card or limit standing, in a host that is not leaving (asleep, it is woken) */
124510
124595
  takesTurn(id3) {
@@ -125447,7 +125532,7 @@ var HostTenure = class {
125447
125532
  this.disposing = true;
125448
125533
  this.leaveHost("Centralu is shutting down");
125449
125534
  const sessions = this.stoppingForUpdate && this.host.keeperOpts.updateResume ? this.host.listSessions() : [];
125450
- const cut3 = cutTurns({ sessions, terminals: 0, commandRuns: 0 }, woken.filter((w) => w.turn).map((w) => w.sessionId));
125535
+ const cut3 = cutTurns({ sessions, terminals: 0, commandRuns: 0 });
125451
125536
  const stopped = stoppedAtUpdate(sessions, (id3, callId) => this.host.store.messages.toolCallInput(id3, callId), woken.flatMap((w) => w.stopped ? [w.stopped] : []));
125452
125537
  for (const [id3, run2] of this.host.record.streams) this.host.record.flushStream(id3, run2);
125453
125538
  await Promise.allSettled([...[...this.host.handles.values()].map((h) => h.dispose()), ...this.host.merges.mergeChecks]);
@@ -125895,11 +125980,11 @@ var SelfCompaction = class {
125895
125980
  * Ends a request that will not compact. With a `then` the session is not left to stall: the step goes as its next turn, with a line saying why (`refuse`).
125896
125981
  * `quiet`: the person took control (they interrupted the turn) or the turn failed, so nothing is sent and the session is told at its next input
125897
125982
  */
125898
- drop(id3, why2, quiet = false) {
125983
+ drop(id3, why2, quiet2 = false) {
125899
125984
  const req = this.pending.get(id3);
125900
125985
  this.settle(id3);
125901
125986
  if (!req?.then) return;
125902
- if (quiet) this.tell(id3, req.then, why2);
125987
+ if (quiet2) this.tell(id3, req.then, why2);
125903
125988
  else this.refuseRequest(id3, req.then, why2);
125904
125989
  }
125905
125990
  /** The turn ended and the size of the context is known (`null`: none since a compaction): compacts when it is over the floor, drops the request otherwise */
@@ -131860,6 +131945,10 @@ var CLAUDE_KNOWN_TYPES = /* @__PURE__ */ new Set([
131860
131945
  "system/hook_progress",
131861
131946
  "system/hook_response",
131862
131947
  "system/thinking_tokens",
131948
+ // ignored: what they say arrives some other way (#2291)
131949
+ "system/commands_changed",
131950
+ "command_lifecycle",
131951
+ "system/permission_denied",
131863
131952
  // correctly ignored
131864
131953
  "system/control_request_progress",
131865
131954
  "system/plugin_install",
@@ -133421,7 +133510,7 @@ var CLAUDE_LIMITATIONS = [
133421
133510
  note: "Declared, but the CLI writes it to stdout only in a remote session, so the goal badge is read off the stream (`ClaudeGoalTracker`). When a CLI sends it, the tracker stands down."
133422
133511
  },
133423
133512
  // The #58 survey's "show or store it, wire it when it is seen" rows: out of CLAUDE_KNOWN_TYPES on purpose
133424
- ...["auth_status", "tool_use_summary", "system/commands_changed", "system/memory_recall", "system/permission_denied"].map(
133513
+ ...["auth_status", "tool_use_summary", "system/memory_recall"].map(
133425
133514
  (name) => ({
133426
133515
  kind: "message",
133427
133516
  name,
@@ -133895,16 +133984,16 @@ var ClaudeSession = class {
133895
133984
  turnInputs() {
133896
133985
  return this.ledger.endingInputs;
133897
133986
  }
133898
- sendInput(text3, uuid3 = centraluInputId(), note, origin, quiet) {
133987
+ sendInput(text3, uuid3 = centraluInputId(), note, origin, quiet2) {
133899
133988
  const goal = isGoalCommand(text3);
133900
133989
  if (!this.sendGate && !(goal && this.goalCommand === void 0)) {
133901
- this.deliver(text3, uuid3, !!note, origin, quiet);
133990
+ this.deliver(text3, uuid3, !!note, origin, quiet2);
133902
133991
  return;
133903
133992
  }
133904
133993
  const gate = this.sendGate = (this.sendGate ?? this.goalKnown).then(() => {
133905
133994
  if (note?.cancelled) return;
133906
133995
  if (!this.closed) {
133907
- this.deliver(text3, uuid3, !!note, origin, quiet);
133996
+ this.deliver(text3, uuid3, !!note, origin, quiet2);
133908
133997
  return;
133909
133998
  }
133910
133999
  this.emit(undeliveredError(this.sessionId, 1, "were still queued when the session closed"));
@@ -133913,8 +134002,8 @@ var ClaudeSession = class {
133913
134002
  if (this.sendGate === gate) this.sendGate = null;
133914
134003
  });
133915
134004
  }
133916
- deliver(text3, uuid3, parentNote, origin, quiet) {
133917
- if (quiet) {
134005
+ deliver(text3, uuid3, parentNote, origin, quiet2) {
134006
+ if (quiet2) {
133918
134007
  const input = { text: text3, uuid: uuid3, parentNote, ...origin ? { origin } : {}, quiet: true };
133919
134008
  this.quietInputs.set(uuid3, input);
133920
134009
  this.queue.push(input);
@@ -134050,10 +134139,10 @@ var ClaudeSession = class {
134050
134139
  for (const id3 of ids) if (this.personInputs.delete(id3)) count++;
134051
134140
  this.reportUndelivered(count);
134052
134141
  for (const id3 of ids) {
134053
- const quiet = this.quietInputs.get(id3);
134054
- if (!quiet) continue;
134142
+ const quiet2 = this.quietInputs.get(id3);
134143
+ if (!quiet2) continue;
134055
134144
  this.quietInputs.delete(id3);
134056
- this.deliver(quiet.text, centraluInputId(), false, quiet.origin, true);
134145
+ this.deliver(quiet2.text, centraluInputId(), false, quiet2.origin, true);
134057
134146
  }
134058
134147
  }
134059
134148
  }
@@ -134176,6 +134265,11 @@ var ClaudeAdapter = class _ClaudeAdapter {
134176
134265
  contextAtRequest = true;
134177
134266
  /** `shouldQuery: false` (sdk.d.ts, measured on the Mac 2026-10-20: no turn, merged into the next message) */
134178
134267
  quietInput = true;
134268
+ /**
134269
+ * Measured with Claude Code 2.1.296 on a real host swap: about 2 s after the first input, before that input's turn, when the update's stop ended a
134270
+ * background task of the session; a cut turn that ran in the foreground only resumed with none (`ANSWERED`, turn-continue.ts)
134271
+ */
134272
+ resumeEndsOwnTurn = true;
134179
134273
  cacheBilling = "anthropic";
134180
134274
  /** What Claude Code offers against what this adapter limits (#270) */
134181
134275
  surface = CLAUDE_SURFACE;
@@ -138609,10 +138703,10 @@ var ProjectRegistry = class {
138609
138703
  * session still starting included), else the one refusal. `boundary` names what crosses, in the refusal and in the
138610
138704
  * log line each crossing writes; `quiet` for a re-read of a crossing already logged. A null caller is the person.
138611
138705
  */
138612
- trustGate(callerId, projectId, boundary, quiet = false) {
138706
+ trustGate(callerId, projectId, boundary, quiet2 = false) {
138613
138707
  if (this.projectTrusted(projectId)) return null;
138614
138708
  const name = this.projectRow(projectId)?.name ?? projectId;
138615
- if (callerId && this.host.autoBoundaryOpen(callerId, quiet ? void 0 : `${boundary} (untrusted project "${name}")`)) return null;
138709
+ if (callerId && this.host.autoBoundaryOpen(callerId, quiet2 ? void 0 : `${boundary} (untrusted project "${name}")`)) return null;
138616
138710
  return `Project "${name}" is not trusted, so ${boundary} is refused \u2014 ${callerId ? `the person can trust it from the project menu. ${ASK_THE_PERSON}` : "trust it from the project menu."}`;
138617
138711
  }
138618
138712
  /**
@@ -140558,13 +140652,6 @@ var ChildOwnershipRecords = class {
140558
140652
  this.db = db;
140559
140653
  }
140560
140654
  db;
140561
- /**
140562
- * The report marks a build of v70 to v73 leaves as it goes (`report_marks`, #646), deleted unread at every start: this build owes nothing by
140563
- * them (docs/plans/mailbox.md §10.6.3), and that build, after a rollback, would make a task of one this build's tasks have since settled
140564
- */
140565
- dropReportMarks() {
140566
- this.db.prepare(`DELETE FROM report_marks`).run();
140567
- }
140568
140655
  // ── start_agent requests waiting for the person (#673) — see migration v50 ──
140569
140656
  listAgentStartRequests() {
140570
140657
  const rows3 = this.db.prepare(`SELECT request_id as requestId, caller_session_id as callerSessionId, request, asked_at as askedAt FROM agent_start_requests ORDER BY asked_at`).all();
@@ -141017,112 +141104,6 @@ var LinkedMachineRecords = class {
141017
141104
  }
141018
141105
  };
141019
141106
 
141020
- // packages/agent-host/src/dev-services/store/mailbox-adopt.ts
141021
- var MOVE_WITHIN_MS = 180 * 24 * 60 * 60 * 1e3;
141022
- var CARRIED_HOLDS = /* @__PURE__ */ new Set([...RECIPIENT_HOLD_WORDS, "released"]);
141023
- function kindOf3(m, threadOrigin) {
141024
- const kinds = { assign: "message", question: "message", answer: "message", note: "message", report: "report", notice: "notice", event: "notice" };
141025
- if (m.kind === "assign" && (threadOrigin === "person" || DELEGATION_ORIGINS.some((o) => o === threadOrigin))) return { kind: "task", needsReply: false };
141026
- return { kind: kinds[m.kind], needsReply: m.kind === "question" };
141027
- }
141028
- function movePendingThreadMail(db, now, projectOf, holdsNow) {
141029
- return db.transaction(() => {
141030
- const pending = db.prepare(
141031
- `SELECT m.*, r.recipient AS r_recipient, r.due_at AS r_due_at, r.attempt_at AS r_attempt_at, r.delivered_at AS r_delivered_at,
141032
- r.read_at AS r_read_at, r.held AS r_held, r.attempts AS r_attempts, r.last_error AS r_last_error,
141033
- t.project_id AS t_project_id, t.owner AS t_owner, t.assignee AS t_assignee, t.origin AS t_origin
141034
- FROM mail_receipts r JOIN mail_messages m ON m.id = r.message_id JOIN mail_threads t ON t.id = m.thread_id
141035
- WHERE r.handled_at IS NULL AND COALESCE(r.held, '') <> 'dismissed' AND m.created_at >= ?
141036
- AND (r.delivered_at IS NULL OR r.read_at IS NULL OR m.kind = 'question')
141037
- ORDER BY m.thread_id, m.seq, r.recipient`
141038
- ).all(now - MOVE_WITHIN_MS);
141039
- const rootOf = db.prepare(`SELECT root_id FROM mail WHERE id = ?`);
141040
- const insertMail = db.prepare(
141041
- `INSERT OR IGNORE INTO mail (id, sender, sender_project, kind, needs_reply, reply_to, root_id, urgent, body, facts, origin, legacy_thread, created_at)
141042
- VALUES (@id, @sender, @senderProject, @kind, @needsReply, @replyTo, @rootId, @urgent, @body, @facts, @origin, @legacyThread, @createdAt)`
141043
- );
141044
- const insertRow = db.prepare(
141045
- `INSERT OR IGNORE INTO mail_recipients (message_id, recipient, via, due_at, attempt_at, delivered_at, read_at, held, attempts, last_error, settled, settled_at)
141046
- VALUES (@messageId, @recipient, @via, @dueAt, @attemptAt, @deliveredAt, @readAt, @held, @attempts, @lastError, @settled, @now)`
141047
- );
141048
- const sessionRow = db.prepare(
141049
- `SELECT is_orchestrator = 1 AND (project_id IS NULL OR deleted_at IS NOT NULL) AS assistant, deleted_at IS NOT NULL AS trashed FROM sessions WHERE id = ?`
141050
- );
141051
- const sessionOf = (address) => {
141052
- const party = parseAddress(address);
141053
- return party?.kind === "session" ? sessionRow.get(party.sessionId) : void 0;
141054
- };
141055
- const releasedTo = /* @__PURE__ */ new Map();
141056
- for (const p of pending) if (p.r_held === "released") releasedTo.set(p.id, [...releasedTo.get(p.id) ?? [], p.r_recipient]);
141057
- const handled = db.prepare(
141058
- `UPDATE mail_receipts SET handled_at = @now, delivered_at = COALESCE(delivered_at, @now), read_at = COALESCE(read_at, @now) WHERE message_id = @id AND recipient = @recipient`
141059
- );
141060
- let messages2 = 0;
141061
- let recipients = 0;
141062
- for (const p of pending) {
141063
- const m = toMessage(p);
141064
- const sender = parseAddress(m.sender);
141065
- const senderProject = sender?.kind === "session" ? projectOf(m.sender) ?? (m.sender === p.t_owner ? p.t_project_id : null) : null;
141066
- const target = m.replyTo === null ? void 0 : rootOf.get(m.replyTo);
141067
- const { kind, needsReply } = kindOf3(m, p.t_origin);
141068
- const facts = {
141069
- ...factsFrom(m.facts),
141070
- legacyKind: p.kind,
141071
- ...wakes(sender?.kind ?? "session", m) ? {} : { quiet: true },
141072
- ...m.needsOwner ? { needsOwner: true } : {},
141073
- ...releasedTo.has(m.id) ? { releasedTo: releasedTo.get(m.id) } : {}
141074
- };
141075
- const to = sessionOf(p.r_recipient);
141076
- messages2 += insertMail.run({
141077
- id: m.id,
141078
- sender: m.sender,
141079
- senderProject,
141080
- kind,
141081
- needsReply: needsReply ? 1 : 0,
141082
- replyTo: target ? m.replyTo : null,
141083
- rootId: target?.root_id ?? m.id,
141084
- urgent: m.urgent ? 1 : 0,
141085
- body: m.body,
141086
- facts: JSON.stringify(facts),
141087
- origin: m.seq === 1 ? p.t_origin : "mail",
141088
- legacyThread: m.threadId,
141089
- createdAt: m.createdAt
141090
- }).changes;
141091
- const via = p.r_recipient === p.t_assignee && to?.assistant === 1 && p.t_owner !== p.r_recipient ? ROLE_VIA : null;
141092
- const carried = p.r_held !== null && CARRIED_HOLDS.has(p.r_held) ? p.r_held : null;
141093
- const ended2 = p.r_held === "budget" || carried === "policy" && !holdsNow({ kind, senderProject }, p.r_recipient);
141094
- recipients += insertRow.run({
141095
- messageId: m.id,
141096
- recipient: p.r_recipient,
141097
- via,
141098
- settled: kind === "task" && to?.trashed === 1 ? "gone" : "legacy",
141099
- dueAt: p.r_due_at,
141100
- attemptAt: ended2 ? null : p.r_attempt_at,
141101
- deliveredAt: p.r_delivered_at,
141102
- readAt: p.r_read_at,
141103
- held: ended2 ? "dismissed" : carried,
141104
- attempts: ended2 ? 0 : p.r_attempts,
141105
- lastError: ended2 ? null : p.r_last_error,
141106
- now
141107
- }).changes;
141108
- handled.run({ now, id: m.id, recipient: p.r_recipient });
141109
- }
141110
- return { messages: messages2, recipients };
141111
- }).immediate();
141112
- }
141113
- function legacyChainFor(db, threadId, messageId, reader, limit) {
141114
- return db.prepare(
141115
- `SELECT * FROM (SELECT m.* FROM mail_messages m
141116
- WHERE m.thread_id = @threadId AND m.seq < (SELECT seq FROM mail_messages WHERE id = @messageId)
141117
- AND (m.sender = @reader OR EXISTS (SELECT 1 FROM mail_receipts r WHERE r.message_id = m.id AND r.recipient = @reader
141118
- AND r.delivered_at IS NOT NULL AND COALESCE(r.held, 'released') = 'released'))
141119
- ORDER BY m.seq DESC LIMIT @limit) ORDER BY seq`
141120
- ).all({ threadId, messageId, reader, limit }).map(toMessage);
141121
- }
141122
- function legacyChain(db, threadId, before, limit) {
141123
- return db.prepare(`SELECT * FROM (SELECT * FROM mail_messages WHERE thread_id = ? AND seq < ? ORDER BY seq DESC LIMIT ?) ORDER BY seq`).all(threadId, before ?? Number.MAX_SAFE_INTEGER, limit).map(toMessage);
141124
- }
141125
-
141126
141107
  // packages/agent-host/src/dev-services/store/user-app-adoption.ts
141127
141108
  var ADOPTED_USER_APPS_KEY = "apps.adoptedUserApps";
141128
141109
  var BUILDERS_KEY = "apps.builders";
@@ -143567,7 +143548,7 @@ var StepsV65 = class extends MigrationRange {
143567
143548
  * such row goes. A `policy` row settled `legacy` stays while `reach.holdFor` (mail/reach.ts) would hold it: a `message` from an untrusted project (a
143568
143549
  * missing project row is untrusted) to a session of another project, which is how a genuine untrusted asker's request is still held. The
143569
143550
  * delivery also holds moved rows that way (it judges a `legacy` row like any other, and `records.hold` writes `held` alone), so the same row looks
143570
- * the same whoever held it, and this step cannot tell them apart; it asks the gate, as the move asks it for the rows it moves from now on. What the
143551
+ * the same whoever held it, and this step cannot tell them apart; it asks the gate, as step 75 asks it for the rows it moves (`endOldHolds`). What the
143571
143552
  * gate would not hold goes, and what goes is `dismissed`, the hold word the person's Dismiss sets (not held for the person, never delivered):
143572
143553
  * `gone` says a sender or recipient is gone and `withdrawn` that the sender said it no longer waits, and neither is so. `settled` stays `legacy`.
143573
143554
  *
@@ -143588,17 +143569,7 @@ var StepsV65 = class extends MigrationRange {
143588
143569
  run: () => {
143589
143570
  if (this.db.prepare(`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'mail_recipients'`).get() === void 0) return;
143590
143571
  if (this.db.prepare(`SELECT 1 FROM mail_recipients WHERE held IN ('budget', 'policy') LIMIT 1`).get() === void 0) return;
143591
- this.db.exec(
143592
- `UPDATE mail_recipients SET held = 'dismissed', attempt_at = NULL, last_error = NULL, attempts = 0
143593
- WHERE held = 'budget'
143594
- OR (held = 'policy' AND settled = 'legacy' AND NOT EXISTS (
143595
- SELECT 1 FROM mail m, sessions s
143596
- WHERE m.id = mail_recipients.message_id AND m.kind = 'message' AND s.deleted_at IS NULL
143597
- AND m.sender_project IS NOT NULL
143598
- AND COALESCE((SELECT p.trusted FROM projects p WHERE p.id = m.sender_project), 0) = 0
143599
- AND mail_recipients.recipient LIKE 'session:%' AND substr(mail_recipients.recipient, instr(mail_recipients.recipient, '/') + 1) = s.id
143600
- AND s.project_id IS NOT m.sender_project))`
143601
- );
143572
+ endOldHolds(this.db);
143602
143573
  }
143603
143574
  },
143604
143575
  {
@@ -143655,7 +143626,7 @@ var StepsV65 = class extends MigrationRange {
143655
143626
  * **A frozen copy of `MessageService.task`, its cut and the old adoption, on purpose**: a step runs once on every store and must not call
143656
143627
  * code that may change. Only the id and address shapes are imported (mail/ids.ts, mail/address.ts), as the stored shapes they are.
143657
143628
  *
143658
- * The tables stay: the builds from v70 to v73 read them at every start. They go in a later step, once the floor is at or above 74.
143629
+ * The tables stay: the builds from v70 to v73 read them at every start. They go in step 76, once step 75 has put the floor at 74.
143659
143630
  */
143660
143631
  run: () => this.oneRecordOfOwedWork()
143661
143632
  }
@@ -143734,6 +143705,21 @@ var OldWorkTasks = class {
143734
143705
  this.row.run({ id: id3, recipient, project: session2.project, dueAt: t.delivered ? this.now : this.now + 2e3, delivered: t.delivered ? this.now : null });
143735
143706
  }
143736
143707
  };
143708
+ function endOldHolds(db, moved) {
143709
+ db.prepare(
143710
+ `UPDATE mail_recipients SET held = 'dismissed', attempt_at = NULL, last_error = NULL, attempts = 0
143711
+ WHERE held = 'budget'
143712
+ OR (held = 'policy'
143713
+ AND CASE WHEN @moved IS NULL THEN settled = 'legacy' ELSE rowid IN (SELECT value FROM json_each(@moved)) END
143714
+ AND NOT EXISTS (
143715
+ SELECT 1 FROM mail m, sessions s
143716
+ WHERE m.id = mail_recipients.message_id AND m.kind = 'message' AND s.deleted_at IS NULL
143717
+ AND m.sender_project IS NOT NULL
143718
+ AND COALESCE((SELECT p.trusted FROM projects p WHERE p.id = m.sender_project), 0) = 0
143719
+ AND mail_recipients.recipient LIKE 'session:%' AND substr(mail_recipients.recipient, instr(mail_recipients.recipient, '/') + 1) = s.id
143720
+ AND s.project_id IS NOT m.sender_project))`
143721
+ ).run({ moved: moved ? JSON.stringify(moved) : null });
143722
+ }
143737
143723
  function addresses(host, callerId, sessionId) {
143738
143724
  try {
143739
143725
  return [sessionAddress(host, callerId), sessionAddress(host, sessionId)];
@@ -143742,6 +143728,162 @@ function addresses(host, callerId, sessionId) {
143742
143728
  }
143743
143729
  }
143744
143730
 
143731
+ // packages/agent-host/src/dev-services/store/migrations/v75.ts
143732
+ var StepsV75 = class extends MigrationRange {
143733
+ steps() {
143734
+ return [
143735
+ {
143736
+ to: 75,
143737
+ breaksOlderReaders: true,
143738
+ minReader: 74,
143739
+ /**
143740
+ * The last move of thread mail (#2258 item 1, docs/plans/mailbox.md §6.3, M7): what a build of v61 to v64 left pending in its thread
143741
+ * tables (`mail_threads`, `mail_messages`, `mail_receipts`) becomes mail once, here. Until this step the host moved it at every start
143742
+ * and read the old tables for the lines before a moved message. From this build on only a migration step names those tables, the two
143743
+ * beside them (`mail_participants`, `mail_blockers`), `report_marks`, `delegated_turns`, `queued_requests` or `sessions.mail_args`.
143744
+ *
143745
+ * Pending is a receipt not handled, not dismissed by the person, of a message sent in the last 180 days (retention would not have kept
143746
+ * an older one waiting), that is not delivered, not read, or a `question` (read and not answered). Each message is copied once under its
143747
+ * own id, its rows settled `legacy` (never awaited), and each old receipt is marked handled, delivered and read. A row to the Assistant in
143748
+ * a session's request (the old thread's assignee, the Assistant or a trashed one) is sent to the role (`via`), so the next Assistant
143749
+ * takes it; a task to a trashed session is settled `gone`. A row the person released is never held again (`releasedTo`). A hold an
143750
+ * earlier build set stays only if today's gate would hold the mail now, as step 72 judged the rows moved before it (`endOldHolds`).
143751
+ * A `policy` hold is judged on the rows this step writes only, since a row moved at an earlier start may be held by the delivery's own
143752
+ * judgement; a `budget` hold, which no delivery sets, ends on whatever row carries it.
143753
+ *
143754
+ * **A frozen copy of the move the host ran (`movePendingThreadMail`) and of what it called, on purpose**: a step runs once on every
143755
+ * store and must not call code that may change. Only the address shape is imported (mail/address.ts), as the stored shape it is. One
143756
+ * thing is read differently: a sender's project comes from its `sessions` row by the session id alone, where the host asked only for a
143757
+ * session of its own (as step 72 reads a recipient's).
143758
+ *
143759
+ * **Breaks the builds of v70 to v73 (beta.58 to beta.69): the floor goes to 74.** Those builds leave a report mark for every session in
143760
+ * a turn as they go, and make a task of each mark at their next start. This build deleted the marks at every start, so that one left
143761
+ * during a rollback never became a task for work settled since; it no longer names `report_marks`, so those builds are refused instead
143762
+ * (`StoreTooNewError`). The build of v74 (beta.70 to beta.72) writes no mark, and its own move at every start finds each receipt handled:
143763
+ * it opens the store and serves it as before. The tables stay for it, unread by this build, and go in the next step.
143764
+ */
143765
+ run: () => this.moveThreadMail()
143766
+ }
143767
+ ];
143768
+ }
143769
+ /** Step 75: every pending receipt of the thread tables written as mail, and the old receipt marked handled */
143770
+ moveThreadMail() {
143771
+ const has = (table) => this.db.prepare(`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?`).get(table) !== void 0;
143772
+ if (!["mail_threads", "mail_messages", "mail_receipts", "mail", "mail_recipients", "sessions", "projects"].every(has)) return;
143773
+ const now = Date.now();
143774
+ const pending = this.pendingReceipts(now);
143775
+ if (pending.length === 0) return;
143776
+ const rootOf = this.db.prepare(`SELECT root_id FROM mail WHERE id = ?`);
143777
+ const insertMail = this.db.prepare(
143778
+ `INSERT OR IGNORE INTO mail (id, sender, sender_project, kind, needs_reply, reply_to, root_id, urgent, body, facts, origin, legacy_thread, created_at)
143779
+ VALUES (@id, @sender, @senderProject, @kind, @needsReply, @replyTo, @rootId, @urgent, @body, @facts, @origin, @legacyThread, @createdAt)`
143780
+ );
143781
+ const insertRow = this.db.prepare(
143782
+ `INSERT OR IGNORE INTO mail_recipients (message_id, recipient, via, due_at, attempt_at, delivered_at, read_at, held, attempts, last_error, settled, settled_at)
143783
+ VALUES (@messageId, @recipient, @via, @dueAt, @attemptAt, @deliveredAt, @readAt, @held, @attempts, @lastError, @settled, @now)`
143784
+ );
143785
+ const handled = this.db.prepare(
143786
+ `UPDATE mail_receipts SET handled_at = @now, delivered_at = COALESCE(delivered_at, @now), read_at = COALESCE(read_at, @now) WHERE message_id = @id AND recipient = @recipient`
143787
+ );
143788
+ const sessionRow = this.db.prepare(
143789
+ `SELECT project_id AS project, is_assistant = 1 AND (project_id IS NULL OR deleted_at IS NOT NULL) AS assistant, deleted_at IS NOT NULL AS trashed FROM sessions WHERE id = ?`
143790
+ );
143791
+ const sessionOf = (address) => {
143792
+ const party = parseAddress(address);
143793
+ return party?.kind === "session" ? sessionRow.get(party.sessionId) : void 0;
143794
+ };
143795
+ const releasedTo = /* @__PURE__ */ new Map();
143796
+ for (const p of pending) if (p.held === "released") releasedTo.set(p.id, [...releasedTo.get(p.id) ?? [], p.recipient]);
143797
+ const moved = [];
143798
+ for (const p of pending) {
143799
+ const sender = parseAddress(p.sender);
143800
+ const from = sessionOf(p.sender);
143801
+ const senderProject = sender?.kind === "session" ? (from?.trashed === 0 ? from.project : null) ?? (p.sender === p.t_owner ? p.t_project_id : null) : null;
143802
+ const target = p.reply_to === null ? void 0 : rootOf.get(p.reply_to);
143803
+ const kind = movedKind(p.kind, p.t_origin);
143804
+ const facts = {
143805
+ ...movedFacts(p.facts),
143806
+ legacyKind: p.kind,
143807
+ ...quiet(sender?.kind ?? "session", p) ? { quiet: true } : {},
143808
+ ...p.needs_owner === 1 ? { needsOwner: true } : {},
143809
+ ...releasedTo.has(p.id) ? { releasedTo: releasedTo.get(p.id) } : {}
143810
+ };
143811
+ insertMail.run({
143812
+ id: p.id,
143813
+ sender: p.sender,
143814
+ senderProject,
143815
+ kind,
143816
+ needsReply: p.kind === "question" ? 1 : 0,
143817
+ // The order is a thread's own (`seq`), so a reply finds its target moved before it, whatever their times say
143818
+ replyTo: target ? p.reply_to : null,
143819
+ rootId: target?.root_id ?? p.id,
143820
+ urgent: p.urgent === 1 ? 1 : 0,
143821
+ body: p.body,
143822
+ facts: JSON.stringify(facts),
143823
+ origin: p.seq === 1 ? p.t_origin : "mail",
143824
+ legacyThread: p.thread_id,
143825
+ createdAt: p.created_at
143826
+ });
143827
+ const to = sessionOf(p.recipient);
143828
+ const row = insertRow.run({
143829
+ messageId: p.id,
143830
+ recipient: p.recipient,
143831
+ via: p.recipient === p.t_assignee && to?.assistant === 1 && p.t_owner !== p.recipient ? "assistant" : null,
143832
+ dueAt: p.due_at,
143833
+ attemptAt: p.attempt_at,
143834
+ deliveredAt: p.delivered_at,
143835
+ readAt: p.read_at,
143836
+ held: p.held !== null && CARRIED_HOLDS.includes(p.held) ? p.held : null,
143837
+ attempts: p.attempts,
143838
+ lastError: p.last_error,
143839
+ settled: kind === "task" && to?.trashed === 1 ? "gone" : "legacy",
143840
+ now
143841
+ });
143842
+ if (row.changes === 1) moved.push(Number(row.lastInsertRowid));
143843
+ handled.run({ now, id: p.id, recipient: p.recipient });
143844
+ }
143845
+ endOldHolds(this.db, moved);
143846
+ }
143847
+ /** The receipts still pending at `now`, each with its message and what the move reads of its thread, in each thread's own order */
143848
+ pendingReceipts(now) {
143849
+ return this.db.prepare(
143850
+ `SELECT m.id, m.thread_id, m.seq, m.sender, m.kind, m.urgent, m.needs_owner, m.wake, m.reply_to, m.body, m.facts, m.created_at,
143851
+ r.recipient, r.due_at, r.attempt_at, r.delivered_at, r.read_at, r.held, r.attempts, r.last_error,
143852
+ t.project_id AS t_project_id, t.owner AS t_owner, t.assignee AS t_assignee, t.origin AS t_origin
143853
+ FROM mail_receipts r JOIN mail_messages m ON m.id = r.message_id JOIN mail_threads t ON t.id = m.thread_id
143854
+ WHERE r.handled_at IS NULL AND COALESCE(r.held, '') <> 'dismissed' AND m.created_at >= ?
143855
+ AND (r.delivered_at IS NULL OR r.read_at IS NULL OR m.kind = 'question')
143856
+ ORDER BY m.thread_id, m.seq, r.recipient`
143857
+ ).all(now - MOVE_WITHIN_MS);
143858
+ }
143859
+ };
143860
+ var MOVE_WITHIN_MS = 180 * 24 * 60 * 60 * 1e3;
143861
+ var CARRIED_HOLDS = ["uncertain", "failed", "loop", "policy", "released", "budget"];
143862
+ var TASK_ORIGINS = ["person", "start_agent", "agent_session", "send_to_session", "create_session", "ask_project"];
143863
+ function movedKind(kind, threadOrigin) {
143864
+ if (kind === "assign" && TASK_ORIGINS.includes(threadOrigin)) return "task";
143865
+ if (kind === "report") return "report";
143866
+ return kind === "notice" || kind === "event" ? "notice" : "message";
143867
+ }
143868
+ function movedFacts(raw) {
143869
+ let value;
143870
+ try {
143871
+ value = JSON.parse(raw);
143872
+ } catch {
143873
+ return {};
143874
+ }
143875
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return {};
143876
+ const facts = { ...value };
143877
+ if (Array.isArray(facts.waitingOn)) facts.waitingOn = facts.waitingOn.length;
143878
+ return facts;
143879
+ }
143880
+ function quiet(senderKind2, m) {
143881
+ if (m.kind === "event") return true;
143882
+ if (senderKind2 === "centralu") return m.wake === "no";
143883
+ if (senderKind2 !== "app") return false;
143884
+ return m.wake === "no" || m.kind === "notice" && m.needs_owner !== 1 && m.wake !== "yes";
143885
+ }
143886
+
143745
143887
  // packages/agent-host/src/dev-services/store/migrations/index.ts
143746
143888
  function migrationSteps(host) {
143747
143889
  return [
@@ -143753,7 +143895,8 @@ function migrationSteps(host) {
143753
143895
  ...new StepsV55(host).steps(),
143754
143896
  ...new StepsV58(host).steps(),
143755
143897
  ...new StepsV62(host).steps(),
143756
- ...new StepsV65(host).steps()
143898
+ ...new StepsV65(host).steps(),
143899
+ ...new StepsV75(host).steps()
143757
143900
  ];
143758
143901
  }
143759
143902
 
@@ -144407,8 +144550,6 @@ var TrashRecords = class {
144407
144550
  const host = this.db.prepare(`SELECT value FROM app_settings WHERE key = ?`).get(HUB_SELF_KEY)?.value;
144408
144551
  if (host) {
144409
144552
  const address = `session:${host}/${sessionId}`;
144410
- this.db.prepare(`DELETE FROM mail_receipts WHERE recipient = ?`).run(address);
144411
- this.db.prepare(`DELETE FROM mail_participants WHERE address = ?`).run(address);
144412
144553
  this.mailbox.purgeParty(address);
144413
144554
  }
144414
144555
  this.db.prepare(`DELETE FROM mail_turns WHERE session_id = ?`).run(sessionId);
@@ -144783,21 +144924,6 @@ var Store = class extends MigrationRunner {
144783
144924
  this.db.pragma(`busy_timeout = ${wait}`);
144784
144925
  }
144785
144926
  }
144786
- /**
144787
- * The thread mail an older build left pending, moved into the message tables and marked handled in the old ones, in one transaction
144788
- * (docs/plans/mailbox.md §6.3): run after every `ready` from M3a to M7, before delivery starts. A second run finds nothing
144789
- */
144790
- movePendingThreadMail(now, projectOf, holdsNow) {
144791
- return movePendingThreadMail(this.db, now, projectOf, holdsNow);
144792
- }
144793
- /** An old thread's messages, read-only (§6.3): the earlier history of a moved message (`legacy_thread`) */
144794
- legacyChain(threadId, before, limit) {
144795
- return legacyChain(this.db, threadId, before, limit);
144796
- }
144797
- /** What `reader` was shown of an old thread before a moved message (§6.3, `legacyChainFor`) */
144798
- legacyChainFor(threadId, messageId, reader, limit) {
144799
- return legacyChainFor(this.db, threadId, messageId, reader, limit);
144800
- }
144801
144927
  /** The migration list. `store/migrations/index.ts` holds it, and the rule a new step follows */
144802
144928
  migrationSteps() {
144803
144929
  return migrationSteps({
@@ -145360,7 +145486,7 @@ function turnRecorder(mail, records, turns) {
145360
145486
  return (sessionId, turn) => {
145361
145487
  const child = mail.sessionAddress(sessionId);
145362
145488
  const taskId = turn.ownerId && turn.by === "work" ? records.newestTask(mail.sessionAddress(turn.ownerId), child)?.id ?? null : null;
145363
- const personWork = () => turn.ownerId ? null : records.newestTask(PERSON, child)?.id ?? null;
145489
+ const personWork = () => turn.ownerId || turn.unowned ? null : records.newestTask(PERSON, child)?.id ?? null;
145364
145490
  const record2 = (by, messageId, owner) => turn.again ? turns.restate(sessionId, by, messageId, owner) : turns.beginOther(sessionId, by, messageId, owner);
145365
145491
  if (turn.by === "person") record2("person", null);
145366
145492
  else if (turn.source === "report") record2("report", null);
@@ -145403,12 +145529,12 @@ var AskProjectFlow = class {
145403
145529
  * already logged the `auto` boundary it opens, so this one does not log it again. `trust`: false leaves the project's
145404
145530
  * trust out, for the one read that decides it once the target is known (§7.4).
145405
145531
  */
145406
- askGateError(callerId, quiet = false, trust = true) {
145532
+ askGateError(callerId, quiet2 = false, trust = true) {
145407
145533
  const caller = this.host.meta.get(callerId);
145408
145534
  if (!caller?.projectId) return "This session belongs to no project, so it cannot ask another one";
145409
145535
  const deep = agentDepthRefusal(this.host, callerId, "ask a project");
145410
145536
  if (deep) return deep;
145411
- return trust ? this.host.trustGate(callerId, caller.projectId, "asking another project", quiet) : null;
145537
+ return trust ? this.host.trustGate(callerId, caller.projectId, "asking another project", quiet2) : null;
145412
145538
  }
145413
145539
  /** The project asked is still registered: the person may remove it while its card stands */
145414
145540
  projectGoneError(target) {
@@ -146020,7 +146146,7 @@ var HostCards = class {
146020
146146
  return new Promise((resolve21) => {
146021
146147
  if (signal?.aborted) return resolve21(null);
146022
146148
  const requestId = card.requestId ?? `${detail.kind === "project_access" ? "xp" : detail.kind === "agent_start" ? "ag" : detail.kind === "centralu_update" || isCentraluApply(detail) ? "up" : "mk"}-${randomUUID25()}`;
146023
- const ask = { requestId, sessionId, detail, shown: card.shown ?? false, resolve: resolve21 };
146149
+ const ask = { requestId, sessionId, detail, shown: card.shown ?? false, resolve: resolve21, ...card.onHeld ? { onHeld: card.onHeld } : {} };
146024
146150
  this.hostAsks.set(requestId, ask);
146025
146151
  signal?.addEventListener("abort", () => this.withdrawHostAsk(requestId), { once: true });
146026
146152
  this.raiseHostAsks(sessionId);
@@ -146115,6 +146241,26 @@ var HostCards = class {
146115
146241
  * conversation never ends up with the same card as two separate lines).
146116
146242
  */
146117
146243
  raiseHostAsks(sessionId) {
146244
+ this.raiseNext(sessionId);
146245
+ this.noteStanding(sessionId);
146246
+ }
146247
+ /**
146248
+ * Tells the callers of a session's cards whether each is in the person's sight (#2271): standing in the session's slot,
146249
+ * or not (another card stands there, or the person's own turn cleared the slot, `cardsDead`, until the turn ends and
146250
+ * raises it again, #673). Only a change is told. Run after every change of the slot (`applyStateHint`) and every raise;
146251
+ * a caller that waits on the person holds its limit meanwhile (a linked machine's ask, `call.hold`)
146252
+ */
146253
+ noteStanding(sessionId) {
146254
+ const slot = this.host.meta.get(sessionId)?.pendingApproval?.requestId;
146255
+ for (const ask of this.hostAsks.values()) {
146256
+ if (ask.sessionId !== sessionId || !ask.onHeld) continue;
146257
+ const held3 = slot !== ask.requestId;
146258
+ if (held3 === (ask.held ?? false)) continue;
146259
+ ask.held = held3;
146260
+ ask.onHeld(held3);
146261
+ }
146262
+ }
146263
+ raiseNext(sessionId) {
146118
146264
  const m = this.host.meta.get(sessionId);
146119
146265
  if (!m || m.pendingApproval) return;
146120
146266
  const next = [...this.hostAsks.values()].find((a) => a.sessionId === sessionId);
@@ -147833,8 +147979,11 @@ var MachineAsks = class {
147833
147979
  ordinary(projectId) {
147834
147980
  return [...this.host.meta.values()].filter((s) => s.projectId === projectId && isOrdinary(s)).map((s) => ({ id: s.id, name: s.name, state: s.state }));
147835
147981
  }
147836
- /** `hub.askProject`: one ask of a machine's session, as `ask_project` is here */
147837
- async ask(machine, p, signal) {
147982
+ /**
147983
+ * `hub.askProject`: one ask of a machine's session, as `ask_project` is here. `hold` holds the call's limit on the machine
147984
+ * while the pair's card is out of the person's sight (#2271)
147985
+ */
147986
+ async ask(machine, p, signal, hold) {
147838
147987
  const shut = this.gate(machine);
147839
147988
  if (shut) return { ok: false, error: shut };
147840
147989
  const here = this.selfName();
@@ -147891,9 +148040,11 @@ var MachineAsks = class {
147891
148040
  closing.signal,
147892
148041
  /*
147893
148042
  * Raised whatever the target session's preset (#550 review): its `auto` is its own, and answers no card of another
147894
- * machine, as start_agent's on another computer is asked every time (#1038)
148043
+ * machine, as start_agent's on another computer is asked every time (#1038). The machine's call waits on the person,
148044
+ * so its limit stops while the person cannot see the card (#2271): their own turn in that session hides it until the
148045
+ * turn ends (#673), or another card stands in its place
147895
148046
  */
147896
- { alwaysAsk: true }
148047
+ { alwaysAsk: true, ...hold ? { onHeld: hold } : {} }
147897
148048
  ).finally(() => {
147898
148049
  signal?.removeEventListener("abort", onAbort);
147899
148050
  mine2.delete(closing);
@@ -148071,6 +148222,10 @@ var SessionManager = class {
148071
148222
  },
148072
148223
  waitEnded: (id3, cause2, end) => this.mail.mailWaitEnded(id3, cause2, this.meta.get(id3)?.askedBy ?? null, end),
148073
148224
  updateStep: (cut3, step, err) => this.tenure.updateStep(cut3, step, err),
148225
+ resumeEndsOwnTurn: (id3) => {
148226
+ const tool = this.meta.get(id3)?.tool;
148227
+ return !!tool && this.adapters.get(tool)?.resumeEndsOwnTurn === true;
148228
+ },
148074
148229
  // Through Centralu's channel: sent only while the wait still stands (a Stop or a message of the person's takes it away, even while a restart is waited out)
148075
148230
  send: (id3, note, gate) => {
148076
148231
  const skipLine = () => !note.line || note.cause === "update" && this.tenure.leavingForUpdate();
@@ -149663,8 +149818,8 @@ var MessageService = class {
149663
149818
  const urgent = input.urgent === true;
149664
149819
  const senderProject = this.reach.projectOf(sender);
149665
149820
  const holds = to.map((r) => this.reach.holdFor({ kind: "message", senderProject }, r));
149666
- const quiet = kind === "message" && target !== void 0 && to.length === 1 && to[0] === target.sender && quietAnswer({ kind, sender, needsReply, urgent }, target, { parent: this.reach.parentOf(target.sender), owesTask: this.records.newestTask(sender, target.sender) !== void 0, request: requests2[0] === true });
149667
- const facts = { ...clarifies !== void 0 ? { clarifies } : {}, ...quiet ? { quiet: true } : {}, ...cited ? { cites: cited } : {}, ...input.picked && cls === "person" ? { picked: true } : {} };
149821
+ const quiet2 = kind === "message" && target !== void 0 && to.length === 1 && to[0] === target.sender && quietAnswer({ kind, sender, needsReply, urgent }, target, { parent: this.reach.parentOf(target.sender), owesTask: this.records.newestTask(sender, target.sender) !== void 0, request: requests2[0] === true });
149822
+ const facts = { ...clarifies !== void 0 ? { clarifies } : {}, ...quiet2 ? { quiet: true } : {}, ...cited ? { cites: cited } : {}, ...input.picked && cls === "person" ? { picked: true } : {} };
149668
149823
  const stored = this.put(
149669
149824
  // The citation's one use: `UNIQUE(sender, dedupe_key)` (`personWord` looked first, in this transaction)
149670
149825
  { ...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) } : {} },
@@ -149677,7 +149832,7 @@ var MessageService = class {
149677
149832
  if (held3.length === 0) this.records.settle(target.id, sender, "answered", now, stored.id);
149678
149833
  else this.answerHeld(target, stored);
149679
149834
  }
149680
- return { message: stored, held: held3, answered: target?.id ?? null, answers: answers2, quiet, asWork, ...cited ? { cited } : {}, ...typeof word === "string" ? { notCited: word } : {} };
149835
+ return { message: stored, held: held3, answered: target?.id ?? null, answers: answers2, quiet: quiet2, asWork, ...cited ? { cited } : {}, ...typeof word === "string" ? { notCited: word } : {} };
149681
149836
  });
149682
149837
  }
149683
149838
  /** A new message id of this host's, for a message another host writes first (#2067 review, `MailAcross.send`) */
@@ -149952,8 +150107,7 @@ var MessageService = class {
149952
150107
  relations.add(relation);
149953
150108
  items.push(this.frameItem(recipient, message, relation, down && row.deliveredAt === null, row.lastError === "maybe_repeated"));
149954
150109
  }
149955
- const calls = this.opts.calls?.(recipient) ?? mailCalls(2, "plain");
149956
- const frame = buildMessageFrame(items, calls);
150110
+ const frame = buildMessageFrame(items, this.opts.calls?.(recipient));
149957
150111
  return {
149958
150112
  text: frame.text,
149959
150113
  messageIds: frame.shown,
@@ -150505,24 +150659,21 @@ var MailPerson = class {
150505
150659
  const root3 = this.rootsOf(threadId)[0];
150506
150660
  if (root3 === void 0) throw refuse4("unknown_message", `There is no mail ${threadId} kept.`);
150507
150661
  const all = this.records.numbered(root3, CHAIN_CAP).map(({ m, n }) => ({ m, seq: n })).filter((s) => this.readable(s.m) || !this.involves(s.m));
150508
- const lookIn = !all.some((s) => this.readable(s.m));
150662
+ const lookIn = opts.lookIn === true || !all.some((s) => this.readable(s.m));
150509
150663
  let page;
150510
150664
  if (opts.after !== void 0) page = all.filter((s) => s.seq > (opts.after ?? 0)).slice(0, opts.all ? void 0 : THREAD_PAGE);
150511
150665
  else if (opts.tail !== void 0 || !opts.all) {
150512
150666
  const upTo = opts.before === void 0 ? all : all.filter((s) => s.seq < (opts.before ?? 0));
150513
150667
  page = upTo.slice(-Math.min(opts.tail ?? THREAD_PAGE, THREAD_PAGE));
150514
150668
  } else page = all;
150515
- this.readFor(page);
150669
+ if (!lookIn) this.readFor(page);
150516
150670
  const first = page[0]?.seq;
150517
150671
  const last = page.at(-1)?.seq;
150518
- const legacy = this.legacyOf(all[0]?.m);
150519
- const fromStart = first === void 0 || first === all[0]?.seq;
150520
- const messages2 = [...(fromStart ? legacy : []).map((m, i) => legacyMessage(m, i - legacy.length + 1, (a) => this.party(a))), ...page.map((s) => this.message(s))];
150521
150672
  return {
150522
150673
  thread: this.row(root3, this.heldIn(root3)) ?? this.lookInRow(root3),
150523
150674
  parties: this.partiesOf(all.map((s) => s.m)),
150524
150675
  blockers: [],
150525
- messages: messages2,
150676
+ messages: page.map((s) => this.message(s)),
150526
150677
  more: last !== void 0 && all.some((s) => s.seq > last),
150527
150678
  older: first !== void 0 && all.some((s) => s.seq < first),
150528
150679
  follows: [],
@@ -150758,17 +150909,6 @@ var MailPerson = class {
150758
150909
  if (m.sender === PERSON) return true;
150759
150910
  return this.records.recipients(m.id).some((r) => r.recipient === PERSON || isPersonHold(r.held));
150760
150911
  }
150761
- /** An old thread's messages before the first one moved from it: the chain's history, read-only (§6.3) */
150762
- legacyOf(first) {
150763
- if (!first?.legacyThread) return [];
150764
- const moved = new Set(this.records.byRoot(first.rootId, { limit: CHAIN_CAP }).map((m) => m.id));
150765
- const earlier = [];
150766
- for (const m of this.host.legacyChain(first.legacyThread)) {
150767
- if (m.id === first.id || moved.has(m.id)) break;
150768
- earlier.push(m);
150769
- }
150770
- return earlier;
150771
- }
150772
150912
  heldIn(root3) {
150773
150913
  return this.records.heldRows().filter((r) => this.records.message(r.messageId)?.rootId === root3).length;
150774
150914
  }
@@ -150937,9 +151077,6 @@ function taskState(m, r, on2) {
150937
151077
  function hasTask(m, r) {
150938
151078
  return m.kind === "task" && parseAddress(r.recipient)?.kind === "session" && r.settled === null && r.releasedAt === null;
150939
151079
  }
150940
- function legacyMessage(m, seq, party) {
150941
- return { id: m.id, seq, sender: party(m.sender), kind: m.kind, urgent: m.urgent, body: m.body, facts: { ...m.facts }, createdAt: m.createdAt };
150942
- }
150943
151080
  function isPersonHold(held3) {
150944
151081
  return PERSON_HOLDS.some((h) => h === held3);
150945
151082
  }
@@ -151487,7 +151624,7 @@ var MailTool = class {
151487
151624
  try {
151488
151625
  const me2 = this.host.caller(sessionId);
151489
151626
  if (!me2) throw refuse4("gone", "this session is not here");
151490
- return { text: this.dispatch(sessionId, me2, args, mailCalls(1, this.host.form(sessionId))) };
151627
+ return { text: this.dispatch(sessionId, me2, args, mailCalls(this.host.form(sessionId))) };
151491
151628
  } catch (e) {
151492
151629
  return failed4(e);
151493
151630
  }
@@ -151505,7 +151642,7 @@ var MailTool = class {
151505
151642
  const pr = args.action === "watch" ? prNumberOf(args.to ?? "") : null;
151506
151643
  if (pr !== null) {
151507
151644
  const watches = this.watchArgs(args);
151508
- return { text: await watches.registerPr(me2.address, pr, args.text?.trim() ?? "", (id3) => mailCalls(1, this.host.form(sessionId)).close(id3), signal) };
151645
+ return { text: await watches.registerPr(me2.address, pr, args.text?.trim() ?? "", (id3) => mailCalls(this.host.form(sessionId)).close(id3), signal) };
151509
151646
  }
151510
151647
  if (args.action === "find") {
151511
151648
  if (!across) return { text: "Finding sessions is not available here.", isError: true };
@@ -151765,25 +151902,11 @@ var MailTool = class {
151765
151902
  const chain = id3 === void 0 ? v.items : v.items.slice(0, -1);
151766
151903
  if (base2 && chain.length > 0) out.push("Earlier in this chain:");
151767
151904
  for (const item of chain) out.push(this.shown(me2, item));
151768
- if (base2) {
151769
- const legacy = base2.message.legacyThread;
151770
- if (legacy && !base2.phantom && chain.length === 0) out.unshift(...this.legacy(me2, legacy, base2.message.id));
151771
- out.push(this.shown(me2, base2));
151772
- }
151905
+ if (base2) out.push(this.shown(me2, base2));
151773
151906
  if (v.older) out.push(`Older messages in this chain: ${calls.read(v.older)}.`);
151774
151907
  if (id3 === void 0 && v.items.length > 0) out.push(`There may be more: ${calls.read()}.`);
151775
151908
  return out.join("\n");
151776
151909
  }
151777
- /** The earlier messages of the thread a moved message came from, read-only (§6.3), each quoted under its sender */
151778
- legacy(me2, threadId, moved) {
151779
- const earlier = this.host.legacyChain(threadId, moved, me2);
151780
- if (earlier.length === 0) return [];
151781
- return [
151782
- `Earlier, in thread ${threadId} (kept from before Centralu's mail had no threads):`,
151783
- ...earlier.map((m) => `[${m.id}] ${m.kind} from ${m.sender === me2 ? "you" : this.name(m.sender)}:
151784
- ${quoted2(escapeFrameTags(m.body))}`)
151785
- ];
151786
- }
151787
151910
  /** One message under Centralu's header (S5); a phantom is one line without words */
151788
151911
  shown(me2, i) {
151789
151912
  const m = i.message;
@@ -151928,6 +152051,10 @@ var AcrossCore = class {
151928
152051
  */
151929
152052
  unsure = /* @__PURE__ */ new Map();
151930
152053
  now;
152054
+ /** This host's id in mail addresses: a hub that links it reads its mail in the hub's terms by it (`host.hubOffer`'s answer, #2268) */
152055
+ get hostId() {
152056
+ return this.d.hostId;
152057
+ }
151931
152058
  // ── Addresses ──
151932
152059
  route(address) {
151933
152060
  const p = parseAddress(address);
@@ -151968,10 +152095,8 @@ var AcrossCore = class {
151968
152095
  }
151969
152096
  /** On a machine, its own session as the hub `hubId` names it */
151970
152097
  asHubNames(hubId, address) {
151971
- if (address === sessionAddress(hubId, PERSON_ID)) return PERSON;
151972
152098
  const you = this.peers?.hub?.(hubId)?.you;
151973
- const p = parseAddress(address);
151974
- return you && p?.kind === "session" && p.host === this.d.hostId && !p.sessionId.includes(".") ? sessionAddress(hubId, `${you}.${p.sessionId}`) : address;
152099
+ return inHubTerms(address, hubId, you ? { host: this.d.hostId, id: you } : void 0);
151975
152100
  }
151976
152101
  /** On a machine, an address as the hub `hubId` names it, as this host names it (its own sessions are its own again) */
151977
152102
  fromHubNames(hubId, address) {
@@ -152391,7 +152516,15 @@ function mayReachAcross(_from, _to) {
152391
152516
  var FOREIGN_ID = /^[^\s/]{1,120}\.m_[0-9A-Za-z]{10,40}$/;
152392
152517
  var FIND_MS = 4e3;
152393
152518
  var NAMED_HERE_MS = 600;
152519
+ var OPEN_ASKED = 500;
152520
+ var ASKED_WITHIN = MAILBOX_RETENTION.settledMs - 24 * 60 * 60 * 1e3;
152521
+ var LACKED_MAX = 5e3;
152522
+ var NAMED_MAX = 10;
152394
152523
  var MailAcross = class extends AcrossReceipts {
152524
+ /** On a hub: tasks whose `host.mail` is under way now, which an offer neither asks about nor deletes */
152525
+ sending = /* @__PURE__ */ new Set();
152526
+ /** On a machine: tasks it told a hub never arrived (`lacking`), by hub, so one hub's many cannot push another's out under `LACKED_MAX` */
152527
+ lacked = /* @__PURE__ */ new Map();
152395
152528
  // ── Sending from here ──
152396
152529
  /**
152397
152530
  * A session's message to a session on another host (`to`: an address, or `parent` for a session a hub started here).
@@ -152437,7 +152570,8 @@ var MailAcross = class extends AcrossReceipts {
152437
152570
  return { ok: false, why: "failed", text: `this computer could not keep its copy of the task, so nothing was sent: ${oneLineText(errorMessage(e), 500)}` };
152438
152571
  }
152439
152572
  }
152440
- const r = this.settle(id3, await this.ask(m, "host.mail", params));
152573
+ this.sending.add(id3);
152574
+ const r = this.settle(id3, await this.ask(m, "host.mail", params).finally(() => this.sending.delete(id3)));
152441
152575
  if (!r.ok) {
152442
152576
  if (!r.maybe) this.d.records.deleteRows([{ messageId: id3, recipient: to }]);
152443
152577
  return { ok: false, why: r.why, text: r.text };
@@ -152445,6 +152579,52 @@ var MailAcross = class extends AcrossReceipts {
152445
152579
  this.names.set(to, `${r.to} on ${m.name}`);
152446
152580
  return { ok: true, messageId: id3, to: r.to, address: to, computer: m.name };
152447
152581
  }
152582
+ /**
152583
+ * On a hub: the open tasks given to `machineId`'s sessions within `ASKED_WITHIN`, oldest first, that no send has under way: what its offer asks it
152584
+ * about (`HubOffer.open`)
152585
+ */
152586
+ openTasksTo(machineId) {
152587
+ const since = this.now() - ASKED_WITHIN;
152588
+ return this.d.records.openTasksToward(sessionAddress(this.d.hostId, `${machineId}.`), since, OPEN_ASKED).filter((id3) => !this.sending.has(id3));
152589
+ }
152590
+ /**
152591
+ * On a hub: `machineId` answered this connection's offer, and `lacks` are the tasks it says never arrived there (#2289): sends whose answer was lost
152592
+ * before the machine wrote them. Nothing there will ever report on one, so each copy still open and in no send now is deleted, as a refusal deletes
152593
+ * one, and each sender is told in one notice and woken once, as for a stop. Then what is owed to the machine goes (`changed`)
152594
+ */
152595
+ offerAnswered(machineId, lacks) {
152596
+ const lost = /* @__PURE__ */ new Map();
152597
+ for (const id3 of lacks) {
152598
+ const m = this.sending.has(id3) ? void 0 : this.d.records.message(id3);
152599
+ const row = m?.kind === "task" ? this.d.records.recipients(id3)[0] : void 0;
152600
+ const r = row && this.route(row.recipient);
152601
+ if (!m || !row || r?.kind !== "machine" || r.machineId !== machineId || row.settled !== null || row.releasedAt !== null) continue;
152602
+ const name = this.foreignName(row.recipient)?.name ?? row.recipient;
152603
+ this.d.records.deleteRows([{ messageId: id3, recipient: row.recipient }]);
152604
+ this.unsure.delete(id3);
152605
+ lost.set(m.sender, [...lost.get(m.sender) ?? [], { id: id3, name: oneLineText(name, 200) }]);
152606
+ this.d.log?.(`[mail] ${id3} never reached ${r.machineId}: its copy is deleted, and its sender told`);
152607
+ }
152608
+ for (const [sender, tasks] of lost) this.d.service.notice(sender, notArrived(tasks));
152609
+ this.changed();
152610
+ }
152611
+ /**
152612
+ * On a machine: which of the tasks hub `hubId`'s offer asks about (`HubOffer.open`) never arrived here. Only that hub's own ids (`<hubId>.m_…`) are
152613
+ * answered: another hub learns nothing of what is stored here, and cannot have a hub's later task refused. Each is remembered for that hub, and a
152614
+ * late one from it is refused (`taskFrom`): a send on a link the hub already counted as dead can still land after this answer. Memory is enough, as
152615
+ * no connection outlives this process: after a restart nothing sent before it can arrive
152616
+ */
152617
+ lacking(hubId, ids) {
152618
+ const lacks = ids.filter((id3) => id3.startsWith(`${hubId}.`) && !id3.startsWith(`${this.d.hostId}.`) && FOREIGN_ID.test(id3) && !this.d.records.message(id3));
152619
+ const lacked = this.lacked.get(hubId) ?? /* @__PURE__ */ new Set();
152620
+ for (const id3 of lacks) lacked.add(id3);
152621
+ for (const old of lacked) {
152622
+ if (lacked.size <= LACKED_MAX) break;
152623
+ lacked.delete(old);
152624
+ }
152625
+ if (lacked.size) this.lacked.set(hubId, lacked);
152626
+ return lacks;
152627
+ }
152448
152628
  /** Why a task to `to` cannot go now (`sendTask` says the same), or null: not a linked machine's session, no such machine, or one that takes no tasks yet or at all */
152449
152629
  taskRefusal(to) {
152450
152630
  const there = this.taskPeer(to);
@@ -152619,6 +152799,7 @@ var MailAcross = class extends AcrossReceipts {
152619
152799
  const role = this.d.ownEntries().find((e) => e.address === to)?.role;
152620
152800
  if (role === "assistant" || role === "coordinator") return { ok: false, why: "not_allowed", text: `Not a session this machine shares: ${this.label(to)}` };
152621
152801
  if (p.id === void 0 || !FOREIGN_ID.test(p.id) || p.id.startsWith(`${this.d.hostId}.`)) return { ok: false, why: "bad_value", text: "a task from another computer comes with the id it gave it." };
152802
+ if (this.lacked.get(hub.id)?.has(p.id)) return { ok: false, why: "not_allowed", text: `${this.selfName()} told ${hub.name} when the link came back that this task never arrived, so it was not written now. Give it again.` };
152622
152803
  const had = this.d.records.message(p.id);
152623
152804
  if (had) return had.sender === from && this.d.records.recipient(p.id, to) ? { ok: true, messageId: p.id, to: this.label(to), address: to } : { ok: false, why: "bad_value", text: `${oneLineText(p.id, 200)} is the id of another message on ${this.selfName()}.` };
152624
152805
  if (this.d.reach.mayWrite(from, to, false) === "gone") return { ok: false, why: "gone", text: `${this.label(to) === to ? "That session" : this.label(to)} is gone from ${this.selfName()}: it is in the session archive there or deleted, so nothing was written.` };
@@ -152772,6 +152953,13 @@ function pick4(p) {
152772
152953
  return { ...p.needsReply !== void 0 ? { needsReply: p.needsReply } : {}, ...p.urgent ? { urgent: true } : {}, ...p.replyTo ? { replyTo: p.replyTo } : {}, ...p.notice ? { notice: true } : {}, ...p.id ? { id: p.id } : {} };
152773
152954
  }
152774
152955
  var noAnswer = (ms3) => `no answer within ${durationText(ms3)}`;
152956
+ function notArrived(tasks) {
152957
+ const ids = tasks.map((t) => t.id);
152958
+ const named3 = tasks.slice(0, NAMED_MAX).map((t) => `${t.id} to ${t.name}`);
152959
+ const more = tasks.length > NAMED_MAX ? `, and ${tasks.length - NAMED_MAX} more` : "";
152960
+ const body = tasks.length === 1 ? `[Centralu] Your task to ${tasks[0]?.name} did not arrive: the link failed while it was being sent, and nobody is working on it. Give it again if it is still needed.` : `[Centralu] ${tasks.length} of your tasks did not arrive: ${named3.join(", ")}${more}. The link failed while they were being sent, and nobody is working on them. Give them again if they are still needed.`;
152961
+ return { body, facts: { notArrived: { messages: ids } }, dedupeKey: `not-arrived:${ids[0]}` };
152962
+ }
152775
152963
 
152776
152964
  // packages/agent-host/src/mail/turns.ts
152777
152965
  var STARTED_BY = ["mail", "person", "caller", "cli", "report", "app"];
@@ -152992,7 +153180,7 @@ function hostMail(store2, sessions, opts) {
152992
153180
  },
152993
153181
  calls: (address) => {
152994
153182
  const party = parseAddress(address);
152995
- return mailCalls(1, party?.kind === "session" && sessions.mailCommand(party.sessionId) ? "command" : "plain");
153183
+ return mailCalls(party?.kind === "session" && sessions.mailCommand(party.sessionId) ? "command" : "plain");
152996
153184
  },
152997
153185
  personSaid: (sessionId) => store2.messages.newestPersonMessage(sessionId),
152998
153186
  standing: (address) => {
@@ -153113,7 +153301,6 @@ function hostMail(store2, sessions, opts) {
153113
153301
  sessions: () => sessions.listSessions().map((s) => ({ id: s.id, name: s.name, project: s.projectId ?? null, state: s.state })),
153114
153302
  form: (id3) => sessions.mailCommand(id3) ? "command" : "plain",
153115
153303
  askerOf: (id3) => askerFacts(askedByHost, id3),
153116
- legacyChain: (threadId, messageId, reader) => store2.legacyChainFor(threadId, messageId, reader, 9),
153117
153304
  across,
153118
153305
  watches,
153119
153306
  ...sessions.work ? { work: sessions.work } : {}
@@ -153233,16 +153420,6 @@ function hostMail(store2, sessions, opts) {
153233
153420
  } catch (e) {
153234
153421
  console.error(`[mail] taking back the notices of ended cards failed: ${errorMessage(e)}`);
153235
153422
  }
153236
- try {
153237
- const moved = store2.movePendingThreadMail(
153238
- now(),
153239
- (address) => reach.projectOf(address),
153240
- (m, recipient) => reach.holdFor(m, recipient) !== null
153241
- );
153242
- if (moved.messages > 0) console.error(`[mail] moved ${moved.messages} pending message(s) an older build left in its threads`);
153243
- } catch (e) {
153244
- console.error(`[mail] moving the thread mail an older build left pending failed: ${errorMessage(e)}`);
153245
- }
153246
153423
  try {
153247
153424
  const open6 = new Map(store2.mailbox.openTurns().map((t) => [t.sessionId, t.turnSeq]));
153248
153425
  const stops = sessions.listSessions().flatMap((s) => {
@@ -153255,11 +153432,6 @@ function hostMail(store2, sessions, opts) {
153255
153432
  } catch (e) {
153256
153433
  console.error(`[mail] telling the senders of the turns the last host's end cut failed: ${errorMessage(e)}`);
153257
153434
  }
153258
- try {
153259
- store2.children.dropReportMarks();
153260
- } catch (e) {
153261
- console.error(`[mail] deleting the report marks an older build left failed: ${errorMessage(e)}`);
153262
- }
153263
153435
  delivery.start();
153264
153436
  for (const s of sessions.listSessions()) sessions.settleAtRest?.(s.id);
153265
153437
  }
@@ -153343,6 +153515,355 @@ function watched(records, changed) {
153343
153515
  });
153344
153516
  }
153345
153517
 
153518
+ // packages/agent-host/src/links/qualifier.ts
153519
+ var onMachine2 = (name, machine) => `${name} on ${machine}`;
153520
+ var CrossMachineError = class extends Error {
153521
+ code = "internal";
153522
+ constructor(what, machine) {
153523
+ super(`${what} belongs to another machine than ${machine}; one call reaches one machine`);
153524
+ }
153525
+ };
153526
+ var Qualifier = class {
153527
+ constructor(machine, slot, ownerOf) {
153528
+ this.machine = machine;
153529
+ this.slot = slot;
153530
+ this.ownerOf = ownerOf;
153531
+ }
153532
+ machine;
153533
+ slot;
153534
+ ownerOf;
153535
+ prefix = () => `${this.machine}.`;
153536
+ /** Set once the machine answered this connection's offer (`LinkedMachineConnection.offerAsks`); null until then, and for a hub with no mail */
153537
+ mail = null;
153538
+ /**
153539
+ * This machine's approval cards the hub could not read (#844), by the machine's own session id and the request id.
153540
+ * The hub's windows show such a card as a fallback with allow and deny only, but a window from before #844 still
153541
+ * offers "always", and the machine would keep it for a kind it knows (a project consent, an agent start). So the hub
153542
+ * refuses "always" for these (`LinkedMachine.call`): nobody can grant for good what was never shown in full here.
153543
+ * Seen on the card's event and on a session row that carries it; an answered card leaves.
153544
+ */
153545
+ unread = /* @__PURE__ */ new Set();
153546
+ noteCard(sessionId, requestId, detail) {
153547
+ if (typeof sessionId !== "string" || typeof requestId !== "string") return;
153548
+ if (isUnknownCard(ApprovalDetail.parse(detail))) this.unread.add(`${sessionId}\0${requestId}`);
153549
+ }
153550
+ /** Whether the hub read this card of the machine (in the machine's own ids) as a fallback */
153551
+ unreadCard(sessionId, requestId) {
153552
+ return typeof sessionId === "string" && typeof requestId === "string" && this.unread.has(`${sessionId}\0${requestId}`);
153553
+ }
153554
+ /** An id of this machine as the hub's UI sees it */
153555
+ id(value) {
153556
+ return qualify(this.machine, value);
153557
+ }
153558
+ /** The same for a value that may be absent or null, which stays so */
153559
+ maybeId(value) {
153560
+ return typeof value === "string" ? this.id(value) : value;
153561
+ }
153562
+ /** Whether a hub-side id names this machine */
153563
+ owns(value) {
153564
+ return typeof value === "string" && value.startsWith(this.prefix());
153565
+ }
153566
+ /** A hub-side id back to the remote's own. Refuses an id of another machine */
153567
+ strip(value, what) {
153568
+ if (typeof value !== "string" || !this.owns(value)) throw new CrossMachineError(what, this.machine);
153569
+ return value.slice(this.prefix().length);
153570
+ }
153571
+ /** The same for a value that may be null or absent, which stays so */
153572
+ stripMaybe(value, what) {
153573
+ return value === null || value === void 0 ? value : this.strip(value, what);
153574
+ }
153575
+ // ── Results ─────────────────────────────────────────────────────────────────────────────
153576
+ /** `SessionInfo` (and `UpdateSettingsResult`, which extends it) */
153577
+ session(s) {
153578
+ if (!isObj(s)) return s;
153579
+ if (isObj(s.pendingApproval)) this.noteCard(s.id, s.pendingApproval.requestId, s.pendingApproval.detail);
153580
+ const id3 = this.maybeId(s.id);
153581
+ const owner = typeof id3 === "string" ? this.ownerOf?.(id3) : void 0;
153582
+ return {
153583
+ ...s,
153584
+ id: id3,
153585
+ projectId: this.maybeId(s.projectId),
153586
+ parentSessionId: this.maybeId(s.parentSessionId),
153587
+ ...owner ? { askedBy: owner } : "askedBy" in s ? { askedBy: this.maybeId(s.askedBy) } : {},
153588
+ scopeSessionIds: Array.isArray(s.scopeSessionIds) ? s.scopeSessionIds.map((x) => this.maybeId(x)) : s.scopeSessionIds,
153589
+ machine: this.machine
153590
+ };
153591
+ }
153592
+ sessions(list2) {
153593
+ return Array.isArray(list2) ? list2.map((s) => this.session(s)) : list2;
153594
+ }
153595
+ /** `{ session, resumed, reason?, ... }` from restart, resume and fork */
153596
+ sessionResult(r) {
153597
+ return isObj(r) ? { ...r, session: this.session(r.session) } : r;
153598
+ }
153599
+ /** `ProjectInfo` */
153600
+ project(p) {
153601
+ if (!isObj(p)) return p;
153602
+ const manager = p.worktreeManager;
153603
+ return {
153604
+ ...p,
153605
+ id: this.maybeId(p.id),
153606
+ worktreeManager: isObj(manager) ? { ...manager, sessionId: this.maybeId(manager.sessionId) } : manager,
153607
+ machine: this.machine
153608
+ };
153609
+ }
153610
+ projects(list2) {
153611
+ return Array.isArray(list2) ? list2.map((p) => this.project(p)) : list2;
153612
+ }
153613
+ /** `TerminalInfo` */
153614
+ terminal(t) {
153615
+ return isObj(t) ? { ...t, terminalId: this.maybeId(t.terminalId) } : t;
153616
+ }
153617
+ /** `CommandRunInfo` — its run id rides the terminal frame lane in place of a terminal id */
153618
+ run(r) {
153619
+ return isObj(r) ? { ...r, runId: this.maybeId(r.runId) } : r;
153620
+ }
153621
+ /** `StoredMessage`: its session, and the ids its payload names (#371's asked-by line, a handoff, an app's text) */
153622
+ message(m) {
153623
+ if (!isObj(m)) return m;
153624
+ return { ...m, sessionId: this.maybeId(m.sessionId), payload: this.payload(m.payload) };
153625
+ }
153626
+ messages(list2) {
153627
+ return Array.isArray(list2) ? list2.map((m) => this.message(m)) : list2;
153628
+ }
153629
+ payload(p) {
153630
+ if (!isObj(p)) return p;
153631
+ const out = { ...p };
153632
+ if (typeof p.sessionId === "string") out.sessionId = this.id(p.sessionId);
153633
+ if (isObj(p.from) && typeof p.from.sessionId === "string") out.from = { ...p.from, sessionId: this.id(p.from.sessionId) };
153634
+ if (typeof p.fromSessionId === "string") out.fromSessionId = this.id(p.fromSessionId);
153635
+ if (isObj(p.fromApp)) out.fromApp = { ...p.fromApp, projectId: this.maybeId(p.fromApp.projectId) };
153636
+ if ("projectId" in p) out.projectId = this.maybeId(p.projectId);
153637
+ if (typeof p.instanceId === "string") out.instanceId = this.id(p.instanceId);
153638
+ if (isObj(p.detail)) out.detail = this.approvalDetail(p.detail);
153639
+ return out;
153640
+ }
153641
+ /** `ApprovalDetail`: the kinds that name a project */
153642
+ approvalDetail(d2) {
153643
+ if (!isObj(d2)) return d2;
153644
+ if (d2.kind === "capability" && isObj(d2.app)) return { ...d2, app: { ...d2.app, projectId: this.maybeId(d2.app.projectId) } };
153645
+ if (d2.kind === "project_access") {
153646
+ const side = (x) => isObj(x) ? { ...x, id: this.maybeId(x.id) } : x;
153647
+ return { ...d2, from: side(d2.from), to: side(d2.to) };
153648
+ }
153649
+ if (d2.kind === "agent_start" && isObj(d2.project)) return { ...d2, project: { ...d2.project, id: this.maybeId(d2.project.id) } };
153650
+ return d2;
153651
+ }
153652
+ /** `TrashedSession` */
153653
+ trashed(t) {
153654
+ if (!isObj(t)) return t;
153655
+ return {
153656
+ ...t,
153657
+ id: this.maybeId(t.id),
153658
+ project: isObj(t.project) ? { ...t.project, id: this.maybeId(t.project.id) } : t.project,
153659
+ machine: this.machine
153660
+ };
153661
+ }
153662
+ /** `TrashedRun` (#378): its app's project is this machine's, and the record is read and deleted here */
153663
+ trashedRun(t) {
153664
+ if (!isObj(t)) return t;
153665
+ return { ...t, app: isObj(t.app) ? { ...t.app, projectId: this.maybeId(t.app.projectId) } : t.app, machine: this.machine };
153666
+ }
153667
+ /** `SubagentStepsHeld` and `TrashedSubagentSteps` (#418) */
153668
+ subagentSteps(t) {
153669
+ if (!isObj(t)) return t;
153670
+ return {
153671
+ ...t,
153672
+ sessionId: this.maybeId(t.sessionId),
153673
+ project: isObj(t.project) ? { ...t.project, id: this.maybeId(t.project.id) } : t.project,
153674
+ machine: this.machine
153675
+ };
153676
+ }
153677
+ /** `ExternalAppInfo`: a project app is that project's; a user-folder app says which machine's folder */
153678
+ app(a) {
153679
+ return isObj(a) ? { ...a, projectId: this.maybeId(a.projectId), machine: this.machine } : a;
153680
+ }
153681
+ /** `ProjectConsent` */
153682
+ consent(c) {
153683
+ return isObj(c) ? { ...c, fromProjectId: this.maybeId(c.fromProjectId), toProjectId: this.maybeId(c.toProjectId), machine: this.machine } : c;
153684
+ }
153685
+ /** One `approvals.rules` row: its numeric id folded (`encodeNumber`), its owner qualified */
153686
+ rule(r, encode3) {
153687
+ if (!isObj(r)) return r;
153688
+ return {
153689
+ ...r,
153690
+ id: typeof r.id === "number" ? encode3(r.id) : r.id,
153691
+ projectId: this.maybeId(r.projectId),
153692
+ sessionId: this.maybeId(r.sessionId),
153693
+ machine: this.machine
153694
+ };
153695
+ }
153696
+ /** `messages.search` hits */
153697
+ hits(list2) {
153698
+ return Array.isArray(list2) ? list2.map((h) => isObj(h) ? { ...h, sessionId: this.maybeId(h.sessionId) } : h) : list2;
153699
+ }
153700
+ /**
153701
+ * `apps.inlineViews` rows and the `apps.inlineReopen` answer. The view instance is qualified like any id: the window
153702
+ * hands it back to open, call and close the view, and the hub routes those by it (plan §11)
153703
+ */
153704
+ inlineView(v) {
153705
+ return isObj(v) ? { ...v, projectId: this.maybeId(v.projectId), instanceId: this.maybeId(v.instanceId) } : v;
153706
+ }
153707
+ /** An `apps.runs` row: its app's project, the session that called it, and the agent session it stood up (the panel links to it) */
153708
+ appRun(r) {
153709
+ return isObj(r) ? { ...r, projectId: this.maybeId(r.projectId), callerSessionId: this.maybeId(r.callerSessionId), sessionId: this.maybeId(r.sessionId) } : r;
153710
+ }
153711
+ /**
153712
+ * The `agents.listExternalSessions` answer. `externalId` is the tool's own id for the conversation, so it stays as it is;
153713
+ * `importedAs` is the id of the Centralu session already open for it, which the window focuses (#701)
153714
+ */
153715
+ externalSessions(r) {
153716
+ if (!isObj(r) || !Array.isArray(r.sessions)) return r;
153717
+ return { ...r, sessions: r.sessions.map((s) => isObj(s) ? { ...s, importedAs: this.maybeId(s.importedAs) } : s) };
153718
+ }
153719
+ /**
153720
+ * The `apps.errors` answer: the app a declined request named is compared with the app on screen, whose project is
153721
+ * qualified, to decide which of the two wordings applies. `runId` is a run's own id and stays as `apps.runs` leaves it
153722
+ */
153723
+ errorBundles(r) {
153724
+ if (!isObj(r)) return r;
153725
+ const bundle = (b2) => isObj(b2) && isObj(b2.denied) ? { ...b2, denied: { ...b2.denied, projectId: this.maybeId(b2.denied.projectId) } } : b2;
153726
+ return { ...r, latest: bundle(r.latest), recent: Array.isArray(r.recent) ? r.recent.map(bundle) : r.recent };
153727
+ }
153728
+ /** The `apps.openView` answer: the pinned view's instance */
153729
+ openedView(v) {
153730
+ return isObj(v) ? { ...v, instanceId: this.maybeId(v.instanceId) } : v;
153731
+ }
153732
+ /** The `apps.viewDocument` answer: the app it names (a user-folder app's null project stays null) */
153733
+ viewDocument(d2) {
153734
+ return isObj(d2) ? { ...d2, projectId: this.maybeId(d2.projectId) } : d2;
153735
+ }
153736
+ /**
153737
+ * A `MailParty` of this machine's mail in the hub's terms (#2268, `inHubTerms`): its own session is `session:<hub>/<machine>.<id>`, named
153738
+ * `<name> on <machine>`; the hub's person is `person`; its own app's project is qualified. The hub's side, `person` and `centralu` stay
153739
+ */
153740
+ mailParty(p) {
153741
+ const t = this.mail;
153742
+ if (!isObj(p) || typeof p.address !== "string" || !t) return p;
153743
+ const address = inHubTerms(p.address, t.hub, t.own === null ? void 0 : { host: t.own, id: this.machine });
153744
+ if (address === PERSON) return { ...p, address, kind: "person", sessionId: null, name: null, state: null };
153745
+ const named3 = parseAddress(address);
153746
+ if (address !== p.address && named3?.kind === "session") {
153747
+ return { ...p, address, sessionId: named3.sessionId, name: typeof p.name === "string" ? onMachine2(p.name, t.computer()) : p.name };
153748
+ }
153749
+ const app2 = parseAddress(p.address);
153750
+ return app2?.kind === "app" && app2.host === t.own ? { ...p, address: appAddress(t.hub, this.id(app2.projectId), app2.appId) } : p;
153751
+ }
153752
+ /** A `mail.tasks` row: its parties in the hub's terms, and its chain qualified so the row opens there (`mail.thread`). The message id is every host's */
153753
+ taskRow(t) {
153754
+ return isObj(t) ? { ...t, root: this.maybeId(t.root), owner: this.mailParty(t.owner), assignee: this.mailParty(t.assignee) } : t;
153755
+ }
153756
+ /**
153757
+ * A `mail.tasks` answer's rows in the hub's terms (`taskRow`), but for the items of this machine's own Inbox: a row its own person gave or has, and one
153758
+ * held there for them to act on. The hub shows nothing of that Inbox (`mail.list` and `mail.held` are the hub's own), so such a row could be neither
153759
+ * answered, closed nor released here, and would stand in the hub's Needs you as the hub's person's own
153760
+ */
153761
+ taskRows(rows3) {
153762
+ const own = (p) => isObj(p) && p.address === PERSON;
153763
+ return (Array.isArray(rows3) ? rows3 : []).flatMap((t) => isObj(t) && (own(t.owner) || own(t.assignee) || t.state === "held") ? [] : [this.taskRow(t)]);
153764
+ }
153765
+ /** A `MailThreadView` of this machine: its chain and the chains it follows qualified, every party in the hub's terms. Message ids are every host's */
153766
+ mailThread(v) {
153767
+ if (!isObj(v)) return v;
153768
+ const party = (x) => this.mailParty(x);
153769
+ const sent = (x) => isObj(x) ? { ...x, sender: party(x.sender) } : x;
153770
+ const list2 = (x, f) => Array.isArray(x) ? x.map((y) => isObj(y) ? f(y) : y) : x;
153771
+ const t = v.thread;
153772
+ return {
153773
+ ...v,
153774
+ thread: isObj(t) ? { ...t, id: this.maybeId(t.id), projectId: this.maybeId(t.projectId), owner: party(t.owner), assignee: party(t.assignee), ask: sent(t.ask), last: sent(t.last) } : t,
153775
+ parties: list2(v.parties, (x) => ({ ...x, party: party(x.party) })),
153776
+ messages: list2(v.messages, (m) => ({ ...m, sender: party(m.sender), ..."receipts" in m ? { receipts: list2(m.receipts, (r) => ({ ...r, recipient: party(r.recipient) })) } : {} })),
153777
+ follows: list2(v.follows, (f) => ({ ...f, id: this.maybeId(f.id) }))
153778
+ };
153779
+ }
153780
+ // ── Events ──────────────────────────────────────────────────────────────────────────────
153781
+ /**
153782
+ * One event of this machine in the hub's terms, or null for one the hub does not pass on.
153783
+ *
153784
+ * Dropped: what is about the remote host itself rather than its sessions and projects. The hub
153785
+ * has its own update, themes, preferences, agent CLIs and screen questions (and a host of v0.1.0-beta.10 or
153786
+ * before still sends `app_state_changed` for its control app), and an app-wide
153787
+ * error from another machine is not this UI's to show (§5). An event of a type this build does
153788
+ * not know is passed when it names a session (qualified), dropped otherwise.
153789
+ */
153790
+ event(e) {
153791
+ if (!isObj(e) || typeof e.type !== "string") return null;
153792
+ const sid = typeof e.sessionId === "string" ? this.id(e.sessionId) : void 0;
153793
+ const base2 = { ...e, ...sid !== void 0 ? { sessionId: sid } : {} };
153794
+ switch (e.type) {
153795
+ // Another machine's agent asking its own windows to apply (#665) must never relaunch the hub's window
153796
+ case "update_status":
153797
+ case "update_apply_request":
153798
+ case "update_apply_go":
153799
+ case "themes_changed":
153800
+ case "prefs_changed":
153801
+ case "app_state_changed":
153802
+ case "agent_versions":
153803
+ case "external_app_questions_changed":
153804
+ case "orchestrator_proposals_changed":
153805
+ case "assistant_proposals_changed":
153806
+ return null;
153807
+ case "error":
153808
+ return sid === void 0 ? null : base2;
153809
+ /*
153810
+ * Its mail moved (#2268): the hub's windows read Tasks again, and the machine's chain if one is open. Never as news for the person: what that
153811
+ * machine's own Inbox holds is not the hub's person's to be told of, and a message to them reaches the hub's mailbox, which tells them itself
153812
+ */
153813
+ case "mail_changed": {
153814
+ const { arrived: _arrived, ...rest } = base2;
153815
+ return { ...rest, threadId: this.maybeId(e.threadId), toPerson: false };
153816
+ }
153817
+ case "session_created":
153818
+ return { ...base2, session: this.session(e.session) };
153819
+ case "user_message": {
153820
+ const out = { ...base2 };
153821
+ if (isObj(e.from) && typeof e.from.sessionId === "string") out.from = { ...e.from, sessionId: this.id(e.from.sessionId) };
153822
+ if (isObj(e.fromApp)) out.fromApp = { ...e.fromApp, projectId: this.maybeId(e.fromApp.projectId) };
153823
+ return out;
153824
+ }
153825
+ // The sender of the message a turn ran for (#1604), named as a message's sender is
153826
+ case "state_change": {
153827
+ const o = e.origin;
153828
+ if (!isObj(o) || !isObj(o.from) || typeof o.from.sessionId !== "string") return base2;
153829
+ return { ...base2, origin: { ...o, from: { ...o.from, sessionId: this.id(o.from.sessionId) } } };
153830
+ }
153831
+ case "handoff":
153832
+ return { ...base2, fromSessionId: this.maybeId(e.fromSessionId) };
153833
+ case "session_owner":
153834
+ return { ...base2, askedBy: (sid !== void 0 ? this.ownerOf?.(sid) : void 0) ?? this.maybeId(e.askedBy), parentSessionId: this.maybeId(e.parentSessionId) };
153835
+ case "approval_request":
153836
+ this.noteCard(e.sessionId, e.requestId, e.detail);
153837
+ return { ...base2, detail: this.approvalDetail(e.detail) };
153838
+ case "approval_resolved":
153839
+ if (typeof e.sessionId === "string" && typeof e.requestId === "string") this.unread.delete(`${e.sessionId}\0${e.requestId}`);
153840
+ return base2;
153841
+ // The view's instance, which the window opens, calls and closes it by (plan §11)
153842
+ case "app_view":
153843
+ return { ...base2, projectId: this.maybeId(e.projectId), instanceId: this.maybeId(e.instanceId) };
153844
+ // The view whose own call caused it, so that view does not re-read what it already has (B-5)
153845
+ case "external_app_state_changed":
153846
+ return {
153847
+ ...base2,
153848
+ projectId: this.maybeId(e.projectId),
153849
+ ...isObj(e.cause) ? { cause: { ...e.cause, instanceId: this.maybeId(e.cause.instanceId) } } : {}
153850
+ };
153851
+ case "external_app_runs_changed":
153852
+ case "fs_changed":
153853
+ return { ...base2, projectId: this.maybeId(e.projectId) };
153854
+ // `projects_changed`: a project another machine made (#515); the hub's windows re-read the merged list
153855
+ case "external_apps_changed":
153856
+ case "project_consents_changed":
153857
+ return base2;
153858
+ // `added` (#1220): a project that machine's assistant added, named as the hub's windows know it
153859
+ case "projects_changed":
153860
+ return typeof e.added === "string" ? { ...base2, added: this.maybeId(e.added) } : base2;
153861
+ default:
153862
+ return sid === void 0 ? null : base2;
153863
+ }
153864
+ }
153865
+ };
153866
+
153346
153867
  // packages/agent-host/src/links/mail-peers.ts
153347
153868
  function mailPeers(o) {
153348
153869
  const { machines, hubs: hubs2, settings } = o;
@@ -153373,7 +153894,7 @@ function mailPeers(o) {
153373
153894
  machineSession: (machineId, sessionId) => {
153374
153895
  const m = machines.get(machineId);
153375
153896
  const row = mirrored(machineId, sessionId);
153376
- return m && row && typeof row.name === "string" ? `${row.name} on ${m.name}` : void 0;
153897
+ return m && row && typeof row.name === "string" ? onMachine2(row.name, m.name) : void 0;
153377
153898
  },
153378
153899
  machineState: (machineId, sessionId) => {
153379
153900
  const state = mirrored(machineId, sessionId)?.state;
@@ -154276,8 +154797,8 @@ function createRpcHandler(mgr2, adapters2, { settleDeletedProjects, deleteOutloo
154276
154797
  },
154277
154798
  "mail.list": async () => requireMail().list(),
154278
154799
  "mail.tasks": async () => requireMail().tasks(),
154279
- "mail.thread": async ({ threadId, after, all, tail, before }) => {
154280
- return requireMail().thread(threadId, { after, all, tail, before });
154800
+ "mail.thread": async ({ threadId, after, all, tail, before, lookIn }) => {
154801
+ return requireMail().thread(threadId, { after, all, tail, before, lookIn });
154281
154802
  },
154282
154803
  "mail.reply": async ({ threadId, text: text3, kind, answers: answers2 }) => {
154283
154804
  return requireMail().reply(threadId, text3, kind, answers2);
@@ -154652,7 +155173,13 @@ function createRpcHandler(mgr2, adapters2, { settleDeletedProjects, deleteOutloo
154652
155173
  "host.hubOffer": async (p, ctx) => {
154653
155174
  const offer = p;
154654
155175
  if (hubs2 && ctx) hubs2.offer(ctx.client, offer);
154655
- return { ok: true, ...mailAcross && hubs2 ? { mail: true, tasks: true } : {}, ...appsAcross && hubs2?.appsOn ? { apps: true } : {} };
155176
+ const lacks = mailAcross && hubs2 && offer.open?.length ? mailAcross.lacking(offer.hub.id, offer.open) : [];
155177
+ return {
155178
+ ok: true,
155179
+ ...mailAcross && hubs2 ? { mail: true, tasks: true, host: mailAcross.hostId } : {},
155180
+ ...lacks.length ? { lacks } : {},
155181
+ ...appsAcross && hubs2?.appsOn ? { apps: true } : {}
155182
+ };
154656
155183
  },
154657
155184
  "host.mail": async (p, ctx) => {
154658
155185
  const hub = ctx ? hubs2?.on?.(ctx.client) : void 0;
@@ -155457,6 +155984,7 @@ var CommandRunner = class {
155457
155984
 
155458
155985
  // packages/agent-host/src/updates.ts
155459
155986
  import { existsSync as existsSync27, readFileSync as readFileSync23 } from "node:fs";
155987
+ import { createRequire as createRequire4 } from "node:module";
155460
155988
  import { dirname as dirname26, join as join54 } from "node:path";
155461
155989
  var REGISTRY_URL = `https://registry.npmjs.org/${APP_SLUG}/latest`;
155462
155990
  var CHECK_INTERVAL_MS = 6 * 60 * 60 * 1e3;
@@ -155481,7 +156009,27 @@ async function npmGlobalPackage() {
155481
156009
  const root3 = out.trim().split(/\r?\n/).at(-1)?.trim();
155482
156010
  if (!root3) return null;
155483
156011
  const launcher = join54(root3, APP_SLUG, "bin", `${APP_SLUG}.mjs`);
155484
- return existsSync27(launcher) ? { launcher, version: packageVersion(join54(root3, APP_SLUG, "package.json")) } : null;
156012
+ if (!existsSync27(launcher)) return null;
156013
+ const manifest = join54(root3, APP_SLUG, "package.json");
156014
+ return { launcher, version: packageVersion(manifest), platform: platformPackage(launcher, manifest, npmMachine()) };
156015
+ }
156016
+ function platformPackage(launcher, manifest, machine) {
156017
+ const name = `@${APP_SLUG}/${machine}`;
156018
+ if (!Object.hasOwn(optionalDependencies(manifest), name)) return null;
156019
+ try {
156020
+ return { name, version: packageVersion(createRequire4(launcher).resolve(`${name}/package.json`)) };
156021
+ } catch {
156022
+ return { name, version: null };
156023
+ }
156024
+ }
156025
+ function optionalDependencies(file2) {
156026
+ try {
156027
+ const pkg = JSON.parse(readFileSync23(file2, "utf8"));
156028
+ const deps = typeof pkg === "object" && pkg !== null && "optionalDependencies" in pkg ? pkg.optionalDependencies : null;
156029
+ return typeof deps === "object" && deps !== null ? { ...deps } : {};
156030
+ } catch {
156031
+ return {};
156032
+ }
155485
156033
  }
155486
156034
  function existingCopy(path2, platform = HOST_PLATFORM) {
155487
156035
  if (!existsSync27(path2)) return null;
@@ -155567,15 +156115,15 @@ function runCommand(file2, args, resolve21) {
155567
156115
  );
155568
156116
  }
155569
156117
  var UpdateService = class {
155570
- constructor(publish, deps = {}) {
156118
+ constructor(publish, deps) {
155571
156119
  this.publish = publish;
155572
156120
  this.deps = {
155573
156121
  current: deps.current ?? APP_VERSION,
155574
156122
  build: deps.build ?? "",
155575
- fetchLatest: deps.fetchLatest ?? fetchLatestFromRegistry,
155576
- run: deps.run ?? runCommand,
155577
- installedCopy: deps.installedCopy ?? (() => existingCopy(installedCopyPath())),
155578
- installedCopyVersion: deps.installedCopyVersion ?? ((copy) => readInstalledCopyVersion(copy)),
156123
+ fetchLatest: deps.fetchLatest,
156124
+ run: deps.run,
156125
+ installedCopy: deps.installedCopy,
156126
+ installedCopyVersion: deps.installedCopyVersion,
155579
156127
  now: deps.now ?? Date.now,
155580
156128
  schedule: deps.schedule ?? ((fn2, ms3) => {
155581
156129
  const t = setTimeout(fn2, ms3);
@@ -155592,7 +156140,7 @@ var UpdateService = class {
155592
156140
  writeAutoApply: deps.writeAutoApply ?? (() => {
155593
156141
  }),
155594
156142
  wait: deps.wait ?? sleep,
155595
- globalPackage: deps.globalPackage ?? npmGlobalPackage,
156143
+ globalPackage: deps.globalPackage,
155596
156144
  node: deps.node ?? process.execPath
155597
156145
  };
155598
156146
  this.status = {
@@ -155792,7 +156340,8 @@ var UpdateService = class {
155792
156340
  this.emit();
155793
156341
  return this.current();
155794
156342
  }
155795
- const failure4 = kept?.phase === "failed" ? kept : null;
156343
+ const failed5 = this.retry?.version;
156344
+ const failure4 = kept?.phase === "failed" && !(failed5 && isNewerVersion(latest, failed5)) ? kept : null;
155796
156345
  this.status = {
155797
156346
  ...this.status,
155798
156347
  latest,
@@ -155924,7 +156473,8 @@ var UpdateService = class {
155924
156473
  * The same two steps as an install from the app (`runApply`): `npm i -g centralu@<this version>`, pinned since the hub
155925
156474
  * decides it, then the npm package's own launcher's `install` by its path (`installCopy`), which on Windows renames the
155926
156475
  * running copy aside. A global package already at or above this version is never taken down to it: only its `install`
155927
- * runs. Nobody sees it: no status changes. A failure is one line on stderr and is tried again at the next host start,
156476
+ * runs, after npm installs that package's own version again when its platform package is missing or at another version
156477
+ * (#2282: an npm that skipped it would otherwise fail every start until a newer release). Nobody sees it: no status changes. A failure is one line on stderr and is tried again at the next host start,
155928
156478
  * which is also when the hub's next update arrives. Never beside an install from the app: one running leaves this for
155929
156479
  * the next start, and one asked for meanwhile waits for this to end (`runApply`).
155930
156480
  */
@@ -155943,7 +156493,8 @@ var UpdateService = class {
155943
156493
  async runFollow(copy, was, to) {
155944
156494
  try {
155945
156495
  const global2 = await this.deps.globalPackage();
155946
- if (!atLeast(global2?.version ?? null, to)) await this.deps.run("npm", ["i", "-g", "--prefer-online", `${APP_SLUG}@${to}`]);
156496
+ if (!atLeast(global2?.version ?? null, to)) await this.installGlobal(to);
156497
+ else if (global2?.version && global2.platform && global2.platform.version !== global2.version) await this.installGlobal(global2.version);
155947
156498
  if (this.stopped) return;
155948
156499
  await this.installCopy();
155949
156500
  console.error(`[updates] the installed copy at ${copy} was refreshed from the npm package at ${global2?.version && atLeast(global2.version, to) ? global2.version : to} (it held ${was ?? "an unreadable version"}; this host is ${to})`);
@@ -155962,7 +156513,8 @@ var UpdateService = class {
155962
156513
  /**
155963
156514
  * A just-published release can be visible from `latest` before its package is on the npm edge
155964
156515
  * this machine reaches: `notarget`/ETARGET while the packument lacks it, or E404 on its own tarball while the packument
155965
- * already lists it (#2279, the registry edge serves the two apart). That narrow condition only; credentials, disk and
156516
+ * already lists it (#2279, the registry edge serves the two apart), or an exit 0 without this machine's platform
156517
+ * package, whose tarball the edge did not serve yet (#2282, `installGlobal`). That narrow condition only; credentials, disk and
155966
156518
  * package errors still fail immediately. The ten minute cap makes this a wait with an end, not
155967
156519
  * a hidden retry loop. `--prefer-online` makes npm revalidate instead of trusting its stale cache.
155968
156520
  */
@@ -155972,11 +156524,11 @@ var UpdateService = class {
155972
156524
  for (; ; ) {
155973
156525
  if (this.stopped) return;
155974
156526
  try {
155975
- await this.deps.run("npm", ["i", "-g", "--prefer-online", `${APP_SLUG}@${version2}`]);
156527
+ await this.installGlobal(version2);
155976
156528
  return;
155977
156529
  } catch (err) {
155978
156530
  if (this.stopped) return;
155979
- if (!npmHasNotServedVersion(err, version2)) throw err;
156531
+ if (!(err instanceof PlatformPackageMissing) && !npmHasNotServedVersion(err, version2)) throw err;
155980
156532
  if (this.deps.now() - started >= NPM_RETRY_WINDOW_MS) throw Object.assign(new Error(`npm did not serve ${version2} within ${NPM_RETRY_WINDOW_MS / 6e4} minutes: ${errorMessage(err)}`), err);
155981
156533
  this.status = { ...this.status, phase: "waiting_for_npm", error: `Waiting for npm to serve ${version2}${notice ? `. ${notice}` : ""}` };
155982
156534
  this.emit();
@@ -155987,6 +156539,19 @@ var UpdateService = class {
155987
156539
  }
155988
156540
  }
155989
156541
  }
156542
+ /**
156543
+ * `npm i -g centralu@<version>`, and this machine's platform package with it (#2282): npm skips an optional dependency
156544
+ * whose tarball the registry edge does not serve yet and exits 0, which leaves a launcher with no app and no host.
156545
+ * That is the same publish race as a 404 on `centralu`'s own tarball, so it throws `PlatformPackageMissing`, which
156546
+ * the install waits out (`installPackage`). A global package npm root does not lead to is left to `installCopy`,
156547
+ * which says so.
156548
+ */
156549
+ async installGlobal(version2) {
156550
+ await this.deps.run("npm", ["i", "-g", "--prefer-online", `${APP_SLUG}@${version2}`]);
156551
+ if (this.stopped) return;
156552
+ const platform = (await this.deps.globalPackage())?.platform;
156553
+ if (platform && platform.version !== version2) throw new PlatformPackageMissing(`npm installed ${APP_SLUG} ${version2} without ${platform.name}@${version2}`);
156554
+ }
155990
156555
  /** `version` is past the release installed and waiting, or nothing is waiting */
155991
156556
  passesInstalled(version2) {
155992
156557
  return !this.installed || isNewerVersion(version2, this.installed.version);
@@ -156005,6 +156570,18 @@ var UpdateService = class {
156005
156570
  this.publish(this.current());
156006
156571
  }
156007
156572
  };
156573
+ function realUpdateService(publish, options = {}) {
156574
+ return new UpdateService(publish, {
156575
+ ...options,
156576
+ fetchLatest: fetchLatestFromRegistry,
156577
+ run: runCommand,
156578
+ installedCopy: () => existingCopy(installedCopyPath()),
156579
+ installedCopyVersion: (copy) => readInstalledCopyVersion(copy),
156580
+ globalPackage: npmGlobalPackage
156581
+ });
156582
+ }
156583
+ var PlatformPackageMissing = class extends Error {
156584
+ };
156008
156585
  function npmHasNotServedVersion(err, version2) {
156009
156586
  const tarball = `/${APP_SLUG}/-/${APP_SLUG}-${version2}.tgz`.replace(/[.+]/g, "\\$&");
156010
156587
  return /\bETARGET\b|\bnotarget\b/i.test(errorMessage(err)) || new RegExp(`\\b404 Not Found - GET \\S+${tarball}(?!\\S)`, "i").test(stderrOf(err));
@@ -158869,301 +159446,6 @@ async function askHubAuto(call2, allowed) {
158869
159446
  // packages/agent-host/src/links/linked-machine-connection.ts
158870
159447
  import { randomBytes as randomBytes15 } from "node:crypto";
158871
159448
 
158872
- // packages/agent-host/src/links/qualifier.ts
158873
- var CrossMachineError = class extends Error {
158874
- code = "internal";
158875
- constructor(what, machine) {
158876
- super(`${what} belongs to another machine than ${machine}; one call reaches one machine`);
158877
- }
158878
- };
158879
- var Qualifier = class {
158880
- constructor(machine, slot, ownerOf) {
158881
- this.machine = machine;
158882
- this.slot = slot;
158883
- this.ownerOf = ownerOf;
158884
- }
158885
- machine;
158886
- slot;
158887
- ownerOf;
158888
- prefix = () => `${this.machine}.`;
158889
- /**
158890
- * This machine's approval cards the hub could not read (#844), by the machine's own session id and the request id.
158891
- * The hub's windows show such a card as a fallback with allow and deny only, but a window from before #844 still
158892
- * offers "always", and the machine would keep it for a kind it knows (a project consent, an agent start). So the hub
158893
- * refuses "always" for these (`LinkedMachine.call`): nobody can grant for good what was never shown in full here.
158894
- * Seen on the card's event and on a session row that carries it; an answered card leaves.
158895
- */
158896
- unread = /* @__PURE__ */ new Set();
158897
- noteCard(sessionId, requestId, detail) {
158898
- if (typeof sessionId !== "string" || typeof requestId !== "string") return;
158899
- if (isUnknownCard(ApprovalDetail.parse(detail))) this.unread.add(`${sessionId}\0${requestId}`);
158900
- }
158901
- /** Whether the hub read this card of the machine (in the machine's own ids) as a fallback */
158902
- unreadCard(sessionId, requestId) {
158903
- return typeof sessionId === "string" && typeof requestId === "string" && this.unread.has(`${sessionId}\0${requestId}`);
158904
- }
158905
- /** An id of this machine as the hub's UI sees it */
158906
- id(value) {
158907
- return qualify(this.machine, value);
158908
- }
158909
- /** The same for a value that may be absent or null, which stays so */
158910
- maybeId(value) {
158911
- return typeof value === "string" ? this.id(value) : value;
158912
- }
158913
- /** Whether a hub-side id names this machine */
158914
- owns(value) {
158915
- return typeof value === "string" && value.startsWith(this.prefix());
158916
- }
158917
- /** A hub-side id back to the remote's own. Refuses an id of another machine */
158918
- strip(value, what) {
158919
- if (typeof value !== "string" || !this.owns(value)) throw new CrossMachineError(what, this.machine);
158920
- return value.slice(this.prefix().length);
158921
- }
158922
- /** The same for a value that may be null or absent, which stays so */
158923
- stripMaybe(value, what) {
158924
- return value === null || value === void 0 ? value : this.strip(value, what);
158925
- }
158926
- // ── Results ─────────────────────────────────────────────────────────────────────────────
158927
- /** `SessionInfo` (and `UpdateSettingsResult`, which extends it) */
158928
- session(s) {
158929
- if (!isObj(s)) return s;
158930
- if (isObj(s.pendingApproval)) this.noteCard(s.id, s.pendingApproval.requestId, s.pendingApproval.detail);
158931
- const id3 = this.maybeId(s.id);
158932
- const owner = typeof id3 === "string" ? this.ownerOf?.(id3) : void 0;
158933
- return {
158934
- ...s,
158935
- id: id3,
158936
- projectId: this.maybeId(s.projectId),
158937
- parentSessionId: this.maybeId(s.parentSessionId),
158938
- ...owner ? { askedBy: owner } : "askedBy" in s ? { askedBy: this.maybeId(s.askedBy) } : {},
158939
- scopeSessionIds: Array.isArray(s.scopeSessionIds) ? s.scopeSessionIds.map((x) => this.maybeId(x)) : s.scopeSessionIds,
158940
- machine: this.machine
158941
- };
158942
- }
158943
- sessions(list2) {
158944
- return Array.isArray(list2) ? list2.map((s) => this.session(s)) : list2;
158945
- }
158946
- /** `{ session, resumed, reason?, ... }` from restart, resume and fork */
158947
- sessionResult(r) {
158948
- return isObj(r) ? { ...r, session: this.session(r.session) } : r;
158949
- }
158950
- /** `ProjectInfo` */
158951
- project(p) {
158952
- if (!isObj(p)) return p;
158953
- const manager = p.worktreeManager;
158954
- return {
158955
- ...p,
158956
- id: this.maybeId(p.id),
158957
- worktreeManager: isObj(manager) ? { ...manager, sessionId: this.maybeId(manager.sessionId) } : manager,
158958
- machine: this.machine
158959
- };
158960
- }
158961
- projects(list2) {
158962
- return Array.isArray(list2) ? list2.map((p) => this.project(p)) : list2;
158963
- }
158964
- /** `TerminalInfo` */
158965
- terminal(t) {
158966
- return isObj(t) ? { ...t, terminalId: this.maybeId(t.terminalId) } : t;
158967
- }
158968
- /** `CommandRunInfo` — its run id rides the terminal frame lane in place of a terminal id */
158969
- run(r) {
158970
- return isObj(r) ? { ...r, runId: this.maybeId(r.runId) } : r;
158971
- }
158972
- /** `StoredMessage`: its session, and the ids its payload names (#371's asked-by line, a handoff, an app's text) */
158973
- message(m) {
158974
- if (!isObj(m)) return m;
158975
- return { ...m, sessionId: this.maybeId(m.sessionId), payload: this.payload(m.payload) };
158976
- }
158977
- messages(list2) {
158978
- return Array.isArray(list2) ? list2.map((m) => this.message(m)) : list2;
158979
- }
158980
- payload(p) {
158981
- if (!isObj(p)) return p;
158982
- const out = { ...p };
158983
- if (typeof p.sessionId === "string") out.sessionId = this.id(p.sessionId);
158984
- if (isObj(p.from) && typeof p.from.sessionId === "string") out.from = { ...p.from, sessionId: this.id(p.from.sessionId) };
158985
- if (typeof p.fromSessionId === "string") out.fromSessionId = this.id(p.fromSessionId);
158986
- if (isObj(p.fromApp)) out.fromApp = { ...p.fromApp, projectId: this.maybeId(p.fromApp.projectId) };
158987
- if ("projectId" in p) out.projectId = this.maybeId(p.projectId);
158988
- if (typeof p.instanceId === "string") out.instanceId = this.id(p.instanceId);
158989
- if (isObj(p.detail)) out.detail = this.approvalDetail(p.detail);
158990
- return out;
158991
- }
158992
- /** `ApprovalDetail`: the kinds that name a project */
158993
- approvalDetail(d2) {
158994
- if (!isObj(d2)) return d2;
158995
- if (d2.kind === "capability" && isObj(d2.app)) return { ...d2, app: { ...d2.app, projectId: this.maybeId(d2.app.projectId) } };
158996
- if (d2.kind === "project_access") {
158997
- const side = (x) => isObj(x) ? { ...x, id: this.maybeId(x.id) } : x;
158998
- return { ...d2, from: side(d2.from), to: side(d2.to) };
158999
- }
159000
- if (d2.kind === "agent_start" && isObj(d2.project)) return { ...d2, project: { ...d2.project, id: this.maybeId(d2.project.id) } };
159001
- return d2;
159002
- }
159003
- /** `TrashedSession` */
159004
- trashed(t) {
159005
- if (!isObj(t)) return t;
159006
- return {
159007
- ...t,
159008
- id: this.maybeId(t.id),
159009
- project: isObj(t.project) ? { ...t.project, id: this.maybeId(t.project.id) } : t.project,
159010
- machine: this.machine
159011
- };
159012
- }
159013
- /** `TrashedRun` (#378): its app's project is this machine's, and the record is read and deleted here */
159014
- trashedRun(t) {
159015
- if (!isObj(t)) return t;
159016
- return { ...t, app: isObj(t.app) ? { ...t.app, projectId: this.maybeId(t.app.projectId) } : t.app, machine: this.machine };
159017
- }
159018
- /** `SubagentStepsHeld` and `TrashedSubagentSteps` (#418) */
159019
- subagentSteps(t) {
159020
- if (!isObj(t)) return t;
159021
- return {
159022
- ...t,
159023
- sessionId: this.maybeId(t.sessionId),
159024
- project: isObj(t.project) ? { ...t.project, id: this.maybeId(t.project.id) } : t.project,
159025
- machine: this.machine
159026
- };
159027
- }
159028
- /** `ExternalAppInfo`: a project app is that project's; a user-folder app says which machine's folder */
159029
- app(a) {
159030
- return isObj(a) ? { ...a, projectId: this.maybeId(a.projectId), machine: this.machine } : a;
159031
- }
159032
- /** `ProjectConsent` */
159033
- consent(c) {
159034
- return isObj(c) ? { ...c, fromProjectId: this.maybeId(c.fromProjectId), toProjectId: this.maybeId(c.toProjectId), machine: this.machine } : c;
159035
- }
159036
- /** One `approvals.rules` row: its numeric id folded (`encodeNumber`), its owner qualified */
159037
- rule(r, encode3) {
159038
- if (!isObj(r)) return r;
159039
- return {
159040
- ...r,
159041
- id: typeof r.id === "number" ? encode3(r.id) : r.id,
159042
- projectId: this.maybeId(r.projectId),
159043
- sessionId: this.maybeId(r.sessionId),
159044
- machine: this.machine
159045
- };
159046
- }
159047
- /** `messages.search` hits */
159048
- hits(list2) {
159049
- return Array.isArray(list2) ? list2.map((h) => isObj(h) ? { ...h, sessionId: this.maybeId(h.sessionId) } : h) : list2;
159050
- }
159051
- /**
159052
- * `apps.inlineViews` rows and the `apps.inlineReopen` answer. The view instance is qualified like any id: the window
159053
- * hands it back to open, call and close the view, and the hub routes those by it (plan §11)
159054
- */
159055
- inlineView(v) {
159056
- return isObj(v) ? { ...v, projectId: this.maybeId(v.projectId), instanceId: this.maybeId(v.instanceId) } : v;
159057
- }
159058
- /** An `apps.runs` row: its app's project, the session that called it, and the agent session it stood up (the panel links to it) */
159059
- appRun(r) {
159060
- return isObj(r) ? { ...r, projectId: this.maybeId(r.projectId), callerSessionId: this.maybeId(r.callerSessionId), sessionId: this.maybeId(r.sessionId) } : r;
159061
- }
159062
- /**
159063
- * The `agents.listExternalSessions` answer. `externalId` is the tool's own id for the conversation, so it stays as it is;
159064
- * `importedAs` is the id of the Centralu session already open for it, which the window focuses (#701)
159065
- */
159066
- externalSessions(r) {
159067
- if (!isObj(r) || !Array.isArray(r.sessions)) return r;
159068
- return { ...r, sessions: r.sessions.map((s) => isObj(s) ? { ...s, importedAs: this.maybeId(s.importedAs) } : s) };
159069
- }
159070
- /**
159071
- * The `apps.errors` answer: the app a declined request named is compared with the app on screen, whose project is
159072
- * qualified, to decide which of the two wordings applies. `runId` is a run's own id and stays as `apps.runs` leaves it
159073
- */
159074
- errorBundles(r) {
159075
- if (!isObj(r)) return r;
159076
- const bundle = (b2) => isObj(b2) && isObj(b2.denied) ? { ...b2, denied: { ...b2.denied, projectId: this.maybeId(b2.denied.projectId) } } : b2;
159077
- return { ...r, latest: bundle(r.latest), recent: Array.isArray(r.recent) ? r.recent.map(bundle) : r.recent };
159078
- }
159079
- /** The `apps.openView` answer: the pinned view's instance */
159080
- openedView(v) {
159081
- return isObj(v) ? { ...v, instanceId: this.maybeId(v.instanceId) } : v;
159082
- }
159083
- /** The `apps.viewDocument` answer: the app it names (a user-folder app's null project stays null) */
159084
- viewDocument(d2) {
159085
- return isObj(d2) ? { ...d2, projectId: this.maybeId(d2.projectId) } : d2;
159086
- }
159087
- // ── Events ──────────────────────────────────────────────────────────────────────────────
159088
- /**
159089
- * One event of this machine in the hub's terms, or null for one the hub does not pass on.
159090
- *
159091
- * Dropped: what is about the remote host itself rather than its sessions and projects. The hub
159092
- * has its own update, themes, preferences, agent CLIs and screen questions (and a host of v0.1.0-beta.10 or
159093
- * before still sends `app_state_changed` for its control app), and an app-wide
159094
- * error from another machine is not this UI's to show (§5). An event of a type this build does
159095
- * not know is passed when it names a session (qualified), dropped otherwise.
159096
- */
159097
- event(e) {
159098
- if (!isObj(e) || typeof e.type !== "string") return null;
159099
- const sid = typeof e.sessionId === "string" ? this.id(e.sessionId) : void 0;
159100
- const base2 = { ...e, ...sid !== void 0 ? { sessionId: sid } : {} };
159101
- switch (e.type) {
159102
- // Another machine's agent asking its own windows to apply (#665) must never relaunch the hub's window
159103
- case "update_status":
159104
- case "update_apply_request":
159105
- case "update_apply_go":
159106
- case "themes_changed":
159107
- case "prefs_changed":
159108
- case "app_state_changed":
159109
- case "agent_versions":
159110
- case "mail_changed":
159111
- case "external_app_questions_changed":
159112
- case "orchestrator_proposals_changed":
159113
- case "assistant_proposals_changed":
159114
- return null;
159115
- case "error":
159116
- return sid === void 0 ? null : base2;
159117
- case "session_created":
159118
- return { ...base2, session: this.session(e.session) };
159119
- case "user_message": {
159120
- const out = { ...base2 };
159121
- if (isObj(e.from) && typeof e.from.sessionId === "string") out.from = { ...e.from, sessionId: this.id(e.from.sessionId) };
159122
- if (isObj(e.fromApp)) out.fromApp = { ...e.fromApp, projectId: this.maybeId(e.fromApp.projectId) };
159123
- return out;
159124
- }
159125
- // The sender of the message a turn ran for (#1604), named as a message's sender is
159126
- case "state_change": {
159127
- const o = e.origin;
159128
- if (!isObj(o) || !isObj(o.from) || typeof o.from.sessionId !== "string") return base2;
159129
- return { ...base2, origin: { ...o, from: { ...o.from, sessionId: this.id(o.from.sessionId) } } };
159130
- }
159131
- case "handoff":
159132
- return { ...base2, fromSessionId: this.maybeId(e.fromSessionId) };
159133
- case "session_owner":
159134
- return { ...base2, askedBy: (sid !== void 0 ? this.ownerOf?.(sid) : void 0) ?? this.maybeId(e.askedBy), parentSessionId: this.maybeId(e.parentSessionId) };
159135
- case "approval_request":
159136
- this.noteCard(e.sessionId, e.requestId, e.detail);
159137
- return { ...base2, detail: this.approvalDetail(e.detail) };
159138
- case "approval_resolved":
159139
- if (typeof e.sessionId === "string" && typeof e.requestId === "string") this.unread.delete(`${e.sessionId}\0${e.requestId}`);
159140
- return base2;
159141
- // The view's instance, which the window opens, calls and closes it by (plan §11)
159142
- case "app_view":
159143
- return { ...base2, projectId: this.maybeId(e.projectId), instanceId: this.maybeId(e.instanceId) };
159144
- // The view whose own call caused it, so that view does not re-read what it already has (B-5)
159145
- case "external_app_state_changed":
159146
- return {
159147
- ...base2,
159148
- projectId: this.maybeId(e.projectId),
159149
- ...isObj(e.cause) ? { cause: { ...e.cause, instanceId: this.maybeId(e.cause.instanceId) } } : {}
159150
- };
159151
- case "external_app_runs_changed":
159152
- case "fs_changed":
159153
- return { ...base2, projectId: this.maybeId(e.projectId) };
159154
- // `projects_changed`: a project another machine made (#515); the hub's windows re-read the merged list
159155
- case "external_apps_changed":
159156
- case "project_consents_changed":
159157
- return base2;
159158
- // `added` (#1220): a project that machine's assistant added, named as the hub's windows know it
159159
- case "projects_changed":
159160
- return typeof e.added === "string" ? { ...base2, added: this.maybeId(e.added) } : base2;
159161
- default:
159162
- return sid === void 0 ? null : base2;
159163
- }
159164
- }
159165
- };
159166
-
159167
159449
  // packages/agent-host/src/links/remote-client.ts
159168
159450
  var MAX_INCOMING_CALLS = 16;
159169
159451
  var DEFAULT_CALL_TIMEOUT_MS = 2e5;
@@ -159405,7 +159687,11 @@ var RemoteClient = class {
159405
159687
  if (this.incoming.size >= MAX_INCOMING_CALLS) return refuse8("Too many calls at once; try again shortly", "internal", true);
159406
159688
  const ctl = new AbortController();
159407
159689
  this.incoming.set(id3, ctl);
159408
- void handle2(method, params, ctl.signal).then(
159690
+ const hold = (held3) => {
159691
+ if (this.ws !== ws2 || this.incoming.get(id3) !== ctl) return;
159692
+ this.call(HOLD_CALL_METHOD, { id: id3, held: held3 }).catch(() => void 0);
159693
+ };
159694
+ void handle2(method, params, ctl.signal, hold).then(
159409
159695
  (result) => answer({ ok: true, result: result ?? null }),
159410
159696
  (err) => {
159411
159697
  const e = asObj(err);
@@ -160289,11 +160575,15 @@ var LinkedMachineConnection = class {
160289
160575
  const on2 = this.record.asks === true;
160290
160576
  let note = null;
160291
160577
  if (this.client === client) this.tasksBack = void 0;
160578
+ const open6 = this.deps.hubMail ? this.deps.openTasks?.(this.id) ?? [] : [];
160579
+ let lacks = [];
160292
160580
  try {
160293
- const answer = await client.call("host.hubOffer", { hub: self2, on: on2, ...this.deps.hubMail ? { mail: true, you: this.id } : {}, ...this.deps.hubApps ? { apps: true } : {} });
160581
+ const answer = await client.call("host.hubOffer", { hub: self2, on: on2, ...this.deps.hubMail ? { mail: true, you: this.id } : {}, ...open6.length ? { open: open6 } : {}, ...this.deps.hubApps ? { apps: true } : {} });
160582
+ if (isObj(answer) && Array.isArray(answer.lacks)) lacks = answer.lacks.filter((id3) => typeof id3 === "string");
160294
160583
  if (this.client === client) this.mailBack = isObj(answer) && answer.mail === true;
160295
160584
  if (this.client === client) this.appsBack = isObj(answer) && answer.apps === true;
160296
160585
  if (this.client === client) this.tasksBack = isObj(answer) && answer.tasks === true;
160586
+ if (this.client === client) this.q.mail = { hub: self2.id, own: isObj(answer) && typeof answer.host === "string" ? answer.host : null, computer: () => this.name };
160297
160587
  } catch (err) {
160298
160588
  if (this.client === client) this.appsBack = false;
160299
160589
  if (this.client === client) this.mailBack = false;
@@ -160301,7 +160591,7 @@ var LinkedMachineConnection = class {
160301
160591
  if (on2) note = `${this.name} could not be told yet (${err.message}); it is told again at the next connect`;
160302
160592
  }
160303
160593
  if (this.client !== client) return;
160304
- this.deps.onOfferAnswered?.(this.id);
160594
+ this.deps.onOfferAnswered?.(this.id, lacks);
160305
160595
  const changed = note !== this.asksNote;
160306
160596
  this.asksNote = note;
160307
160597
  if (changed) this.deps.broadcast({ type: "machine_status", machine: this.info() });
@@ -160506,7 +160796,7 @@ var LinkedMachineConnection = class {
160506
160796
  if (this.stopped) return;
160507
160797
  const readsOnly = this.readsOnly;
160508
160798
  this.readsOnly = false;
160509
- const quiet = this.quietRetry;
160799
+ const quiet2 = this.quietRetry;
160510
160800
  this.quietRetry = false;
160511
160801
  const { dataDir, shell } = this.record.remote;
160512
160802
  const badDir = dataDir ? dataDirError(dataDir, shell) : null;
@@ -160516,7 +160806,7 @@ var LinkedMachineConnection = class {
160516
160806
  this.client = null;
160517
160807
  }
160518
160808
  if (this.heldBack && !this.startAsked) this.setStatus("stopped", this.heldBack);
160519
- else if (!(quiet && this.status === "away")) this.setStatus("connecting", null);
160809
+ else if (!(quiet2 && this.status === "away")) this.setStatus("connecting", null);
160520
160810
  let endpoint = await this.openTunnel();
160521
160811
  if (!endpoint) return;
160522
160812
  if (this.status === "away") this.setStatus("connecting", null);
@@ -160747,7 +161037,7 @@ var LinkedMachineConnection = class {
160747
161037
  hello: (h) => void this.onHello(client, h),
160748
161038
  event: (e) => this.onEvent(e),
160749
161039
  // The machine's calls to this hub (#550): answered as this machine, whatever they say, by the hub's allowlist
160750
- ...this.deps.reverse ? { call: (method, params, signal) => this.deps.reverse({ id: this.id, name: this.name }, method, params, signal) } : {},
161040
+ ...this.deps.reverse ? { call: (method, params, signal, hold) => this.deps.reverse({ id: this.id, name: this.name }, method, params, signal, hold) } : {},
160751
161041
  terminal: (f) => this.deps.terminal({ ...f, terminalId: this.q.id(f.terminalId) }),
160752
161042
  down: (reason, detail) => {
160753
161043
  if (this.client !== client) return;
@@ -160805,9 +161095,12 @@ var LinkedMachineConnection = class {
160805
161095
  if (!mayConnect(v)) return;
160806
161096
  }
160807
161097
  try {
160808
- const [sessions, projects] = await Promise.all([client.call("sessions.list", {}), client.call("projects.list", {})]);
160809
- if (Array.isArray(sessions)) this.observe("sessions", sessions);
160810
- if (Array.isArray(projects)) this.observe("projects", projects);
161098
+ await Promise.all(
161099
+ ["sessions", "projects"].map(async (kind) => {
161100
+ const list2 = await client.call(kind === "sessions" ? "sessions.list" : "projects.list", {});
161101
+ if (Array.isArray(list2)) this.observe(kind, list2);
161102
+ })
161103
+ );
160811
161104
  } catch (err) {
160812
161105
  this.deps.log?.(`[links] ${this.name}: could not read its lists after connecting: ${err.message}`);
160813
161106
  }
@@ -160868,15 +161161,31 @@ var LinkedMachineConnection = class {
160868
161161
  this.deps.mirror.removeSession(this.id, sid);
160869
161162
  } else if (raw.type === "session_title" && typeof raw.title === "string") {
160870
161163
  this.deps.mirror.patchSession(this.id, sid, { name: raw.title });
160871
- } else if (raw.type === "state_change" && typeof raw.state === "string") {
160872
- this.deps.mirror.patchSession(this.id, sid, { state: raw.state });
160873
161164
  } else if (raw.type === "session_owner") {
160874
161165
  this.deps.mirror.patchSession(this.id, sid, { askedBy: raw.askedBy ?? null, parentSessionId: raw.parentSessionId ?? null });
161166
+ } else {
161167
+ this.followState(sid, raw);
160875
161168
  }
160876
161169
  }
160877
161170
  const out = this.q.event(raw);
160878
161171
  if (out) this.deps.broadcast(out);
160879
161172
  }
161173
+ /**
161174
+ * The mirror's row follows every event that moves the session's state (#2288), by the one state rule the machine's host
161175
+ * and the windows run (`applySessionState`). It used to take `state_change` alone, so a turn's end (`turn_complete`), a
161176
+ * card, a limit or an error left the row as it was: a session that had finished its turn still read as working to every
161177
+ * reader of the mirror. An `activity` (a compaction, a review, a retry: rare) is followed too, as the rule writes it. An
161178
+ * event or a row this build cannot read changes nothing; the machine's next list replaces the rows whole (`observe`).
161179
+ */
161180
+ followState(sid, raw) {
161181
+ const e = NormalizedEvent.safeParse(raw);
161182
+ if (!e.success || nextStateFor(e.data) === null && e.data.type !== "activity") return;
161183
+ const row = (this.deps.mirror.read(this.id, "sessions") ?? []).find((s) => isObj(s) && s.id === sid);
161184
+ const live2 = LiveStateFields.safeParse(row);
161185
+ if (!live2.success) return;
161186
+ applySessionState(live2.data, e.data, Date.now());
161187
+ this.deps.mirror.patchSession(this.id, sid, live2.data);
161188
+ }
160880
161189
  classify(s) {
160881
161190
  if (!isObj(s) || typeof s.id !== "string") return;
160882
161191
  if (!hiddenKind(s)) this.shown.add(s.id);
@@ -162477,9 +162786,17 @@ var ROUTES = {
162477
162786
  "workspace.load": HUB,
162478
162787
  // The mailbox is the hub's: a linked machine's mail reaches it there (slice 4 of #1347)
162479
162788
  "mail.list": HUB,
162480
- // This host's tasks only: a linked machine's are not listed yet, and its chains do not open from the hub (mail.thread is the hub's)
162481
- "mail.tasks": HUB,
162482
- "mail.thread": HUB,
162789
+ // Every machine's open work in one list (#2268, router.ts); a machine's chain opens there, to read only: reply and close are the hub's mailbox's,
162790
+ // and the machine reads nothing in it for its own person (`lookIn`)
162791
+ "mail.tasks": MERGE,
162792
+ "mail.thread": {
162793
+ kind: "chain",
162794
+ params: (p) => ({ ...p, lookIn: true }),
162795
+ result: (r, q2) => {
162796
+ const v = q2.mailThread(r);
162797
+ return isObj(v) ? { ...v, lookIn: true, canReply: false } : v;
162798
+ }
162799
+ },
162483
162800
  "mail.reply": HUB,
162484
162801
  "mail.close": HUB,
162485
162802
  "mail.held": HUB,
@@ -162616,6 +162933,8 @@ var Router = class {
162616
162933
  return this.byKey(method, params, route.key ?? "projectId", route, ctx);
162617
162934
  case "terminal":
162618
162935
  return this.byKey(method, params, "terminalId", route, ctx);
162936
+ case "chain":
162937
+ return this.byKey(method, params, "threadId", { ...route, accepts: isChainId }, ctx);
162619
162938
  case "view":
162620
162939
  return this.byView(method, params, route, ctx);
162621
162940
  case "noRemote": {
@@ -162631,9 +162950,10 @@ var Router = class {
162631
162950
  return this.merge(method, params, ctx);
162632
162951
  }
162633
162952
  };
162634
- /** The linked machine an id names, or null for the hub's own (an unprefixed id, or a prefix no link has) */
162635
- owner(value) {
162636
- return typeof value === "string" ? qualifiedMachine(this.opts.machines(), value)?.machine ?? null : null;
162953
+ /** The linked machine an id names, or null for the hub's own (an unprefixed id, a prefix no link has, or what follows it not an id `accepts`) */
162954
+ owner(value, accepts2) {
162955
+ const found = typeof value === "string" ? qualifiedMachine(this.opts.machines(), value) : null;
162956
+ return found && (accepts2?.(found.id) ?? true) ? found.machine : null;
162637
162957
  }
162638
162958
  machineById(id3) {
162639
162959
  return typeof id3 === "string" ? findMachine(this.opts.machines(), id3) : null;
@@ -162655,7 +162975,7 @@ var Router = class {
162655
162975
  const r5 = await this.forward(m2, method, route.params ? route.params(rest, m2.q) : rest, ctx);
162656
162976
  return route.result ? route.result(r5, m2.q) : r5;
162657
162977
  }
162658
- const m = this.owner(params[key2]);
162978
+ const m = this.owner(params[key2], route.accepts);
162659
162979
  if (!m) return this.opts.local(method, params, ctx);
162660
162980
  const { machine: _machine, ...own } = params;
162661
162981
  let p = { ...route.orMachine ? own : params, [key2]: m.q.strip(params[key2], "The id") };
@@ -162853,8 +163173,10 @@ var Router = class {
162853
163173
  const answers2 = await Promise.all(
162854
163174
  machines.filter((m) => m.reachable).map(async (m) => {
162855
163175
  try {
163176
+ if (method === "mail.tasks") await m.offerAnswered?.();
162856
163177
  return { m, r: await callOn(m, method, params, ctx) };
162857
- } catch {
163178
+ } catch (e) {
163179
+ if (method === "mail.tasks" && older2(e)) return null;
162858
163180
  missed.push(m);
162859
163181
  return null;
162860
163182
  }
@@ -162874,11 +163196,47 @@ var Router = class {
162874
163196
  const failed5 = Array.isArray(out.failed) ? out.failed : [];
162875
163197
  out = { ...out, failed: [...failed5, ...missed.map((m) => ({ sessionId: m.id, name: m.name, error: "this machine could not be reached, so its archived sessions were not deleted" }))] };
162876
163198
  }
162877
- if ((method === "trash.list" || method === "subagents.usage") && missed.length && isObj(out)) {
163199
+ if (method === "mail.tasks" && isObj(out)) out = this.oneTaskEach(out);
163200
+ if ((method === "trash.list" || method === "subagents.usage" || method === "mail.tasks") && missed.length && isObj(out)) {
162878
163201
  out = { ...out, unreached: missed.map((m) => ({ machineId: m.id, name: m.name })) };
162879
163202
  }
162880
163203
  return out;
162881
163204
  }
163205
+ /**
163206
+ * Tasks one row per message and recipient (#2268, docs/plans/linked-mail.md §11). Mail that crossed is stored on both hosts under one id, so two
163207
+ * hosts list it. The hub's own row is kept, as it opens there to answer; a machine's mail to another machine, which the hub keeps no copy of, keeps
163208
+ * the row of the machine its recipient is on. That machine is the authority on its row and alone knows `running`, so the kept row takes its state.
163209
+ * A host that capped its list makes the answer say how many open rows it shows, counted once de-duplicated, as the window counts its rows
163210
+ */
163211
+ oneTaskEach(out) {
163212
+ const from = (t) => this.owner(t.root, isChainId);
163213
+ const kept = /* @__PURE__ */ new Map();
163214
+ const odd = [];
163215
+ for (const t of listIn(out, "tasks")) {
163216
+ if (!isObj(t) || !isObj(t.assignee)) {
163217
+ odd.push(t);
163218
+ continue;
163219
+ }
163220
+ const origin = from(t);
163221
+ const on2 = this.owner(t.assignee.sessionId);
163222
+ const authority = on2 !== null && origin === on2 ? t : null;
163223
+ const key2 = `${String(t.id)}\0${String(t.assignee.address)}`;
163224
+ const seen = kept.get(key2);
163225
+ if (!seen) kept.set(key2, { row: t, hub: origin === null, authority });
163226
+ else if (seen.hub || !authority) kept.set(key2, { ...seen, authority: seen.authority ?? authority });
163227
+ else kept.set(key2, { row: t, hub: false, authority });
163228
+ }
163229
+ const rows3 = [...kept.values()].map(
163230
+ ({ row, authority }) => authority && authority !== row ? { ...row, state: authority.state, outcome: authority.outcome, updatedAt: authority.updatedAt } : row
163231
+ );
163232
+ const capped = typeof out.capped === "number" ? rows3.filter((t) => t.state !== "done").length : null;
163233
+ return { ...out, tasks: [...rows3, ...odd], capped };
163234
+ }
163235
+ };
163236
+ var listIn = (x, field) => isObj(x) && Array.isArray(x[field]) ? x[field] : [];
163237
+ var isChainId = (id3) => {
163238
+ const kind = parseMailId(id3)?.kind;
163239
+ return kind === "message" || kind === "thread";
162882
163240
  };
162883
163241
  function combine(method, acc, r, q2) {
162884
163242
  const list2 = (x) => Array.isArray(x) ? x : [];
@@ -162904,6 +163262,12 @@ function combine(method, acc, r, q2) {
162904
163262
  ..."subagentSteps" in a || "subagentSteps" in b2 ? { subagentSteps: [...list2(a.subagentSteps), ...list2(b2.subagentSteps).map((t) => q2.subagentSteps(t))] } : {}
162905
163263
  };
162906
163264
  }
163265
+ case "mail.tasks": {
163266
+ const a = isObj(acc) ? acc : { tasks: [] };
163267
+ const b2 = isObj(r) ? r : { tasks: [] };
163268
+ const capped = typeof a.capped === "number" ? a.capped : typeof b2.capped === "number" ? b2.capped : null;
163269
+ return { ...a, tasks: [...listIn(a, "tasks"), ...q2.taskRows(listIn(b2, "tasks"))], capped };
163270
+ }
162907
163271
  case "subagents.usage": {
162908
163272
  const a = isObj(acc) ? acc : { sessions: [] };
162909
163273
  const b2 = isObj(r) ? r : { sessions: [] };
@@ -162989,12 +163353,12 @@ function linkDepsFor(store2, rest) {
162989
163353
  const log = (line) => rest.log?.(stamped(line));
162990
163354
  return { ...rest, log, mirror: storeMirror(store2), registry: storeRegistry(store2), tunnelFor: tunnelsFor(store2, log) };
162991
163355
  }
162992
- var kindOf4 = (k2) => k2 === "sessions" ? "session" : "project";
163356
+ var kindOf3 = (k2) => k2 === "sessions" ? "session" : "project";
162993
163357
  var withIds = (list2) => list2.filter((x) => isObj(x) && typeof x.id === "string");
162994
163358
  function storeMirror(store2) {
162995
163359
  return {
162996
- read: (machine, kind) => store2.machines.machineHeaders(machine, kindOf4(kind)),
162997
- replace: (machine, kind, list2) => store2.machines.replaceMachineHeaders(machine, kindOf4(kind), withIds(list2)),
163360
+ read: (machine, kind) => store2.machines.machineHeaders(machine, kindOf3(kind)),
163361
+ replace: (machine, kind, list2) => store2.machines.replaceMachineHeaders(machine, kindOf3(kind), withIds(list2)),
162998
163362
  upsertSession: (machine, session2) => {
162999
163363
  if (typeof session2.id === "string") store2.machines.upsertMachineSession(machine, session2);
163000
163364
  },
@@ -163157,7 +163521,11 @@ var LinkedHubs = class {
163157
163521
  if (h.client === null) return { ok: false, error: `${h.name} is ${NOT_REACHABLE}. Try again once its link is back.` };
163158
163522
  let raw;
163159
163523
  try {
163160
- raw = await this.deps.call(h.client, "hub.askProject", params, { signal, ...this.deps.askTimeoutMs ? { timeoutMs: this.deps.askTimeoutMs } : {} });
163524
+ raw = await this.deps.call(h.client, "hub.askProject", params, {
163525
+ signal,
163526
+ ...this.deps.askTimeoutMs ? { timeoutMs: this.deps.askTimeoutMs } : {},
163527
+ ...this.deps.askHoldMaxMs ? { holdMaxMs: this.deps.askHoldMaxMs } : {}
163528
+ });
163161
163529
  } catch (err) {
163162
163530
  if (signal?.aborted) return { ok: false, error: "The call was cancelled." };
163163
163531
  if (older3(err)) return { ok: false, error: `${h.name} runs a Centralu from before this, so it cannot be asked. Update it there.` };
@@ -163244,7 +163612,7 @@ var LinkedHubs = class {
163244
163612
 
163245
163613
  // packages/agent-host/src/links/reverse-calls.ts
163246
163614
  function reverseCalls(o) {
163247
- return async (machine, method, params, signal) => {
163615
+ return async (machine, method, params, signal, hold) => {
163248
163616
  const apps = o.apps;
163249
163617
  if (apps && method === "hub.apps") {
163250
163618
  const p2 = read(HubMethods["hub.apps"].params.safeParse(params));
@@ -163275,7 +163643,7 @@ function reverseCalls(o) {
163275
163643
  if (method === "hub.projects") return { projects: o.projects() };
163276
163644
  const p = HubMethods["hub.askProject"].params.safeParse(params);
163277
163645
  if (!p.success) throw rpcError("Not an ask this computer reads");
163278
- return o.ask(machine, p.data, signal);
163646
+ return o.ask(machine, p.data, signal, hold);
163279
163647
  };
163280
163648
  }
163281
163649
  function read(parsed) {
@@ -163512,7 +163880,7 @@ function workJobLine(job) {
163512
163880
  // packages/agent-host/src/dev-services/broker-pty.ts
163513
163881
  import { spawn as startProcess } from "node:child_process";
163514
163882
  import { existsSync as existsSync30 } from "node:fs";
163515
- import { createRequire as createRequire4 } from "node:module";
163883
+ import { createRequire as createRequire5 } from "node:module";
163516
163884
  import { createInterface as createInterface2 } from "node:readline";
163517
163885
  import { fileURLToPath as fileURLToPath7 } from "node:url";
163518
163886
  function parseBrokerEvent(line) {
@@ -163688,7 +164056,7 @@ function openInHost(url2) {
163688
164056
  } catch {
163689
164057
  }
163690
164058
  }
163691
- var require4 = createRequire4(import.meta.url);
164059
+ var require4 = createRequire5(import.meta.url);
163692
164060
  function loadNodePty() {
163693
164061
  const loaded = require4("node-pty");
163694
164062
  if (!isPtyModule(loaded)) throw new Error("node-pty did not load as a terminal module");
@@ -163744,7 +164112,7 @@ var handedToken = launch.tokenOnStdin ? await readHandedToken(process.stdin).cat
163744
164112
  console.error(`[agent-host] the launcher did not hand over the token: ${e.message}`);
163745
164113
  process.exit(1);
163746
164114
  }) : launch.token;
163747
- var BUILD = true ? "fe64d79" : "dev";
164115
+ var BUILD = true ? "b4e9fc0" : "dev";
163748
164116
  var { values } = parseArgs({
163749
164117
  options: {
163750
164118
  port: { type: "string", default: "5175" },
@@ -163921,7 +164289,6 @@ var mailPerson = new MailPerson(hostMailbox.service, store.mailbox, mailDelivery
163921
164289
  const s = mgr.sessionInfo(id3);
163922
164290
  return s ? { name: s.name, state: s.state } : void 0;
163923
164291
  }, hostMailbox),
163924
- legacyChain: (threadId) => store.legacyChain(threadId, void 0, 100),
163925
164292
  projectLabel: (projectId) => hostMailbox.reach.projectLabel(projectId),
163926
164293
  untrusted: (projectId) => hostMailbox.reach.untrusted(projectId),
163927
164294
  // A session's turn on a chain, from the turn records while the session is in a turn: the session Mark done and Drop tell, though they stop nothing (C12)
@@ -163955,7 +164322,7 @@ var installByDefault = installsByDefault({
163955
164322
  var { auto: autoUpdateCheck, autoApply: autoApplyUpdates } = updateSwitches(store.settings, { installByDefault });
163956
164323
  var themes = new ThemeFiles(join58(dataRoot(), "themes"), () => events.push({ type: "themes_changed" }));
163957
164324
  await themes.start().catch((e) => console.error(`[themes] the themes folder is unavailable: ${e.message}`));
163958
- var updates = new UpdateService((status) => events.push({ type: "update_status", status }), {
164325
+ var updates = realUpdateService((status) => events.push({ type: "update_status", status }), {
163959
164326
  // A host from source never installs by itself, whatever is stored (#1501 review, `installsByItself`)
163960
164327
  build: BUILD,
163961
164328
  // On by default when nothing has been saved yet. Since the check is read-only and every failure
@@ -164081,8 +164448,9 @@ var links = new Links(linkDepsFor(store, {
164081
164448
  hubMail: true,
164082
164449
  // This hub's apps used by the agents its sessions started on a machine (#1938, §13.5)
164083
164450
  hubApps: true,
164084
- // A machine that took this hub's mail at a connect hears what became of mail that crossed while it was away (#2067 review)
164085
- onOfferAnswered: () => hostMailbox.across.changed(),
164451
+ // A machine that took this hub's mail at a connect hears what became of mail that crossed while it was away (#2067 review); the tasks it says never arrived are settled (#2289)
164452
+ onOfferAnswered: (machineId, lacks) => hostMailbox.across.offerAnswered(machineId, lacks),
164453
+ openTasks: (machineId) => hostMailbox.across.openTasksTo(machineId),
164086
164454
  // When agents compact: this hub's setting governs the machines it links (#1376)
164087
164455
  autoCompact: () => autoCompactOf(mgr.prefs.uiPreferences()),
164088
164456
  // Automatic updates cover the linked machines too (#1508): one on an older release follows this hub's version; none starts while this host drains to stop
@@ -164090,7 +164458,7 @@ var links = new Links(linkDepsFor(store, {
164090
164458
  reverse: reverseCalls({
164091
164459
  allowed: (machineId) => store.machines.linkedMachineAsks(machineId),
164092
164460
  projects: () => mgr.projectsForMachines(),
164093
- ask: (machine, params, signal) => mgr.machineAsks.ask(machine, params, signal),
164461
+ ask: (machine, params, signal, hold) => mgr.machineAsks.ask(machine, params, signal, hold),
164094
164462
  selfName: hubName,
164095
164463
  // Every session on a machine mails every session this hub reaches, and finds them (#2067, docs/plans/linked-mail.md §5 to §8)
164096
164464
  across: hostMailbox.across,