spur-board 0.170.0 → 0.170.1

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.
@@ -1,4 +1,4 @@
1
- import { d as tokenRequestStatusSchema, gt as errorEnvelopeSchema, ht as errorContextSchema, l as tokenRequestResultSchema, pt as ERRORS, vt as successEnvelopeSchema, x as renderJsonError } from "./chunk-Chj2wumn.mjs";
1
+ import { d as tokenRequestStatusSchema, gt as errorEnvelopeSchema, ht as errorContextSchema, l as tokenRequestResultSchema, pt as ERRORS, vt as successEnvelopeSchema, x as renderJsonError } from "./chunk-BebxFmW0.mjs";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { z } from "zod";
4
4
  import { request } from "node:http";
@@ -3761,7 +3761,7 @@ const serviceSchema = z.strictObject({
3761
3761
  "failing"
3762
3762
  ]).describe("failing: a blind source, a github-project source whose last poll failed, or a gateway that is down; degraded: a source that never completed, is stale, warms up or waits for its rate budget, or a daemon with no completed board tick for over 120 seconds; else healthy. A source service takes its worst source."),
3763
3763
  since: z.iso.datetime().nullable().describe("Healthy: since when the service has been usable in this daemon run. That is daemon.startedAt for the daemon, the latest healthySince of its sources for github, github-project, jira and spur, and for a gateway the end of its last recorded outage or daemon.startedAt, whichever is later. Failing gateway: when the outage started. Otherwise null."),
3764
- lastGoodAt: z.iso.datetime().nullable().describe("Last sign of work: the last completed board tick for the daemon, the oldest latest observation of its sources for github, github-project, jira and spur (null when one has none); null for a gateway."),
3764
+ lastGoodAt: z.iso.datetime().nullable().describe("Last sign of work: the last completed board tick for the daemon, the oldest latest observation of its sources for github, github-project, jira and spur (null when one has none); for a gateway, the time of this read while its Socket Mode connection is up in this daemon run, even when a delivery failure makes it failing (`state` and `reason` name that failure); otherwise when it was last known up (when its connection dropped, or its last connect in an earlier daemon run); null for a gateway that was never up."),
3765
3765
  reason: z.string().nullable().describe("Why the service is not healthy, from its first worst source for github, jira and spur; null when healthy.")
3766
3766
  }).describe("Health of one service.");
