spur-board 0.78.0 → 0.80.0

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/dist/daemon.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as err, A as prSourceId, B as prFactsSchema, C as userIdSchema, D as AdapterError, E as eventPayloadSchemas, F as REVIEW_STATES, G as JIRA_PROJECT_KEY, H as ringMarker, I as SESSION_HEALTH_STATES, J as encodeActorId, K as REF_NUMBER, L as SESSION_STATUSES, M as sourceCursorSchema, N as trackerSourceId, O as batchSchema, P as PR_STATES, Q as ERRORS, R as isExternalAuthor, S as messageRefSchema, St as VIAS, T as GATE_REASONS, U as sessionFactsSchema, V as prRefSchema, W as ticketFactsSchema, X as parseActorId, Y as errorCodeOf, Z as parseRef$1, _t as COLUMN_IDS, a as requestHashOf, at as DEFAULT_LINK, b as inboundEventSchema, bt as SLACK_BOT_SCOPES, c as tokenRequestStatusSchema, d as buildCatalogSnapshot, dt as configBindings, f as roleCanUseOperation, ft as configSchema, gt as resolveWebOrigin, h as renderHttpProblem, ht as requiredSecretKeys, i as TOKEN_REQUEST_LIMITS, j as sessionTransitionSchema, k as entityRefSchema, l as BOARD_TICK_MS, lt as RESERVED_PROJECT, m as turnHandedSchema, mt as plainHttpAllowed, n as doctorReportSchema, nt as ok, o as tokenRequestResultSchema, p as OPERATIONS, pt as defaultAddressee, q as actorIdSchema, rt as successEnvelopeSchema, s as tokenRequestSchema, st as DEFAULT_SLACK_COMMAND, t as assertNever, ut as boardWideSpurProject, v as SPACE_IDS, vt as DISPATCHER_MODES, w as EVENT_KINDS, x as interactionRefSchema, xt as TASK_HOLDS, y as conversationRefSchema, yt as ITEM_KINDS, z as parseRingMarker } from "./chunk-7XUx0JWq.mjs";
1
+ import { $ as err, A as prSourceId, B as prFactsSchema, C as userIdSchema, D as AdapterError, E as eventPayloadSchemas, F as REVIEW_STATES, G as JIRA_PROJECT_KEY, H as ringMarker, I as SESSION_HEALTH_STATES, J as encodeActorId, K as REF_NUMBER, L as SESSION_STATUSES, M as sourceCursorSchema, N as trackerSourceId, O as batchSchema, P as PR_STATES, Q as ERRORS, R as isExternalAuthor, S as messageRefSchema, St as VIAS, T as GATE_REASONS, U as sessionFactsSchema, V as prRefSchema, W as ticketFactsSchema, X as parseActorId, Y as errorCodeOf, Z as parseRef$1, _t as COLUMN_IDS, a as requestHashOf, at as DEFAULT_LINK, b as inboundEventSchema, bt as SLACK_BOT_SCOPES, c as tokenRequestStatusSchema, d as buildCatalogSnapshot, dt as configBindings, f as roleCanUseOperation, ft as configSchema, gt as resolveWebOrigin, h as renderHttpProblem, ht as requiredSecretKeys, i as TOKEN_REQUEST_LIMITS, j as sessionTransitionSchema, k as entityRefSchema, l as BOARD_TICK_MS, lt as RESERVED_PROJECT, m as turnHandedSchema, mt as plainHttpAllowed, n as doctorReportSchema, nt as ok, o as tokenRequestResultSchema, p as OPERATIONS, pt as defaultAddressee, q as actorIdSchema, rt as successEnvelopeSchema, s as tokenRequestSchema, st as DEFAULT_SLACK_COMMAND, t as assertNever, ut as boardWideSpurProject, v as SPACE_IDS, vt as DISPATCHER_MODES, w as EVENT_KINDS, x as interactionRefSchema, xt as TASK_HOLDS, y as conversationRefSchema, yt as ITEM_KINDS, z as parseRingMarker } from "./chunk-BN-Cz4Ql.mjs";
2
2
  import { t as apiBaseUrl } from "./chunk-DAMwWWmT.mjs";
3
3
  import { createRequire } from "node:module";
4
4
  import { createHash, randomUUID } from "node:crypto";
@@ -15,6 +15,7 @@ import { Kysely, SqliteDialect, sql } from "kysely";
15
15
  import { AsyncLocalStorage } from "node:async_hooks";
16
16
  import perf_hooks from "node:perf_hooks";
17
17
  import Fastify from "fastify";
18
+ import { PassThrough } from "node:stream";
18
19
  import { pino } from "pino";
19
20
  import { WebAPIHTTPError, WebAPIPlatformError, WebAPIRateLimitedError, WebClient } from "@slack/web-api";
20
21
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
@@ -11235,7 +11236,7 @@ async function createApiServer(options) {
11235
11236
  });
11236
11237
  const snapshot = await buildCatalogSnapshot(OPERATIONS);
11237
11238
  /** Lets clients notice a daemon restart and check its catalog again. */
11238
- const instance = randomUUID();
11239
+ const instance = options.instance ?? randomUUID();
11239
11240
  const callers = /* @__PURE__ */ new WeakMap();
