@centralu/host-win32-x64 0.1.0-beta.66 → 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.66";
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 {
@@ -137477,8 +137589,8 @@ function newestVersion(names) {
137477
137589
  const key = (n) => {
137478
137590
  const m = VERSION.exec(n);
137479
137591
  if (!m) return null;
137480
- const pad = (s) => (s ?? "00").padStart(2, "0");
137481
- 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])}`;
137482
137594
  };
137483
137595
  const dated = names.flatMap((n) => {
137484
137596
  const k2 = key(n);
@@ -143699,6 +143811,41 @@ var StepsV65 = class extends MigrationRange {
143699
143811
  AND s.project_id IS NOT m.sender_project))`
143700
143812
  );
143701
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
+ }
143702
143849
  }
143703
143850
  ];
143704
143851
  }
@@ -144880,8 +145027,38 @@ function noteGhFailure(branch, e) {
144880
145027
  console.error(`[git] gh could not read the pull request of ${branch}: ${why2}`);
144881
145028
  }
144882
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) {
144883
145060
  try {
144884
- 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(",")], {
144885
145062
  cwd: projectCwd,
144886
145063
  timeoutMs,
144887
145064
  maxBuffer: OK2.maxBuffer,
@@ -144892,25 +145069,20 @@ async function gitBranchPr(projectCwd, branch, signal, timeoutMs = OK2.timeout)
144892
145069
  });
144893
145070
  if (run2.ended) return null;
144894
145071
  if (run2.code !== 0) {
144895
- noteGhFailure(branch, { stderr: run2.stderr.toString("utf8").slice(-GH_STDERR_KEEP) });
144896
- 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;
144897
145075
  }
144898
145076
  const j2 = JSON.parse(run2.stdout.toString("utf8"));
144899
- if (!isObj(j2)) return null;
144900
- if (typeof j2.number !== "number" || typeof j2.state !== "string" || typeof j2.url !== "string") return null;
144901
- return {
144902
- number: j2.number,
144903
- state: j2.state === "MERGED" ? "merged" : j2.state === "CLOSED" ? "closed" : "open",
144904
- url: j2.url,
144905
- ...typeof j2.headRefOid === "string" && j2.headRefOid ? { headOid: j2.headRefOid } : {}
144906
- };
145077
+ return isObj(j2) ? j2 : null;
144907
145078
  } catch (e) {
144908
145079
  const failure4 = execFailure(e);
144909
145080
  if (failure4.code === "ENOENT") return "unavailable";
144910
- noteGhFailure(branch, failure4);
145081
+ noteGhFailure(ref, failure4);
144911
145082
  return null;
144912
145083
  }
144913
145084
  }
145085
+ var SIGNED_OUT = /gh auth login|not logged in/i;
144914
145086
 
144915
145087
  // packages/agent-host/src/dev-services/file-search.ts
144916
145088
  import { readdir as readdir13 } from "node:fs/promises";
@@ -148614,6 +148786,7 @@ var SessionManager = class {
148614
148786
  mailStopped: (id3, why2, o) => self2.mail.mailStopped(id3, why2, o),
148615
148787
  mailRequestTurnEnded: (id3) => self2.mail.mailRequestTurnEnded(id3),
148616
148788
  mailLastResponse: (id3, last) => self2.mail.mailLastResponse(id3, last),
148789
+ mailWatchedAtRest: (id3) => self2.mail.mailWatchedAtRest(id3),
148617
148790
  mailTurnInputs: (id3, turn) => self2.mail.mailTurnInputs(id3, turn),
148618
148791
  mailEvent: (e, ended2) => {
148619
148792
  try {
@@ -149815,7 +149988,7 @@ var MessageService = class {
149815
149988
  row,
149816
149989
  message,
149817
149990
  request,
149818
- 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 })
149819
149992
  });
149820
149993
  }
149821
149994
  const wakesIt = (c) => wakesMessage(c.message);
@@ -150778,12 +150951,494 @@ function tellCard(service, giver, card, body, delivered) {
150778
150951
  }
150779
150952
  function withdrawEndedCards(records, session2, stands2) {
150780
150953
  records.transaction(() => {
150781
- 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));
150782
150955
  if (gone2.length) records.deleteRows(gone2.map(({ row }) => ({ messageId: row.messageId, recipient: row.recipient })));
150783
150956
  });
150784
150957
  }