3767
3767
  const statusInputSchema = z.strictObject({
@@ -1,5 +1,5 @@
1
- import { Mt as plainHttpAllowed, g as OPERATIONS, kt as configSchema, m as buildCatalogSnapshot } from "./chunk-Chj2wumn.mjs";
2
- import { o as CliError, t as fetchCatalogVersion } from "./chunk-BLaWsiXP.mjs";
1
+ import { Mt as plainHttpAllowed, g as OPERATIONS, kt as configSchema, m as buildCatalogSnapshot } from "./chunk-BebxFmW0.mjs";
2
+ import { o as CliError, t as fetchCatalogVersion } from "./chunk-BbohDnMm.mjs";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
5
5
  import { homedir } from "node:os";
package/dist/cli.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import { Ct as DEFAULT_STAND_PORT_RANGE, Ft as resolveWebOrigin, It as slackConfigured, Pt as requiredSecretKeys, Ut as SLACK_BOT_SCOPES, c as requestHashOf, ct as actorIdSchema, g as OPERATIONS, h as roleCanUseOperation, j as sortSkillFiles, k as skillReloadFileSchema, kt as configSchema, n as SLACK_OFF_FIX, o as remoteDoctorReportSchema, p as SYSTEMD_SERVICE_SETTINGS, pt as ERRORS, r as SLACK_PARTLY_FIX, vt as successEnvelopeSchema } from "./chunk-Chj2wumn.mjs";
1
+ import { Ct as DEFAULT_STAND_PORT_RANGE, Ft as resolveWebOrigin, It as slackConfigured, Pt as requiredSecretKeys, Ut as SLACK_BOT_SCOPES, c as requestHashOf, ct as actorIdSchema, g as OPERATIONS, h as roleCanUseOperation, j as sortSkillFiles, k as skillReloadFileSchema, kt as configSchema, n as SLACK_OFF_FIX, o as remoteDoctorReportSchema, p as SYSTEMD_SERVICE_SETTINGS, pt as ERRORS, r as SLACK_PARTLY_FIX, vt as successEnvelopeSchema } from "./chunk-BebxFmW0.mjs";
2
2
  import { t as apiBaseUrl } from "./chunk-Bzb7aI8R.mjs";
3
- import { a as requestTokenEnrollment, c as renderCliError, i as requestSkillReload, l as escapeTerminalControls, n as fetchTokenStatus, o as CliError, r as requestOperation, s as errorExitCode } from "./chunk-BLaWsiXP.mjs";
4
- import { a as memoryVerdictCache, c as loadClientConfig, d as resolveDaemonAddress, f as tokenInFolder, i as fileVerdictCache, l as loadEnrollmentConfig, n as cliPackageVersion, o as configFile, s as dataDirectory, t as checkCatalog, u as readConfiguredPort } from "./chunk-DI3BTuEX.mjs";
3
+ import { a as requestTokenEnrollment, c as renderCliError, i as requestSkillReload, l as escapeTerminalControls, n as fetchTokenStatus, o as CliError, r as requestOperation, s as errorExitCode } from "./chunk-BbohDnMm.mjs";
4
+ import { a as memoryVerdictCache, c as loadClientConfig, d as resolveDaemonAddress, f as tokenInFolder, i as fileVerdictCache, l as loadEnrollmentConfig, n as cliPackageVersion, o as configFile, s as dataDirectory, t as checkCatalog, u as readConfiguredPort } from "./chunk-DEHqpoRe.mjs";
5
5
  import { createHash, randomBytes, randomUUID } from "node:crypto";
6
6
  import { accessSync, chmodSync, closeSync, constants, cpSync, existsSync, ftruncateSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
7
7
  import { homedir, hostname, tmpdir, userInfo } from "node:os";
package/dist/client.mjs CHANGED
@@ -1 +1 @@
1
- export { t as fetchCatalogVersion, n as fetchTokenStatus, r as requestOperation, i as requestSkillReload, a as requestTokenEnrollment } from "./chunk-BLaWsiXP.mjs";
1
+ export { t as fetchCatalogVersion, n as fetchTokenStatus, r as requestOperation, i as requestSkillReload, a as requestTokenEnrollment } from "./chunk-BbohDnMm.mjs";
package/dist/daemon.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as prApprovalPairSchema, A as skillReloadFilesSchema, At as defaultAddressee, B as entityRefSchema, Bt as COLUMN_IDS, C as SPACE_IDS, D as messageRefSchema, Dt as columnTurnTimings, E as interactionRefSchema, Et as boardWideSpurProject, F as AdapterError, Ft as resolveWebOrigin, G as trackerSourceId, Gt as TODO_GROUP_COLUMN_IDS, H as prSourceId, Ht as ITEM_KINDS, I as MIRROR_FAILURES, It as slackConfigured, J as REVIEW_STATES, K as PR_STATES, Kt as VIAS, L as MIRROR_FAILURE_CODES, Lt as BLOCK_TYPES, M as EVENT_KINDS, Mt as plainHttpAllowed, N as GATE_REASONS, Nt as readyMirrorOf, O as userIdSchema, Ot as configBindings, P as eventPayloadSchemas, Pt as requiredSecretKeys, Q as parseRingMarker, R as batchSchema, Rt as COLUMNS, St as DEFAULT_SLACK_COMMAND, T as inboundEventSchema, Tt as approvalRuleOf, U as sessionTransitionSchema, Ut as SLACK_BOT_SCOPES, V as mirrorSourceId, Vt as DISPATCHER_MODES, W as sourceCursorSchema, Wt as TASK_HOLDS, X as SESSION_STATUSES, Y as SESSION_HEALTH_STATES, Z as isExternalAuthor, _ as defaultBranchViewSchema, _t as ok, a as doctorReportSchema, at as ticketFactsSchema, b as renderHttpProblem, bt as DEFAULT_LINK, c as requestHashOf, ct as actorIdSchema, d as tokenRequestStatusSchema, dt as parseActorId, et as prFactsSchema, f as BOARD_TICK_MS, ft as parseRef$1, g as OPERATIONS, h as roleCanUseOperation, i as SPUR_MIN_VERSION, it as sessionFactsSchema, j as sortSkillFiles, jt as externalQuietAfterMs, kt as configSchema, l as tokenRequestResultSchema, lt as encodeActorId, m as buildCatalogSnapshot, mt as err, n as SLACK_OFF_FIX, nt as prReviewRuleSchema, ot as JIRA_PROJECT_KEY, pt as ERRORS, q as REVIEW_DECISIONS, qt as isTodoGroupColumn, r as SLACK_PARTLY_FIX, rt as ringMarker, s as TOKEN_REQUEST_LIMITS, st as REF_NUMBER, t as assertNever, tt as prRefSchema, u as tokenRequestSchema, ut as errorCodeOf, v as inboxNoSessionSchema, vt as successEnvelopeSchema, w as conversationRefSchema, wt as RESERVED_PROJECT, y as turnHandedSchema, z as defaultBranchFactSchema, zt as COLUMN_GROUPS } from "./chunk-Chj2wumn.mjs";
1
+ import { $ as prApprovalPairSchema, A as skillReloadFilesSchema, At as defaultAddressee, B as entityRefSchema, Bt as COLUMN_IDS, C as SPACE_IDS, D as messageRefSchema, Dt as columnTurnTimings, E as interactionRefSchema, Et as boardWideSpurProject, F as AdapterError, Ft as resolveWebOrigin, G as trackerSourceId, Gt as TODO_GROUP_COLUMN_IDS, H as prSourceId, Ht as ITEM_KINDS, I as MIRROR_FAILURES, It as slackConfigured, J as REVIEW_STATES, K as PR_STATES, Kt as VIAS, L as MIRROR_FAILURE_CODES, Lt as BLOCK_TYPES, M as EVENT_KINDS, Mt as plainHttpAllowed, N as GATE_REASONS, Nt as readyMirrorOf, O as userIdSchema, Ot as configBindings, P as eventPayloadSchemas, Pt as requiredSecretKeys, Q as parseRingMarker, R as batchSchema, Rt as COLUMNS, St as DEFAULT_SLACK_COMMAND, T as inboundEventSchema, Tt as approvalRuleOf, U as sessionTransitionSchema, Ut as SLACK_BOT_SCOPES, V as mirrorSourceId, Vt as DISPATCHER_MODES, W as sourceCursorSchema, Wt as TASK_HOLDS, X as SESSION_STATUSES, Y as SESSION_HEALTH_STATES, Z as isExternalAuthor, _ as defaultBranchViewSchema, _t as ok, a as doctorReportSchema, at as ticketFactsSchema, b as renderHttpProblem, bt as DEFAULT_LINK, c as requestHashOf, ct as actorIdSchema, d as tokenRequestStatusSchema, dt as parseActorId, et as prFactsSchema, f as BOARD_TICK_MS, ft as parseRef$1, g as OPERATIONS, h as roleCanUseOperation, i as SPUR_MIN_VERSION, it as sessionFactsSchema, j as sortSkillFiles, jt as externalQuietAfterMs, kt as configSchema, l as tokenRequestResultSchema, lt as encodeActorId, m as buildCatalogSnapshot, mt as err, n as SLACK_OFF_FIX, nt as prReviewRuleSchema, ot as JIRA_PROJECT_KEY, pt as ERRORS, q as REVIEW_DECISIONS, qt as isTodoGroupColumn, r as SLACK_PARTLY_FIX, rt as ringMarker, s as TOKEN_REQUEST_LIMITS, st as REF_NUMBER, t as assertNever, tt as prRefSchema, u as tokenRequestSchema, ut as errorCodeOf, v as inboxNoSessionSchema, vt as successEnvelopeSchema, w as conversationRefSchema, wt as RESERVED_PROJECT, y as turnHandedSchema, z as defaultBranchFactSchema, zt as COLUMN_GROUPS } from "./chunk-BebxFmW0.mjs";
2
2
  import { t as apiBaseUrl } from "./chunk-Bzb7aI8R.mjs";
3
3
  import { createRequire } from "node:module";
4
4
  import { createHash, randomUUID } from "node:crypto";
@@ -19,7 +19,7 @@ import { PassThrough } from "node:stream";
19
19
  import { pino } from "pino";
20
20
  import { WebAPIHTTPError, WebAPIPlatformError, WebAPIRateLimitedError, WebClient } from "@slack/web-api";
21
21
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
22
- import { SocketModeClient } from "@slack/socket-mode";
22
+ import { LogLevel, SocketModeClient, UnrecoverableSocketModeStartError } from "@slack/socket-mode";
23
23
  // \0rolldown/runtime.js
24
24
  var __create = Object.create;
25
25
  var __defProp = Object.defineProperty;
@@ -21054,6 +21054,41 @@ async function conversationsForRecovery(trx, gateway, now) {
21054
21054
  since: rows[0] === void 0 ? now : new Date(rows[0].created_at)
21055
21055
  };
21056
21056
  }
21057
+ // ../core/src/app/transport-connection.ts
21058
+ const KEY_PREFIX = "transport_connection:";
21059
+ /** The last connection event of one gateway: `up` at its connect, `down` at its drop. */
21060
+ const connectionSchema = z.strictObject({
21061
+ state: z.enum(["up", "down"]),
21062
+ at: z.iso.datetime()
21063
+ });
21064
+ /** Stores the gateway's last connection event; `at` becomes ISO-8601 UTC. */
21065
+ async function writeConnection(trx, gateway, state, at) {
21066
+ const value = JSON.stringify({
21067
+ state,
21068
+ at: at.toISOString()
21069
+ });
21070
+ await trx.insertInto("meta").values({
21071
+ key: `${KEY_PREFIX}${gateway}`,
21072
+ value
21073
+ }).onConflict((oc) => oc.column("key").doUpdateSet({ value })).execute();
21074
+ }
21075
+ /** Each gateway's connection record; a malformed value reads as no record. */
21076
+ async function readConnections(db) {
21077
+ const rows = await db.selectFrom("meta").select(["key", "value"]).where("key", "like", `${KEY_PREFIX}%`).execute();
21078
+ const records = /* @__PURE__ */ new Map();
21079
+ for (const row of rows) {
21080
+ if (!row.key.startsWith(KEY_PREFIX)) continue;
21081
+ let parsed;
21082
+ try {
21083
+ parsed = JSON.parse(row.value);
21084
+ } catch {
21085
+ continue;
21086
+ }
21087
+ const record = connectionSchema.safeParse(parsed);
21088
+ if (record.success) records.set(row.key.slice(21), record.data);
21089
+ }
21090
+ return records;
21091
+ }
21057
21092
  // ../core/src/app/sender.ts
21058
21093
  /**
21059
21094
  * Spur refused a doorbell for good (a permanent 4xx): the sender stops ringing and ends the ring
@@ -21250,6 +21285,8 @@ function createSender(options) {
21250
21285
  let downSince;
21251
21286
  /** Set once this outage's down rows were written; reset on `up`. */
21252
21287
  let downRecorded = false;
21288
+ /** This run's connection state, read by `status.get` without waiting for a tick. */
21289
+ const live = /* @__PURE__ */ new Map();
21253
21290
  /** The last tick started; a new tick runs after it, so two ticks never interleave. */
21254
21291
  let ticking = Promise.resolve();
21255
21292
  /** Sets the comments of `rows` that carry one to `superseded`. */
@@ -21702,20 +21739,31 @@ function createSender(options) {
21702
21739
  return run;
21703
21740
  },
21704
21741
  recordConnection(state, at) {
21742
+ if (gateway !== void 0 && (state === "up" || live.get(gatewayKind)?.state !== "down")) live.set(gatewayKind, {
21743
+ state,
21744
+ at: at.toISOString()
21745
+ });
21705
21746
  const run = ticking.then(async () => {
21706
21747
  if (state === "down") {
21707
- downSince ??= at.getTime();
21748
+ if (downSince !== void 0) return;
21749
+ downSince = at.getTime();
21750
+ if (gateway === void 0) return;
21751
+ await scanTransaction(store, options.config, (trx) => writeConnection(trx, gatewayKind, "down", at));
21708
21752
  return;
21709
21753
  }
21710
21754
  downSince = void 0;
21711
21755
  downRecorded = false;
21712
21756
  if (gateway === void 0) return;
21713
21757
  await scanTransaction(store, options.config, async (trx) => {
21758
+ await writeConnection(trx, gatewayKind, "up", at);
21714
21759
  if ((await trx.deleteFrom("transport_health").where("gateway", "=", gatewayKind).where("reason", "=", "down").returning("space").execute()).length > 0) await syncTransportItem(trx, gatewayKind, at);
21715
21760
  });
21716
21761
  });
21717
21762
  ticking = run.catch(() => void 0);
21718
21763
  return run;
21764
+ },
21765
+ liveConnections() {
21766
+ return live;
21719
21767
  }
21720
21768
  };
