@centralu/host-win32-x64 0.1.0-beta.65 → 0.1.0-beta.67

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.65";
43049
+ var APP_VERSION = "0.1.0-beta.67";
43050
43050
 
43051
43051
  // packages/protocol/src/brand.ts
43052
43052
  var APP_NAME = "Centralu";
@@ -59698,6 +59698,18 @@ var MailThreadView = external_exports.object({
59698
59698
  */
59699
59699
  canReply: external_exports.boolean().optional()
59700
59700
  });
59701
+ var WatchView = external_exports.object({
59702
+ id: external_exports.string(),
59703
+ source: external_exports.enum(["session", "time", "pr", "other"]).catch("other"),
59704
+ what: external_exports.string().default(""),
59705
+ at: external_exports.number().nullable().default(null),
59706
+ everyMinutes: external_exports.number().nullable().default(null),
59707
+ /** When it ends if nothing fires it */
59708
+ until: external_exports.number(),
59709
+ /** The session's own note, at most 300 characters; empty for none */
59710
+ note: external_exports.string().default(""),
59711
+ createdAt: external_exports.number()
59712
+ });
59701
59713
 
59702
59714
  // packages/protocol/src/entities/host-requests.ts
59703
59715
  var HostRequest = external_exports.object({
@@ -60342,6 +60354,11 @@ var NormalizedEvent = external_exports.discriminatedUnion("type", [
60342
60354
  */
60343
60355
  snapshot: external_exports.boolean().optional()
60344
60356
  }),
60357
+ /**
60358
+ * The watches a session keeps changed (#1324, docs/plans/mailbox.md §18.8): one was set, fired, ended or cancelled. A signal, not
60359
+ * the list: the header asks `watches.list` again. Live-only and never stored
60360
+ */
60361
+ external_exports.object({ ...base, type: external_exports.literal("watches_changed") }),
60345
60362
  /**
60346
60363
  * The version of the agent CLI this session's process runs (#297): Claude's init message (`claude_code_version`), the
60347
60364
  * Codex app-server's `initialize` answer (its `userAgent`). Sent once per process. Live-only and never stored, like
@@ -62081,7 +62098,11 @@ var mailParams = {
62081
62098
  "sessionId or threadId, not both"
62082
62099
  ),
62083
62100
  /** The person's answer to "N sessions have mail from while Centralu was off": wake them, or leave them for their next turn (§7.9) */
62084
- "mail.wake": external_exports.object({ wake: external_exports.boolean() })
62101
+ "mail.wake": external_exports.object({ wake: external_exports.boolean() }),
62102
+ /** The watches a session keeps (#1324, docs/plans/mailbox.md §18.8): what its header's badge lists. An older host answers `unknown_method`, and the window shows no badge */
62103
+ "watches.list": external_exports.object({ sessionId: external_exports.string() }),
62104
+ /** The person cancels a watch: it ends, its firing not given yet is taken back, and its session gets one quiet notice saying so */
62105
+ "watches.cancel": external_exports.object({ id: external_exports.string() })
62085
62106
  };
62086
62107
 
62087
62108
  // packages/protocol/src/commands/methods/mail.results.ts
@@ -62097,7 +62118,10 @@ var mailResults = {
62097
62118
  "mail.close": MailThreadRow,
62098
62119
  "mail.held": external_exports.object({ changed: external_exports.number() }),
62099
62120
  "mail.resume": external_exports.object({ ok: external_exports.literal(true) }),
62100
- "mail.wake": external_exports.object({ ok: external_exports.literal(true) })
62121
+ "mail.wake": external_exports.object({ ok: external_exports.literal(true) }),
62122
+ "watches.list": external_exports.object({ watches: external_exports.array(WatchView).default([]) }),
62123
+ /** `cancelled: false`: the watch had ended already (it fired, expired or was cancelled), and nothing changed */
62124
+ "watches.cancel": external_exports.object({ cancelled: external_exports.boolean() })
62101
62125
  };
62102
62126
 
62103
62127
  // packages/protocol/src/commands/methods/mail.ts
@@ -67451,6 +67475,9 @@ var METHOD_RIGHTS = {
67451
67475
  "mail.held": "window",
67452
67476
  "mail.resume": "window",
67453
67477
  "mail.wake": "window",
67478
+ // The person's list and cancel of the watches sessions keep (#1324): an agent cancels its own through the `mail` tool
67479
+ "watches.list": "window",
67480
+ "watches.cancel": "window",
67454
67481
  // Host to host: a hub linked to this host
67455
67482
  "host.activity": "everyday",
67456
67483
  "host.sessions": "link",
@@ -77169,8 +77196,8 @@ var require_formats = /* @__PURE__ */ __commonJSMin(((exports) => {
77169
77196
  if (!matches2) return false;
77170
77197
  const year = +matches2[1];
77171
77198
  const month = +matches2[2];
77172
- const day3 = +matches2[3];
77173
- return month >= 1 && month <= 12 && day3 >= 1 && day3 <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]);
77199
+ const day4 = +matches2[3];
77200
+ return month >= 1 && month <= 12 && day4 >= 1 && day4 <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]);
77174
77201
  }
77175
77202
  function compareDate(d1, d2) {
77176
77203
  if (!(d1 && d2)) return void 0;
@@ -98545,8 +98572,8 @@ var require_formats2 = /* @__PURE__ */ __commonJSMin2(((exports) => {
98545
98572
  if (!matches2) return false;
98546
98573
  const year = +matches2[1];
98547
98574
  const month = +matches2[2];
98548
- const day3 = +matches2[3];
98549
- return month >= 1 && month <= 12 && day3 >= 1 && day3 <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]);
98575
+ const day4 = +matches2[3];
98576
+ return month >= 1 && month <= 12 && day4 >= 1 && day4 <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]);
98550
98577
  }
