omni-notify-mcp 1.3.461 → 1.3.463

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.
@@ -170,9 +170,9 @@ export class AgentGateway {
170
170
  void this.awaitTurn(c.id, Number(turn), partsRelay((part) => door(c, part), carriageOf(c.platform, c.chat ?? "")), pending).catch((err) => appendEvent(c.id, { role: "system", kind: "status", text: `❌ The answer could not be sent to this ${c.platform} thread after the BN restart: ${err instanceof Error ? err.message : String(err)}` }));
171
171
  }
172
172
  }
173
- /** No turn running or queued, no chat message waiting on its conversation's creation, and no chat waiting on an answer: the gateway can pass to another process without losing one. */
173
+ /** No chat message waiting on its conversation's creation: the gateway can pass to another process without losing one. A turn under way never holds it — the next build takes a cut turn up again on its session and sends its answer to its chat (#2116, #4584). */
174
174
  quiet() {
175
- return this.driver.quiet() && !creationsPending() && [...this.turns.values()].every((turns) => turns.size === 0);
175
+ return !creationsPending();
176
176
  }
177
177
  /** Gives the store back when this process hands the gateway over. */
178
178
  async shutdown() {
@@ -34,6 +34,7 @@ export const SETTINGS = [
34
34
  { path: ["slack", "enabled"], label: "Enabled", kind: "toggle" },
35
35
  { path: ["slack", "botToken"], label: "Bot token", kind: "secret", hint: "Starts with xoxb-. api.slack.com/apps, your app, OAuth & Permissions, Bot User OAuth Token. Needs the chat:write scope. Use this with Channels, or use the Webhook URL instead." },
36
36
  { path: ["slack", "configToken"], label: "Configuration token", kind: "secret", hint: "Lets BN repair its own Slack app (scopes, the Messages tab). api.slack.com/apps, Your App Configuration Tokens, Generate Token." },
37
+ { path: ["slack", "configRefreshToken"], label: "Configuration refresh token", kind: "secret", hint: "Generated with the configuration token. BN renews the 12-hour token with it, so setup keeps working." },
37
38
  { path: ["slack", "channels"], label: "Channels (comma-separated)", kind: "list", hint: "Channel ids like C0123ABCD (Slack: channel name, View channel details, bottom of the About tab). Invite the bot to each channel first." },
38
39
  { path: ["slack", "webhookUrl"], label: "Webhook URL", kind: "secret", hint: "Simplest option: https://hooks.slack.com/services/... from your app, Incoming Webhooks, Add New Webhook to Workspace." },
39
40
  ] },
@@ -203,18 +203,30 @@ function control(row) {
203
203
  }
204
204
  return wrap;
205
205
  }
206
- function setupText(r) { return ["Intent:"].concat(r.intent.map(function (x) { return "• " + x; }), ["Installed:"], r.installed.length ? r.installed.map(function (x) { return "• " + x; }) : ["• nothing yet"], r.repaired.length ? ["Repaired just now:"].concat(r.repaired.map(function (x) { return "• " + x; })) : [], r.gaps.length ? ["Still missing:"].concat(r.gaps.map(function (x) { return "• " + x; })) : []).join("\n"); }
206
+ var busy = {};
207
+ function factRows(table, label, items) { items.forEach(function (x, i) { var tr = el("tr"); tr.append(el("td", "name", i === 0 ? label : ""), el("td", "", x)); table.append(tr); }); }
207
208
  function setupRow(g) {
208
- var row = el("tr"), cell = el("td"), button = el("button", "", "🔁 Reinstall"), detail = el("pre", "hint");
209
+ var row = el("tr"), cell = el("td"), button = el("button", "", "🔁 Reinstall"), working = el("span", "hint", ""), facts = el("table"), last = g.setup && g.setup.last;
209
210
  button.title = "Makes what is installed match what is set above, and shows both";
210
- detail.textContent = g.setup && g.setup.last ? setupText({ intent: g.setup.intent, installed: g.setup.last.installed, repaired: g.setup.last.repaired, gaps: g.setup.last.gaps }) : "Intent:\n" + (g.setup ? g.setup.intent.map(function (x) { return "• " + x; }).join("\n") : "");
211
+ facts.setAttribute("aria-label", g.title + " setup");
212
+ factRows(facts, "Intent", g.setup ? g.setup.intent : []);
213
+ factRows(facts, "Installed", last ? (last.installed.length ? last.installed : ["nothing yet"]) : ["not checked yet"]);
214
+ if (last && last.repaired.length) factRows(facts, "Repaired", last.repaired);
215
+ if (last) factRows(facts, "Missing", last.gaps.length ? last.gaps : ["nothing"]);
216
+ var inFlight = !!busy[g.messenger] || !!(g.setup && g.setup.running);
217
+ button.disabled = inFlight;
218
+ working.textContent = inFlight ? "⏳ Working" : "";
211
219
  button.onclick = async function () {
212
- button.disabled = true;
213
- try { var r = await call("POST", "/v1/messenger-setup", { messenger: g.messenger }); detail.textContent = setupText(r); say(r.gaps.length ? "error" : "good", r.gaps.length ? "⚠️ " + g.title + " still lacks " + r.gaps.length + " thing(s) — see the list" : "✅ " + g.title + " installed to match your settings"); }
214
- catch (e) { say("error", "❌ " + g.title + " reinstall failed — " + plainWhy(e)); }
215
- button.disabled = false;
220
+ busy[g.messenger] = true; button.disabled = true; working.textContent = "⏳ Working";
221
+ try {
222
+ var r = await call("POST", "/v1/messenger-setup", { messenger: g.messenger });
223
+ button.title = r.gaps.length ? r.gaps.join("\n") : "Everything this messenger needs is in place";
224
+ say(r.gaps.length ? "error" : "good", r.gaps.length ? "⚠️ " + g.messenger.toUpperCase() + " " + r.gaps.length + " MISSING" : "✅ " + g.messenger.toUpperCase() + " INSTALLED");
225
+ } catch (e) { button.title = plainWhy(e); say("error", "❌ " + g.messenger.toUpperCase() + " FAILED"); }
226
+ busy[g.messenger] = false;
227
+ await load();
216
228
  };
217
- cell.colSpan = 2; cell.append(button, detail); row.append(cell); return row;
229
+ cell.colSpan = 2; cell.append(button, working, facts); row.append(cell); return row;
218
230
  }