21721
21769
  }
@@ -22189,6 +22237,16 @@ function sourceHealth(source) {
22189
22237
  };
22190
22238
  }
22191
22239
  /**
22240
+ * A gateway's last good time: the read time while this daemon run's connection is up, even when
22241
+ * a delivery failure makes its row failing; its drop time while this run's connection is down;
22242
+ * before this run has connection state, the stored record of an earlier run (its last connect or
22243
+ * drop); null when it was never up.
22244
+ */
22245
+ function gatewayLastGoodAt(live, stored, now) {
22246
+ if (live !== void 0) return live.state === "up" ? new Date(now).toISOString() : live.at;
22247
+ return stored?.at ?? null;
22248
+ }
22249
+ /**
22192
22250
  * One health row per service: the daemon, each gateway (board-wide), then github,
22193
22251
  * github-project, spur and jira rolled up from the given sources only.
22194
22252
  */
@@ -22205,17 +22263,18 @@ function services(input) {
22205
22263
  }];
22206
22264
  for (const gateway of input.transport) {
22207
22265
  const ended = input.outageEnds.get(gateway.gateway);
22266
+ const lastGoodAt = gatewayLastGoodAt(input.liveConnections.get(gateway.gateway), input.connections.get(gateway.gateway), now);
22208
22267
  rows.push(gateway.state === "down" ? {
22209
22268
  service: gateway.gateway,
22210
22269
  state: "failing",
22211
22270
  since: gateway.since,
22212
- lastGoodAt: null,
22271
+ lastGoodAt,
22213
22272
  reason: gateway.reason
22214
22273
  } : {
22215
22274
  service: gateway.gateway,
22216
22275
  state: "healthy",
22217
22276
  since: ended !== void 0 && Date.parse(ended) > Date.parse(daemon.startedAt) ? ended : daemon.startedAt,
22218
- lastGoodAt: null,
22277
+ lastGoodAt,
22219
22278
  reason: null
22220
22279
  });
22221
22280
  }