11240
11241
  let doctorInFlight = null;
11241
11242
  let doctorCached = null;
@@ -14284,7 +14285,7 @@ async function readStatusTurns(db, projectIds) {
14284
14285
  "turn.created_at",
14285
14286
  "turn.acked_by",
14286
14287
  "turn.acked_at"
14287
- ]).select(["task.key as task_key", "notification.recipient_session"]).where("turn.closed_at", "is", null).where("task.membership", "!=", "archived").where("task.project", "in", [...projectIds]).execute();
14288
+ ]).select(["task.key as task_key", "notification.recipient_session"]).select((eb) => eb.selectFrom("operator_item").select((eb) => eb.fn.min("operator_item.fact_at").as("fact_at")).where("operator_item.cleared_at", "is", null).where("operator_item.item_key", ">=", sql`'turn-stall:' || ${sql.ref("turn.id")} || ':'`).where("operator_item.item_key", "<", sql`'turn-stall:' || ${sql.ref("turn.id")} || ';'`).as("stalled_since")).where("turn.closed_at", "is", null).where("task.membership", "!=", "archived").where("task.project", "in", [...projectIds]).execute();
14288
14289
  return new Map(turnRows.map((turn) => [turn.task_id, {
14289
14290
  id: `T${String(turn.id)}`,
14290
14291
  task: turn.task_key,
@@ -14297,9 +14298,65 @@ async function readStatusTurns(db, projectIds) {
14297
14298
  by: turn.acked_by,
14298
14299
  at: turn.acked_at
14299
14300
  },
14300
- addressedTo: turn.acked_at === null ? turn.recipient_session : null
14301
+ addressedTo: turn.acked_at === null ? turn.recipient_session : null,
14302
+ stalledSince: turn.stalled_since
14301
14303
  }]));
14302
14304
  }
14305
+ /**
14306
+ * Load the return marker of each visible Dev task once for the page: set while the newest column
14307
+ * change of the task (a move, a non-shadow correction, a submit or an add) is the `task.return`
14308
+ * move into Dev, which journals its turn and block.
14309
+ */
14310
+ async function readStatusReturns(db, projectIds) {
14311
+ const rows = await db.selectFrom("task").innerJoin("event", (join) => join.onRef("event.task_id", "=", "task.id").on("event.id", "=", (eb) => eb.selectFrom("event as newest").select("newest.id").whereRef("newest.task_id", "=", "task.id").where((eb) => eb.or([eb("newest.kind", "in", [
14312
+ "task_moved",
14313
+ "task_submitted",
14314
+ "task_added"
14315
+ ]), eb.and([eb("newest.kind", "=", "task_corrected"), eb(sql`coalesce(json_extract(newest.payload, '$.shadow'), 0)`, "=", 0)])])).orderBy("newest.id", "desc").limit(1))).select([
14316
+ "task.id as task_id",
14317
+ "event.at",
14318
+ "event.actor",
14319
+ "event.actor_ref",
14320
+ "event.payload"
14321
+ ]).where("task.column", "=", "dev").where("task.membership", "!=", "archived").where("task.project", "in", [...projectIds]).where("event.kind", "=", "task_moved").execute();
14322
+ const returns = /* @__PURE__ */ new Map();
14323
+ for (const row of rows) {
14324
+ const parsed = eventPayloadSchemas.task_moved.safeParse(JSON.parse(row.payload));
14325
+ if (!parsed.success) continue;
14326
+ const { from, to, turn, block, findings } = parsed.data;
14327
+ if (turn === void 0 || block === void 0 || to !== "dev") continue;
14328
+ returns.set(row.task_id, {
14329
+ from,
14330
+ at: row.at,
14331
+ by: eventActor(row),
14332
+ block,
14333
+ findings: findings ?? null
14334
+ });
14335
+ }
14336
+ return returns;
14337
+ }
14338
+ /**
14339
+ * Load the open blocks of visible tasks once for the page, oldest first, each with the session
14340
+ * the newest block notification for its current addressee role went to.
14341
+ */
14342
+ async function readStatusBlocks(db, projectIds) {
14343
+ const rows = await db.selectFrom("block").innerJoin("task", "task.id", "block.task_id").leftJoin("notification", (join) => join.onRef("notification.block_id", "=", "block.id").on("notification.kind", "=", "block").onRef("notification.role", "=", "block.addressee_role").on("notification.id", "=", (eb) => eb.selectFrom("notification as newest").select((eb) => eb.fn.max("newest.id").as("id")).whereRef("newest.block_id", "=", "block.id").where("newest.kind", "=", "block").whereRef("newest.role", "=", "block.addressee_role"))).select([
14344
+ "block.id",
14345
+ "task.id as task_id",
14346
+ "block.addressee_role"
14347
+ ]).select("notification.recipient_session").where("block.state", "=", "open").where("task.membership", "!=", "archived").where("task.project", "in", [...projectIds]).orderBy("block.id").execute();
14348
+ const blocks = /* @__PURE__ */ new Map();
14349
+ for (const row of rows) {
14350
+ const list = blocks.get(row.task_id) ?? [];
14351
+ list.push({
14352
+ id: `B${String(row.id)}`,
14353
+ addressee: row.addressee_role,
14354
+ session: row.addressee_role === "operator" ? null : row.recipient_session
14355
+ });
14356
+ blocks.set(row.task_id, list);
14357
+ }
14358
+ return blocks;
14359
+ }
14303
14360
  //#endregion