98551
98578
  function compareDate(d1, d2) {
98552
98579
  if (!(d1 && d2)) return void 0;
@@ -108342,14 +108369,14 @@ var PLAN_LIMIT = /hit your (?:\w+ ){0,2}limit\b|Claude AI usage limit reached/i;
108342
108369
  function planLimitResetAt(message, now) {
108343
108370
  const m = RESET_WORDS.exec(message);
108344
108371
  if (!m) return void 0;
108345
- const [, month, day3, year, hour, minute, half] = m;
108372
+ const [, month, day4, year, hour, minute, half] = m;
108346
108373
  if (Number(hour) < 1 || Number(hour) > 12 || Number(minute ?? 0) > 59) return void 0;
108347
108374
  const h = Number(hour) % 12 + (half?.toLowerCase() === "p" ? 12 : 0);
108348
108375
  const min = Number(minute ?? 0);
108349
- if (month && day3 && year) {
108376
+ if (month && day4 && year) {
108350
108377
  const mi2 = MONTHS.indexOf(month.slice(0, 3).toLowerCase());
108351
108378
  if (mi2 < 0) return void 0;
108352
- return new Date(Number(year), mi2, Number(day3), h, min).getTime();
108379
+ return new Date(Number(year), mi2, Number(day4), h, min).getTime();
108353
108380
  }
108354
108381
  const at2 = new Date(now);
108355
108382
  at2.setHours(h, min, 0, 0);
@@ -108436,6 +108463,7 @@ function interruptionWords(i) {
108436
108463
  }
108437
108464
  }
108438
108465
  var wentWithItsProcess = (i) => i?.reason === "quit" || i?.reason === "shutdown";
108466
+ var heldToContinue = (i) => !!i?.autoContinue;
108439
108467
  var UPDATE_CONTINUE_LINE = "Centralu was updated during this turn, which stopped it; Centralu continued it on the new version.";
108440
108468
  var UPDATE_TASKS_LINE = "Centralu was updated, which stopped background work of this session; Centralu told the agent so it can start again what it needs.";
108441
108469
 
@@ -109751,7 +109779,9 @@ var REFUSALS = [
109751
109779
  "assistant_asks",
109752
109780
  "removed",
109753
109781
  "untrusted_project",
109754
- "answered"
109782
+ "answered",
109783
+ // a pull request watch where gh is not installed or not signed in (§18.3)
109784
+ "unavailable"
109755
109785
  ];
109756
109786
  function refuse4(reason, message, more = {}) {
109757
109787
  return rpcError(message, "refused", { retryable: false, data: { reason, ...more } });
@@ -109814,6 +109844,18 @@ var REMINDER = {
109814
109844
  /** After delivery a needsReply row is released: the one 2-hour constant, which also bounds a cover (D23, D25) */
109815
109845
  unansweredAfterMs: 2 * HOUR_MS
109816
109846
  };
109847
+ var WATCH = {
109848
+ perSession: 20,
109849
+ everyAtLeastMs: 10 * MINUTE_MS,
109850
+ aheadAtMostMs: 7 * 24 * HOUR_MS,
109851
+ /** How long a session or `every` watch lasts; setting it again extends it */
109852
+ lastsMs: 24 * HOUR_MS,
109853
+ noteChars: 300,
109854
+ /** How often the host asks gh for the pull requests watched (§18.3, owner 2026-11-13): once a minute, one call per pull request */
109855
+ prPollMs: MINUTE_MS,
109856
+ /** Firings to one session in an hour past which the person is warned once per clock hour */
109857
+ warnWakesPerHour: 6
109858
+ };
109817
109859
  var REFUSAL_TEXT = {
109818
109860
  gone: (address) => `${address} is gone: it is in the session archive or deleted.`,
109819
109861
  no_mailbox: () => "that session cannot read mail: only an ordinary session in a project, or the Assistant, has the mail tool",
@@ -109835,6 +109877,7 @@ var WARNING_TEXT = {
109835
109877
  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.`,
109836
109878
  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.`,
109837
109879
  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.`,
109880
+ 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.`,
109838
109881
  /** The three guards that refuse rather than warn (#1684, #2035): the person hears of the first refusal of each kind a clock hour */
109839
109882
  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.`,
109840
109883
  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.`,
@@ -109874,7 +109917,7 @@ function pickWork(candidates, now) {
109874
109917
  return best;
109875
109918
  }
109876
109919
  function flowsDownTo(f) {
109877
- if (f.fromPerson) return true;
109920
+ if (f.fromPerson || f.watch) return true;
109878
109921
  if (!f.fromSession || f.toAssistant) return false;
109879
109922
  return f.kind === "task" || f.kind === "message" && f.fromParent;
109880
109923
  }
@@ -109910,8 +109953,9 @@ var MailDelivery = class {
109910
109953
  });
109911
109954
  this.heartbeat = opts.heartbeat;
109912
109955
  this.turns = opts.turns;
109913
- this.o = { ...DEFAULTS2, ...Object.fromEntries(Object.entries(opts).filter(([k2]) => k2 !== "now" && k2 !== "schedule" && k2 !== "heartbeat" && k2 !== "turns" && k2 !== "across")) };
109956
+ this.o = { ...DEFAULTS2, ...Object.fromEntries(Object.entries(opts).filter(([k2]) => k2 !== "now" && k2 !== "schedule" && k2 !== "heartbeat" && k2 !== "turns" && k2 !== "across" && k2 !== "watches")) };
109914
109957
  this.across = opts.across;
109958
+ this.watches = opts.watches;
109915
109959
  }
109916
109960
  service;
109917
109961
  records;
@@ -109920,6 +109964,7 @@ var MailDelivery = class {
109920
109964
  schedule;
109921
109965
  o;
109922
109966
  across;
109967
+ watches;
109923
109968
  heartbeat;
109924
109969
  turns;
109925
109970
  /** One delivery in flight per mailbox; a change that comes meanwhile is looked at when it ends */
@@ -109979,11 +110024,13 @@ var MailDelivery = class {
109979
110024
  });
109980
110025
  };
109981
110026
  loop();
110027
+ this.watches?.start(this.schedule);
109982
110028
  void this.sweep();
109983
110029
  }
109984
110030
  stop() {
109985
110031
  if (!this.crowd) this.heartbeat?.write(this.now());
109986
110032
  this.running = false;
110033
+ this.watches?.stop();
109987
110034
  this.stopListening?.();
109988
110035
  this.stopSweep?.();
109989
110036
  for (const cancel of this.timers.values()) cancel();
@@ -110018,6 +110065,11 @@ var MailDelivery = class {
110018
110065
  this.catchUpPending = true;
110019
110066
  }
110020
110067
  this.lastSweepAt = now;
110068
+ try {
110069
+ this.watches?.due(now);
110070
+ } catch (e) {
110071
+ console.error(`[mail] the watches' sweep failed; it runs again at the next one: ${errorMessage(e)}`);
110072
+ }
110021
110073
  this.moveOnWorkOfGoneSessions();
110022
110074
  const recipients = this.records.dueRecipients().filter(this.here);
110023
110075
  if (this.catchUpPending) {
@@ -111172,19 +111224,13 @@ var MAIL_TOOLS = [
111172
111224
  name: "mail",
111173
111225
  description: `Work and messages with sessions, apps and the person; cite=true (to "assistant") only when the person's last message here asked for it. Ask the person with kind "question". In a report, say what each claim was checked against, and what was not.`,
111174
111226
  schema: external_exports.object({
111175
- action: external_exports.enum(["inbox", "read", "handled", "send", "reply", "update", "close", "find"]),
111227
+ action: external_exports.enum(["inbox", "read", "handled", "send", "reply", "close", "find", "watch"]),
111176
111228
  thread: external_exports.string().optional(),
111177
- to: external_exports.string().optional().describe('"parent": the session that started you, for a question; "assistant": the Centralu Assistant, for what only it can decide; "person": the human; or a session by name or id. For find: words (name, project, machine, role) to search every computer'),
111229
+ to: external_exports.string().optional().describe('"parent": the session that started you, for a question; "assistant": the Assistant, for what only it can decide; "person": the human; or a session by name or id. For find: words (name, project, machine, role) to search every computer. For watch: a session, "in 30m", "at 16:30", "every 30m" or PR "#123"'),
111178
111230
  kind: external_exports.string().optional(),
111179
111231
  subject: external_exports.string().optional(),
111180
111232
  text: external_exports.string().optional(),
111181
- state: external_exports.string().optional(),
111182
- outcome: external_exports.string().optional(),
111183
- next: external_exports.string().optional(),
111184
- blocker: external_exports.string().optional(),
111185
- unblock: external_exports.number().int().optional(),
111186
111233
  urgent: external_exports.boolean().optional(),
111187
- follows: external_exports.array(external_exports.string()).optional(),
111188
111234
  cite: external_exports.boolean().optional(),
111189
111235
  choices: external_exports.array(external_exports.string()).optional(),
111190
111236
  // A fork instead of a mail task, for a busy session the caller started (#1948); the mailed answer names it
@@ -111193,7 +111239,7 @@ var MAIL_TOOLS = [
111193
111239
  deferred: true
111194
111240
  }
111195
111241
  ];
111196
- var MAIL_BUDGET_CHARS = 1355;
111242
+ var MAIL_BUDGET_CHARS = 1175;
111197
111243
  var COMPACT_TOOLS = [
111198
111244
  {
111199
111245
  name: "compact_self",
@@ -117224,13 +117270,13 @@ var ChildReports = class {
117224
117270
  /**
117225
117271
  * The session's own background work changed, or this host started: once that work is over and no turn runs, the turn its end may start (Claude starts
117226
117272
  * one within a second) answers; if none starts within `OWN_WORK_SETTLE_MS`, its last response answers the tasks no stop released (#721), the
117227
- * person's own work's too. Only for a session with something to answer
117273
+ * person's own work's too, and a watch on it hears its turn ended (docs/plans/mailbox.md §18.3). Only for a session with something to answer or tell
117228
117274
  */
117229
117275
  settleAtRest(sessionId) {
117230
117276
  this.stopSettling(sessionId);
117231
117277
  const m = this.host.meta.get(sessionId);
117232
117278
  if (this.host.disposing || !m || inTurn(m.state) || this.ownTasksRunning(sessionId).length > 0) return;
117233
- if (this.host.children.openTasks(sessionId, "to").length === 0) return;
117279
+ if (this.host.children.openTasks(sessionId, "to").length === 0 && !this.host.mailWatchedAtRest(sessionId)) return;
117234
117280
  const timer = setTimeout(() => {
117235
117281
  this.settles.delete(sessionId);
117236
117282
  const now = this.host.meta.get(sessionId);
@@ -121578,7 +121624,7 @@ ${note}` : note;
121578
121624
  // packages/agent-host/src/mail/ids.ts
121579
121625
  import { randomBytes as randomBytes7 } from "node:crypto";
121580
121626
  var CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
121581
- var ID_RE = /^([a-z0-9][a-z0-9-]*)\.(t|m)_([0-9A-HJKMNP-TV-Z]{26})$/;
121627
+ var ID_RE = /^([a-z0-9][a-z0-9-]*)\.(t|m|w)_([0-9A-HJKMNP-TV-Z]{26})$/;
121582
121628
  var UlidMaker = class {
121583
121629
  constructor(random = randomBytes7) {
121584
121630
  this.random = random;
@@ -121628,10 +121674,11 @@ function encodeTime(time3) {
121628
121674
  return out;
121629
121675
  }
121630
121676
  var messageIdOf = (host, ulid3) => `${host}.m_${ulid3}`;
121677
+ var watchIdOf = (host, ulid3) => `${host}.w_${ulid3}`;
121631
121678
  function parseMailId(id3) {
121632
121679
  const m = ID_RE.exec(id3);
121633
121680
  const [, host, kind, ulid3] = m ?? [];
121634
- return host !== void 0 && ulid3 !== void 0 ? { host, kind: kind === "t" ? "thread" : "message", ulid: ulid3 } : null;
121681
+ return host !== void 0 && ulid3 !== void 0 ? { host, kind: kind === "t" ? "thread" : kind === "w" ? "watch" : "message", ulid: ulid3 } : null;
121635
121682
  }
121636
121683
 
121637
121684
  // packages/agent-host/src/dev-services/store/mail-facts.ts
@@ -121658,6 +121705,13 @@ var MailFacts = external_exports.looseObject({
121658
121705
  pairTurns: external_exports.object({ sessions: external_exports.array(external_exports.string()), turns: external_exports.number() }).optional(),
121659
121706
  /** On Centralu's warning to the person (#2024): the session that went through more compaction cycles (`compact_self` with `then`) in the hour than it warns at, and how many */
121660
121707
  compactCycles: external_exports.object({ session: external_exports.string(), count: external_exports.number() }).optional(),
121708
+ /** On Centralu's warning to the person (#1324): the session whose watches woke it more times in the hour than it warns at, and how many */
121709
+ watchWakes: external_exports.object({ session: external_exports.string(), count: external_exports.number() }).optional(),
121710
+ /**
121711
+ * On a watch's notice to the session that set it (docs/plans/mailbox.md §18.5): the watch, what it waits for, what changed (`turn_ended`, `asked`,
121712
+ * `stopped`, `gone`, a time's slot `due`, or its end: `expired`, `cancelled`) and whether the host fired it late
121713
+ */
121714
+ watch: external_exports.object({ id: external_exports.string(), source: external_exports.string(), change: external_exports.string(), late: external_exports.boolean().optional() }).optional(),
121661
121715
  /** On Centralu's warning to the person (#1684): a send a guard refused (`repeat`, `rate_limited`, `ask_rate`), and whose */
121662
121716
  guardRefused: external_exports.object({ sender: external_exports.string(), reason: external_exports.string() }).optional(),
121663
121717
  answerHeld: external_exports.object({ question: external_exports.string(), answer: external_exports.string() }).optional(),
@@ -122352,11 +122406,12 @@ var MailboxRecords = class {
122352
122406
  AND EXISTS (SELECT 1 FROM json_each(mail.facts, '$.releasedTo') WHERE value = @from)`
122353
122407
  ).run({ messageId, from, to });
122354
122408
  }
122355
- /** The trash was emptied of `address`: its rows go, and each message left with no row but the person's own. Returns the rows deleted */
122409
+ /** The trash was emptied of `address`: its rows and watches go, and each message left with no row but the person's own. Returns the rows deleted */
122356
122410
  purgeParty(address) {
122357
122411
  return this.transaction(() => {
122358
122412
  const ids = this.db.prepare(`SELECT message_id AS id FROM mail_recipients WHERE recipient = ?`).all(address).map((r) => r.id);
122359
122413
  const n = this.db.prepare(`DELETE FROM mail_recipients WHERE recipient = ?`).run(address).changes;
122414
+ this.deleteWatchesOf(address);
122360
122415
  this.dropOrphans(ids, { keepPerson: true });
122361
122416
  return n;
122362
122417
  });
@@ -122388,8 +122443,10 @@ var MailboxRecords = class {
122388
122443
  return this.db.prepare(`DELETE FROM mail WHERE id IN (SELECT value FROM json_each(?))`).run(ids).changes;
122389
122444
  });
122390
122445
  messages2 += n;
122391
- if (n === 0) return { messages: messages2 };
122446
+ if (n === 0) break;
122392
122447
  }
122448
+ this.db.prepare(`DELETE FROM mail_watches WHERE state <> 'active' AND ended_at <= ?`).run(now - l.readNoticeMs);
122449
+ return { messages: messages2 };
122393
122450
  }
122394
122451
  // ── Turns (`mail_turns`, read and written by `MailTurns`, M3a) ──
122395
122452
  /**
@@ -122408,10 +122465,55 @@ var MailboxRecords = class {
122408
122465
  const row = this.db.prepare(`SELECT * FROM mail_turns WHERE session_id = ? AND turn_seq = ?`).get(sessionId, turnSeq);
122409
122466
  return row ? toTurnRecord(row) : null;
122410
122467
  }
122411
- /** Centralu's notices of cards in `session` (an address, `facts.card.session`; every session's when null) that no delivery has begun to give (mailbox.md §10.6.4) */
122412
- undeliveredCardNotices(session2) {
122413
- const card = `json_extract(m.facts, '$.card.session')`;
122414
- return this.withMessages(this.rows(`m.sender = 'centralu' AND m.kind = 'notice' AND r.delivered_at IS NULL AND r.attempt_at IS NULL AND json_valid(m.facts) AND ${card} = COALESCE(?, ${card}) ORDER BY m.created_at, m.id`, session2));
122468
+ /**
122469
+ * Centralu's notices that no delivery has begun to give whose fact `fact` is `value` (any value when null): a card's in a session (`$.card.session`,
122470
+ * mailbox.md §10.6.4) or a watch's (`$.watch.id`, §18.5), taken back once the card or the watch no longer stands
122471
+ */
122472
+ undeliveredNotices(fact, value) {
122473
+ const of2 = `json_extract(m.facts, '${fact}')`;
122474
+ return this.withMessages(this.rows(`m.sender = 'centralu' AND m.kind = 'notice' AND r.delivered_at IS NULL AND r.attempt_at IS NULL AND json_valid(m.facts) AND ${of2} = COALESCE(?, ${of2}) ORDER BY m.created_at, m.id`, value));
122475
+ }
122476
+ /** The number of the session's last turn that ended (a canceled delivery is no turn), 0 for none: a session watch's baseline (§18.3) */
122477
+ lastEndedTurn(sessionId) {
122478
+ return this.count(`SELECT COALESCE(MAX(turn_seq), 0) AS n FROM mail_turns WHERE session_id = ? AND ended_at IS NOT NULL AND COALESCE(outcome, '') <> 'canceled'`, sessionId);
122479
+ }
122480
+ // ── Watches (`mail_watches`, read and written by `Watches`, docs/plans/mailbox.md §18.4) ──
122481
+ /** Writes the watch as given, a new one or one changed */
122482
+ saveWatch(w) {
122483
+ this.db.prepare(
122484
+ `INSERT INTO mail_watches (id, owner, source, target, spec, note, state, last_key, fired_count, created_at, expires_at, next_at, ended_at, ended_by)
122485
+ VALUES (@id, @owner, @source, @target, @spec, @note, @state, @lastKey, @firedCount, @createdAt, @expiresAt, @nextAt, @endedAt, @endedBy)
122486
+ ON CONFLICT(id) DO UPDATE SET owner = excluded.owner, target = excluded.target, spec = excluded.spec, note = excluded.note, state = excluded.state,
122487
+ last_key = excluded.last_key, fired_count = excluded.fired_count, expires_at = excluded.expires_at, next_at = excluded.next_at,
122488
+ ended_at = excluded.ended_at, ended_by = excluded.ended_by`
122489
+ ).run(w);
122490
+ }
122491
+ watch(id3) {
122492
+ return this.watchRows(`id = @id`, { id: id3 })[0];
122493
+ }
122494
+ /** The active watches, of an owner, on a target, or due by a time, oldest first */
122495
+ activeWatches(by = {}) {
122496
+ return this.watchRows(
122497
+ `state = 'active' AND (@owner IS NULL OR owner = @owner) AND (@target IS NULL OR target = @target) AND (@due IS NULL OR next_at <= @due)`,
122498
+ { owner: by.owner ?? null, target: by.target ?? null, due: by.dueBy ?? null }
122499
+ );
122500
+ }
122501
+ /** The owner's watches go with it (a session deleted) */
122502
+ deleteWatchesOf(owner) {
122503
+ return this.db.prepare(`DELETE FROM mail_watches WHERE owner = ?`).run(owner).changes;
122504
+ }
122505
+ /** The watch firings `owner` was sent since `since`, its quiet notices apart: what the person's warning counts (§18.7) */
122506
+ watchFiringsSince(owner, since) {
122507
+ return this.count(
122508
+ `SELECT COUNT(*) AS n FROM mail m JOIN mail_recipients r ON r.message_id = m.id
122509
+ WHERE m.sender = 'centralu' AND r.recipient = ? AND m.created_at >= ? AND json_valid(m.facts) AND json_type(m.facts, '$.watch') IS NOT NULL
122510
+ AND COALESCE(json_extract(m.facts, '$.quiet'), 0) = 0`,
122511
+ owner,
122512
+ since
122513
+ );
122514
+ }
122515
+ watchRows(where2, args) {
122516
+ return this.db.prepare(`SELECT * FROM mail_watches WHERE ${where2} ORDER BY created_at, id`).all(args).map((r) => ({ id: r.id, owner: r.owner, source: r.source, target: r.target, spec: r.spec, note: r.note, state: r.state, lastKey: r.last_key, firedCount: r.fired_count, createdAt: r.created_at, expiresAt: r.expires_at, nextAt: r.next_at, endedAt: r.ended_at, endedBy: r.ended_by }));
122415
122517
  }
122416
122518
  nextTurnSeq(sessionId) {
122417
122519
  return this.count(`SELECT COALESCE(MAX(turn_seq), 0) + 1 AS n FROM mail_turns WHERE session_id = ?`, sessionId);
@@ -122636,7 +122738,8 @@ function mailCalls(version2, form) {
122636
122738
  answer: (id3) => call2(version2 === 2 ? "send" : "reply", { [target]: id3, text: "\u2026" }),
122637
122739
  done: (id3) => call2(version2 === 2 ? "done" : "handled", { [target]: id3 }),
122638
122740
  inbox: () => call2("inbox"),
122639
- sessions: () => call2("sessions")
122741
+ sessions: () => call2("sessions"),
122742
+ close: (id3) => call2("close", { thread: id3 })
122640
122743
  };
122641
122744
  }
122642
122745
  var PLAIN_MESSAGE_CALLS = mailCalls(2, "plain");
@@ -123802,7 +123905,7 @@ var SessionEvents = class {
123802
123905
  const stopWhy = workEnded && e.sessionId && !this.host.restartPolicy.continuingTurns.has(e.sessionId) ? stopOf(e, nowInterrupted) : null;
123803
123906
  if (stopWhy && e.sessionId) {
123804
123907
  this.host.reports.turnStopped(e.sessionId);
123805
- const held3 = !!nowInterrupted?.autoContinue;
123908
+ const held3 = heldToContinue(nowInterrupted);
123806
123909
  this.host.mailStopped(e.sessionId, stopWhy, { ...this.stopTold(e.sessionId, waited, delegation?.callerId), ...held3 ? { held: held3 } : {} });
123807
123910
  } else if (workEnded && e.sessionId) {
123808
123911
  this.host.mailRequestTurnEnded(e.sessionId);
@@ -124212,6 +124315,15 @@ var MailSessionsView = class {
124212
124315
  console.error(`[mail] ${sessionId.slice(0, 8)}: its last response could not answer its tasks (${errorMessage(e)})`);
124213
124316
  }
124214
124317
  }
124318
+ /** Whether a watch waits for the session's rest (`MailHooks.watchedAtRest`). Never throws */
124319
+ mailWatchedAtRest(sessionId) {
124320
+ try {
124321
+ return this.hooks?.watchedAtRest?.(sessionId) === true;
124322
+ } catch (e) {
124323
+ console.error(`[mail] ${sessionId.slice(0, 8)}: its watches could not be read (${errorMessage(e)})`);
124324
+ return false;
124325
+ }
124326
+ }
124215
124327
  /** The Assistant's turn ended as a turn does (`MailHooks.requestTurnEnded`). Never throws */
124216
124328
  mailRequestTurnEnded(assistantId) {
124217
124329
  try {
@@ -135477,6 +135589,7 @@ function launchedThreads(n) {
135477
135589
  if (str(item.type) !== "collabAgentToolCall" || str(item.tool) !== "spawnAgent" || !codexItemOk(item)) return [];
135478
135590
  return (Array.isArray(item.receiverThreadIds) ? item.receiverThreadIds : []).filter((t) => typeof t === "string" && t !== "");
135479
135591
  }
135592
+ var GOAL_ID = "goal";
135480
135593
  var CodexChildTracker = class {
135481
135594
  constructor(sessionId) {
135482
135595
  this.sessionId = sessionId;
@@ -135498,6 +135611,12 @@ var CodexChildTracker = class {
135498
135611
  held = /* @__PURE__ */ new Map();
135499
135612
  /** Children whose turn already ended, so a launch result arriving after that is not held (the latest few) */
135500
135613
  done = [];
135614
+ /** The session's own commands started and not completed, by item id; `kept` once a turn ended with it running (#2027) */
135615
+ commands = /* @__PURE__ */ new Map();
135616
+ /** The objective of the thread's goal while it is active (#2027) */
135617
+ goal = null;
135618
+ /** Whether the active goal is left idle by a stopped turn: not listed until Codex says more of it or a turn starts */
135619
+ goalStopped = false;
135501
135620
  /** A launch call's result, held while the children it started run; false when it goes out now (none still runs) */
135502
135621
  hold(result, threads) {
135503
135622
  const running2 = threads.filter((t) => !this.done.includes(t));
@@ -135553,13 +135672,54 @@ var CodexChildTracker = class {
135553
135672
  }
135554
135673
  return [];
135555
135674
  }
135675
+ /** A notification of the session's own thread: the commands and the goal it keeps past a turn (#2027) */
135676
+ own(n) {
135677
+ const p = asObj(n.params);
135678
+ if (n.method === "item/started" || n.method === "item/completed") {
135679
+ const item = asObj(p.item);
135680
+ const id3 = str(item.id);
135681
+ if (str(item.type) !== "commandExecution" || !id3) return [];
135682
+ if (n.method === "item/started") {
135683
+ if (!this.commands.has(id3)) this.commands.set(id3, { command: str(item.command), kept: false });
135684
+ return [];
135685
+ }
135686
+ const c = this.commands.get(id3);
135687
+ this.commands.delete(id3);
135688
+ return c?.kept ? this.changed([{ ...this.keptTask(id3, c.command), status: codexItemOk(item) ? "completed" : "failed" }]) : [];
135689
+ }
135690
+ if (n.method === "turn/started" && this.goalStopped) {
135691
+ this.goalStopped = false;
135692
+ return this.changed();
135693
+ }
135694
+ if (n.method === "turn/completed") {
135695
+ const open6 = [...this.commands.values()].filter((c) => !c.kept);
135696
+ for (const c of open6) c.kept = true;
135697
+ const stopped = this.goal !== null && !this.goalStopped && str(asObj(p.turn).status) === "interrupted";
135698
+ if (stopped) this.goalStopped = true;
135699
+ return open6.length > 0 || stopped ? this.changed() : [];
135700
+ }
135701
+ if (n.method === "thread/goal/updated") return this.goalIs(goalFromCodex(asObj(p.goal)));
135702
+ if (n.method === "thread/goal/cleared") return this.goalIs(null);
135703
+ return [];
135704
+ }
135705
+ /** The thread's goal as read: a notification, or `thread/goal/get` on resume */
135706
+ goalIs(g5) {
135707
+ const objective = g5?.status === "active" ? g5.objective : null;
135708
+ if (objective === this.goal && !this.goalStopped) return [];
135709
+ this.goal = objective;
135710
+ this.goalStopped = false;
135711
+ return this.changed();
135712
+ }
135556
135713
  /** The turn to interrupt to stop this child, if one is running. */
135557
135714
  turnOf(thread) {
135558
135715
  return this.threads.get(thread)?.turnId ?? null;
135559
135716
  }
135560
135717
  /** The app-server went away and its child threads with it. */
135561
135718
  release(why2) {
135562
- const live2 = this.live();
135719
+ const live2 = this.live().filter((t) => t.id !== GOAL_ID);
135720
+ this.commands.clear();
135721
+ this.goal = null;
135722
+ this.goalStopped = false;
135563
135723
  for (const t of this.threads.values()) {
135564
135724
  t.active = false;
135565
135725
  t.turnId = null;
@@ -135567,7 +135727,7 @@ var CodexChildTracker = class {
135567
135727
  const held3 = [...this.held.keys()].map((callId) => ({ type: "tool_result", sessionId: this.sessionId, callId, ok: false, summary: why2 }));
135568
135728
  const carded = new Set(this.held.keys());
135569
135729
  this.held.clear();
135570
- if (live2.length === 0) return held3;
135730
+ if (live2.length === 0) return [...this.changed(), ...held3];
135571
135731
  return [...this.changed(live2.map((task) => ({ ...task, status: "stopped", summary: why2 })), carded), ...held3];
135572
135732
  }
135573
135733
  ended(thread, status, summary) {
@@ -135588,12 +135748,17 @@ var CodexChildTracker = class {
135588
135748
  status: "running"
135589
135749
  };
135590
135750
  }
135751
+ keptTask(id3, command) {
135752
+ return { id: id3, kind: "shell", description: firstLine2(command.trim()) || "Command", parentCallId: id3, stopsWithTurn: false, stoppable: false, status: "running" };
135753
+ }
135591
135754
  live() {
135592
135755
  const out = [];
135593
135756
  for (const [thread, t] of this.threads) {
135594
135757
  const task = t.active ? this.task(thread) : null;
135595
135758
  if (task) out.push(task);
135596
135759
  }
135760
+ for (const [id3, c] of this.commands) if (c.kept) out.push(this.keptTask(id3, c.command));
135761
+ if (this.goal !== null && !this.goalStopped) out.push({ id: GOAL_ID, kind: "other", description: `Goal: ${firstLine2(this.goal.trim())}`, stopsWithTurn: false, stoppable: false, status: "running" });
135597
135762
  return out;
135598
135763
  }
135599
135764
  /** The event when the live set or an ending moved; nothing when neither did. */
@@ -136479,8 +136644,8 @@ var CodexSession = class {
136479
136644
  * way to find the actual cause.
136480
136645
  */
136481
136646
  /*
136482
- * The ledger says whether it went with work in flight (a crash) or idle (asleep: a Codex session keeps its app-server
136483
- * while idle, #568, so a shutdown or a kill lands on sessions doing nothing, #1397). What it printed last is the reason
136647
+ * The ledger says whether it went with work in flight (a crash) or idle (asleep: an idle Codex session keeps its
136648
+ * app-server until it is put to sleep, #568, #2027, so a shutdown or a kill lands on sessions doing nothing, #1397). What it printed last is the reason
136484
136649
  * a person can act on: a lock, a bad config line, a panic
136485
136650
  */
136486
136651
  onExit: (code2, expected) => this.ledger.exited(expected, withStderrTail(`codex app-server exited (code ${code2 ?? "null"})`, this.client))
@@ -136627,6 +136792,7 @@ var CodexSession = class {
136627
136792
  void this.client.request("thread/goal/get", { threadId: this.threadId }).then((r) => {
136628
136793
  const g5 = r.goal ? goalFromCodex(r.goal) : null;
136629
136794
  if (g5) this.emit({ type: "goal", sessionId: this.sessionId, goal: g5 });
136795
+ for (const e of this.childThreads.children.goalIs(g5)) this.emit(e);
136630
136796
  }).catch(() => {
136631
136797
  });
136632
136798
  } else {
@@ -136696,6 +136862,7 @@ var CodexSession = class {
136696
136862
  return;
136697
136863
  }
136698
136864
  if (n.method === "mcpServer/startupStatus/updated" && !this.threadServers.firstMcpFailure(n.params)) return;
136865
+ for (const e of this.childThreads.children.own(n)) this.emit(e);
136699
136866
  this.emitNotification(n);
136700
136867
  this.childThreads.noteSpawn(n);
136701
136868
  this.childThreads.noteTurnEnd(n);
@@ -137264,7 +137431,7 @@ var CodexAdapter = class {
137264
137431
  // translates). This is a guarantee that every record change while we hold the handle is ours,
137265
137432
  // and the manager marks a catch-up skip on top of it (the basis for skipping a 48.6MB/8-second thread/read).
137266
137433
  exclusiveWriter: true,
137267
- // Child agents, from their threads' status and turns (#290, CodexChildTracker)
137434
+ // Child agents, from their threads' status and turns (#290), and a command or an active goal kept past a turn (#2027): CodexChildTracker
137268
137435
  backgroundTasks: true,
137269
137436
  toolDeferral: false,
137270
137437
  instructionChannel: "developer",
@@ -137275,11 +137442,12 @@ var CodexAdapter = class {
137275
137442
  // 0.160 TurnStartParams: turn/start steers an already-active regular turn; compact/review input is queued.
137276
137443
  midTurnInput: true,
137277
137444
  /*
137278
- * Not put to sleep (#568). Waking a large thread measured 7-13 s (`thread/resume` scales with the rollout, ~13.5 s for
137279
- * 550 MB), and its cache on resume is unmeasured. The memory is better won by one shared app-server per account
137280
- * (#561 E3: 379 MB vs 2,584 MB for ten threads), decided separately.
137445
+ * Put to sleep like Claude (#568, #2027; docs/plans/sleep-every-tool.md §3a, measured 2026-11-13 on codex-cli 0.160.0,
137446
+ * gpt-5.6-luna): the woken turn read the cache as the live one did (.99 against .91-.97 live, at 2 and 16 min, rollouts
137447
+ * of 1, 47 and 513 MB), and the wake added 3.4-4.8 s, nearly all of it the new process's first model request: a new
137448
+ * app-server was ready in 30-70 ms and `thread/resume` without turns took 33-73 ms even for 513 MB.
137281
137449
  */
137282
- sleep: false
137450
+ sleep: true
137283
137451
  };
137284
137452
  launchSettingsFingerprint(settings) {
137285
137453
  return JSON.stringify({ v: 2, cwd: settings.cwd, permission: launchPreset(settings.permissionPreset), sandbox: permissionOptionsFor2(settings.permissionPreset).sandbox, trusted: !!settings.projectTrusted, noSettings: !!settings.noSettingFiles });
@@ -137421,8 +137589,8 @@ function newestVersion(names) {
137421
137589
  const key = (n) => {
137422
137590
  const m = VERSION.exec(n);
137423
137591
  if (!m) return null;
137424
- const pad = (s) => (s ?? "00").padStart(2, "0");
137425
- return `${m[1]}${pad(m[2])}${pad(m[3])}${pad(m[4])}${pad(m[5])}${pad(m[6])}`;
137592
+ const pad2 = (s) => (s ?? "00").padStart(2, "0");
137593
+ return `${m[1]}${pad2(m[2])}${pad2(m[3])}${pad2(m[4])}${pad2(m[5])}${pad2(m[6])}`;
137426
137594
  };
137427
137595
  const dated = names.flatMap((n) => {
137428
137596
  const k2 = key(n);
@@ -141069,7 +141237,7 @@ function kindOf3(m, threadOrigin) {
141069
141237
  if (m.kind === "assign" && (threadOrigin === "person" || DELEGATION_ORIGINS.some((o) => o === threadOrigin))) return { kind: "task", needsReply: false };
141070
141238
  return { kind: kinds[m.kind], needsReply: m.kind === "question" };
141071
141239
  }
141072
- function movePendingThreadMail(db, now, projectOf) {
141240
+ function movePendingThreadMail(db, now, projectOf, holdsNow) {
141073
141241
  return db.transaction(() => {
141074
141242
  const pending = db.prepare(
141075
141243
  `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,
@@ -141106,6 +141274,7 @@ function movePendingThreadMail(db, now, projectOf) {
141106
141274
  for (const p of pending) {
141107
141275
  const m = toMessage(p);
141108
141276
  const sender = parseAddress(m.sender);
141277
+ const senderProject = sender?.kind === "session" ? projectOf(m.sender) ?? (m.sender === p.t_owner ? p.t_project_id : null) : null;
141109
141278
  const target = m.replyTo === null ? void 0 : rootOf.get(m.replyTo);
141110
141279
  const { kind, needsReply } = kindOf3(m, p.t_origin);
141111
141280
  const facts = {
@@ -141119,7 +141288,7 @@ function movePendingThreadMail(db, now, projectOf) {
141119
141288
  messages2 += insertMail.run({
141120
141289
  id: m.id,
141121
141290
  sender: m.sender,
141122
- senderProject: sender?.kind === "session" ? projectOf(m.sender) ?? (m.sender === p.t_owner ? p.t_project_id : null) : null,
141291
+ senderProject,
141123
141292
  kind,
141124
141293
  needsReply: needsReply ? 1 : 0,
141125
141294
  replyTo: target ? m.replyTo : null,
@@ -141131,18 +141300,21 @@ function movePendingThreadMail(db, now, projectOf) {
141131
141300
  legacyThread: m.threadId,
141132
141301
  createdAt: m.createdAt
141133
141302
  }).changes;
141303
+ const via = p.r_recipient === p.t_assignee && to?.assistant === 1 && p.t_owner !== p.r_recipient ? ROLE_VIA : null;
141304
+ const carried = p.r_held !== null && CARRIED_HOLDS.has(p.r_held) ? p.r_held : null;
141305
+ const ended2 = carried === "budget" || carried === "policy" && !holdsNow({ kind, senderProject }, p.r_recipient);
141134
141306
  recipients += insertRow.run({
141135
141307
  messageId: m.id,
141136
141308
  recipient: p.r_recipient,
141137
- via: p.r_recipient === p.t_assignee && to?.assistant === 1 && p.t_owner !== p.r_recipient ? ROLE_VIA : null,
141309
+ via,
141138
141310
  settled: kind === "task" && to?.trashed === 1 ? "gone" : "legacy",
141139
141311
  dueAt: p.r_due_at,
141140
- attemptAt: p.r_attempt_at,
141312
+ attemptAt: ended2 ? null : p.r_attempt_at,
141141
141313
  deliveredAt: p.r_delivered_at,
141142
141314
  readAt: p.r_read_at,
141143
- held: p.r_held !== null && CARRIED_HOLDS.has(p.r_held) ? p.r_held : null,
141144
- attempts: p.r_attempts,
141145
- lastError: p.r_last_error,
141315
+ held: ended2 ? "dismissed" : carried,
141316
+ attempts: ended2 ? 0 : p.r_attempts,
141317
+ lastError: ended2 ? null : p.r_last_error,
141146
141318
  now
141147
141319
  }).changes;
141148
141320
  handled.run({ now, id: m.id, recipient: p.r_recipient });
@@ -143592,6 +143764,88 @@ var StepsV65 = class extends MigrationRange {
143592
143764
  run: () => {
143593
143765
  this.addColumn("mail", "subject", "TEXT");
143594
143766
  }
143767
+ },
143768
+ {
143769
+ to: 72,
143770
+ breaksOlderReaders: false,
143771
+ /**
143772
+ * The holds of an earlier build, ended (#2243). The mail token guard (`budget`) went with D32 (#2014, beta.49) and the `auto` receiver's
143773
+ * first-contact hold (`holdsInbound`) with D10, but the rows an earlier build held kept their hold when the v65 move carried them (settled
143774
+ * `legacy`), so the Inbox's Waiting listed "Paused: this session has used its share of turns started by mail" and "Held: this session runs
143775
+ * without asking" weeks after nothing could write such a hold.
143776
+ *
143777
+ * **One meaning: a hold from an earlier build stays only if today's gate would hold the mail now.** `budget` is never set by today's code, so every
143778
+ * 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
143779
+ * missing project row is untrusted) to a session of another project, which is how a genuine untrusted asker's request is still held. The
143780
+ * 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
143781
+ * 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
143782
+ * 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):
143783
+ * `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`.
143784
+ *
143785
+ * **This is a frozen copy of `holdFor`'s conditions, on purpose.** A step runs once on every store and must not call code that may change later;
143786
+ * if `holdFor` changes, this step does not. It mirrors: `m.kind === 'message'`; `leaves(senderProject, recipientProject)` = the sender's project is
143787
+ * not null and untrusted (`projects.trusted = 0`, or no such project) and is not the recipient session's project; the recipient is a session of this
143788
+ * host that is kept (a `sessions` row with `deleted_at` NULL: the live session lookup skips a trashed one, so the gate holds nothing for it). The
143789
+ * recipient's project is read from `sessions.project_id` and the sender's from `mail.sender_project`, as the move wrote it.
143790
+ *
143791
+ * **Not mirrored: a recipient on another machine** (a linked hub's session, a linked-machine child), which the live gate holds and this step
143792
+ * dismisses, since it compares the session id with this host's `sessions` rows only. That is acceptable: no such row is on the owner's store (read
143793
+ * only, 2026-11-13: all six held rows leave), and an old hold on another machine's session could not be released from this one in any case (Release
143794
+ * sends through this host's delivery to a session it keeps). There is no cheap exact way: the far session's project is not stored here.
143795
+ *
143796
+ * **Rewrite data one way (#292's rule 1).** An older build reads `dismissed` as it reads the person's own Dismiss (it is in its `HELD` filter),
143797
+ * and does not bring the holds back. Nothing is deleted: the message and its row stay. The sender is not told: the person did not dismiss it.
143798
+ */
143799
+ run: () => {
143800
+ if (this.db.prepare(`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'mail_recipients'`).get() === void 0) return;
143801
+ if (this.db.prepare(`SELECT 1 FROM mail_recipients WHERE held IN ('budget', 'policy') LIMIT 1`).get() === void 0) return;
143802
+ this.db.exec(
143803
+ `UPDATE mail_recipients SET held = 'dismissed', attempt_at = NULL, last_error = NULL, attempts = 0
143804
+ WHERE held = 'budget'
143805
+ OR (held = 'policy' AND settled = 'legacy' AND NOT EXISTS (
143806
+ SELECT 1 FROM mail m, sessions s
143807
+ WHERE m.id = mail_recipients.message_id AND m.kind = 'message' AND s.deleted_at IS NULL
143808
+ AND m.sender_project IS NOT NULL
143809
+ AND COALESCE((SELECT p.trusted FROM projects p WHERE p.id = m.sender_project), 0) = 0
143810
+ AND mail_recipients.recipient LIKE 'session:%' AND substr(mail_recipients.recipient, instr(mail_recipients.recipient, '/') + 1) = s.id
143811
+ AND s.project_id IS NOT m.sender_project))`
143812
+ );
143813
+ }
143814
+ },
143815
+ {
143816
+ to: 73,
143817
+ breaksOlderReaders: false,
143818
+ /**
143819
+ * The watches sessions keep (#1324, docs/plans/mailbox.md §18.4): `mail_watches`, one row per watch. `source` and `target` say what it
143820
+ * waits for (`session` and an address, `time` and the words given), `spec` the rest as JSON (a slot and period, or a session's baseline),
143821
+ * `state` one of `active`, `fired`, `expired`, `cancelled`, `gone`. No CHECK on a word, as v58: a newer build may write one this build
143822
+ * does not know.
143823
+ *
143824
+ * **Expand only (#292's rule).** A new table and its indexes. An older build never names it: after a rollback the watches sleep and fire
143825
+ * nothing, and an update back picks them up.
143826
+ */
143827
+ run: () => {
143828
+ this.db.exec(`
143829
+ CREATE TABLE IF NOT EXISTS mail_watches (
143830
+ id TEXT PRIMARY KEY,
143831
+ owner TEXT NOT NULL,
143832
+ source TEXT NOT NULL,
143833
+ target TEXT NOT NULL,
143834
+ spec TEXT NOT NULL,
143835
+ note TEXT NOT NULL DEFAULT '',
143836
+ state TEXT NOT NULL,
143837
+ last_key TEXT,
143838
+ fired_count INTEGER NOT NULL DEFAULT 0,
143839
+ created_at INTEGER NOT NULL,
143840
+ expires_at INTEGER NOT NULL,
143841
+ next_at INTEGER,
143842
+ ended_at INTEGER,
143843
+ ended_by TEXT
143844
+ );
143845
+ CREATE INDEX IF NOT EXISTS mail_watches_owner ON mail_watches(owner, state);
143846
+ CREATE INDEX IF NOT EXISTS mail_watches_due ON mail_watches(state, next_at);
143847
+ `);
143848
+ }
143595
143849
  }
143596
143850
  ];
143597
143851
  }
@@ -144649,8 +144903,8 @@ var Store = class extends MigrationRunner {
144649
144903
  * The thread mail an older build left pending, moved into the message tables and marked handled in the old ones, in one transaction
144650
144904
  * (docs/plans/mailbox.md §6.3): run after every `ready` from M3a to M7, before delivery starts. A second run finds nothing
144651
144905
  */
144652
- movePendingThreadMail(now, projectOf) {
144653
- return movePendingThreadMail(this.db, now, projectOf);
144906
+ movePendingThreadMail(now, projectOf, holdsNow) {
144907
+ return movePendingThreadMail(this.db, now, projectOf, holdsNow);
144654
144908
  }
144655
144909
  /** An old thread's messages, read-only (§6.3): the earlier history of a moved message (`legacy_thread`) */
144656
144910
  legacyChain(threadId, before, limit) {
@@ -144773,8 +145027,38 @@ function noteGhFailure(branch, e) {
144773
145027
  console.error(`[git] gh could not read the pull request of ${branch}: ${why2}`);
144774
145028
  }
144775
145029
  async function gitBranchPr(projectCwd, branch, signal, timeoutMs = OK2.timeout) {
145030
+ const j2 = await ghPrView(projectCwd, branch, ["number", "state", "url", "headRefOid"], signal, timeoutMs);
145031
+ if (j2 === "unavailable") return "unavailable";
145032
+ if (!j2 || j2 === "signed_out" || typeof j2.number !== "number" || typeof j2.state !== "string" || typeof j2.url !== "string") return null;
145033
+ return {
145034
+ number: j2.number,
145035
+ state: prState(j2.state),
145036
+ url: j2.url,
145037
+ ...typeof j2.headRefOid === "string" && j2.headRefOid ? { headOid: j2.headRefOid } : {}
145038
+ };
145039
+ }
145040
+ var prState = (state) => state === "MERGED" ? "merged" : state === "CLOSED" ? "closed" : "open";
145041
+ var FAILED = /* @__PURE__ */ new Set(["FAILURE", "TIMED_OUT", "ACTION_REQUIRED", "STARTUP_FAILURE", "ERROR"]);
145042
+ async function prChecks(projectCwd, number4, signal) {
145043
+ const j2 = await ghPrView(projectCwd, String(number4), ["state", "headRefOid", "statusCheckRollup"], signal);
145044
+ if (j2 === null || j2 === "unavailable" || j2 === "signed_out") return j2;
145045
+ if (typeof j2.state !== "string" || typeof j2.headRefOid !== "string" || !Array.isArray(j2.statusCheckRollup)) return null;
145046
+ let pending = 0;
145047
+ let failed4 = 0;
145048
+ let cancelled2 = 0;
145049
+ for (const c of j2.statusCheckRollup) {
145050
+ if (!isObj(c)) continue;
145051
+ const end = typeof c.conclusion === "string" && c.conclusion ? c.conclusion : typeof c.state === "string" ? c.state : "";
145052
+ const running2 = "status" in c ? c.status !== "COMPLETED" : end === "PENDING" || end === "EXPECTED";
145053
+ if (running2) pending++;
145054
+ else if (FAILED.has(end)) failed4++;
145055
+ else if (end === "CANCELLED") cancelled2++;
145056
+ }
145057
+ return { state: prState(j2.state), headOid: j2.headRefOid, total: j2.statusCheckRollup.length, pending, failed: failed4, cancelled: cancelled2 };
145058
+ }
145059
+ async function ghPrView(projectCwd, ref, fields5, signal, timeoutMs = OK2.timeout) {
144776
145060
  try {
144777
- const run2 = await realOs().processes.run(programPath("gh"), ["pr", "view", branch, "--json", "number,state,url,headRefOid"], {
145061
+ const run2 = await realOs().processes.run(programPath("gh"), ["pr", "view", ref, "--json", fields5.join(",")], {
144778
145062
  cwd: projectCwd,
144779
145063
  timeoutMs,
144780
145064
  maxBuffer: OK2.maxBuffer,
@@ -144785,25 +145069,20 @@ async function gitBranchPr(projectCwd, branch, signal, timeoutMs = OK2.timeout)
144785
145069
  });
144786
145070
  if (run2.ended) return null;
144787
145071
  if (run2.code !== 0) {
144788
- noteGhFailure(branch, { stderr: run2.stderr.toString("utf8").slice(-GH_STDERR_KEEP) });
144789
- return null;
145072
+ const stderr = run2.stderr.toString("utf8").slice(-GH_STDERR_KEEP);
145073
+ noteGhFailure(ref, { stderr });
145074
+ return SIGNED_OUT.test(stderr) ? "signed_out" : null;
144790
145075
  }
144791
145076
  const j2 = JSON.parse(run2.stdout.toString("utf8"));
144792
- if (!isObj(j2)) return null;
144793
- if (typeof j2.number !== "number" || typeof j2.state !== "string" || typeof j2.url !== "string") return null;
144794
- return {
144795
- number: j2.number,
144796
- state: j2.state === "MERGED" ? "merged" : j2.state === "CLOSED" ? "closed" : "open",
144797
- url: j2.url,
144798
- ...typeof j2.headRefOid === "string" && j2.headRefOid ? { headOid: j2.headRefOid } : {}
144799
- };
145077
+ return isObj(j2) ? j2 : null;
144800
145078
  } catch (e) {
144801
145079
  const failure4 = execFailure(e);
144802
145080
  if (failure4.code === "ENOENT") return "unavailable";
144803
- noteGhFailure(branch, failure4);
145081
+ noteGhFailure(ref, failure4);
144804
145082
  return null;
144805
145083
  }
144806
145084
  }
145085
+ var SIGNED_OUT = /gh auth login|not logged in/i;
144807
145086
 
144808
145087
  // packages/agent-host/src/dev-services/file-search.ts
144809
145088
  import { readdir as readdir13 } from "node:fs/promises";
@@ -148507,6 +148786,7 @@ var SessionManager = class {
148507
148786
  mailStopped: (id3, why2, o) => self2.mail.mailStopped(id3, why2, o),
148508
148787
  mailRequestTurnEnded: (id3) => self2.mail.mailRequestTurnEnded(id3),
148509
148788
  mailLastResponse: (id3, last) => self2.mail.mailLastResponse(id3, last),
148789
+ mailWatchedAtRest: (id3) => self2.mail.mailWatchedAtRest(id3),
148510
148790
  mailTurnInputs: (id3, turn) => self2.mail.mailTurnInputs(id3, turn),
148511
148791
  mailEvent: (e, ended2) => {
148512
148792
  try {
@@ -149708,7 +149988,7 @@ var MessageService = class {
149708
149988
  row,
149709
149989
  message,
149710
149990
  request,
149711
- down: flowsDownTo({ fromPerson: sender === "person", fromSession: sender === "session", kind: message.kind, toAssistant, fromParent: parent === message.sender })
149991
+ down: flowsDownTo({ fromPerson: sender === "person", fromSession: sender === "session", kind: message.kind, toAssistant, fromParent: parent === message.sender, watch: sender === "centralu" && message.facts.watch !== void 0 })
149712
149992
  });
149713
149993
  }
149714
149994
  const wakesIt = (c) => wakesMessage(c.message);
@@ -150671,12 +150951,494 @@ function tellCard(service, giver, card, body, delivered) {
150671
150951
  }
150672
150952
  function withdrawEndedCards(records, session2, stands2) {
150673
150953
  records.transaction(() => {
150674
- const gone2 = records.undeliveredCardNotices(session2).filter(({ message: { facts } }) => facts.card && !stands2(facts.card.session, facts.card.requestId));
150954
+ const gone2 = records.undeliveredNotices("$.card.session", session2).filter(({ message: { facts } }) => facts.card && !stands2(facts.card.session, facts.card.requestId));
150675
150955
  if (gone2.length) records.deleteRows(gone2.map(({ row }) => ({ messageId: row.messageId, recipient: row.recipient })));
150676
150956
  });
150677
150957
  }
150678
150958
 
150959
+ // packages/agent-host/src/mail/watches.ts
150960
+ var WATCH_STATES = ["active", "fired", "expired", "cancelled", "gone"];
150961
+ var WATCH_ENDED_BY = ["owner", "person", "host"];
150962
+ var StoredSpec = {
150963
+ time: external_exports.object({ kind: external_exports.enum(["in", "at", "every"]), slotMs: external_exports.number(), periodMin: external_exports.number().optional() }),
150964
+ session: external_exports.object({ baselineTurn: external_exports.number(), baselineCards: external_exports.array(external_exports.string()) }),
150965
+ pr: external_exports.object({ project: external_exports.string(), number: external_exports.number(), headOid: external_exports.string() })
150966
+ };
150967
+ function readWatch(row) {
150968
+ const state = WATCH_STATES.find((s) => s === row.state);
150969
+ const endedBy = row.endedBy === null ? null : WATCH_ENDED_BY.find((b2) => b2 === row.endedBy);
150970
+ if (!state || endedBy === void 0) return void 0;
150971
+ const raw = parseJson(row.spec);
150972
+ let spec;
150973
+ if (row.source === "time") {
150974
+ const t = StoredSpec.time.safeParse(raw);
150975
+ spec = t.success ? { source: "time", ...t.data } : void 0;
150976
+ } else if (row.source === "session") {
150977
+ const s = StoredSpec.session.safeParse(raw);
150978
+ spec = s.success ? { source: "session", target: row.target, ...s.data } : void 0;
150979
+ } else if (row.source === "pr") {
150980
+ const pr = StoredSpec.pr.safeParse(raw);
150981
+ spec = pr.success ? { source: "pr", ...pr.data } : void 0;
150982
+ }
150983
+ return spec && { ...row, spec, state, endedBy };
150984
+ }
150985
+ function writeWatch(w) {
150986
+ const { spec } = w;
150987
+ if (spec.source === "session") return { ...w, source: spec.source, target: spec.target, spec: JSON.stringify({ baselineTurn: spec.baselineTurn, baselineCards: spec.baselineCards }) };
150988
+ const { source, ...stored } = spec;
150989
+ return { ...w, source, spec: JSON.stringify(stored) };
150990
+ }
150991
+ var isTimeWatch = (to) => /^(in|at|every)\s/i.test(to.trim());
150992
+ var prNumberOf = (to) => {
150993
+ const m = /^#(\d{1,9})$/.exec(to.trim());
150994
+ return m ? Number(m[1]) : null;
150995
+ };
150996
+ var checksEnded = (number4, r) => r.total === 0 ? `No checks ran on #${number4}` : `The checks on #${number4} finished: ${r.failed === 0 ? "none" : r.failed} failed${r.cancelled ? `, ${r.cancelled} cancelled` : ""}`;
150997
+ function timeSpec(to, now) {
150998
+ const t = to.trim();
150999
+ const units = { m: MINUTE_MS, h: HOUR_MS, d: 24 * HOUR_MS };
151000
+ const span = /^(in|every)\s+(\d{1,6})\s*([mhd])$/i.exec(t);
151001
+ if (span) {
151002
+ const ms3 = Number(span[2]) * (units[(span[3] ?? "m").toLowerCase()] ?? MINUTE_MS);
151003
+ if (span[1]?.toLowerCase() === "every") {
151004
+ if (ms3 < WATCH.everyAtLeastMs) throw refuse4("bad_value", `"every" is at least ${WATCH.everyAtLeastMs / MINUTE_MS} minutes.`);
151005
+ return { source: "time", kind: "every", slotMs: now + ms3, periodMin: ms3 / MINUTE_MS };
151006
+ }
151007
+ if (ms3 <= 0 || ms3 > WATCH.aheadAtMostMs) throw refuse4("bad_value", "a time is at most 7 days ahead.");
151008
+ return { source: "time", kind: "in", slotMs: now + ms3 };
151009
+ }
151010
+ const at2 = /^at\s+(\d{1,2}):(\d{2})$/i.exec(t);
151011
+ if (at2 && Number(at2[1]) < 24 && Number(at2[2]) < 60) {
151012
+ const d2 = new Date(now);
151013
+ d2.setHours(Number(at2[1]), Number(at2[2]), 0, 0);
151014
+ if (d2.getTime() <= now) d2.setDate(d2.getDate() + 1);
151015
+ return { source: "time", kind: "at", slotMs: d2.getTime() };
151016
+ }
151017
+ throw refuse4("bad_value", USAGE);
151018
+ }
151019
+ var USAGE = `a watch needs to: a session by name or id, "in 30m", "at 16:30" (this computer's time, the next such minute), "every 30m" (at least 10 minutes) or "#123" (a pull request's checks), and may take text, your note of at most 300 characters.`;
151020
+ function checkNote(note) {
151021
+ if (note.length > WATCH.noteChars) throw refuse4("too_long", `a watch's note is at most ${WATCH.noteChars} characters.`);
151022
+ }
151023
+ var pad = (n) => String(n).padStart(2, "0");
151024
+ var day3 = (d2) => `${d2.getFullYear()}-${pad(d2.getMonth() + 1)}-${pad(d2.getDate())}`;
151025
+ var slotKey = (ms3) => {
151026
+ const d2 = new Date(ms3);
151027
+ return `${day3(d2)}T${pad(d2.getHours())}:${pad(d2.getMinutes())}`;
151028
+ };
151029
+ var CHANGE_TEXT = {
151030
+ turn_ended: "its turn ended. Read what it said with read_session.",
151031
+ asked: "it asked a question or for an approval. See it with read_session.",
151032
+ stopped: "it stopped before its turn ended. See why with read_session.",
151033
+ gone: "it is gone: in the session archive or deleted."
151034
+ };
151035
+ var GH_MISSING = {
151036
+ unavailable: "gh is not installed on this computer",
151037
+ signed_out: "gh is not signed in on this computer (gh auth login)"
151038
+ };
151039
+ var Watches = class {
151040
+ constructor(host) {
151041
+ this.host = host;
151042
+ this.now = host.now ?? Date.now;
151043
+ }
151044
+ host;
151045
+ now;
151046
+ ulids = new UlidMaker();
151047
+ listeners = createListeners((e) => console.error(`[mail] a watches listener failed: ${errorMessage(e)}`));
151048
+ schedule = null;
151049
+ cancelTimer = null;
151050
+ /** When the pull requests were last asked of gh, and whether an asking runs: one at a time, at most once a `WATCH.prPollMs` */
151051
+ polledAt = -Infinity;
151052
+ polling = false;
151053
+ /** For each pull request polled, its head and number of checks when the last poll found none running: a finish is believed when two polls agree */
151054
+ settledAt = /* @__PURE__ */ new Map();
151055
+ /** Hears the session (its id) whose watches changed: one was set, fired, ended or cancelled */
151056
+ onChange(listener) {
151057
+ return this.listeners.add(listener);
151058
+ }
151059
+ /** The delivery started: what changed while none ran fires once, then what is due, and the timer runs */
151060
+ start(schedule) {
151061
+ this.schedule = schedule;
151062
+ try {
151063
+ this.catchUp();
151064
+ } catch (e) {
151065
+ console.error(`[mail] catching up the watches failed: ${errorMessage(e)}`);
151066
+ }
151067
+ this.due();
151068
+ }
151069
+ stop() {
151070
+ this.cancelTimer?.();
151071
+ this.cancelTimer = null;
151072
+ this.schedule = null;
151073
+ this.settledAt = /* @__PURE__ */ new Map();
151074
+ }
151075
+ /** Sets a watch, or extends the same one (same owner, source and target) with this note; returns the answer the tool gives (§18.2) */
151076
+ register(owner, to, note, close) {
151077
+ const now = this.now();
151078
+ const spec = isTimeWatch(to) ? timeSpec(to, now) : this.sessionSpec(owner, to);
151079
+ const { w, id: id3 } = this.put(owner, spec, spec.source === "session" ? spec.target : to.trim(), note, close, now);
151080
+ if (spec.source === "time") {
151081
+ return spec.kind === "every" ? `Watching every ${spec.periodMin} minutes until ${this.clock(w.expiresAt)}, first at ${this.clock(spec.slotMs)}. ${id3}` : `Watching for ${this.clock(spec.slotMs)}: Centralu wakes you then. ${id3}`;
151082
+ }
151083
+ const s = this.host.session(w.target);
151084
+ const doing = s?.cards.length ? "it is waiting on a question or an approval now" : s?.working ? "it is working now" : "it is at rest now";
151085
+ return `Watching ${this.what(w)} until ${this.clock(w.expiresAt)}; ${doing}. ${id3}`;
151086
+ }
151087
+ /**
151088
+ * A watch on a pull request's checks (`#123`, §18.3), asked of gh first: gh missing or signed out, or a pull request it cannot read, is refused
151089
+ * and writes no row; one that has ended, or whose checks on its head have finished, has nothing to wait for
151090
+ */
151091
+ async registerPr(owner, number4, note, close, signal) {
151092
+ checkNote(note);
151093
+ const project2 = this.host.projectOf(owner);
151094
+ if (!project2) throw refuse4("bad_value", "a pull request is watched from a session in its project, and this session has none.");
151095
+ const r = await this.host.prChecks(project2, number4, signal);
151096
+ if (r === "unavailable" || r === "signed_out") throw refuse4("unavailable", `${GH_MISSING[r]}, so Centralu cannot watch #${number4} here.`);
151097
+ if (r === null) throw refuse4("bad_value", `gh cannot read pull request #${number4} in this session's project now.`);
151098
+ if (r.state !== "open") return `#${number4} is ${r.state} already: nothing to watch.`;
151099
+ if (r.total > 0 && r.pending === 0) return `${checksEnded(number4, r)} already: nothing to watch. A push starts new checks; watch again after it.`;
151100
+ const { w, id: id3 } = this.put(owner, { source: "pr", project: project2, number: number4, headOid: r.headOid }, `${project2}#${number4}`, note, close, this.now());
151101
+ return `Watching ${this.what(w)} until ${this.clock(w.expiresAt)}; ${r.pending} of ${r.total} still run. ${id3}`;
151102
+ }
151103
+ /** The row of a new watch, or the same one (owner, source, target) extended with this note (§18.2); refused past `WATCH.perSession` */
151104
+ put(owner, spec, target, note, close, now) {
151105
+ checkNote(note);
151106
+ const active = this.list(owner);
151107
+ const same = active.find((w2) => w2.spec.source === spec.source && w2.target === target);
151108
+ if (!same && active.length >= WATCH.perSession) {
151109
+ throw refuse4("not_allowed", `a session keeps at most ${WATCH.perSession} watches. Cancel one with ${close("<id>")}.`);
151110
+ }
151111
+ const expiresAt = spec.source === "time" && spec.kind !== "every" ? spec.slotMs : now + WATCH.lastsMs;
151112
+ const w = {
151113
+ ...same ?? { id: watchIdOf(this.host.hostId, this.ulids.next(now)), owner, state: "active", lastKey: null, firedCount: 0, createdAt: now, endedAt: null, endedBy: null },
151114
+ target,
151115
+ spec,
151116
+ note,
151117
+ expiresAt,
151118
+ nextAt: spec.source === "time" ? Math.min(spec.slotMs, expiresAt) : expiresAt
151119
+ };
151120
+ this.host.records.saveWatch(writeWatch(w));
151121
+ this.emit(owner);
151122
+ return { w, id: `id ${w.id}. Cancel with ${close(w.id)}.` };
151123
+ }
151124
+ /**
151125
+ * Ends a watch (`by` its owner or the person), and takes back its firing not given yet: `cancelled` when it was active, `withdrawn` when it had ended
151126
+ * but its notice had not reached its owner, `ended` when there was nothing left to do (or no such watch)
151127
+ */
151128
+ cancel(id3, by) {
151129
+ const now = this.now();
151130
+ const done2 = this.host.records.transaction(() => {
151131
+ const w = this.read(id3);
151132
+ if (!w) return void 0;
151133
+ const undelivered = this.host.records.undeliveredNotices("$.watch.id", id3).filter(({ message }) => message.facts.quiet !== true);
151134
+ if (undelivered.length) this.host.records.deleteRows(undelivered.map(({ row }) => ({ messageId: row.messageId, recipient: row.recipient })));
151135
+ if (w.state !== "active") return undelivered.length ? { w, how: "withdrawn" } : void 0;
151136
+ this.host.records.saveWatch(writeWatch({ ...w, state: "cancelled", endedAt: now, endedBy: by, nextAt: null }));
151137
+ if (by === "person") {
151138
+ this.host.service.notice(w.owner, { body: `The person cancelled your watch on ${this.what(w)}.`, facts: { quiet: true, watch: { id: id3, source: w.spec.source, change: "cancelled" } }, dedupeKey: this.key(w, "cancelled") });
151139
+ }
151140
+ return { w, how: "cancelled" };
151141
+ });
151142
+ if (!done2) return "ended";
151143
+ this.emit(done2.w.owner);
151144
+ return done2.how;
151145
+ }
151146
+ /** A watch by id, active or ended, as this build reads it */
151147
+ read(id3) {
151148
+ const row = this.host.records.watch(id3);
151149
+ return row && readWatch(row);
151150
+ }
151151
+ /** The owner's active watches, oldest first */
151152
+ list(owner) {
151153
+ return this.host.records.activeWatches({ owner }).flatMap((r) => readWatch(r) ?? []);
151154
+ }
151155
+ /** The session's active watches as the person's window lists them (`watches.list`, §18.8) */
151156
+ views(sessionId) {
151157
+ return this.list(sessionAddress(this.host.hostId, sessionId)).map((w) => ({
151158
+ id: w.id,
151159
+ source: w.spec.source,
151160
+ what: w.spec.source === "session" ? this.host.service.labelOf(w.spec.target) : w.spec.source === "pr" ? `#${w.spec.number}` : "",
151161
+ at: w.spec.source === "time" ? w.spec.slotMs : null,
151162
+ everyMinutes: w.spec.source === "time" ? w.spec.periodMin ?? null : null,
151163
+ until: w.expiresAt,
151164
+ note: w.note,
151165
+ createdAt: w.createdAt
151166
+ }));
151167
+ }
151168
+ /** What a watch waits for, in Centralu's words: `<name> (<address>)`, `a timer for 16:30`, `a timer every 30 minutes` */
151169
+ what(w) {
151170
+ if (w.spec.source === "session") return `${this.host.service.labelOf(w.spec.target)} (${w.spec.target})`;
151171
+ if (w.spec.source === "pr") return `the checks on #${w.spec.number}`;
151172
+ return w.spec.kind === "every" ? `a timer every ${w.spec.periodMin} minutes` : `a timer for ${this.clock(w.spec.slotMs)}`;
151173
+ }
151174
+ /** A watched session changed (the mail hooks, §18.3): each active watch on it fires once, and ends. `card`: the request id a card was raised with */
151175
+ changed(target, change, card) {
151176
+ if (!this.schedule) return;
151177
+ for (const row of this.host.records.activeWatches({ target })) {
151178
+ const w = readWatch(row);
151179
+ if (w?.spec.source !== "session" || card !== void 0 && w.spec.baselineCards.includes(card)) continue;
151180
+ try {
151181
+ this.fireSession(w, change);
151182
+ } catch (e) {
151183
+ console.error(`[mail] watch ${row.id}: ${errorMessage(e)}`);
151184
+ }
151185
+ }
151186
+ }
151187
+ /** Whether a session watch on `target` waits for its rest: a turn of it ended since the watch was set, and its own background work held the end (§18.3) */
151188
+ waitsForRest(target) {
151189
+ const party = parseAddress(target);
151190
+ const ended2 = party?.kind === "session" ? this.host.records.lastEndedTurn(party.sessionId) : 0;
151191
+ return this.host.records.activeWatches({ target }).some((r) => {
151192
+ const w = readWatch(r);
151193
+ return w?.spec.source === "session" && ended2 > w.spec.baselineTurn;
151194
+ });
151195
+ }
151196
+ /**
151197
+ * A session left (the session archive or deleted): the watches on it fire `gone`. Its own stay, as its mail does, while the archive may give it back;
151198
+ * they are deleted with its mail when it is deleted for good (`MailboxRecords.purgeParty`, §18.4)
151199
+ */
151200
+ gone(address) {
151201
+ this.changed(address, "gone");
151202
+ }
151203
+ /**
151204
+ * A handoff moves `from`'s mailbox to `to` (`moveMail`: `MessageService.handOver`, scope `all`), in one transaction with this: its active watches
151205
+ * are `to`'s, the same rows, and the watches others keep on `from` wait for `to`, from `to`'s state now. One that would have `to` watch itself (the
151206
+ * original's on its heir, or the heir's on the original) ends, and nobody is told: no one set a watch on itself
151207
+ */
151208
+ handOver(from, to, moveMail) {
151209
+ const now = this.now();
151210
+ const owners = /* @__PURE__ */ new Set([from, to]);
151211
+ const moved = this.host.records.transaction(() => {
151212
+ for (const row of this.host.records.activeWatches({ owner: from })) this.host.records.saveWatch({ ...row, owner: to });
151213
+ for (const row of this.host.records.activeWatches({ target: from })) {
151214
+ const w = readWatch(row);
151215
+ if (w?.spec.source !== "session") continue;
151216
+ this.host.records.saveWatch(writeWatch({ ...w, spec: { ...w.spec, ...this.baseline(to), target: to } }));
151217
+ owners.add(w.owner);
151218
+ }
151219
+ for (const row of this.host.records.activeWatches({ owner: to })) {
151220
+ if (row.target === to) this.host.records.saveWatch({ ...row, state: "cancelled", endedAt: now, endedBy: "host", nextAt: null });
151221
+ }
151222
+ return moveMail();
151223
+ });
151224
+ for (const owner of owners) this.emit(owner);
151225
+ return moved;
151226
+ }
151227
+ /** What is due by now fires (a time's slot) or ends (its 24 hours), then the timer is set to the next one. Also the delivery's sweep's safety net */
151228
+ due(now = this.now()) {
151229
+ if (!this.schedule) return;
151230
+ if (!this.polling && now - this.polledAt >= WATCH.prPollMs) void this.pollPrs(now);
151231
+ for (const row of this.host.records.activeWatches({ dueBy: now })) {
151232
+ const w = readWatch(row);
151233
+ try {
151234
+ if (w?.spec.source === "time" && w.spec.slotMs <= now) this.fireTime(w, w.spec, now);
151235
+ else if (w && w.expiresAt <= now) this.expire(w, now);
151236
+ } catch (e) {
151237
+ console.error(`[mail] watch ${row.id}: ${errorMessage(e)}`);
151238
+ }
151239
+ }
151240
+ this.arm();
151241
+ }
151242
+ /** Every active session watch against its target's stored state (§18.5 catch-up): a change while no delivery ran fires once */
151243
+ catchUp() {
151244
+ for (const owner of new Set(this.host.records.activeWatches().map((r) => r.owner))) {
151245
+ if (!this.host.session(owner) && !this.host.archived(owner)) this.host.records.deleteWatchesOf(owner);
151246
+ }
151247
+ for (const row of this.host.records.activeWatches()) {
151248
+ const w = readWatch(row);
151249
+ if (w?.spec.source !== "session") continue;
151250
+ const s = this.host.session(w.spec.target);
151251
+ const party = parseAddress(w.spec.target);
151252
+ const baseline = w.spec.baselineCards;
151253
+ const ended2 = party?.kind === "session" && this.host.records.lastEndedTurn(party.sessionId) > w.spec.baselineTurn;
151254
+ const change = !s ? "gone" : s.cards.some((c) => !baseline.includes(c)) ? "asked" : ended2 && !s.working && !s.held ? s.interrupted ? "stopped" : "turn_ended" : null;
151255
+ if (change) this.fireSession(w, change);
151256
+ }
151257
+ }
151258
+ fireSession(w, change) {
151259
+ if (w.spec.source !== "session") return;
151260
+ const target = w.spec.target;
151261
+ this.fire(w.id, change, (now) => ({
151262
+ body: `Your watch on ${this.what(w)}: ${CHANGE_TEXT[change]}`,
151263
+ facts: { watch: { id: w.id, source: "session", change }, about: { session: target }, reason: change },
151264
+ next: { state: change === "gone" ? "gone" : "fired", endedAt: now, endedBy: "host", nextAt: null }
151265
+ }));
151266
+ }
151267
+ /**
151268
+ * A time's slot is due: the latest slot passed by now and not after the watch's end fires once (missed `every` slots are one firing), `late` when the
151269
+ * host was not there for the first slot missed
151270
+ */
151271
+ fireTime(w, spec, now) {
151272
+ const period = (spec.periodMin ?? 0) * MINUTE_MS;
151273
+ const last = Math.min(now, w.expiresAt);
151274
+ const slot = period > 0 ? spec.slotMs + Math.floor((last - spec.slotMs) / period) * period : spec.slotMs;
151275
+ const late = now - spec.slotMs > MINUTE_MS;
151276
+ const next = period > 0 ? slot + period : null;
151277
+ const every = spec.kind === "every" ? `, every ${spec.periodMin} minutes,` : "";
151278
+ this.fire(w.id, slotKey(slot), (at2) => ({
151279
+ body: `Your timer set at ${this.clock(w.createdAt)}${every} for ${this.clock(slot)} is due.${late ? ` It fires late: Centralu was not running at ${this.clock(spec.slotMs)}, or the computer slept.` : ""}`,
151280
+ facts: { watch: { id: w.id, source: "time", change: "due", ...late ? { late: true } : {} } },
151281
+ next: next !== null && next <= w.expiresAt ? { spec: { ...spec, slotMs: next }, nextAt: next } : { state: next === null ? "fired" : "expired", endedAt: at2, endedBy: "host", nextAt: null }
151282
+ }));
151283
+ }
151284
+ /** It reached its end without a change: one quiet notice when it never fired (§18.4) */
151285
+ expire(w, now) {
151286
+ this.endQuietly(w.id, now, "expired", (fresh) => fresh.firedCount === 0 ? `Your watch on ${this.what(fresh)} ended after 24 hours without a change.` : null);
151287
+ }
151288
+ /** Ends an active watch by the host, with one quiet notice to its owner when `body` gives one */
151289
+ endQuietly(id3, now, change, body) {
151290
+ const ended2 = this.host.records.transaction(() => {
151291
+ const fresh = this.read(id3);
151292
+ if (fresh?.state !== "active") return void 0;
151293
+ this.host.records.saveWatch(writeWatch({ ...fresh, state: "expired", endedAt: now, endedBy: "host", nextAt: null }));
151294
+ const text3 = body(fresh);
151295
+ if (text3 !== null) {
151296
+ this.host.service.notice(fresh.owner, { body: text3, facts: { quiet: true, watch: { id: id3, source: fresh.spec.source, change } }, dedupeKey: this.key(fresh, change) });
151297
+ }
151298
+ return fresh;
151299
+ });
151300
+ if (ended2) this.emit(ended2.owner);
151301
+ }
151302
+ /**
151303
+ * Asks gh once for each pull request an active watch names, however many name it (§18.3), and fires what ended: the checks on its head finished,
151304
+ * or none ran, as two polls in a row agree; or the pull request was merged or closed. A new head starts the wait again. gh gone or signed out ends
151305
+ * each watch with one quiet notice saying so; a gh that cannot answer now is asked again at the next poll
151306
+ */
151307
+ async pollPrs(now) {
151308
+ this.polling = true;
151309
+ this.polledAt = now;
151310
+ try {
151311
+ const byPr = /* @__PURE__ */ new Map();
151312
+ for (const row of this.host.records.activeWatches()) {
151313
+ const w = readWatch(row);
151314
+ if (w?.spec.source === "pr") byPr.set(w.target, [...byPr.get(w.target) ?? [], w]);
151315
+ }
151316
+ const settled = /* @__PURE__ */ new Map();
151317
+ for (const [target, watches] of byPr) {
151318
+ const first = watches[0]?.spec;
151319
+ if (first?.source !== "pr") continue;
151320
+ const r = await this.host.prChecks(first.project, first.number).catch(() => null);
151321
+ if (!this.schedule || r === null) continue;
151322
+ const seen = typeof r === "object" && r.pending === 0 ? `${r.headOid}:${r.total}` : null;
151323
+ const agreed = seen !== null && this.settledAt.get(target) === seen;
151324
+ if (seen !== null) settled.set(target, seen);
151325
+ for (const w of watches) this.prChanged(w, r, agreed);
151326
+ }
151327
+ if (this.schedule) this.settledAt = settled;
151328
+ } catch (e) {
151329
+ console.error(`[mail] asking gh for the watched pull requests failed: ${errorMessage(e)}`);
151330
+ } finally {
151331
+ this.polling = false;
151332
+ }
151333
+ }
151334
+ prChanged(w, r, agreed) {
151335
+ if (w.spec.source !== "pr") return;
151336
+ const { number: number4 } = w.spec;
151337
+ if (r === "unavailable" || r === "signed_out") {
151338
+ this.endQuietly(w.id, this.now(), "gh", () => `Your watch on ${this.what(w)} ended: ${GH_MISSING[r]}.`);
151339
+ return;
151340
+ }
151341
+ if (r.state !== "open") {
151342
+ this.fire(w.id, r.state, (at2) => ({ body: `Pull request #${number4} was ${r.state}.`, facts: { watch: { id: w.id, source: "pr", change: r.state } }, next: { state: "fired", endedAt: at2, endedBy: "host", nextAt: null } }));
151343
+ return;
151344
+ }
151345
+ if (r.headOid !== w.spec.headOid) this.moveHead(w.id, r.headOid);
151346
+ if (!agreed) return;
151347
+ this.fire(w.id, `checks:${r.headOid}`, (at2) => ({
151348
+ body: `${checksEnded(number4, r)}.`,
151349
+ facts: { watch: { id: w.id, source: "pr", change: "checks" } },
151350
+ next: { state: "fired", endedAt: at2, endedBy: "host", nextAt: null }
151351
+ }));
151352
+ }
151353
+ /** A push moved the pull request's head: the row, re-read in a transaction, waits for the new one if it is still active (gh was asked meanwhile) */
151354
+ moveHead(id3, headOid) {
151355
+ this.host.records.transaction(() => {
151356
+ const fresh = this.read(id3);
151357
+ if (fresh?.state === "active" && fresh.spec.source === "pr") this.host.records.saveWatch(writeWatch({ ...fresh, spec: { ...fresh.spec, headOid } }));
151358
+ });
151359
+ }
151360
+ /**
151361
+ * The firing (§18.5), one transaction: the row re-read and still active, its change not the last one fired; the notice to its owner, under a key
151362
+ * that makes a second evaluation (two hosts on one store, a sweep racing an event) post nothing; the row moved on or ended
151363
+ */
151364
+ fire(id3, change, make) {
151365
+ const now = this.now();
151366
+ const w = this.host.records.transaction(() => {
151367
+ const w2 = this.read(id3);
151368
+ if (w2?.state !== "active" || w2.lastKey === change) return void 0;
151369
+ const { body, facts, next } = make(now);
151370
+ const note = w2.note ? `
151371
+
151372
+ Your note:
151373
+ ${quoted2(w2.note)}` : "";
151374
+ this.host.service.notice(w2.owner, { body: body + note, facts, dedupeKey: this.key(w2, change) });
151375
+ this.host.records.saveWatch(writeWatch({ ...w2, lastKey: change, firedCount: w2.firedCount + 1, ...next }));
151376
+ return w2;
151377
+ });
151378
+ if (!w) return;
151379
+ this.warn(w.owner, now);
151380
+ this.emit(w.owner);
151381
+ }
151382
+ /** The person's warning when a session's watches woke it more than `warnWakesPerHour` times in the hour, counted from the store (§18.7) */
151383
+ warn(owner, now) {
151384
+ const n = this.host.records.watchFiringsSince(owner, now - HOUR_MS);
151385
+ if (n <= WATCH.warnWakesPerHour) return;
151386
+ this.host.service.notice(PERSON, { body: WARNING_TEXT.watchWakes(this.host.service.labelOf(owner), n), facts: { watchWakes: { session: owner, count: n } }, dedupeKey: hourlyKey(`watchwakes:${owner}`, now) });
151387
+ }
151388
+ /** A session watch's target, refused as §18.3 says, and its baseline: the target's last ended turn and its cards now */
151389
+ sessionSpec(owner, target) {
151390
+ const party = parseAddress(target);
151391
+ const me2 = parseAddress(owner);
151392
+ if (party?.kind !== "session" || me2?.kind !== "session") throw refuse4("bad_value", USAGE);
151393
+ if (target === owner) throw refuse4("bad_value", "a session does not watch itself.");
151394
+ if (this.host.elsewhere(target)) throw refuse4("elsewhere", `${target} is on another computer, and a watch waits only for a session on this one.`);
151395
+ if (!this.host.session(target)) throw refuse4("gone", `${target} is gone: it is in the session archive or deleted.`);
151396
+ if (!this.host.mayRead(owner, target)) throw refuse4("not_allowed", `${target} is not a session you can read with read_session, so you cannot watch it.`);
151397
+ if (openTaskParties(this.host.records, target, "to").includes(me2.sessionId)) {
151398
+ throw refuse4("not_allowed", `you gave ${this.host.service.labelOf(target)} work that is open: its last response or reply reaches you as mail, and so does its stop, without a watch.`);
151399
+ }
151400
+ return { source: "session", target, ...this.baseline(target) };
151401
+ }
151402
+ baseline(target) {
151403
+ const party = parseAddress(target);
151404
+ return { baselineTurn: party?.kind === "session" ? this.host.records.lastEndedTurn(party.sessionId) : 0, baselineCards: this.host.session(target)?.cards ?? [] };
151405
+ }
151406
+ key(w, change) {
151407
+ return `watch:${w.owner}:${w.id}:${change}`;
151408
+ }
151409
+ /** One timer, to the earliest active watch this build reads, through the delivery's `schedule` */
151410
+ arm() {
151411
+ const schedule = this.schedule;
151412
+ this.cancelTimer?.();
151413
+ this.cancelTimer = null;
151414
+ if (!schedule) return;
151415
+ const next = Math.min(...this.host.records.activeWatches().flatMap((r) => readWatch(r) && r.nextAt !== null ? [r.nextAt] : []));
151416
+ if (next === Infinity) return;
151417
+ this.cancelTimer = schedule(Math.max(0, next - this.now()), () => {
151418
+ this.cancelTimer = null;
151419
+ this.due();
151420
+ });
151421
+ }
151422
+ /** The owner's watch set changed: the window is told, and the timer follows */
151423
+ emit(owner) {
151424
+ const party = parseAddress(owner);
151425
+ if (party?.kind === "session") this.listeners.emit(party.sessionId);
151426
+ this.arm();
151427
+ }
151428
+ /** A time as the session reads it: the host's local `16:30`, with the date when it is not today */
151429
+ clock(ms3) {
151430
+ const d2 = new Date(ms3);
151431
+ const hm2 = `${pad(d2.getHours())}:${pad(d2.getMinutes())}`;
151432
+ return day3(d2) === day3(new Date(this.now())) ? hm2 : `${day3(d2)} ${hm2}`;
151433
+ }
151434
+ };
151435
+
150679
151436
  // packages/agent-host/src/mail/tool.ts
151437
+ var CANCEL_ANSWER = {
151438
+ cancelled: (id3) => `Cancelled watch ${id3}.`,
151439
+ withdrawn: (id3) => `Watch ${id3} had fired, and its notice had not reached you yet: it will not come.`,
151440
+ ended: (id3) => `Watch ${id3} had ended already.`
151441
+ };
150680
151442
  var MailTool = class {
150681
151443
  constructor(service, records, reach, host) {
150682
151444
  this.service = service;
@@ -150709,6 +151471,11 @@ var MailTool = class {
150709
151471
  const across = this.host.across;
150710
151472
  if (!me2) return this.run(sessionId, args);
150711
151473
  try {
151474
+ const pr = args.action === "watch" ? prNumberOf(args.to ?? "") : null;
151475
+ if (pr !== null) {
151476
+ const watches = this.watchArgs(args);
151477
+ return { text: await watches.registerPr(me2.address, pr, args.text?.trim() ?? "", (id3) => mailCalls(1, this.host.form(sessionId)).close(id3), signal) };
151478
+ }
150712
151479
  if (args.action === "find") {
150713
151480
  if (!across) return { text: "Finding sessions is not available here.", isError: true };
150714
151481
  return { text: await across.find((args.to ?? args.text ?? "").trim(), me2.address) };
@@ -150814,14 +151581,35 @@ var MailTool = class {
150814
151581
  }
150815
151582
  case "find":
150816
151583
  throw refuse4("bad_value", "find searches other computers too, which this call does not reach");
150817
- case "update":
150818
- case "close":
151584
+ case "watch":
151585
+ return this.watch(sessionId, me2, a, calls);
151586
+ case "close": {
151587
+ const id3 = a.thread?.trim() ?? "";
151588
+ const w = parseMailId(id3)?.kind === "watch" ? this.host.watches?.read(id3) : void 0;
151589
+ if (w?.owner === me2.address) return CANCEL_ANSWER[this.host.watches?.cancel(id3, "owner") ?? "ended"](id3);
150819
151590
  throw refuse4(
150820
151591
  "removed",
150821
- `Centralu's mail has no threads any more, so "${a.action}" is gone. Answer a message with ${calls.answer("<message id>")}, and mark one that needs nothing with ${calls.done("<message id>")}.`
151592
+ `Centralu's mail has no threads any more, so "close" closes only a watch of yours. Answer a message with ${calls.answer("<message id>")}, and mark one that needs nothing with ${calls.done("<message id>")}.`
150822
151593
  );
151594
+ }
150823
151595
  }
150824
151596
  }
151597
+ /** `watch` (§18.2): `to` a session, resolved as `send` resolves it, or a time; `text` the session's note. No other field */
151598
+ watch(sessionId, me2, a, calls) {
151599
+ const watches = this.watchArgs(a);
151600
+ const to = a.to?.trim() ?? "";
151601
+ if (!to) return `A watch needs to: a session by name or id, "in 30m", "at 16:30" (this computer's time), "every 30m" (at least 10 minutes) or "#123" (a pull request's checks); text is your note, at most 300 characters.`;
151602
+ const target = isTimeWatch(to) ? to : to === sessionId || to === me2.address ? me2.address : this.party(sessionId, me2, to).address;
151603
+ return watches.register(me2.address, target, a.text?.trim() ?? "", (id3) => calls.close(id3));
151604
+ }
151605
+ /** The watches, for a `watch` that names only `to` and `text` */
151606
+ watchArgs(a) {
151607
+ const watches = this.host.watches;
151608
+ if (!watches) throw refuse4("no_mailbox", "watches are not available here");
151609
+ const other = ["thread", "kind", "subject", "urgent", "cite", "choices", "ifBusy"].find((k2) => a[k2] !== void 0);
151610
+ if (other) throw refuse4("field_not_allowed", `a watch takes to and text only, not ${other}.`);
151611
+ return watches;
151612
+ }
150825
151613
  need(value, name) {
150826
151614
  if (!value?.trim()) throw new Error(`${name} is needed for this action`);
150827
151615
  return value.trim();
@@ -150912,14 +151700,17 @@ var MailTool = class {
150912
151700
  /** `inbox` (S6): what waits for the caller's answer, what is unread, what it asked and is not answered, and its mail held for the person */
150913
151701
  inbox(me2, calls) {
150914
151702
  const v = this.service.inbox(me2);
151703
+ const ws2 = this.host.watches;
151704
+ const watching = ws2 ? ws2.list(me2).map((w) => `Watching: ${w.id} ${ws2.what(w)} until ${ws2.clock(w.expiresAt)}${w.note ? `: ${w.note}` : ""}`) : [];
150915
151705
  const total = v.needReply.length + v.unread.length + v.waiting.length + v.held.length;
150916
- if (total === 0) return "Your mailbox is empty.";
151706
+ if (total === 0) return ["Your mailbox is empty.", ...watching].join("\n");
150917
151707
  const lines = [
150918
151708
  `${v.needReply.length} waiting for your reply, ${v.unread.length} unread, ${v.waiting.length} of yours waiting for a reply, ${v.held.length} held. Read with ${calls.read()}.`,
150919
151709
  ...v.needReply.map((i) => `reply ${i.message.id} from ${i.relation} ${this.name(i.message.sender)}, ${this.age(i.message.createdAt)} ago${i.row?.readAt === null ? ", unread" : ""}`),
150920
151710
  ...v.unread.map((i) => `unread ${i.message.id} ${i.message.kind} from ${i.relation} ${this.name(i.message.sender)}, ${this.age(i.message.createdAt)} ago${i.withheld ? " (a request: its words are shown in the turn it starts)" : ""}`),
150921
151711
  ...v.waiting.map((w) => `you asked ${w.message.id} ${this.name(w.row.recipient)}, ${this.age(w.message.createdAt)} ago: ${w.row.answerId ? "answered, the answer held for the person" : "not answered"}`),
150922
- ...v.held.map((h) => `held ${h.message.id} to ${this.name(h.row.recipient)}: ${h.why === "loop" ? "waits until the person lets it go" : `waits until the person trusts ${h.message.senderProject ?? "your project"}`}`)
151712
+ ...v.held.map((h) => `held ${h.message.id} to ${this.name(h.row.recipient)}: ${h.why === "loop" ? "waits until the person lets it go" : `waits until the person trusts ${h.message.senderProject ?? "your project"}`}`),
151713
+ ...watching
150923
151714
  ];
150924
151715
  return lines.join("\n");
150925
151716
  }
@@ -151856,7 +152647,37 @@ function hostMail(store2, sessions, opts) {
151856
152647
  service.onChange((c) => {
151857
152648
  if (c.recipients.some((r) => across.foreign(r))) void across.passOn(c.messageId);
151858
152649
  });
152650
+ const watches = new Watches({
152651
+ hostId,
152652
+ service,
152653
+ records,
152654
+ now,
152655
+ session: (address) => {
152656
+ const party = parseAddress(address);
152657
+ const s = party?.kind === "session" ? sessions.sessionInfo(party.sessionId) : void 0;
152658
+ const cards = s ? [...s.pendingQuestions.map((q2) => q2.requestId), ...s.pendingApproval ? [s.pendingApproval.requestId] : []] : [];
152659
+ return s && { working: inTurn(s.state), cards, interrupted: (s.interruption ?? null) !== null, held: heldToContinue(s.interruption) };
152660
+ },
152661
+ mayRead: (reader, target) => {
152662
+ const [from, to] = [parseAddress(reader), parseAddress(target)];
152663
+ return from?.kind === "session" && to?.kind === "session" && sessions.readsSession?.(from.sessionId, to.sessionId) === true;
152664
+ },
152665
+ elsewhere: (address) => {
152666
+ const party = parseAddress(address);
152667
+ return party?.kind !== "session" || party.host !== hostId || reach.elsewhere(address);
152668
+ },
152669
+ archived: (address) => {
152670
+ const party = parseAddress(address);
152671
+ return party?.kind === "session" && party.host === hostId && store2.trash.isTrashed(party.sessionId);
152672
+ },
152673
+ projectOf: (address) => reach.projectOf(address),
152674
+ prChecks: async (project2, number4, signal) => {
152675
+ const path2 = projects().find((p) => p.id === project2)?.path;
152676
+ return path2 ? prChecks(path2, number4, signal) : null;
152677
+ }
152678
+ });
151859
152679
  const delivery = new MailDelivery(service, records, sessions.mailSessions(), {
152680
+ watches,
151860
152681
  turns: mailTurns,
151861
152682
  ...opts.now ? { now: opts.now } : {},
151862
152683
  // When it last ran: a host that was off a long while does not wake a crowd of sleeping sessions. A setting the previous build never reads
@@ -151899,6 +152720,7 @@ function hostMail(store2, sessions, opts) {
151899
152720
  askerOf: (id3) => askerFacts(askedByHost, id3),
151900
152721
  legacyChain: (threadId, messageId, reader) => store2.legacyChainFor(threadId, messageId, reader, 9),
151901
152722
  across,
152723
+ watches,
151902
152724
  ...sessions.work ? { work: sessions.work } : {}
151903
152725
  });
151904
152726
  const cardStands = (session2, requestId) => {
@@ -151908,20 +152730,35 @@ function hostMail(store2, sessions, opts) {
151908
152730
  };
151909
152731
  const hooks = {
151910
152732
  askedBy: (id3) => askedBy(askedByHost, id3),
151911
- sessionGone: (id3) => service.stops.partyGone(addressOf(id3)),
152733
+ sessionGone: (id3) => {
152734
+ service.stops.partyGone(addressOf(id3));
152735
+ watches.gone(addressOf(id3));
152736
+ },
151912
152737
  linkedGone: linkedGoneRecorder(service, store2.mailbox),
151913
152738
  // The turn that was cut is the session's latest: the questions delivered in it are the ones it left unanswered
151914
- stopped: (id3, why2, o) => void service.stops.sessionStopped(addressOf(id3), why2, { turnSeq: mailTurns.latest(id3)?.seq ?? null, ...o?.told ? { told: o.told.map(addressOf) } : {}, ...o?.starter ? { starter: addressOf(o.starter) } : {}, ...o?.held ? { held: true } : {} }),
151915
- waitEnded: (id3, why2, starter, end) => service.stops.stopWaitEnded(addressOf(id3), why2, starter ? addressOf(starter) : null, end),
152739
+ stopped: (id3, why2, o) => {
152740
+ void service.stops.sessionStopped(addressOf(id3), why2, { turnSeq: mailTurns.latest(id3)?.seq ?? null, ...o?.told ? { told: o.told.map(addressOf) } : {}, ...o?.starter ? { starter: addressOf(o.starter) } : {}, ...o?.held ? { held: true } : {} });
152741
+ if (!o?.held) watches.changed(addressOf(id3), "stopped");
152742
+ },
152743
+ waitEnded: (id3, why2, starter, end) => {
152744
+ service.stops.stopWaitEnded(addressOf(id3), why2, starter ? addressOf(starter) : null, end);
152745
+ if (!end.continued) watches.changed(addressOf(id3), "stopped");
152746
+ },
151916
152747
  leaving: (inTurn2) => leaveForEarlierBuild(service, store2, inTurn2),
151917
- handOver: (from, to, which, children) => aboutSessions(service.handOver(addressOf(from), addressOf(to), which === "all" ? "all" : { senders: which.senders.map(addressOf) }, children.map(addressOf))),
152748
+ handOver: (from, to, which, children) => {
152749
+ const moveMail = () => service.handOver(addressOf(from), addressOf(to), which === "all" ? "all" : { senders: which.senders.map(addressOf) }, children.map(addressOf));
152750
+ return aboutSessions(which === "all" ? watches.handOver(addressOf(from), addressOf(to), moveMail) : moveMail());
152751
+ },
151918
152752
  handOverPreview: (from, to) => aboutSessions(service.handOverPreview(addressOf(from), addressOf(to))),
151919
152753
  openWork: (id3) => openWork(service, store2, addressOf(id3)),
151920
152754
  sessionChanged: (id3) => delivery.poke(id3),
151921
152755
  waiting: (id3) => service.wakingFor(addressOf(id3)),
151922
152756
  // The person's warning, written as the mailbox writes its own (delivery.ts `warnIfRunning`): one a clock hour for the session, and nothing waits for it
151923
152757
  compactCycles: (id3, count) => service.notice(PERSON, { body: WARNING_TEXT.compactCycles(service.labelOf(addressOf(id3)), count), facts: { compactCycles: { session: addressOf(id3), count } }, dedupeKey: hourlyKey(`compactcycles:${addressOf(id3)}`, now()) }),
151924
- sessionEvent: (e, ended2) => mailTurns.observe(e, ended2),
152758
+ sessionEvent: (e, ended2) => {
152759
+ mailTurns.observe(e, ended2);
152760
+ if ((e.type === "question_request" || e.type === "approval_request") && e.sessionId) watches.changed(addressOf(e.sessionId), "asked", e.requestId);
152761
+ },
151925
152762
  tool: (id3, args, signal) => tool.call(id3, args, signal),
151926
152763
  // Work a session gave another is a task, beside the old path that delivered it (§9.1)
151927
152764
  delegated: delegationRecorder(service, mailTurns),
@@ -151941,20 +152778,25 @@ function hostMail(store2, sessions, opts) {
151941
152778
  answers: (sender) => sender === PERSON || parseAddress(sender)?.kind === "session",
151942
152779
  queued: delivery.queuedFor(addressOf(id3))
151943
152780
  });
151944
- for (const taskId of answered) {
151945
- const owner = records.message(taskId)?.sender ?? "";
151946
- const party = parseAddress(owner);
151947
- const report = records.reportsOn(taskId).at(-1);
151948
- if (party?.kind !== "session" || sessions.canReadMail(party.sessionId) || !report) continue;
151949
- relay(party.sessionId, () => {
151950
- const at2 = now();
151951
- records.markDelivered(owner, [report.id], at2, null);
151952
- records.markRead(owner, [report.id], at2);
151953
- });
152781
+ try {
152782
+ for (const taskId of answered) {
152783
+ const owner = records.message(taskId)?.sender ?? "";
152784
+ const party = parseAddress(owner);
152785
+ const report = records.reportsOn(taskId).at(-1);
152786
+ if (party?.kind !== "session" || sessions.canReadMail(party.sessionId) || !report) continue;
152787
+ relay(party.sessionId, () => {
152788
+ const at2 = now();
152789
+ records.markDelivered(owner, [report.id], at2, null);
152790
+ records.markRead(owner, [report.id], at2);
152791
+ });
152792
+ }
152793
+ } finally {
152794
+ watches.changed(addressOf(id3), "turn_ended");
151954
152795
  }
151955
152796
  },
151956
152797
  requestTurnEnded: requestTurnRecorder(service, mailTurns, addressOf),
151957
152798
  openTasks: (id3, side) => openTaskParties(store2.mailbox, addressOf(id3), side),
152799
+ watchedAtRest: (id3) => watches.waitsForRest(addressOf(id3)),
151958
152800
  // A card a session raised is told to the givers of its open work, and answered by one of them only as the gate allows (§10.6.4)
151959
152801
  cards: {
151960
152802
  // Only a turn the giver's own work started, as the turn owner was: one the mailbox started for its task (the session was busy) is told only
@@ -151978,6 +152820,7 @@ function hostMail(store2, sessions, opts) {
151978
152820
  reach,
151979
152821
  turns: mailTurns,
151980
152822
  delivery,
152823
+ watches,
151981
152824
  tool,
151982
152825
  hooks,
151983
152826
  afterReady: () => {
@@ -151987,7 +152830,11 @@ function hostMail(store2, sessions, opts) {
151987
152830
  console.error(`[mail] taking back the notices of ended cards failed: ${errorMessage(e)}`);
151988
152831
  }
151989
152832
  try {
151990
- const moved = store2.movePendingThreadMail(now(), (address) => reach.projectOf(address));
152833
+ const moved = store2.movePendingThreadMail(
152834
+ now(),
152835
+ (address) => reach.projectOf(address),
152836
+ (m, recipient) => reach.holdFor(m, recipient) !== null
152837
+ );
151991
152838
  if (moved.messages > 0) console.error(`[mail] moved ${moved.messages} pending message(s) an older build left in its threads`);
151992
152839
  } catch (e) {
151993
152840
  console.error(`[mail] moving the thread mail an older build left pending failed: ${errorMessage(e)}`);
@@ -152739,7 +153586,7 @@ var toInfo = (h) => ({
152739
153586
  history: h.history(),
152740
153587
  alive: h.alive
152741
153588
  });
152742
- function createRpcHandler(mgr2, adapters2, { settleDeletedProjects, deleteOutlook, terminals: terminals2, updates: updates2, commands, externalApps: externalApps2, views: views2, inlineViews: inlineViews2, themes: themes2, agentVersions: agentVersions2, sleeper: sleeper2, machines, stopHost, stopGate, handover: handover2, systemEnding: systemEnding2, activity: activity2, updateApply: updateApply2, hubs: hubs2, mailAcross, mail, requests: requests2, serveCredentials } = {}) {
153589
+ function createRpcHandler(mgr2, adapters2, { settleDeletedProjects, deleteOutlook, terminals: terminals2, updates: updates2, commands, externalApps: externalApps2, views: views2, inlineViews: inlineViews2, themes: themes2, agentVersions: agentVersions2, sleeper: sleeper2, machines, stopHost, stopGate, handover: handover2, systemEnding: systemEnding2, activity: activity2, updateApply: updateApply2, hubs: hubs2, mailAcross, mail, watches, requests: requests2, serveCredentials } = {}) {
152743
153590
  const reportUiCrash = createUiCrashLog((line) => console.error(line));
152744
153591
  const sessionToolSchemas = (sessionId) => {
152745
153592
  if (!sessionId) return centraluToolSchemas("assistant");
@@ -152820,6 +153667,9 @@ function createRpcHandler(mgr2, adapters2, { settleDeletedProjects, deleteOutloo
152820
153667
  requireMail().wake(RpcMethods["mail.wake"].params.parse(p).wake);
152821
153668
  return { ok: true };
152822
153669
  },
153670
+ // A host without watches (a test's) lists none and cancels nothing
153671
+ "watches.list": async (p) => ({ watches: watches?.views(RpcMethods["watches.list"].params.parse(p).sessionId) ?? [] }),
153672
+ "watches.cancel": async (p) => ({ cancelled: (watches?.cancel(RpcMethods["watches.cancel"].params.parse(p).id, "person") ?? "ended") !== "ended" }),
152823
153673
  "apps.inlineViews": async (p) => inlineViews2?.list(RpcMethods["apps.inlineViews"].params.parse(p).sessionId) ?? [],
152824
153674
  "apps.importPrepare": async (p) => requireExternalApps().prepareImport(RpcMethods["apps.importPrepare"].params.parse(p).source),
152825
153675
  "apps.importCancel": async (p) => {
@@ -157546,7 +158396,7 @@ function parseAutostartLine(stdout) {
157546
158396
  }
157547
158397
  return null;
157548
158398
  }
157549
- var FAILED = {
158399
+ var FAILED2 = {
157550
158400
  on: "could not be set to start at boot",
157551
158401
  off: "could not stop starting at boot",
157552
158402
  remove: "could not remove its start at boot",
@@ -157564,7 +158414,7 @@ async function autostartRemote(c, action) {
157564
158414
  const why2 = lastLine(r.stderr);
157565
158415
  throw new Error(`Centralu on ${c.target} gave no answer about starting at boot${why2 ? `: ${why2}` : r.code ? ` (exit ${r.code})` : ""}`);
157566
158416
  }
157567
- if (!answer.ok) throw new Error(`Centralu on ${c.target} ${FAILED[action]}: ${answer.message ?? "no reason given"}`);
158417
+ if (!answer.ok) throw new Error(`Centralu on ${c.target} ${FAILED2[action]}: ${answer.message ?? "no reason given"}`);
157568
158418
  return answer.state;
157569
158419
  }
157570
158420
  async function removeAutostart(c) {
@@ -161185,6 +162035,9 @@ var ROUTES = {
161185
162035
  "mail.held": HUB,
161186
162036
  "mail.resume": HUB,
161187
162037
  "mail.wake": HUB,
162038
+ // A watch lives on its owner's host (docs/plans/mailbox.md §18.6): the window lists the watches of the host it talks to
162039
+ "watches.list": HUB,
162040
+ "watches.cancel": HUB,
161188
162041
  "grid.get": HUB,
161189
162042
  "grid.set": HUB,
161190
162043
  "prefs.get": HUB,
@@ -162166,7 +163019,7 @@ var handedToken = launch.tokenOnStdin ? await readHandedToken(process.stdin).cat
162166
163019
  console.error(`[agent-host] the launcher did not hand over the token: ${e.message}`);
162167
163020
  process.exit(1);
162168
163021
  }) : launch.token;
162169
- var BUILD = true ? "d0e7c4b" : "dev";
163022
+ var BUILD = true ? "b37235c" : "dev";
162170
163023
  var { values } = parseArgs({
162171
163024
  options: {
162172
163025
  port: { type: "string", default: "5175" },
@@ -162352,6 +163205,7 @@ var mailPerson = new MailPerson(hostMailbox.service, store.mailbox, mailDelivery
162352
163205
  tell: (id3, text3) => mgr.mail.tellMailNow(id3, text3)
162353
163206
  });
162354
163207
  hostMailbox.service.onChange((c) => events.push(mailPerson.changeEvent(c)));
163208
+ hostMailbox.watches.onChange((sessionId) => events.push({ type: "watches_changed", sessionId }));
162355
163209
  var terminals = new TerminalService(screens.push, ptyBroker ? brokerPtyModule(ptyBroker) : void 0);
162356
163210
  var commandRuns = new CommandRunner(screens.push);
162357
163211
  restartEnded(mgr.tenure.takeUpdateEnded(), {
@@ -162582,6 +163436,7 @@ var router = new Router({
162582
163436
  hubs,
162583
163437
  mailAcross: hostMailbox.across,
162584
163438
  mail: mailPerson,
163439
+ watches: hostMailbox.watches,
162585
163440
  requests
162586
163441
  }),
162587
163442
  machines: () => links.all(),