@@ -22533,6 +22592,8 @@ async function getStatus(deps, options = {}) {
22533
22592
  daemon,
22534
22593
  transport,
22535
22594
  outageEnds: await readOutageEnds(store.db),
22595
+ connections: await readConnections(store.db),
22596
+ liveConnections: deps.liveConnections ?? /* @__PURE__ */ new Map(),
22536
22597
  sources
22537
22598
  }),
22538
22599
  transport,
@@ -24797,7 +24858,8 @@ function createOperationRegistry(deps) {
24797
24858
  },
24798
24859
  healthySince: deps.healthySince,
24799
24860
  budgetWaits: deps.budgetWaits?.(),
24800
- host: deps.hostMetrics?.()
24861
+ host: deps.hostMetrics?.(),
24862
+ liveConnections: deps.liveConnections?.()
24801
24863
  }, {
24802
24864
  project: input.project,
24803
24865
  visibleProjects: visibleProjects(config, actor),
@@ -32815,13 +32877,316 @@ async function rootFor(client, channel, threadTs) {
32815
32877
  if (root === void 0) throw new Error("Slack thread root unavailable");
32816
32878
  return root;
32817
32879
  }
32818
- /** Socket Mode owns transport reconnects; this layer owns sink-before-ack ordering. */
32880
+ /**
32881
+ * The wait before reconnect attempt `attempt` (1-based): equal jitter over a ceiling that doubles
32882
+ * from `baseDelayMs` up to `maxDelayMs`.
32883
+ */
32884
+ function reconnectDelay(attempt, options, random) {
32885
+ const ceiling = Math.min(options.maxDelayMs, options.baseDelayMs * 2 ** (attempt - 1));
32886
+ return Math.round(ceiling / 2 + random() * ceiling / 2);
32887
+ }
32888
+ const closeFrameLine = /^WebSocket close frame received \(code: (\d+), reason: (.*)\)$/s;
32889
+ const socketErrorLine = /^WebSocket error occurred: (.*)$/s;
32890
+ const carriedLines = [
32891
+ /^Failed to retrieve a new WSS URL/,
32892
+ /^http request failed/,
32893
+ /^WebSocket error! /
32894
+ ];
32895
+ /**
32896
+ * The logger one SDK client gets. Debug and info lines never leave it (they carry payloads and
32897
+ * the WSS URL); it records the close frame and socket error into `record`, and forwards every
32898
+ * other warn and error line as its string arguments joined by a space.
32899
+ */
32900
+ function createSdkLogger(record, forward) {
32901
+ const detailOf = (args) => args.filter((arg) => typeof arg === "string").join(" ");
32902
+ function line(level, args) {
32903
+ const detail = detailOf(args);
32904
+ if (level === "error") {
32905
+ const socketError = socketErrorLine.exec(detail);
32906
+ if (socketError !== null) {
32907
+ if (socketError[1] !== void 0 && socketError[1].length > 0) record.socketError = socketError[1];
32908
+ return;
32909
+ }
32910
+ }
32911
+ if (carriedLines.some((pattern) => pattern.test(detail))) return;
32912
+ forward(level, detail);
32913
+ }
32914
+ return {
32915
+ debug(...args) {
32916
+ const frame = closeFrameLine.exec(detailOf(args));
32917
+ if (frame === null) return;
32918
+ record.closeCode = Number(frame[1]);
32919
+ if (frame[2] === void 0 || frame[2] === "") delete record.closeReason;
32920
+ else record.closeReason = frame[2];
32921
+ },
32922
+ info() {},
32923
+ warn(...args) {
32924
+ line("warn", args);
32925
+ },
32926
+ error(...args) {
32927
+ line("error", args);
32928
+ },
32929
+ getLevel: () => LogLevel.INFO,
32930
+ setLevel() {},
32931
+ setName() {}
32932
+ };
32933
+ }
32934
+ /** The `reason` of a Socket Mode `disconnect` message, else undefined. */
32935
+ function disconnectReasonOf(data) {
32936
+ if (typeof data !== "string" || !data.includes("\"disconnect\"")) return void 0;
32937
+ try {
32938
+ const message = fieldsOf(JSON.parse(data));
32939
+ return textOf(message?.type) === "disconnect" ? textOf(message?.reason) : void 0;
32940
+ } catch {
32941
+ return;
32942
+ }
32943
+ }
32944
+ function unrecoverable(err) {
32945
+ const codes = Object.values(UnrecoverableSocketModeStartError);
32946
+ return err instanceof WebAPIPlatformError && codes.includes(err.data.error);
32947
+ }
32948
+ /** Slack's `disconnect` reasons that ask for a new connection while the old one still serves. */
32949
+ const refreshReasons = ["refresh_requested", "warning"];
32950
+ /**
32951
+ * An SDK client that hands a refresh `disconnect` to the gateway. With its reconnect off the SDK
32952
+ * would close the socket at once; this client keeps it open when `onRefresh` takes the notice.
32953
+ */
32954
+ var RefreshingClient = class extends SocketModeClient {
32955
+ onRefresh = () => false;
32956
+ async onWebSocketMessage(...args) {
32957
+ const [data, isBinary] = args;
32958
+ const reason = isBinary ? void 0 : disconnectReasonOf(data);
32959
+ if (reason !== void 0 && refreshReasons.includes(reason) && this.onRefresh(reason)) return;
32960
+ await super.onWebSocketMessage(...args);
32961
+ }
32962
+ };
32963
+ /**
32964
+ * The gateway owns transport reconnects: every drop after an `up` schedules attempts with
32965
+ * jittered backoff until `stop()`, each on a fresh SDK client with its reconnect turned off. A
32966
+ * refresh `disconnect` opens the replacement at once while the old socket keeps serving; the old
32967
+ * one closes after the replacement's hello. This layer also owns sink-before-ack ordering.
32968
+ */
32819
32969
  function createSocket(api, config, botIdentity) {
32820
- let socket;
32970
+ const baseDelayMs = config.reconnect?.baseDelayMs ?? 1e3;
32971
+ const maxDelayMs = config.reconnect?.maxDelayMs ?? 6e4;
32972
+ const helloTimeoutMs = config.reconnect?.helloTimeoutMs ?? 3e4;
32973
+ let started = false;
32974
+ let current;
32975
+ let replacement;
32976
+ let retiring;
32977
+ let supervisor;
32978
+ let halt = new AbortController();
32821
32979
  let sink;
32822
32980
  let stopping = false;
32823
- let connected = false;
32824
32981
  const pending = /* @__PURE__ */ new Set();
32982
+ function log(level, fields, msg) {
32983
+ try {
32984
+ config.onLog?.(level, fields, msg);
32985
+ } catch {}
32986
+ }
32987
+ function connectionEvent(state) {
32988
+ track(emit({
32989
+ kind: "connection",
32990
+ state,
32991
+ dedupeKey: `slack:connection:${randomUUID()}`
32992
+ }), "connection");
32993
+ }
32994
+ /**
32995
+ * One connection attempt on a fresh client; `number` is 0 for the first start. A handover
32996
+ * attempt names the up attempt it `replaces` and the reason Slack gave.
32997
+ */
32998
+ function connect(appToken, number, replaces) {
32999
+ const record = {};
33000
+ let disconnectReason;
33001
+ const outcome = Promise.withResolvers();
33002
+ const ended = Promise.withResolvers();
33003
+ const inFlight = /* @__PURE__ */ new Set();
33004
+ let closing = Promise.resolve();
33005
+ let disconnecting;
33006
+ let state = "connecting";
33007
+ const quiet = () => state !== "connecting" && state !== "up";
33008
+ const client = new RefreshingClient({
33009
+ appToken,
33010
+ autoReconnectEnabled: false,
33011
+ logger: createSdkLogger(record, (level, detail) => {
33012
+ if (!quiet()) log(level, { detail }, "slack socket-mode sdk");
33013
+ }),
33014
+ clientOptions: {
33015
+ retryConfig: { retries: 0 },
33016
+ rejectRateLimitedCalls: true,
33017
+ timeout: config.requestTimeoutMs ?? 1e4,
33018
+ ...config.apiUrl === void 0 ? {} : { slackApiUrl: config.apiUrl }
33019
+ }
33020
+ });
33021
+ const disconnect = () => disconnecting ??= client.disconnect();
33022
+ const socketFields = () => ({
33023
+ ...disconnectReason === void 0 ? {} : { disconnectReason },
33024
+ closeCode: record.closeCode ?? 1006,
33025
+ ...record.closeReason === void 0 ? {} : { closeReason: record.closeReason },
33026
+ ...record.socketError === void 0 ? {} : { socketError: record.socketError }
33027
+ });
33028
+ function fail(fields, err) {
33029
+ if (state !== "connecting") return;
33030
+ state = "failed";
33031
+ clearTimeout(helloTimer);
33032
+ log(unrecoverable(err) ? "error" : "warn", {
33033
+ attempt: number,
33034
+ ...fields,
33035
+ ...err === void 0 ? {} : { err }
33036
+ }, "slack socket attempt failed");
33037
+ outcome.resolve("failed");
33038
+ }
33039
+ const attempt = {
33040
+ outcome: outcome.promise,
33041
+ ended: ended.promise,
33042
+ abandon() {
33043
+ if (state === "connecting") {
33044
+ clearTimeout(helloTimer);
33045
+ outcome.resolve("abandoned");
33046
+ }
33047
+ if (state === "connecting" || state === "up" || state === "retired") {
33048
+ state = "abandoned";
33049
+ closing = disconnect();
33050
+ }
33051
+ ended.resolve(void 0);
33052
+ },
33053
+ retire(next) {
33054
+ if (state !== "up") return false;
33055
+ state = "retired";
33056
+ ended.resolve(next);
33057
+ closing = (async () => {
33058
+ while (inFlight.size > 0) await Promise.allSettled([...inFlight]);
33059
+ await disconnect();
33060
+ })();
33061
+ return true;
33062
+ },
33063
+ closed: () => closing
33064
+ };
33065
+ const helloTimer = setTimeout(() => {
33066
+ fail({ failure: "hello_timeout" });
33067
+ closing = disconnect();
33068
+ }, helloTimeoutMs);
33069
+ client.onRefresh = (reason) => {
33070
+ if (state !== "up" || stopping) return false;
33071
+ disconnectReason = reason;
33072
+ handover(appToken, attempt, reason);
33073
+ return true;
33074
+ };
33075
+ client.on("ws_message", (data) => {
33076
+ disconnectReason = disconnectReasonOf(data) ?? disconnectReason;
33077
+ });
33078
+ client.on("connected", () => {
33079
+ if (state !== "connecting") return;
33080
+ state = "up";
33081
+ clearTimeout(helloTimer);
33082
+ const old = replaces?.attempt;
33083
+ if (old?.retire(attempt) === true) {
33084
+ current = attempt;
33085
+ replacement = void 0;
33086
+ retiring = old;
33087
+ old.closed().then(() => {
33088
+ if (retiring === old) retiring = void 0;
33089
+ });
33090
+ log("info", { disconnectReason: replaces?.reason }, "slack socket refreshed");
33091
+ } else {
33092
+ log("info", { attempt: number }, "slack socket up");
33093
+ connectionEvent("up");
33094
+ }
33095
+ outcome.resolve("up");
33096
+ });
33097
+ client.on("disconnected", () => {
33098
+ if (state === "connecting") {
33099
+ fail({
33100
+ failure: "closed_before_hello",
33101
+ ...socketFields()
33102
+ });
33103
+ return;
33104
+ }
33105
+ if (state !== "up") return;
33106
+ log("warn", socketFields(), "slack socket down");
33107
+ state = "down";
33108
+ connectionEvent("down");
33109
+ ended.resolve(void 0);
33110
+ });
33111
+ client.on("slack_event", (envelope) => {
33112
+ if (state !== "up" && state !== "retired") return;
33113
+ const work = handle(envelope);
33114
+ inFlight.add(work);
33115
+ work.catch(() => void 0).finally(() => inFlight.delete(work));
33116
+ track(work, "envelope");
33117
+ });
33118
+ client.start().catch((err) => {
33119
+ fail({ failure: "connections_open" }, err);
33120
+ });
33121
+ return attempt;
33122
+ }
33123
+ /**
33124
+ * Opens the replacement of the up attempt `old` at once; `old` keeps serving until the
33125
+ * replacement's hello. A replacement that fails leaves `old` serving, and its drop then runs
33126
+ * the usual backoff. A refresh notice while a replacement is connecting or closing is ignored:
33127
+ * `old` serves until Slack closes it, then the usual loop runs.
33128
+ */
33129
+ function handover(appToken, old, reason) {
33130
+ if (replacement !== void 0) return;
33131
+ log("info", { disconnectReason: reason }, "slack socket refreshing");
33132
+ const next = connect(appToken, 1, {
33133
+ attempt: old,
33134
+ reason
33135
+ });
33136
+ replacement = next;
33137
+ next.outcome.then(async (outcome) => {
33138
+ if (outcome === "up") return;
33139
+ await next.closed();
33140
+ if (replacement === next) replacement = void 0;
33141
+ });
33142
+ }
33143
+ /** Reconnects after every drop until stop; stopping is its only exit. */
33144
+ async function supervise(appToken, first) {
33145
+ let serving = first;
33146
+ let attempt = 0;
33147
+ for (;;) {
33148
+ const handedTo = await serving.ended;
33149
+ if (stopping) return;
33150
+ if (handedTo !== void 0) {
33151
+ serving = handedTo;
33152
+ continue;
33153
+ }
33154
+ let next = replacement;
33155
+ replacement = void 0;
33156
+ if (next !== void 0) attempt = 1;
33157
+ for (;;) {
33158
+ if (next === void 0) {
33159
+ attempt += 1;
33160
+ const delayMs = reconnectDelay(attempt, {
33161
+ baseDelayMs,
33162
+ maxDelayMs
33163
+ }, Math.random);
33164
+ log("info", {
33165
+ attempt,
33166
+ delayMs
33167
+ }, "slack socket reconnecting");
33168
+ try {
33169
+ await setTimeout$1(delayMs, void 0, {
33170
+ signal: halt.signal,
33171
+ ref: false
33172
+ });
33173
+ } catch {
33174
+ return;
33175
+ }
33176
+ if (halt.signal.aborted) return;
33177
+ next = connect(appToken, attempt);
33178
+ }
33179
+ current = next;
33180
+ if (await next.outcome === "up") {
33181
+ attempt = 0;
33182
+ serving = next;
33183
+ break;
33184
+ }
33185
+ await next.closed();
33186
+ next = void 0;
33187
+ }
33188
+ }
33189
+ }
32825
33190
  function track(work, kind) {
32826
33191
  pending.add(work);
32827
33192
  work.catch((err) => config.onError?.(err, kind)).finally(() => pending.delete(work)).catch(() => {});
@@ -32872,58 +33237,43 @@ function createSocket(api, config, botIdentity) {
32872
33237
  }
32873
33238
  return {
32874
33239
  async start(nextSink) {
32875
- if (socket !== void 0) throw new Error("Slack gateway already started");
33240
+ if (started) throw new Error("Slack gateway already started");
32876
33241
  sink = nextSink;
32877
33242
  stopping = false;
32878
- if (config.appToken === void 0) return;
33243
+ const appToken = config.appToken;
33244
+ if (appToken === void 0) return;
32879
33245
  await botIdentity();
32880
- const client = new SocketModeClient({
32881
- appToken: config.appToken,
32882
- autoReconnectEnabled: true,
32883
- clientOptions: {
32884
- retryConfig: { retries: 0 },
32885
- rejectRateLimitedCalls: true,
32886
- timeout: config.requestTimeoutMs ?? 1e4,
32887
- ...config.apiUrl === void 0 ? {} : { slackApiUrl: config.apiUrl }
32888
- }
32889
- });
32890
- socket = client;
32891
- client.on("connected", () => {
32892
- connected = true;
32893
- track(emit({
32894
- kind: "connection",
32895
- state: "up",
32896
- dedupeKey: `slack:connection:${randomUUID()}`
32897
- }), "connection");
32898
- });
32899
- client.on("close", () => {
32900
- if (!connected || stopping) return;
32901
- connected = false;
32902
- track(emit({
32903
- kind: "connection",
32904
- state: "down",
32905
- dedupeKey: `slack:connection:${randomUUID()}`
32906
- }), "connection");
32907
- });
32908
- client.on("slack_event", (envelope) => {
32909
- track(handle(envelope), "envelope");
32910
- });
32911
- try {
32912
- await client.start();
32913
- } catch {
32914
- socket = void 0;
33246
+ started = true;
33247
+ halt = new AbortController();
33248
+ const first = connect(appToken, 0);
33249
+ current = first;
33250
+ if (await first.outcome !== "up") {
33251
+ await first.closed();
33252
+ started = false;
33253
+ current = void 0;
32915
33254
  sink = void 0;
32916
33255
  throw new Error("Slack Socket Mode start failed");
32917
33256
  }
33257
+ supervisor = supervise(appToken, first);
32918
33258
  },
32919
33259
  async stop() {
32920
33260
  stopping = true;
32921
- const client = socket;
32922
- socket = void 0;
32923
- if (client !== void 0) await client.disconnect();
33261
+ halt.abort();
33262
+ const attempts = [
33263
+ current,
33264
+ replacement,
33265
+ retiring
33266
+ ].filter((attempt) => attempt !== void 0);
33267
+ current = void 0;
33268
+ replacement = void 0;
33269
+ retiring = void 0;
33270
+ for (const attempt of attempts) attempt.abandon();
33271
+ await Promise.all(attempts.map((attempt) => attempt.closed()));
33272
+ await supervisor;
33273
+ supervisor = void 0;
32924
33274
  while (pending.size > 0) await Promise.allSettled([...pending]);
32925
33275
  sink = void 0;
32926
- connected = false;
33276
+ started = false;
32927
33277
  }
32928
33278
  };
32929
33279
  }
@@ -34364,7 +34714,8 @@ function createOutboxModule(ctx, gateway, options = {}) {
34364
34714
  });
34365
34715
  updating = Promise.all([updating, update]).then(() => void 0);
34366
34716
  return update;
34367
- }
34717
+ },
34718
+ liveConnections: () => sender.liveConnections()
34368
34719
  };