150785
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
+
150786
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
+ };
150787
151442
  var MailTool = class {
150788
151443
  constructor(service, records, reach, host) {
150789
151444
  this.service = service;
@@ -150816,6 +151471,11 @@ var MailTool = class {
150816
151471
  const across = this.host.across;
150817
151472
  if (!me2) return this.run(sessionId, args);
150818
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
+ }
150819
151479
  if (args.action === "find") {
150820
151480
  if (!across) return { text: "Finding sessions is not available here.", isError: true };
150821
151481
  return { text: await across.find((args.to ?? args.text ?? "").trim(), me2.address) };
@@ -150921,14 +151581,35 @@ var MailTool = class {
150921
151581
  }
150922
151582
  case "find":
150923
151583
  throw refuse4("bad_value", "find searches other computers too, which this call does not reach");
150924
- case "update":
150925
- 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);
150926
151590
  throw refuse4(
150927
151591
  "removed",
150928
- `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>")}.`
150929
151593
  );
151594
+ }
150930
151595
  }
150931
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
+ }
150932
151613
  need(value, name) {
150933
151614
  if (!value?.trim()) throw new Error(`${name} is needed for this action`);
150934
151615
  return value.trim();
@@ -151019,14 +151700,17 @@ var MailTool = class {
151019
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 */
151020
151701
  inbox(me2, calls) {
151021
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}` : ""}`) : [];
151022
151705
  const total = v.needReply.length + v.unread.length + v.waiting.length + v.held.length;
151023
- if (total === 0) return "Your mailbox is empty.";
151706
+ if (total === 0) return ["Your mailbox is empty.", ...watching].join("\n");
151024
151707
  const lines = [
151025
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()}.`,
151026
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" : ""}`),
151027
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)" : ""}`),
151028
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"}`),
151029
- ...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
151030
151714
  ];
151031
151715
  return lines.join("\n");
151032
151716
  }
@@ -151963,7 +152647,37 @@ function hostMail(store2, sessions, opts) {
151963
152647
  service.onChange((c) => {
151964
152648
  if (c.recipients.some((r) => across.foreign(r))) void across.passOn(c.messageId);
151965
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
+ });
151966
152679
  const delivery = new MailDelivery(service, records, sessions.mailSessions(), {
152680
+ watches,
151967
152681
  turns: mailTurns,
151968
152682
  ...opts.now ? { now: opts.now } : {},
151969
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
@@ -152006,6 +152720,7 @@ function hostMail(store2, sessions, opts) {
152006
152720
  askerOf: (id3) => askerFacts(askedByHost, id3),
152007
152721
  legacyChain: (threadId, messageId, reader) => store2.legacyChainFor(threadId, messageId, reader, 9),
152008
152722
  across,
152723
+ watches,
152009
152724
  ...sessions.work ? { work: sessions.work } : {}
152010
152725
  });
152011
152726
  const cardStands = (session2, requestId) => {
@@ -152015,20 +152730,35 @@ function hostMail(store2, sessions, opts) {
152015
152730
  };
152016
152731
  const hooks = {
152017
152732
  askedBy: (id3) => askedBy(askedByHost, id3),
152018
- sessionGone: (id3) => service.stops.partyGone(addressOf(id3)),
152733
+ sessionGone: (id3) => {
152734
+ service.stops.partyGone(addressOf(id3));
152735
+ watches.gone(addressOf(id3));
152736
+ },
152019
152737
  linkedGone: linkedGoneRecorder(service, store2.mailbox),
152020
152738
  // The turn that was cut is the session's latest: the questions delivered in it are the ones it left unanswered
152021
- 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 } : {} }),
152022
- 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
+ },
152023
152747
  leaving: (inTurn2) => leaveForEarlierBuild(service, store2, inTurn2),
152024
- 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
+ },
152025
152752
  handOverPreview: (from, to) => aboutSessions(service.handOverPreview(addressOf(from), addressOf(to))),
152026
152753
  openWork: (id3) => openWork(service, store2, addressOf(id3)),
152027
152754
  sessionChanged: (id3) => delivery.poke(id3),
152028
152755
  waiting: (id3) => service.wakingFor(addressOf(id3)),
152029
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
152030
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()) }),
152031
- 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
+ },
152032
152762
  tool: (id3, args, signal) => tool.call(id3, args, signal),
152033
152763
  // Work a session gave another is a task, beside the old path that delivered it (§9.1)
152034
152764
  delegated: delegationRecorder(service, mailTurns),
@@ -152048,20 +152778,25 @@ function hostMail(store2, sessions, opts) {
152048
152778
  answers: (sender) => sender === PERSON || parseAddress(sender)?.kind === "session",
152049
152779
  queued: delivery.queuedFor(addressOf(id3))
152050
152780
  });
152051
- for (const taskId of answered) {
152052
- const owner = records.message(taskId)?.sender ?? "";
152053
- const party = parseAddress(owner);
152054
- const report = records.reportsOn(taskId).at(-1);
152055
- if (party?.kind !== "session" || sessions.canReadMail(party.sessionId) || !report) continue;
152056
- relay(party.sessionId, () => {
152057
- const at2 = now();
152058
- records.markDelivered(owner, [report.id], at2, null);
152059
- records.markRead(owner, [report.id], at2);
152060
- });
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");
152061
152795
  }