219
231
  function shownOf(s) { return JSON.stringify([s.state, s.conversation, s.groups, s.configPath]); }
220
232
  function draw(s) {
@@ -106,6 +106,19 @@ export class PollCursors {
106
106
  writeFileSync(staged, JSON.stringify(all));
107
107
  renameSync(staged, this.path);
108
108
  }
109
+ keys() {
110
+ return Object.keys(this.read());
111
+ }
112
+ delete(key) {
113
+ const all = this.read();
114
+ if (!(key in all))
115
+ return;
116
+ delete all[key];
117
+ mkdirSync(dirname(this.path), { recursive: true });
118
+ const staged = `${this.path}.tmp`;
119
+ writeFileSync(staged, JSON.stringify(all));
120
+ renameSync(staged, this.path);
121
+ }
109
122
  getNumber(key) {
110
123
  const stored = this.get(key);
111
124
  if (stored === undefined)
@@ -263,9 +263,11 @@ export class EmailAgentInbox {
263
263
  return this.answer({ messageId: thread.messageIds.at(-1), references: thread.messageIds.slice(0, -1) }, thread.subject, text);
264
264
  }
265
265
  /** One answer, mailed to his own account as a reply in the thread of the mail it answers; replying to it reaches the agent again. */
266
- answer(mail, subject, text) {
267
- const { user } = this.account();
268
- return this.mail({
266
+ async answer(mail, subject, text) {
267
+ const { user, pass } = this.account();
268
+ const server = this.smtpServer();
269
+ const transport = createTransport({ ...server, auth: { user: user, pass: pass } });
270
+ const message = {
269
271
  from: { name: "BN agent", address: user },
270
272
  to: user,
271
273
  replyTo: agentAddress(user),
@@ -274,23 +276,7 @@ export class EmailAgentInbox {
274
276
  references: [...mail.references, mail.messageId],
275
277
  headers: { [AGENT_HEADER]: "answer" },
276
278
  text,
277
- });
278
- }
279
- /** #4581 — the `email` priority's one channel: a notification mailed whole to his own account, its first line the subject. */
280
- notifyOwner(text) {
281
- const { user } = this.account();
282
- return this.mail({ from: { name: "BullseyeNotify", address: user }, to: user, subject: text.split("\n", 1)[0].replace(/\*/g, "").trim() || "BullseyeNotify", text });
283
- }
284
- /** #4581 — logs in to the account's SMTP server and sends nothing; throws why the login failed. */
285
- async verify() {
286
- const { user, pass } = this.account();
287
- await createTransport({ ...this.smtpServer(), auth: { user: user, pass: pass } }).verify();
288
- }
289
- /** Sends one mail through the account's SMTP server, retrying a transient refusal; throws why it did not go. */
290
- async mail(message) {
291
- const { user, pass } = this.account();
292
- const server = this.smtpServer();
293
- const transport = createTransport({ ...server, auth: { user: user, pass: pass } });
279
+ };
294
280
  for (let attempt = 1;; attempt++) {
295
281
  try {
296
282
  await transport.sendMail(message);
@@ -298,7 +284,7 @@ export class EmailAgentInbox {
298
284
  }
299
285
  catch (err) {
300
286
  if (attempt >= SMTP_ATTEMPTS || !transientSmtp(err))
301
- throw new Error(`${server.host} did not take the mail after ${attempt} attempt(s): ${err instanceof Error ? err.message : String(err)}`);
287
+ throw new Error(`${server.host} did not take the answer after ${attempt} attempt(s): ${err instanceof Error ? err.message : String(err)}`);
302
288
  await new Promise((resolve) => setTimeout(resolve, 2000 * 2 ** (attempt - 1)));
303
289
  }
304
290
  }
@@ -337,18 +337,25 @@ const SLACK_HINTS = {
337
337
  token_revoked: "the bot token was revoked — reinstall the BN Slack app and paste its new token",
338
338
  account_inactive: "the bot's Slack account is deactivated — reinstall the BN Slack app",
339
339
  missing_scope: "the BN Slack app lacks a permission this needs (im:history, im:write, chat:write, users:read) — add it and reinstall the app",
340
+ token_expired: "the configuration token expired — paste a new configuration token and its refresh token into BN settings, Slack",
341
+ invalid_refresh_token: "Slack refused the configuration refresh token — paste a new configuration token and its refresh token into BN settings, Slack",
342
+ messages_tab_disabled: "the app's App Home Messages tab does not let people message it — BN setup turns it on once it holds a configuration token",
340
343
  fatal_error: "Slack failed on its side and part of the call may have gone through, so it is not sent again — nothing shows twice",
341
344
  };
342
345
  // GATE: the errors Slack's method pages document as passing — rate limited, a transient issue on its end, unavailable for now, mid-migration, or
343
346
  // the POST data missing or cut short on the way — the same call is tried again after a wait. fatal_error is not among them: Slack says part of the
344
347
  // call may have gone through, so a post tried again could show twice.
348
+ // GATE: Slack says an internal_error on these methods may have gone through, so a post or an opening tried again could show twice — it is refused here, never re-sent.
349
+ const SLACK_NOT_RESENT = new Set(["chat.postMessage", "conversations.open", "conversations.join"]);
345
350
  const SLACK_PASSING = new Set(["ratelimited", "rate_limited", "internal_error", "service_unavailable", "team_added_to_org", "request_timeout"]);
346
- // GATE: the errors Slack documents as refusals on the methods this bridge calls (chat.postMessage, chat.update, conversations.open, conversations.history) — terminal, never re-sent.
351
+ // GATE: the errors Slack documents as refusals on the methods this bridge calls (chat.postMessage, chat.update, conversations.open, conversations.join, conversations.history, apps.manifest.export, apps.manifest.update, tooling.tokens.rotate) — terminal, never re-sent.
347
352
  const SLACK_REFUSALS = new Set([
348
353
  "access_denied", "account_inactive", "fatal_error", "channel_not_found", "cannot_dm_bot", "cant_update_message", "deprecated_endpoint", "edit_window_closed", "ekm_access_denied",
349
354
  "enterprise_is_restricted", "invalid_arguments", "invalid_auth", "invalid_blocks", "invalid_charset", "invalid_cursor", "invalid_form_data", "invalid_ts_latest", "invalid_ts_oldest",
350
355
  "is_archived", "message_not_found", "method_deprecated", "missing_scope", "msg_too_long", "no_permission", "no_text", "not_allowed_token_type", "not_authed", "not_in_channel",
351
- "org_login_required", "restricted_action", "team_access_not_granted", "token_expired", "token_revoked", "too_many_users", "two_factor_setup_required", "user_not_found", "user_not_visible", "users_list_not_supplied",
356
+ "org_login_required", "restricted_action", "method_not_supported_for_channel_type", "invalid_refresh_token", "invalid_manifest", "invalid_app_id", "app_not_found",
357
+ "messages_tab_disabled", "restricted_action_read_only_channel", "posting_to_channel_denied", "message_limit_exceeded", "missing_argument", "user_disabled", "app_cannot_join_channel", "not_enough_users",
358
+ "channel_is_limited_access", "not_workspace_member", "too_many_members", "failed_export", "app_not_eligible", "app_edit_disabled", "invalid_app", "accesslimited", "team_access_not_granted", "token_expired", "token_revoked", "too_many_users", "two_factor_setup_required", "user_not_found", "user_not_visible", "users_list_not_supplied",
352
359
  ]);
353
360
  /** One Slack Web API call, a form POST (the one body every method takes, read methods included): retried on a network failure, a 5xx, a 429 (after its Retry-After) or a documented passing error, refused on a documented error, thrown whole on anything else. */
354
361
  export async function slackCall(base, token, method, body, tries = TELEGRAM_TRIES) {
@@ -388,17 +395,53 @@ export async function slackCall(base, token, method, body, tries = TELEGRAM_TRIE
388
395
  if (response.status === 200 && json.ok === true)
389
396
  return json;
390
397
  const error = String(json.error ?? "");
391
- if (response.status === 200 && SLACK_PASSING.has(error)) {
398
+ const named = method.split("?")[0];
399
+ const resendable = SLACK_PASSING.has(error) && !(error === "internal_error" && SLACK_NOT_RESENT.has(named));
400
+ if (response.status === 200 && resendable) {
392
401
  if (last)
393
402
  throw new SlackUnreachable(`Slack kept answering ${method} with ${error} through ${attempt} tries`);
394
403
  await sleep(backoff);
395
404
  continue;
396
405
  }
397
- if (response.status === 200 && SLACK_REFUSALS.has(error))
406
+ if (response.status === 200 && (SLACK_REFUSALS.has(error) || (error === "internal_error" && SLACK_NOT_RESENT.has(named))))
398
407
  throw new SlackRefused(method, error);
399
408
  throw new SlackUnknown(method, response.status, raw, response.headers);
400
409
  }
401
410
  }
411
+ // GATE: the bodies Slack's incoming-webhook documentation lists as refusals of a post — terminal, never re-sent. A 429 or 5xx is passing and is tried again.
412
+ const SLACK_WEBHOOK_REFUSALS = new Set(["invalid_payload", "user_not_found", "channel_not_found", "channel_is_archived", "action_prohibited", "posting_to_general_channel_denied", "no_service", "no_service_id", "no_team", "team_disabled", "invalid_token", "no_active_hooks", "no_text", "too_many_attachments"]);
413
+ /** One post to an incoming webhook: retried on a network failure, a 5xx or a 429; refused on a documented body; thrown whole on anything else. */
414
+ export async function slackWebhookPost(url, payload, tries = TELEGRAM_TRIES) {
415
+ for (let attempt = 1;; attempt++) {
416
+ const last = attempt >= tries;
417
+ const backoff = 1000 * 2 ** (attempt - 1);
418
+ let response;
419
+ try {
420
+ response = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload), signal: AbortSignal.timeout(15_000) });
421
+ }
422
+ catch (err) {
423
+ if (!(err instanceof TypeError) && !(err instanceof DOMException))
424
+ throw err;
425
+ if (last)
426
+ throw new SlackUnreachable(`the Slack webhook could not be reached after ${attempt} tries: ${err.message}`);
427
+ await sleep(backoff);
428
+ continue;
429
+ }
430
+ const body = (await response.text()).trim();
431
+ if (response.ok)
432
+ return;
433
+ if (response.status === 429 || response.status >= 500) {
434
+ if (last)
435
+ throw new SlackUnreachable(`the Slack webhook kept answering ${response.status} through ${attempt} tries`);
436
+ const after = Number(response.headers.get("retry-after"));
437
+ await sleep(Number.isFinite(after) && after > 0 ? after * 1000 : backoff);
438
+ continue;
439
+ }
440
+ if (SLACK_WEBHOOK_REFUSALS.has(body))
441
+ throw new SlackRefused("the incoming webhook", body);
442
+ throw new SlackUnknown("the incoming webhook", response.status, body, response.headers);
443
+ }
444
+ }
402
445
  /** The agent's markdown in Slack's mrkdwn, built on the one Telegram converter: the same headings, bullets, tables-as-bullets and escapes (Slack escapes &, < and > as HTML does). */
403
446
  export function markdownToSlackMrkdwn(text) {
404
447
  return markdownToTelegramHtml(text)
@@ -15,8 +15,6 @@ export function formatIdleReading(reading) {
15
15
  : `idle: could not measure — ${reading.why} — user activity unknown, so activity gating is skipped`;
16
16
  }
17
17
  const EVERY_PRIORITY = ["low", "normal", "high"];
18
- /** #4581 — every priority a caller may name: the three that fan out, and `email`, which reaches the one email channel and nothing else. */
19
- export const PRIORITIES = [...EVERY_PRIORITY, "email"];
20
18
  // GATE: which priorities reach each channel, in send order, and what an at-keyboard user holds back — a channel is never attempted for a priority outside its list
21
19
  const CHANNEL_ROUTES = [
22
20
  { channel: "desktop", priorities: ["normal", "high"], atKeyboard: "desktopSignal" },
@@ -26,10 +24,9 @@ const CHANNEL_ROUTES = [
26
24
  { channel: "slack", priorities: EVERY_PRIORITY, atKeyboard: "channelLog" },
27
25
  { channel: "teams", priorities: EVERY_PRIORITY, atKeyboard: "heldBack" },
28
26
  { channel: "sms", priorities: ["high"], atKeyboard: "heldBack" },
29
- { channel: "email", priorities: ["email"], atKeyboard: "heldBack" },
30
27
  ];
31
28
  export function describePriorityRouting() {
32
- return PRIORITIES
29
+ return EVERY_PRIORITY
33
30
  .map((priority) => `${priority}=${CHANNEL_ROUTES.filter((route) => route.priorities.includes(priority)).map((route) => route.channel).join("+")}`)
34
31
  .join("; ");
35
32
  }
@@ -45,12 +42,12 @@ export function computeDesktopOnlyMode(priority, policy, ctx) {
45
42
  reason: "DND active — every priority is held, no channel was attempted",
46
43
  };
47
44
  }
48
- if (priority === "high" || priority === "email") {
45
+ if (priority === "high") {
49
46
  return {
50
47
  desktopOnly: false,
51
48
  idle: ctx.idle,
52
49
  idleKnown,
53
- reason: `priority=${priority} — every enabled channel of that priority is used and activity gating is waived`,
50
+ reason: "priority=high — every enabled channel is used and activity gating is waived",
54
51
  };
55
52
  }
56
53
  // The measurement FAILED: a deliberate fail-open. Stated as its own branch so
@@ -111,7 +108,6 @@ export async function sendWithRouting(options) {
111
108
  slack: options.enableSlack,
112
109
  teams: options.enableTeams,
113
110
  sms: options.enableSms,
114
- email: options.enableEmail,
115
111
  };
116
112
  const decision = computeDesktopOnlyMode(priority, policy, ctx);
117
113
  if (decision.suppressedReason === "dnd") {
@@ -1,7 +1,8 @@
1
- /** The one setup path both messengers use: BN's start and the UI's Reinstall run the same reconcile. */
1
+ /** The one setup path both messengers use: BN's start and the UI's Reinstall run the same reconcile, one at a time per messenger. */
2
2
  class MessengerSetups {
3
3
  setups = new Map();
4
4
  lastReports = new Map();
5
+ chains = new Map();
5
6
  add(setup) {
6
7
  this.setups.set(setup.name, setup);
7
8
  }
@@ -14,18 +15,41 @@ class MessengerSetups {
14
15
  /** The intent of one messenger beside its last report, for the page to draw. */
15
16
  view(name) {
16
17
  const setup = this.setups.get(name);
17
- return setup === undefined ? undefined : { intent: setup.intent(), last: this.lastReports.get(name) };
18
+ return setup === undefined ? undefined : { intent: setup.intent(), last: this.lastReports.get(name), running: this.running.has(name) };
18
19
  }
19
- async reconcile(name) {
20
- const report = await this.of(name).reconcile();
21
- this.lastReports.set(name, report);
22
- return report;
20
+ running = new Set();
21
+ /** Runs `work` after everything already queued for this messenger — its setup, its direct-message reads — and before anything queued later. */
22
+ exclusive(name, work) {
23
+ const run = (this.chains.get(name) ?? Promise.resolve()).then(work);
24
+ this.chains.set(name, run.then(() => undefined, () => undefined));
25
+ return run;
23
26
  }
24
- async reconcileAll() {
25
- const reports = [];
26
- for (const name of this.setups.keys())
27
- reports.push(await this.reconcile(name));
28
- return reports;
27
+ /** One reconcile of one messenger. A failure its service documents is a gap in the report; any other failure is thrown. */
28
+ reconcile(name) {
29
+ const setup = this.of(name);
30
+ return this.exclusive(name, async () => {
31
+ this.running.add(name);
32
+ try {
33
+ let report;
34
+ try {
35
+ report = await setup.reconcile();
36
+ }
37
+ catch (err) {
38
+ const why = setup.describeFailure(err);
39
+ if (why === undefined)
40
+ throw err;
41
+ report = { messenger: name, intent: setup.intent(), installed: [], repaired: [], gaps: [why], at: Date.now() };
42
+ }
43
+ this.lastReports.set(name, report);
44
+ return report;
45
+ }
46
+ finally {
47
+ this.running.delete(name);
48
+ }
49
+ });
50
+ }
51
+ names() {
52
+ return [...this.setups.keys()];
29
53
  }
30
54
  }
31
55
  export const MESSENGER_SETUPS = new MessengerSetups();
@@ -1,6 +1,6 @@
1
- import { SlackRefused, slackCall } from "./messenger.js";
1
+ import { SlackRefused, SlackUnreachable, SlackUnknown, slackCall } from "./messenger.js";
2
2
  /** Every bot scope BN's Slack side uses: the DM chat (im:*, chat:write), the bus channel (channels:*, groups:*) and finding Meni (users:read). */
3
- export const SLACK_BOT_SCOPES = ["chat:write", "channels:history", "channels:read", "channels:join", "groups:history", "groups:read", "im:history", "im:read", "im:write", "users:read", "incoming-webhook"];
3
+ export const SLACK_BOT_SCOPES = ["chat:write", "channels:history", "channels:read", "channels:join", "groups:history", "groups:read", "im:history", "im:read", "im:write", "users:read"];
4
4
  /** The app BN needs, as Slack's manifest states it: a bot user people can message from the App Home Messages tab, with every scope above. */
5
5
  export function slackAppManifest(name) {
6
6
  return {
@@ -9,21 +9,21 @@ export function slackAppManifest(name) {
9
9
  bot_user: { display_name: name, always_online: true },
10
10
  app_home: { home_tab_enabled: false, messages_tab_enabled: true, messages_tab_read_only_enabled: false },
11
11
  },
12
- oauth_config: { scopes: { bot: [...SLACK_BOT_SCOPES.filter((s) => s !== "incoming-webhook")] } },
12
+ oauth_config: { scopes: { bot: [...SLACK_BOT_SCOPES] } },
13
13
  settings: { org_deploy_enabled: false, socket_mode_enabled: false, token_rotation_enabled: false },
14
14
  };
15
15
  }
16
- /** The things the Slack setup still lacks after every repair BN can make itself; each names the one act left. */
17
- export class SlackSetupGaps extends Error {
18
- gaps;
19
- constructor(gaps) {
20
- super(gaps.join("; "));
21
- this.gaps = gaps;
22
- }
16
+ /** The failure classes Slack's documented answers and an unreachable Slack make: a gap in the report, never a stop. */
17
+ export function isSlackFailure(err) {
18
+ return err instanceof SlackRefused || err instanceof SlackUnreachable || err instanceof SlackUnknown;
23
19
  }
24
- /** Reads who the token is and what it may do: auth.test's granted scopes (a response header), then the app behind the bot. */
20
+ /** Reads who the token is and what Slack granted it: auth.test's scopes header, then the app behind the bot. */
25
21
  export async function slackStanding(base, token) {
26
- const auth = await fetch(`${base}/auth.test`, { method: "POST", headers: { Authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(15_000) });
22
+ const auth = await fetch(`${base}/auth.test`, { method: "POST", headers: { Authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(15_000) }).catch((err) => {
23
+ if (!(err instanceof TypeError) && !(err instanceof DOMException))
24
+ throw err;
25
+ throw new SlackUnreachable(`Slack could not be reached for auth.test: ${err.message}`);
26
+ });
27
27
  const body = await auth.json();
28
28
  if (body.ok !== true)
29
29
  throw new SlackRefused("auth.test", String(body.error ?? "unknown"));
@@ -31,31 +31,129 @@ export async function slackStanding(base, token) {
31
31
  const bot = (await slackCall(base, token, "bots.info", { bot: String(body.bot_id) })).bot;
32
32
  return { appId: bot.app_id, botName: bot.name, granted };
33
33
  }
34
- /**
35
- * Brings the Slack app to the manifest above through Slack's own app-configuration API, which needs the configuration token of BN settings.
36
- * Slack asks the workspace owner to approve changed scopes, so a repair that changed them names the one tap left: the reinstall.
37
- */
38
- async function repairManifest(base, configToken, standing, wanted) {
39
- const current = (await slackCall(base, configToken, "apps.manifest.export", { app_id: standing.appId })).manifest;
34
+ /** Slack's own renewal of a configuration token: a new token and a new refresh token, the old pair dead. */
35
+ async function rotateConfigToken(base, refresh) {
36
+ const r = await fetch(`${base}/tooling.tokens.rotate`, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ refresh_token: refresh }), signal: AbortSignal.timeout(15_000) })
37
+ .catch((err) => {
38
+ if (!(err instanceof TypeError) && !(err instanceof DOMException))
39
+ throw err;
40
+ throw new SlackUnreachable(`Slack could not be reached for tooling.tokens.rotate: ${err.message}`);
41
+ });
42
+ const body = await r.json();
43
+ if (body.ok !== true)
44
+ throw new SlackRefused("tooling.tokens.rotate", String(body.error ?? "unknown"));
45
+ return { token: String(body.token), refresh: String(body.refresh_token) };
46
+ }
47
+ /** One call with the configuration token; an expired token is renewed once with the refresh token and the call made again. */
48
+ async function configCall(i, method, body) {
49
+ try {
50
+ return await slackCall(i.base, i.tokens.token, method, body);
51
+ }
52
+ catch (err) {
53
+ if (!(err instanceof SlackRefused) || err.error !== "token_expired" || i.tokens.refresh === undefined)
54
+ throw err;
55
+ const renewed = await rotateConfigToken(i.base, i.tokens.refresh);
56
+ i.persistTokens(renewed);
57
+ i.tokens = { token: renewed.token, refresh: renewed.refresh };
58
+ return slackCall(i.base, renewed.token, method, body);
59
+ }
60
+ }
61
+ /** Brings the Slack app to the manifest through Slack's app-configuration API; reads the Messages tab and the declared scopes, and writes only what differs. */
62
+ async function reconcileManifest(i, standing, facts) {
63
+ const wanted = slackAppManifest(i.appName);
64
+ const current = (await configCall(i, "apps.manifest.export", { app_id: standing.appId })).manifest;
40
65
  const declared = current.oauth_config?.scopes?.bot ?? [];
41
- const scopesWhole = wanted.oauth_config.scopes.bot.every((s) => declared.includes(s));
42
- const messagesOpen = current.features?.app_home?.messages_tab_enabled === true && current.features?.app_home?.messages_tab_read_only_enabled === false;
43
- if (scopesWhole && messagesOpen && current.features?.bot_user !== undefined)
44
- return [];
45
- const merged = { ...current, features: { ...current.features, bot_user: current.features?.bot_user ?? wanted.features.bot_user, app_home: { ...current.features?.app_home, ...wanted.features.app_home } }, oauth_config: { ...current.oauth_config, scopes: { ...current.oauth_config?.scopes, bot: [...new Set([...declared, ...wanted.oauth_config.scopes.bot])] } } };
46
- await slackCall(base, configToken, "apps.manifest.update", { app_id: standing.appId, manifest: JSON.stringify(merged) });
47
- return [`the Slack app ${standing.botName} was updated to hold every scope and the Messages tab; Slack needs the workspace owner to approve it once: open https://api.slack.com/apps/${standing.appId}/install-on-team and tap Reinstall`];
66
+ const scopesDeclared = SLACK_BOT_SCOPES.every((s) => declared.includes(s));
67
+ const home = current.features?.app_home;
68
+ const messagesOpen = home?.messages_tab_enabled === true && home?.messages_tab_read_only_enabled === false;
69
+ if (scopesDeclared && messagesOpen && current.features?.bot_user !== undefined) {
70
+ facts.installed.push("the app declares every scope and its Messages tab is open for sending");
71
+ return;
72
+ }
73
+ const merged = {
74
+ ...current,
75
+ features: { ...current.features, bot_user: current.features?.bot_user ?? wanted.features.bot_user, app_home: { ...home, ...wanted.features.app_home } },
76
+ oauth_config: { ...current.oauth_config, scopes: { ...current.oauth_config?.scopes, bot: [...new Set([...declared, ...SLACK_BOT_SCOPES])] } },
77
+ };
78
+ await configCall(i, "apps.manifest.update", { app_id: standing.appId, manifest: JSON.stringify(merged) });
79
+ facts.repaired.push("the app now declares every scope and its Messages tab is open for sending");
80
+ }
81
+ /** One bus channel: readable by the bot, and read by BN's own listener. A bot outside a public channel joins it; where it cannot, the gap names the act left. */
82
+ async function reconcileChannel(i, standing, channel, facts) {
83
+ try {
84
+ await slackCall(i.base, i.token, "conversations.history", { channel, limit: 1 });
85
+ }
86
+ catch (err) {
87
+ if (!(err instanceof SlackRefused))
88
+ throw err;
89
+ if (err.error === "channel_not_found")
90
+ throw new SlackRefused("conversations.history", `channel_not_found — ${channel} is a private channel the bot is not in, or its id is wrong: invite the bot there (/invite @${standing.botName}) and check the id in BN settings`);
91
+ if (err.error !== "not_in_channel")
92
+ throw err;
93
+ if (!standing.granted.includes("channels:join"))
94
+ throw new SlackRefused("conversations.history", `not_in_channel — invite the bot to ${channel} (/invite @${standing.botName}), or grant the app channels:join`);
95
+ await slackCall(i.base, i.token, "conversations.join", { channel });
96
+ facts.repaired.push(`the bot joined the bus channel ${channel}`);
97
+ }
98
+ if (await i.polled(channel))
99
+ facts.installed.push(`the bot is in the bus channel ${channel} and BN's listener reads it`);
100
+ else
101
+ facts.gaps.push(`the bus channel ${channel} is readable but BN's listener has not read it`);
48
102
  }
49
103
  /**
50
- * The check BN makes of its own Slack setup: the token's standing, then the repair of what is missing through the same code. Returns what is still
51
- * missing, each item naming the one act left — empty when the setup is whole.
104
+ * BN's check of its own Slack setup, and the repair of what it can: the token's standing, the scopes Slack GRANTED, the app's manifest and Messages
105
+ * tab, the webhook, and every bus channel — one step each, run by one loop that owns every failure Slack documents (or an unreachable Slack) as a
106
+ * gap in the facts. A failure that is none of those is thrown.
52
107
  */
53
- export async function slackVerifyAndRepair(base, token, configToken, appName) {
54
- const standing = await slackStanding(base, token);
55
- const missing = SLACK_BOT_SCOPES.filter((s) => s !== "incoming-webhook" && !standing.granted.includes(s));
56
- if (configToken === undefined) {
57
- const gaps = missing.length === 0 ? [] : [`the Slack app ${standing.botName} lacks the scopes ${missing.join(", ")}, and BN cannot see or open its App Home Messages tab (without it Slack refuses a direct message to the bot with \"failed to send\"), because BN holds no Slack configuration token to repair it: create one at https://api.slack.com/apps (Your App Configuration Tokens) and paste it into BN settings, Slack, Configuration token`];
58
- return { standing, gaps };
108
+ export async function slackVerifyAndRepair(i) {
109
+ const facts = { installed: [], repaired: [], gaps: [] };
110
+ const steps = [{ name: "the bot token", fatal: true, run: async () => { facts.standing = await slackStanding(i.base, i.token); } }];
111
+ steps.push({
112
+ name: "the app manifest",
113
+ fatal: false,
114
+ run: async (standing) => {
115
+ if (i.tokens.token === undefined) {
116
+ facts.gaps.push("BN cannot read or open the App Home Messages tab, and cannot add scopes, because BN holds no Slack configuration token: create one at https://api.slack.com/apps (Your App Configuration Tokens) and paste it, with its refresh token, into BN settings, Slack");
117
+ return;
118
+ }
119
+ await reconcileManifest(i, standing, facts);
120
+ },
121
+ });
122
+ steps.push({
123
+ name: "the scopes",
124
+ fatal: false,
125
+ run: async (standing) => {
126
+ const lacking = SLACK_BOT_SCOPES.filter((s) => !standing.granted.includes(s));
127
+ if (lacking.length === 0)
128
+ facts.installed.push(`Slack has granted the app all ${SLACK_BOT_SCOPES.length} scopes`);
129
+ else
130
+ facts.gaps.push(`Slack has not granted the scopes ${lacking.join(", ")}: approve the app once at https://api.slack.com/apps/${standing.appId}/install-on-team and tap Reinstall`);
131
+ },
132
+ });
133
+ steps.push({
134
+ name: "the incoming webhook",
135
+ fatal: false,
136
+ run: async () => {
137
+ if (i.webhook !== undefined)
138
+ facts.installed.push("an incoming webhook is set");
139
+ else if (i.webhookIsRoute)
140
+ facts.gaps.push("no incoming webhook is set in BN settings, and it is the only way BN's notifications reach Slack: set one, or give BN a bot token and a channel");
141
+ },
142
+ });
143
+ for (const channel of i.channels)
144
+ steps.push({ name: `bus channel ${channel}`, fatal: false, run: (standing) => reconcileChannel(i, standing, channel, facts) });
145
+ for (const step of steps) {
146
+ try {
147
+ await step.run(facts.standing);
148
+ }
149
+ catch (err) {
150
+ // OWNER: ITER/LOOP — one setup step's failure Slack documents (a refusal, an unreachable Slack) is a gap in the facts naming what Slack said, and the later steps still run unless this one is the standing they stand on.
151
+ if (!isSlackFailure(err))
152
+ throw err;
153
+ facts.gaps.push(`${step.name}: ${err.message}`);
154
+ if (step.fatal)
155
+ return facts;
156
+ }
59
157
  }
60
- return { standing, gaps: await repairManifest(base, configToken, standing, slackAppManifest(appName)) };
158
+ return facts;
61
159
  }