34369
34720
  }
34370
34721
  // ../daemon/src/systemd.ts
@@ -34491,6 +34842,9 @@ function createDaemonModules(ctxFor, ports = {}) {
34491
34842
  now: () => ctx.clock.now(),
34492
34843
  onError: (err, work) => {
34493
34844
  ctx.log.error({ err }, work === "connection" ? "slack connection event failed" : "slack envelope failed");
34845
+ },
34846
+ onLog: (level, fields, msg) => {
34847
+ ctx.log[level](fields, msg);
34494
34848
  }
34495
34849
  }));
34496
34850
  const hostCtx = ctxFor("host-metrics");
@@ -34512,6 +34866,7 @@ function createDaemonModules(ctxFor, ports = {}) {
34512
34866
  reapplyInbound: () => inbound?.reapply,
34513
34867
  prPoller: () => boardModules.pollPr,
34514
34868
  budgetWaits: () => boardModules.budgetWaits(),
34869
+ liveConnections: () => outbox.liveConnections(),
34515
34870
  ...ports.productVersion === void 0 ? {} : { productVersion: ports.productVersion },
34516
34871
  lastDispatchAt: () => lastDispatchAt,
34517
34872
  webOrigin: () => webPort === void 0 ? void 0 : resolveWebOrigin(board.config.web, webPort)
package/dist/mcp.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { S as renderMcpError, g as OPERATIONS, pt as ERRORS } from "./chunk-Chj2wumn.mjs";
2
- import { o as CliError, r as requestOperation } from "./chunk-BLaWsiXP.mjs";
3
- import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./chunk-DI3BTuEX.mjs";
1
+ import { S as renderMcpError, g as OPERATIONS, pt as ERRORS } from "./chunk-BebxFmW0.mjs";
2
+ import { o as CliError, r as requestOperation } from "./chunk-BbohDnMm.mjs";
3
+ import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./chunk-DEHqpoRe.mjs";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { readFileSync } from "node:fs";
6
6
  import { z } from "zod";