152062
152796
  },
152063
152797
  requestTurnEnded: requestTurnRecorder(service, mailTurns, addressOf),
152064
152798
  openTasks: (id3, side) => openTaskParties(store2.mailbox, addressOf(id3), side),
152799
+ watchedAtRest: (id3) => watches.waitsForRest(addressOf(id3)),
152065
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)
152066
152801
  cards: {
152067
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
@@ -152085,6 +152820,7 @@ function hostMail(store2, sessions, opts) {
152085
152820
  reach,
152086
152821
  turns: mailTurns,
152087
152822
  delivery,
152823
+ watches,
152088
152824
  tool,
152089
152825
  hooks,
152090
152826
  afterReady: () => {
@@ -152850,7 +153586,7 @@ var toInfo = (h) => ({
152850
153586
  history: h.history(),
152851
153587
  alive: h.alive
152852
153588
  });
152853
- 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 } = {}) {
152854
153590
  const reportUiCrash = createUiCrashLog((line) => console.error(line));
152855
153591
  const sessionToolSchemas = (sessionId) => {
152856
153592
  if (!sessionId) return centraluToolSchemas("assistant");
@@ -152931,6 +153667,9 @@ function createRpcHandler(mgr2, adapters2, { settleDeletedProjects, deleteOutloo
152931
153667
  requireMail().wake(RpcMethods["mail.wake"].params.parse(p).wake);
152932
153668
  return { ok: true };
152933
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" }),
152934
153673
  "apps.inlineViews": async (p) => inlineViews2?.list(RpcMethods["apps.inlineViews"].params.parse(p).sessionId) ?? [],
152935
153674
  "apps.importPrepare": async (p) => requireExternalApps().prepareImport(RpcMethods["apps.importPrepare"].params.parse(p).source),
152936
153675
  "apps.importCancel": async (p) => {
@@ -157657,7 +158396,7 @@ function parseAutostartLine(stdout) {
157657
158396
  }
157658
158397
  return null;
157659
158398
  }
157660
- var FAILED = {
158399
+ var FAILED2 = {
157661
158400
  on: "could not be set to start at boot",
157662
158401
  off: "could not stop starting at boot",
157663
158402
  remove: "could not remove its start at boot",
@@ -157675,7 +158414,7 @@ async function autostartRemote(c, action) {
157675
158414
  const why2 = lastLine(r.stderr);
157676
158415
  throw new Error(`Centralu on ${c.target} gave no answer about starting at boot${why2 ? `: ${why2}` : r.code ? ` (exit ${r.code})` : ""}`);
157677
158416
  }
157678
- 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"}`);
157679
158418
  return answer.state;
157680
158419
  }
157681
158420
  async function removeAutostart(c) {
@@ -161296,6 +162035,9 @@ var ROUTES = {
161296
162035
  "mail.held": HUB,
161297
162036
  "mail.resume": HUB,
161298
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,
161299
162041
  "grid.get": HUB,
161300
162042
  "grid.set": HUB,
161301
162043
  "prefs.get": HUB,
@@ -162277,7 +163019,7 @@ var handedToken = launch.tokenOnStdin ? await readHandedToken(process.stdin).cat
162277
163019
  console.error(`[agent-host] the launcher did not hand over the token: ${e.message}`);
162278
163020
  process.exit(1);
162279
163021
  }) : launch.token;
162280
- var BUILD = true ? "617c696" : "dev";
163022
+ var BUILD = true ? "b37235c" : "dev";
162281
163023
  var { values } = parseArgs({
162282
163024
  options: {
162283
163025
  port: { type: "string", default: "5175" },
@@ -162463,6 +163205,7 @@ var mailPerson = new MailPerson(hostMailbox.service, store.mailbox, mailDelivery
162463
163205
  tell: (id3, text3) => mgr.mail.tellMailNow(id3, text3)
162464
163206
  });
162465
163207
  hostMailbox.service.onChange((c) => events.push(mailPerson.changeEvent(c)));
163208
+ hostMailbox.watches.onChange((sessionId) => events.push({ type: "watches_changed", sessionId }));
162466
163209
  var terminals = new TerminalService(screens.push, ptyBroker ? brokerPtyModule(ptyBroker) : void 0);
162467
163210
  var commandRuns = new CommandRunner(screens.push);
162468
163211
  restartEnded(mgr.tenure.takeUpdateEnded(), {
@@ -162693,6 +163436,7 @@ var router = new Router({
162693
163436
  hubs,
162694
163437
  mailAcross: hostMailbox.across,
162695
163438
  mail: mailPerson,
163439
+ watches: hostMailbox.watches,
162696
163440
  requests
162697
163441
  }),
162698
163442
  machines: () => links.all(),