14304
14361
  //#region ../core/src/app/status.ts
14305
14362
  function sessionView(fact) {
@@ -14362,6 +14419,11 @@ function interval(config, source) {
14362
14419
  /** Reads the board's latest facts, items and source availability. */
14363
14420
  async function getStatus(deps, options = {}) {
14364
14421
  const { store, config, clock, completeSince, gateways = [] } = deps;
14422
+ const daemon = deps.daemon ?? {
14423
+ version: "unknown",
14424
+ startedAt: new Date(clock.now()).toISOString(),
14425
+ lastDispatchAt: null
14426
+ };
14365
14427
  const { project: projectId, visibleProjects, detail = false } = options;
14366
14428
  const includeBoardItems = options.includeBoardItems ?? visibleProjects === void 0;
14367
14429
  const operatorProjects = options.operatorProjects ?? /* @__PURE__ */ new Set();
@@ -14369,8 +14431,7 @@ async function getStatus(deps, options = {}) {
14369
14431
  if (projects.length === 0) throw new CommandError("not_found", "Check the project ID.");
14370
14432
  const projectIds = new Set(projects.map((project) => project.id));
14371
14433
  const rows = await store.db.selectFrom("task").selectAll().where("membership", "!=", "archived").execute();
14372
- const blockRows = await store.db.selectFrom("block").select(["task_id", (eb) => eb.fn.countAll().as("open")]).where("state", "=", "open").groupBy("task_id").execute();
14373
- const openBlocks = new Map(blockRows.map((row) => [row.task_id, row.open]));
14434
+ const openBlocks = await readStatusBlocks(store.db, projectIds);
14374
14435
  const projectBlockRows = await store.db.selectFrom("block").select(["project", (eb) => eb.fn.countAll().as("open")]).where("state", "=", "open").where("task_id", "is", null).groupBy("project").execute();
14375
14436
  const openProjectBlocks = new Map(projectBlockRows.map((row) => [row.project, row.open]));
14376
14437
  const projectBlocks = projects.map((project) => ({
@@ -14380,6 +14441,7 @@ async function getStatus(deps, options = {}) {
14380
14441
  const sourceRows = await store.db.selectFrom("source_state").selectAll().execute();
14381
14442
  const sourceById = new Map(sourceRows.map((row) => [row.source, row]));
14382
14443
  const turns = await readStatusTurns(store.db, projectIds);
14444
+ const returns = await readStatusReturns(store.db, projectIds);
14383
14445
  const tasks = [];
14384
14446
  for (const task of rows) {
14385
14447
  if (!projectIds.has(task.project)) continue;
@@ -14427,6 +14489,8 @@ async function getStatus(deps, options = {}) {
14427
14489
  if (parseJson(prFactsSchema, snapshot.detail).ticketKeys.some((key) => key.toLowerCase() === task.key.toLowerCase())) continue;
14428
14490
  linkHints.push(`Session ${session.id} has PR ${pr.repo}#${String(pr.number)}, but the link rules give it no link to this task; check projects[].link in config.yaml.`);
14429
14491
  }
14492
+ const blocks = openBlocks.get(task.id) ?? [];
14493
+ const returned = returns.get(task.id);
14430
14494
  tasks.push({
14431
14495
  key: task.key,
14432
14496
  project: task.project,
@@ -14439,7 +14503,9 @@ async function getStatus(deps, options = {}) {
14439
14503
  state: taskState(ticketFacts, prs, sessionStates),
14440
14504
  prCount: links.filter((link) => link.entity === "pr").length,
14441
14505
  sessionCount: links.filter((link) => link.entity === "session").length,
14442
- openBlocks: openBlocks.get(task.id) ?? 0,
14506
+ openBlocks: blocks.length,
14507
+ blocks,
14508
+ ...returned === void 0 ? {} : { returned },
14443
14509
  turn: turns.get(task.id) ?? null,
14444
14510
  prSummary: summaries.length === 0 ? null : summaries,
14445
14511
  links: {
@@ -14598,7 +14664,8 @@ async function getStatus(deps, options = {}) {
14598
14664
  unlinkedSessions,
14599
14665
  hiddenUnlinkedPrs: prRows.length - unlinkedPrs.length,
14600
14666
  hiddenUnlinkedSessions: sessionRows.length - unlinkedSessions.length,
14601
- bindings: configBindings(config, projectIds)
14667
+ bindings: configBindings(config, projectIds),
14668
+ daemon
14602
14669
  };
14603
14670
  }
14604
14671
  const HOLD_ONLY = /* @__PURE__ */ new Set([
@@ -15973,7 +16040,7 @@ async function voidSubmits(trx, taskId, to, at) {
15973
16040
  * `limitReached` tells the dispatcher to stop the cascade.
15974
16041
  */
15975
16042
  async function moveLeft(trx, input) {
15976
- const { task, to, at, actor, config, turn, block, reason, gate } = input;
16043
+ const { task, to, at, actor, config, turn, block, reason, gate, findings } = input;
15977
16044
  const moved = await trx.updateTable("task").set({
15978
16045
  column: to,
15979
16046
  column_epoch: task.column_epoch + 1,
@@ -15992,7 +16059,8 @@ async function moveLeft(trx, input) {
15992
16059
  ...turn === void 0 ? {} : { turn },
15993
16060
  ...block === void 0 ? {} : { block },
15994
16061
  ...reason === void 0 ? {} : { reason },
15995
- ...gate === void 0 ? {} : { gate: [...gate] }
16062
+ ...gate === void 0 ? {} : { gate: [...gate] },
16063
+ ...findings === void 0 ? {} : { findings }
15996
16064
  }, actor);
15997
16065
  const project = config.projects.find((entry) => entry.id === task.project);
15998
16066
  const column = project?.columns.find((entry) => entry.id === task.column);
@@ -17402,7 +17470,8 @@ function createTurnMutations(deps) {
17402
17470
  actor: ctx.actor,
17403
17471
  config,
17404
17472
  turn: turnLabel(turn.id),
17405
- block: `B${String(block.id)}`
17473
+ block: `B${String(block.id)}`,
17474
+ findings: input.findings
17406
17475
  });
17407
17476
  const moved = await dispatched(trx, task.id, ctx.at, ctx.actor);
17408
17477
  return {
@@ -17452,6 +17521,10 @@ const catalog = await buildCatalogSnapshot(OPERATIONS);
17452
17521
  /** Concrete handlers shared by the daemon's HTTP and inbound transports. */
17453
17522
  function createOperationRegistry(deps) {
17454
17523
  const { config, clock, completeSince, gateways } = deps;
17524
+ const startedAt = new Date(clock.now()).toISOString();
17525
+ const productVersion = deps.productVersion ?? "unknown";
17526
+ const lastDispatchAt = deps.lastDispatchAt ?? (() => null);
17527
+ const webOrigin = deps.webOrigin ?? (() => config.web.port === 0 ? void 0 : resolveWebOrigin(config.web));
17455
17528
  const items = createItemMutations(deps);
17456
17529
  const membership = createMembershipMutations(config);
17457
17530
  const links = createLinkMutations(config, { prPoller: deps.prPoller });
@@ -17510,7 +17583,12 @@ function createOperationRegistry(deps) {
17510
17583
  config,
17511
17584
  clock,
17512
17585
  completeSince,
17513
- gateways
17586
+ gateways,
17587
+ daemon: {
17588
+ version: productVersion,
17589
+ startedAt,
17590
+ lastDispatchAt: lastDispatchAt()
17591
+ }
17514
17592
  }, {
17515
17593
  project: input.project,
17516
17594
  visibleProjects: visibleProjects(config, actor),
@@ -17533,25 +17611,31 @@ function createOperationRegistry(deps) {
17533
17611
  },
17534
17612
  run(_trx, input, actor) {
17535
17613
  const visible = visibleProjects(config, actor);
17536
- return Promise.resolve({ projects: config.projects.filter((project) => visible.has(project.id) && (input.project === void 0 || input.project === project.id)).map((project) => ({
17537
- id: project.id,
17538
- columns: project.columns.filter((column) => column.enabled).map((column) => {
17539
- const named = column.orchestrator === "none" || column.orchestrator === "operator" ? void 0 : project.spurProjects.find((spur) => spur.name === column.orchestrator);
17540
- return {
17541
- id: column.id,
17542
- executor: {
17543
- kind: column.orchestrator === "operator" ? "operator" : named?.role === "curator" ? "curator" : named !== void 0 ? "orchestrator" : column.id === "external-review" ? "dispatcher" : "worker",
17544
- name: named?.name ?? null
17545
- }
17546
- };
17547
- }),
17548
- dispatcher: { mode: project.dispatcher.mode },
17549
- spurProjects: project.spurProjects.map((spur) => ({
17550
- name: spur.name,
17551
- role: spur.role,
17552
- displayName: spur.displayName ?? spur.name
17553
- }))
17554
- })) });
17614
+ return Promise.resolve({
17615
+ projects: config.projects.filter((project) => visible.has(project.id) && (input.project === void 0 || input.project === project.id)).map((project) => ({
17616
+ id: project.id,
17617
+ columns: project.columns.filter((column) => column.enabled).map((column) => {
17618
+ const named = column.orchestrator === "none" || column.orchestrator === "operator" ? void 0 : project.spurProjects.find((spur) => spur.name === column.orchestrator);
17619
+ return {
17620
+ id: column.id,
17621
+ executor: {
17622
+ kind: column.orchestrator === "operator" ? "operator" : named?.role === "curator" ? "curator" : named !== void 0 ? "orchestrator" : column.id === "external-review" ? "dispatcher" : "worker",
17623
+ name: named?.name ?? null
17624
+ }
17625
+ };
17626
+ }),
17627
+ dispatcher: { mode: project.dispatcher.mode },
17628
+ spurProjects: project.spurProjects.map((spur) => ({
17629
+ name: spur.name,
17630
+ role: spur.role,
17631
+ displayName: spur.displayName ?? spur.name
17632
+ }))
17633
+ })),
17634
+ web: {
17635
+ publicOrigin: webOrigin() ?? null,
17636
+ spurUiOrigin: config.web.spurUiOrigin ?? null
17637
+ }
17638
+ });
17555
17639
  }
17556
17640
  },
17557
17641
  "task.get": taskQueries.get,
@@ -19619,6 +19703,268 @@ function createInbound(input) {
19619
19703
  };
19620
19704
  }
19621
19705
  //#endregion
19706
+ //#region ../core/src/api/sse.ts
19707
+ const POLL_MS = 300;
19708
+ const HEARTBEAT_MS = 15e3;
19709
+ const STATUS_MS = 3e4;
19710
+ const END_GRACE_MS = 1e3;
19711
+ const MAX_STREAMS = 32;
19712
+ const BATCH = 500;
19713
+ function frame(event, head, data) {
19714
+ return `event: ${event}\nid: ${String(head)}\ndata: ${JSON.stringify(data)}\n\n`;
19715
+ }
19716
+ /**
19717
+ * Tails the journal for open web streams: one poll every `POLL_MS` while any stream is open,
19718
+ * one `invalidate` per read batch, filtered per caller. Reads only through `db`, never inside
19719
+ * a transaction, so it sees committed rows only.
19720
+ */
19721
+ function createEventHub(options) {
19722
+ const subscribers = /* @__PURE__ */ new Set();
19723
+ let pending = 0;
19724
+ let closed = false;
19725
+ let closing;
19726
+ let cursor = 0;
19727
+ let pollTimer;
19728
+ let heartbeatTimer;
19729
+ let statusTimer;
19730
+ let polling;
19731
+ let statusRound;
19732
+ const isClosed = () => closed;
19733
+ const idle = () => closed || subscribers.size === 0;
19734
+ async function readHead() {
19735
+ return (await options.db.selectFrom("event").select(sql`max(id)`.as("head")).executeTakeFirst())?.head ?? 0;
19736
+ }
19737
+ function send(subscriber, chunk) {
19738
+ if (isClosed() || subscriber.done) return;
19739
+ if (subscriber.blocked) {
19740
+ subscriber.skipped = true;
19741
+ return;
19742
+ }
19743
+ if (subscriber.sink.write(chunk)) return;
19744
+ subscriber.blocked = true;
19745
+ subscriber.sink.once("drain", () => {
19746
+ subscriber.blocked = false;
19747
+ if (!subscriber.skipped) return;
19748
+ subscriber.skipped = false;
19749
+ send(subscriber, frame("reset", cursor, { head: cursor }));
19750
+ });
19751
+ }
19752
+ function deliver(rows) {
19753
+ const head = rows.at(-1)?.id ?? cursor;
19754
+ for (const subscriber of subscribers) {
19755
+ const projects = /* @__PURE__ */ new Set();
19756
+ const tasks = /* @__PURE__ */ new Set();
19757
+ for (const row of rows) {
19758
+ if (!subscriber.visible.has(row.project)) continue;
19759
+ projects.add(row.project);
19760
+ if (row.key !== null) tasks.add(row.key);
19761
+ }
19762
+ if (projects.size === 0) continue;
19763
+ send(subscriber, frame("invalidate", head, {
19764
+ head,
19765
+ projects: [...projects],
19766
+ tasks: [...tasks]
19767
+ }));
19768
+ }
19769
+ }
19770
+ async function poll() {
19771
+ while (!idle()) {
19772
+ let rows;
19773
+ try {
19774
+ rows = await options.db.selectFrom("event").leftJoin("task", "task.id", "event.task_id").select([
19775
+ "event.id as id",
19776
+ "event.project as project",
19777
+ "task.key as key"
19778
+ ]).where("event.id", ">", cursor).orderBy("event.id").limit(BATCH).execute();
19779
+ } catch (err) {
19780
+ options.onError?.({
19781
+ err,
19782
+ step: "poll"
19783
+ });
19784
+ return;
19785
+ }
19786
+ const last = rows.at(-1);
19787
+ if (last === void 0) return;
19788
+ cursor = Math.max(cursor, last.id);
19789
+ if (isClosed()) return;
19790
+ deliver(rows);
19791
+ if (rows.length < BATCH) return;
19792
+ }
19793
+ }
19794
+ function armPoll() {
19795
+ if (idle() || pollTimer !== void 0 || polling !== void 0) return;
19796
+ pollTimer = setTimeout(() => {
19797
+ pollTimer = void 0;
19798
+ polling = poll().finally(() => {
19799
+ polling = void 0;
19800
+ armPoll();
19801
+ });
19802
+ }, POLL_MS);
19803
+ }
19804
+ function armHeartbeat() {
19805
+ if (idle() || heartbeatTimer !== void 0) return;
19806
+ heartbeatTimer = setTimeout(() => {
19807
+ heartbeatTimer = void 0;
19808
+ for (const subscriber of subscribers) send(subscriber, ": heartbeat\n\n");
19809
+ armHeartbeat();
19810
+ }, HEARTBEAT_MS);
19811
+ }
19812
+ async function readStatuses() {
19813
+ const callers = new Set([...subscribers].map((subscriber) => subscriber.caller));
19814
+ for (const caller of callers) {
19815
+ if (idle()) return;
19816
+ let status;
19817
+ try {
19818
+ status = await options.readStatus(caller);
19819
+ } catch (err) {
19820
+ options.onError?.({
19821
+ err,
19822
+ step: "status"
19823
+ });
19824
+ continue;
19825
+ }
19826
+ const { warmingUp, spurUnavailable, hostLoad, transport, sources } = status;
19827
+ const chunk = `event: status\ndata: ${JSON.stringify({
19828
+ warmingUp,
19829
+ spurUnavailable,
19830
+ hostLoad,
19831
+ transport,
19832
+ sources
19833
+ })}\n\n`;
19834
+ for (const subscriber of subscribers) if (subscriber.caller === caller) send(subscriber, chunk);
19835
+ }
19836
+ }
19837
+ function armStatus() {
19838
+ if (idle() || statusTimer !== void 0 || statusRound !== void 0) return;
19839
+ statusTimer = setTimeout(() => {
19840
+ statusTimer = void 0;
19841
+ statusRound = readStatuses().finally(() => {
19842
+ statusRound = void 0;
19843
+ armStatus();
19844
+ });
19845
+ }, STATUS_MS);
19846
+ }
19847
+ function stopTimers() {
19848
+ clearTimeout(pollTimer);
19849
+ clearTimeout(heartbeatTimer);
19850
+ clearTimeout(statusTimer);
19851
+ pollTimer = heartbeatTimer = statusTimer = void 0;
19852
+ }
19853
+ async function shut(subscriber) {
19854
+ subscriber.done = true;
19855
+ if (subscriber.blocked) {
19856
+ await subscriber.sink.destroy();
19857
+ return;
19858
+ }
19859
+ let grace;
19860
+ const ended = await Promise.race([subscriber.sink.end().then(() => true, () => true), new Promise((resolve) => {
19861
+ grace = setTimeout(() => {
19862
+ resolve(false);
19863
+ }, END_GRACE_MS);
19864
+ })]);
19865
+ clearTimeout(grace);
19866
+ if (!ended) await subscriber.sink.destroy();
19867
+ }
19868
+ return {
19869
+ async subscribe(caller, lastId, sink) {
19870
+ if (isClosed() || subscribers.size + pending >= MAX_STREAMS) return "full";
19871
+ pending += 1;
19872
+ let head;
19873
+ try {
19874
+ head = await readHead();
19875
+ } finally {
19876
+ pending -= 1;
19877
+ }
19878
+ if (isClosed()) return "full";
19879
+ const subscriber = {
19880
+ caller,
19881
+ sink,
19882
+ visible: /* @__PURE__ */ new Set([...visibleProjects(options.config, caller), RESERVED_PROJECT]),
19883
+ blocked: false,
19884
+ skipped: false,
19885
+ done: false
19886
+ };
19887
+ const first = subscribers.size === 0;
19888
+ subscribers.add(subscriber);
19889
+ if (first) {
19890
+ cursor = Math.max(cursor, head);
19891
+ armPoll();
19892
+ armHeartbeat();
19893
+ armStatus();
19894
+ }
19895
+ send(subscriber, frame("hello", head, {
19896
+ head,
19897
+ instance: options.instance
19898
+ }));
19899
+ if (lastId !== void 0 && lastId !== "" && (!/^\d+$/.test(lastId) || Number(lastId) > head)) send(subscriber, frame("reset", head, { head }));
19900
+ return { unsubscribe() {
19901
+ subscriber.done = true;
19902
+ if (!subscribers.delete(subscriber)) return;
19903
+ if (subscribers.size === 0) stopTimers();
19904
+ } };
19905
+ },
19906
+ close() {
19907
+ closing ??= (async () => {
19908
+ closed = true;
19909
+ stopTimers();
19910
+ const open = [...subscribers];
19911
+ subscribers.clear();
19912
+ await Promise.all([
19913
+ ...open.map(shut),
19914
+ polling,
19915
+ statusRound
19916
+ ]);
19917
+ })();
19918
+ return closing;
19919
+ }
19920
+ };
19921
+ }
19922
+ /**
19923
+ * `GET /v1/events` on the web listener: an SSE stream fed by `hub`. The listener's `onRequest`
19924
+ * guard has already checked Host and fetch metadata; the route adds the Origin check.
19925
+ */
19926
+ function installEventStream(app, options) {
19927
+ app.get("/v1/events", { exposeHeadRoute: false }, async (request, reply) => {
19928
+ const browserOrigin = request.headers.origin;
19929
+ if (browserOrigin !== void 0 && browserOrigin !== options.origin()) throw new CommandError("forbidden", "Use the configured web origin.");
19930
+ if (!options.ready()) throw new CommandError(options.stopping?.() === true ? "stopping" : "starting", "Wait until the daemon is ready.");
19931
+ const raw = reply.raw;
19932
+ raw.once("close", () => {
19933
+ options.audit(request, reply);
19934
+ });
19935
+ const closed = new Promise((resolve) => {
19936
+ if (raw.destroyed) resolve();
19937
+ else raw.once("close", () => {
19938
+ resolve();
19939
+ });
19940
+ });
19941
+ const pass = new PassThrough();
19942
+ const writable = () => !pass.writableEnded && !pass.destroyed;
19943
+ const sink = {
19944
+ write: (chunk) => writable() ? pass.write(chunk) : true,
19945
+ end() {
19946
+ if (writable()) pass.end();
19947
+ return closed;
19948
+ },
19949
+ destroy() {
19950
+ raw.destroy();
19951
+ return closed;
19952
+ },
19953
+ once(event, listener) {
19954
+ pass.once(event, listener);
19955
+ }
19956
+ };
19957
+ const lastId = request.headers["last-event-id"];
19958
+ const subscription = await options.hub.subscribe("operator", typeof lastId === "string" ? lastId : void 0, sink);
19959
+ if (subscription === "full") return reply.code(503).header("retry-after", "5").type("text/plain; charset=utf-8").send("Too many open event streams: close a board tab or retry later.");
19960
+ if (raw.destroyed) subscription.unsubscribe();
19961
+ else raw.once("close", () => {
19962
+ subscription.unsubscribe();
19963
+ });
19964
+ return reply.header("content-type", "text/event-stream").header("cache-control", "no-cache").header("x-accel-buffering", "no").send(pass);
19965
+ });
19966
+ }
19967
+ //#endregion
19622
19968
  //#region ../core/src/api/web-server.ts
19623
19969
  const mime = {
19624
19970
  ".html": "text/html; charset=utf-8",
@@ -19671,10 +20017,13 @@ async function createWebServer(options) {
19671
20017
  }
19672
20018
  });
19673
20019
  const errorHandler = installOperationErrors(app, options);
20020
+ function resolvedOrigin() {
20021
+ const address = app.server.address();
20022
+ return resolveWebOrigin(options.config.web, address !== null && typeof address === "object" ? address.port : void 0);
20023
+ }
19674
20024
  function guard(request, reply) {
19675
20025
  reply.header("x-request-id", request.id);
19676
- const address = app.server.address();
19677
- const origin = resolveWebOrigin(options.config.web, address !== null && typeof address === "object" ? address.port : void 0);
20026
+ const origin = resolvedOrigin();
19678
20027
  if (origin === void 0 || request.headers.host !== new URL(origin).host) throw new CommandError("forbidden", "Use the configured web host.");
19679
20028
  if (request.headers["sec-fetch-site"] === "cross-site") throw new CommandError("forbidden", "Cross-site requests are not accepted.");
19680
20029
  if (request.method !== "GET" && request.method !== "HEAD" && request.headers.origin !== origin) throw new CommandError("forbidden", "Use the configured web origin.");
@@ -19694,7 +20043,10 @@ async function createWebServer(options) {
19694
20043
  reply.header("x-content-type-options", "nosniff");
19695
20044
  reply.header("referrer-policy", "no-referrer");
19696
20045
  }
20046
+ const audited = /* @__PURE__ */ new WeakSet();
19697
20047
  function audit(request, reply) {
20048
+ if (audited.has(request)) return;
20049
+ audited.add(request);
19698
20050
  const forwardedFor = request.headers["x-forwarded-for"];
19699
20051
  const userAgent = request.headers["user-agent"];
19700
20052
  options.logRequest({
@@ -19728,6 +20080,21 @@ async function createWebServer(options) {
19728
20080
  if (options.firstPollDone === void 0) throw new CommandError("not_found", "Health is unavailable.");
19729
20081
  return { firstPollDone: await options.firstPollDone() };
19730
20082
  });
20083
+ const hub = createEventHub({
20084
+ db: options.store.db,
20085
+ config: options.config,
20086
+ instance: options.instance ?? randomUUID(),
20087
+ readStatus: (caller) => dispatchOperation(options, "status.get", {}, caller),
20088
+ onError: options.logStreamError
20089
+ });
20090
+ installEventStream(app, {
20091
+ hub,
20092
+ ready: options.ready,
20093
+ stopping: options.stopping,
20094
+ origin: resolvedOrigin,
20095
+ audit
20096
+ });
20097
+ app.addHook("preClose", () => hub.close());
19731
20098
  app.setNotFoundHandler(async (request, reply) => {
19732
20099
  const path = request.url.split("?", 1)[0] ?? "/";
19733
20100
  if (request.method !== "GET" && request.method !== "HEAD" || path === "/v1" || path.startsWith("/v1/")) throw new CommandError("not_found", "This web route is not available.");
@@ -25076,6 +25443,10 @@ const sessionDetailWire = z.object({
25076
25443
  project: z.string().min(1),
25077
25444
  status: z.enum(SESSION_STATUSES)
25078
25445
  });
25446
+ /** Port of an http listener address; URL parsing drops the default port 80, so restore it. */
25447
+ function listenerPort(address) {
25448
+ return Number(new URL(address).port || 80);
25449
+ }
25079
25450
  /** Fetch one session after a snapshot miss; 404 is a confirmed unknown session. */
25080
25451
  async function lookupLiveSession(baseUrl, id, fetcher = fetch) {
25081
25452
  const response = await fetcher(new URL(`sessions/${encodeURIComponent(id)}`, apiBaseUrl(baseUrl)), { signal: AbortSignal.timeout(SESSION_TIMEOUT_MS) });
@@ -25099,6 +25470,7 @@ function createHttpModule(ctx, options = {}) {
25099
25470
  store: ctx.store,
25100
25471
  config: ctx.config,
25101
25472
  port: ctx.config.http.port,
25473
+ ...options.instance === void 0 ? {} : { instance: options.instance },
25102
25474
  ready: () => ctx.state() === "ready",
25103
25475
  stopping: () => ctx.state() === "stopping",
25104
25476
  clock: ctx.clock,
@@ -25135,7 +25507,7 @@ function createHttpModule(ctx, options = {}) {
25135
25507
  if (aborted()) return;
25136
25508
  options.onListening?.(address);
25137
25509
  app = server;
25138
- ctx.log.info({ port: Number(new URL(address).port) }, "http listening");
25510
+ ctx.log.info({ port: listenerPort(address) }, "http listening");
25139
25511
  } finally {
25140
25512
  if (app !== server) await server.close();
25141
25513
  }
@@ -25176,7 +25548,14 @@ function createWebModule(ctx, options) {
25176
25548
  requestId,
25177
25549
  err
25178
25550
  }, "web request failed");
25179
- }
25551
+ },
25552
+ logStreamError: ({ err, step }) => {
25553
+ ctx.log.warn({
25554
+ err,
25555
+ step
25556
+ }, "event stream read failed");
25557
+ },
25558
+ ...options.instance === void 0 ? {} : { instance: options.instance }
25180
25559
  });
25181
25560
  if (aborted()) return;
25182
25561
  const address = await server.listen({
@@ -25186,7 +25565,7 @@ function createWebModule(ctx, options) {
25186
25565
  if (aborted()) return;
25187
25566
  options.onListening?.(address);
25188
25567
  app = server;
25189
- ctx.log.info({ port: Number(new URL(address).port) }, "web listening");
25568
+ ctx.log.info({ port: listenerPort(address) }, "web listening");
25190
25569
  } catch (err) {
25191
25570
  ctx.log.error({
25192
25571
  err,
@@ -25474,13 +25853,18 @@ function createDaemonModules(ctxFor, ports = {}) {
25474
25853
  ctx.log.error({ err }, work === "connection" ? "slack connection event failed" : "slack envelope failed");
25475
25854
  }
25476
25855
  }));
25856
+ let webPort;
25857
+ let lastDispatchAt = null;
25477
25858
  const registry = createOperationRegistry({
25478
25859
  config: board.config,
25479
25860
  clock: board.clock,
25480
25861
  completeSince: core.completeSince,
25481
25862
  gateways: gateway === void 0 ? [] : [gateway.kind],
25482
25863
  reapplyInbound: () => inbound?.reapply,
25483
- prPoller: () => boardModules.pollPr
25864
+ prPoller: () => boardModules.pollPr,
25865
+ ...ports.productVersion === void 0 ? {} : { productVersion: ports.productVersion },
25866
+ lastDispatchAt: () => lastDispatchAt,
25867
+ webOrigin: () => webPort === void 0 ? void 0 : resolveWebOrigin(board.config.web, webPort)
25484
25868
  });
25485
25869
  const notifier = createSystemdNotifier({
25486
25870
  log: ctxFor("systemd").log,
@@ -25519,6 +25903,7 @@ function createDaemonModules(ctxFor, ports = {}) {
25519
25903
  ...ports.startAdapters === void 0 ? {} : { startAdapters: ports.startAdapters },
25520
25904
  ...ports.tick === void 0 ? {} : { tick: ports.tick },
25521
25905
  onTick: () => {
25906
+ lastDispatchAt = new Date(board.clock.now()).toISOString();
25522
25907
  notifier.watchdog();
25523
25908
  }
25524
25909
  });
@@ -25553,13 +25938,18 @@ function createDaemonModules(ctxFor, ports = {}) {
25553
25938
  module: outbox
25554
25939
  });
25555
25940
  const runOperation = (id, input, run) => id === "item.retry" && inbound !== void 0 && isItemInput(input) ? inbound.retrying(input.item, run) : run();
25941
+ const instance = randomUUID();
25556
25942
  const web = board.config.web.port === void 0 ? void 0 : createWebModule(ctxFor("web"), {
25557
25943
  registry,
25558
25944
  runOperation,
25945
+ instance,
25559
25946
  firstPollDone: () => firstPollDone(board.store.db, board.config, core.completeSince),
25560
25947
  ...ports.afterOperation === void 0 ? {} : { afterOperation: ports.afterOperation },
25561
25948
  ...ports.webRoot === void 0 ? {} : { webRoot: ports.webRoot },
25562
- ...ports.onWebListening === void 0 ? {} : { onListening: ports.onWebListening }
25949
+ onListening: (address) => {
25950
+ webPort = listenerPort(address);
25951
+ ports.onWebListening?.(address);
25952
+ }
25563
25953
  });
25564
25954
  if (web !== void 0) entries.push({
25565
25955
  name: "web",
@@ -25572,6 +25962,7 @@ function createDaemonModules(ctxFor, ports = {}) {
25572
25962
  module: createHttpModule(ctxFor("http"), {
25573
25963
  registry,
25574
25964
  runOperation,
25965
+ instance,
25575
25966
  webListening: () => web?.listening() === true,
25576
25967
  firstPollDone: () => firstPollDone(board.store.db, board.config, core.completeSince),
25577
25968
  ...ports.productVersion === void 0 ? {} : { productVersion: ports.productVersion },