@uniquedivine/mcp-slack 4.5.1 → 4.5.3

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/lib/handlers.js CHANGED
@@ -14,7 +14,7 @@ import {
14
14
  isAutoRefreshAvailable,
15
15
  getLastExtractionError
16
16
  } from "./token-store.js";
17
- import { slackAPI, resolveUser, formatTimestamp, sleep, checkTokenHealth, getUserCacheStats } from "./slack-client.js";
17
+ import { slackAPI, resolveUser, formatTimestamp, sleep, checkTokenHealth, getUserCacheStats, manualRefreshAdvice } from "./slack-client.js";
18
18
  import {
19
19
  saveProfile as workflowSaveProfile,
20
20
  listProfiles as workflowListProfiles,
@@ -22,6 +22,7 @@ import {
22
22
  } from "./workflow-store.js";
23
23
  import { withRichMessageFields } from "./rich-message-fields.js";
24
24
  import { isAuthDeath, lifeboatResponse } from "./lifeboat.js";
25
+ import { withWriteLog } from "./write-log.js";
25
26
  import {
26
27
  checkOwnMessage,
27
28
  createRetryTracker,
@@ -140,7 +141,8 @@ export async function handleTokenStatus() {
140
141
  enabled: isAutoRefreshAvailable(),
141
142
  interval: "4 hours",
142
143
  last_attempt: health.refreshed ? "just_now" : null,
143
- requires: isAutoRefreshAvailable() ? "Slack tab open in Chrome" : "Not supported on this platform"
144
+ requires: isAutoRefreshAvailable() ? "Slack tab open in Chrome" : "Not supported on this platform",
145
+ manual_refresh: isAutoRefreshAvailable() ? null : manualRefreshAdvice()
144
146
  },
145
147
  cache: {
146
148
  users: cacheStats,
@@ -598,7 +600,7 @@ async function isGoneOnReread(channel, timestamp, selfId) {
598
600
  * before calling chat.delete, and maps known Slack errors to clear results.
599
601
  */
600
602
  export async function handleDeleteMessage(args) {
601
- return deleteMessage(args, { ignoreAge: false });
603
+ return withWriteLog("slack_delete_message", args, (recorder) => deleteMessage(args, { ignoreAge: false, recorder }));
602
604
  }
603
605
 
604
606
  /**
@@ -606,10 +608,10 @@ export async function handleDeleteMessage(args) {
606
608
  * age window, for deliberate cleanup of older messages.
607
609
  */
608
610
  export async function handleDeleteMessageUnsafe(args) {
609
- return deleteMessage(args, { ignoreAge: true });
611
+ return withWriteLog("slack_delete_message_unsafe", args, (recorder) => deleteMessage(args, { ignoreAge: true, recorder }));
610
612
  }
611
613
 
612
- async function deleteMessage(args, { ignoreAge }) {
614
+ async function deleteMessage(args, { ignoreAge, recorder }) {
613
615
  const invalid = validateTargetArgs(args);
614
616
  if (invalid) return invalid;
615
617
 
@@ -622,6 +624,7 @@ async function deleteMessage(args, { ignoreAge }) {
622
624
  ignoreAge,
623
625
  unsafeTool: "slack_delete_message_unsafe"
624
626
  });
627
+ recorder?.verify(ownership.verified);
625
628
  if (!ownership.ok) return ownership.result;
626
629
  const oldText = ownership.message.text ?? "";
627
630
 
@@ -677,7 +680,7 @@ async function deleteMessage(args, { ignoreAge }) {
677
680
  export const UPDATE_TEXT_MAX_CHARS = 4000;
678
681
 
679
682
  export async function handleUpdateMessage(args) {
680
- return updateMessage(args, { ignoreAge: false });
683
+ return withWriteLog("slack_update_message", args, (recorder) => updateMessage(args, { ignoreAge: false, recorder }));
681
684
  }
682
685
 
683
686
  /**
@@ -685,10 +688,10 @@ export async function handleUpdateMessage(args) {
685
688
  * age window, for deliberate cleanup of older messages.
686
689
  */
687
690
  export async function handleUpdateMessageUnsafe(args) {
688
- return updateMessage(args, { ignoreAge: true });
691
+ return withWriteLog("slack_update_message_unsafe", args, (recorder) => updateMessage(args, { ignoreAge: true, recorder }));
689
692
  }
690
693
 
691
- async function updateMessage(args, { ignoreAge }) {
694
+ async function updateMessage(args, { ignoreAge, recorder }) {
692
695
  const invalid = validateTargetArgs(args);
693
696
  if (invalid) return invalid;
694
697
  if (typeof args.text !== "string" || args.text.trim() === "") {
@@ -707,6 +710,7 @@ async function updateMessage(args, { ignoreAge }) {
707
710
  ignoreAge,
708
711
  unsafeTool: "slack_update_message_unsafe"
709
712
  });
713
+ recorder?.verify(ownership.verified);
710
714
  if (!ownership.ok) return ownership.result;
711
715
 
712
716
  const sessionChanged = sessionChangedResult(ownership, details);
@@ -8,11 +8,19 @@
8
8
  * tests fail when the copies drift apart.
9
9
  *
10
10
  * The server never updates itself: the client config pins an exact version,
11
- * so what runs is what was reviewed. At startup the server reads the npm
12
- * registry's latest version in the background (2 s timeout, 24 h cache,
13
- * silent on failure). The first successful tool result after that check
14
- * carries a one-line notice when the running version is behind. Set
15
- * JIYUU_MCP_NO_UPDATE_CHECK=1 to turn the check off.
11
+ * so what runs is what was reviewed. Two callers read the npm registry's
12
+ * latest version, each with a 2 s timeout:
13
+ *
14
+ * - At startup, in the background, through a 1 h cache. The first successful
15
+ * tool result after that check carries a one-line notice when the running
16
+ * version is behind. Failures are silent.
17
+ * - Tool mcp_info reads the registry on every call and rewrites the cache.
18
+ * When the registry can't be read, it reports the cached answer and marks
19
+ * it with source "cache".
20
+ *
21
+ * A cached latest version older than the running version is out of date, so
22
+ * both callers ignore it. Set JIYUU_MCP_NO_UPDATE_CHECK=1 to turn the check
23
+ * off.
16
24
  */
17
25
  import { execFile } from "node:child_process";
18
26
  import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
@@ -20,7 +28,7 @@ import { homedir } from "node:os";
20
28
  import { dirname, join, resolve, sep } from "node:path";
21
29
 
22
30
  export const OPT_OUT_ENV = "JIYUU_MCP_NO_UPDATE_CHECK";
23
- export const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
31
+ export const CACHE_TTL_MS = 60 * 60 * 1000;
24
32
  export const FETCH_TIMEOUT_MS = 2000;
25
33
  /** Only names Jiyuu publishes are checked; upstream names are someone else's. */
26
34
  export const PUBLISHED_SCOPE = "@uniquedivine/";
@@ -44,6 +52,8 @@ export interface UpdateStatus {
44
52
  runningVersion: string;
45
53
  latestVersion: string;
46
54
  checkedAt: string;
55
+ /** "live" when this call read the registry; "cache" for a cached answer. */
56
+ source: "live" | "cache";
47
57
  }
48
58
 
49
59
  export interface GitState {
@@ -156,7 +166,7 @@ export function isNewer(candidate: string, running: string): boolean {
156
166
  return compareIdentifiers(c.prerelease, r.prerelease) > 0;
157
167
  }
158
168
 
159
- export function updateAvailable(status: UpdateStatus | null): boolean {
169
+ export function updateAvailable(status: UpdateStatus | null): status is UpdateStatus {
160
170
  return status !== null && isNewer(status.latestVersion, status.runningVersion);
161
171
  }
162
172
 
@@ -181,16 +191,26 @@ export function cacheFile(cacheDir: string, name: string): string {
181
191
  return join(cacheDir, `${name.replace(/[^A-Za-z0-9._-]/g, "_")}.json`);
182
192
  }
183
193
 
194
+ export interface CacheReadOptions {
195
+ /** A cached latest version older than this one is out of date. */
196
+ runningVersion?: string;
197
+ /** Maximum entry age; null accepts any age. */
198
+ maxAgeMs?: number | null;
199
+ }
200
+
184
201
  export function readCache(
185
202
  path: string,
186
203
  name: string,
187
204
  now: Date,
205
+ options: CacheReadOptions = {},
188
206
  ): { latestVersion: string; checkedAt: string } | null {
189
207
  try {
190
208
  const data = JSON.parse(readFileSync(path, "utf8"));
191
209
  if (data?.name !== name || typeof data.latestVersion !== "string") return null;
210
+ const { runningVersion, maxAgeMs = CACHE_TTL_MS } = options;
211
+ if (runningVersion !== undefined && isNewer(runningVersion, data.latestVersion)) return null;
192
212
  const age = now.getTime() - Date.parse(data.checkedAt);
193
- if (!(age >= 0 && age < CACHE_TTL_MS)) return null;
213
+ if (!(age >= 0 && (maxAgeMs === null || age < maxAgeMs))) return null;
194
214
  return { latestVersion: data.latestVersion, checkedAt: data.checkedAt };
195
215
  } catch {
196
216
  return null;
@@ -225,23 +245,15 @@ export interface CheckOptions {
225
245
  timeoutMs?: number;
226
246
  }
227
247
 
228
- /**
229
- * Return the latest published version, from cache or the registry. Returns
230
- * null when the check is off, the name isn't Jiyuu's, or the registry can't be
231
- * read. Never throws.
232
- */
233
- export async function checkForUpdate(
248
+ /** Read the registry and rewrite the cache; null on any failure. */
249
+ async function readRegistry(
234
250
  name: string,
235
251
  runningVersion: string,
236
- options: CheckOptions = {},
252
+ path: string,
253
+ now: Date,
254
+ options: CheckOptions,
237
255
  ): Promise<UpdateStatus | null> {
238
- const env = options.env ?? process.env;
239
- if (checkDisabled(env) || !isPublishedName(name)) return null;
240
256
  try {
241
- const now = options.now ?? new Date();
242
- const path = cacheFile(options.cacheDir ?? defaultCacheDir(env), name);
243
- const cached = readCache(path, name, now);
244
- if (cached) return { name, runningVersion, ...cached };
245
257
  const body = await (options.fetch ?? fetchText)(
246
258
  latestVersionUrl(name),
247
259
  options.timeoutMs ?? FETCH_TIMEOUT_MS,
@@ -250,12 +262,51 @@ export async function checkForUpdate(
250
262
  if (!latestVersion) return null;
251
263
  const checkedAt = now.toISOString().replace(/\.\d{3}Z$/, "Z");
252
264
  writeCache(path, { name, latestVersion, checkedAt });
253
- return { name, runningVersion, latestVersion, checkedAt };
265
+ return { name, runningVersion, latestVersion, checkedAt, source: "live" };
254
266
  } catch {
255
267
  return null;
256
268
  }
257
269
  }
258
270
 
271
+ /**
272
+ * The startup check: a fresh cache entry if one exists, else the registry.
273
+ * Returns null when the check is off, the name isn't Jiyuu's, or the registry
274
+ * can't be read. Never throws.
275
+ */
276
+ export async function checkForUpdate(
277
+ name: string,
278
+ runningVersion: string,
279
+ options: CheckOptions = {},
280
+ ): Promise<UpdateStatus | null> {
281
+ const env = options.env ?? process.env;
282
+ if (checkDisabled(env) || !isPublishedName(name)) return null;
283
+ const now = options.now ?? new Date();
284
+ const path = cacheFile(options.cacheDir ?? defaultCacheDir(env), name);
285
+ const cached = readCache(path, name, now, { runningVersion });
286
+ if (cached) return { name, runningVersion, ...cached, source: "cache" };
287
+ return await readRegistry(name, runningVersion, path, now, options);
288
+ }
289
+
290
+ /**
291
+ * The mcp_info check: always the registry, then the cache of any age when the
292
+ * registry can't be read. Returns null when the check is off, the name isn't
293
+ * Jiyuu's, or neither source has an answer. Never throws.
294
+ */
295
+ export async function checkLatest(
296
+ name: string,
297
+ runningVersion: string,
298
+ options: CheckOptions = {},
299
+ ): Promise<UpdateStatus | null> {
300
+ const env = options.env ?? process.env;
301
+ if (checkDisabled(env) || !isPublishedName(name)) return null;
302
+ const now = options.now ?? new Date();
303
+ const path = cacheFile(options.cacheDir ?? defaultCacheDir(env), name);
304
+ const live = await readRegistry(name, runningVersion, path, now, options);
305
+ if (live) return live;
306
+ const cached = readCache(path, name, now, { runningVersion, maxAgeMs: null });
307
+ return cached ? { name, runningVersion, ...cached, source: "cache" } : null;
308
+ }
309
+
259
310
  export function formatNotice(status: UpdateStatus): string {
260
311
  return (
261
312
  `Update available: ${status.name} ${status.latestVersion} ` +
@@ -351,7 +402,7 @@ export function buildMcpInfo(input: McpInfoInput): Record<string, unknown> {
351
402
  if (checkDisabled(env)) notChecked = `disabled by ${OPT_OUT_ENV}`;
352
403
  else if (!isPublishedName(identity.name))
353
404
  notChecked = `'${identity.name}' is not a name Jiyuu publishes`;
354
- else if (!status) notChecked = "no registry result yet (offline, pending, or failed)";
405
+ else if (!status) notChecked = "registry unreachable and no cached result";
355
406
  return {
356
407
  server: input.server,
357
408
  name: identity.name,
@@ -366,7 +417,9 @@ export function buildMcpInfo(input: McpInfoInput): Record<string, unknown> {
366
417
  latestVersion: status?.latestVersion ?? null,
367
418
  updateAvailable: updateAvailable(status),
368
419
  checkedAt: status?.checkedAt ?? null,
369
- pinCommand: status ? pinCommand(status.name, status.latestVersion) : null,
420
+ // Only an upgrade gets a command; a pin to an older release downgrades.
421
+ pinCommand: updateAvailable(status) ? pinCommand(status.name, status.latestVersion) : null,
422
+ source: status?.source ?? null,
370
423
  notChecked,
371
424
  },
372
425
  runtime: {
@@ -381,27 +434,36 @@ export function buildMcpInfo(input: McpInfoInput): Record<string, unknown> {
381
434
  };
382
435
  }
383
436
 
437
+ export interface JiyuuMcpInfoChecks {
438
+ /** The startup check behind the one-time notice; default checkForUpdate. */
439
+ startup?: () => Promise<UpdateStatus | null>;
440
+ /** The check each mcp_info call runs; default checkLatest. */
441
+ live?: (env: Env) => Promise<UpdateStatus | null>;
442
+ }
443
+
384
444
  /** Wire-up for one server process: identity, notifier and the tool body. */
385
445
  export class JiyuuMcpInfo {
386
446
  readonly identity: PackageIdentity;
387
447
  readonly notifier: UpdateNotifier;
448
+ private readonly liveCheck: (env: Env) => Promise<UpdateStatus | null>;
388
449
 
389
450
  constructor(
390
451
  private readonly server: string,
391
452
  packageRoot: string,
392
453
  private readonly envPrefixes: string[],
393
- check?: () => Promise<UpdateStatus | null>,
454
+ checks: JiyuuMcpInfoChecks = {},
394
455
  ) {
395
456
  this.identity = readPackageIdentity(packageRoot);
396
457
  const { name, version } = this.identity;
397
- this.notifier = new UpdateNotifier(check ?? (() => checkForUpdate(name, version)));
458
+ this.notifier = new UpdateNotifier(checks.startup ?? (() => checkForUpdate(name, version)));
459
+ this.liveCheck = checks.live ?? ((env) => checkLatest(name, version, { env }));
398
460
  }
399
461
 
400
462
  async callTool(env: Env = process.env) {
401
- this.notifier.start();
402
- const status = await this.notifier.status(FETCH_TIMEOUT_MS + 500);
403
- const git =
404
- this.identity.provenance === "source-checkout" ? await gitState(this.identity.root) : null;
463
+ const [status, git] = await Promise.all([
464
+ this.liveCheck(env).catch(() => null),
465
+ this.identity.provenance === "source-checkout" ? gitState(this.identity.root) : null,
466
+ ]);
405
467
  const report = buildMcpInfo({
406
468
  server: this.server,
407
469
  identity: this.identity,
package/lib/lifeboat.js CHANGED
@@ -15,9 +15,18 @@
15
15
  * - The long-form message is emitted at most once per process per hour;
16
16
  * subsequent failures inside that window get a one-line version so agents
17
17
  * in retry loops do not spam.
18
- * - Never reads or logs token values — it only inspects error codes.
18
+ * - Never reads or logs token values — it only inspects error codes and
19
+ * the credential source label.
20
+ * - The self-fix fits the setup. Credentials from SLACK_TOKEN/SLACK_COOKIE
21
+ * take precedence over the file --setup writes, so env users are told to
22
+ * update or unset those variables. Off macOS, where Chrome auto-heal and
23
+ * slack_refresh_tokens can't run, the advice is a manual refresh. macOS
24
+ * with file or keychain credentials keeps the original wording.
19
25
  */
20
26
 
27
+ import { platform as osPlatform } from "node:os";
28
+ import { loadTokensReadOnly } from "./token-store.js";
29
+
21
30
  // Slack API error codes (and the HTTP 401 case) that mean the session token
22
31
  // is dead and cannot be auto-healed — the point where the Lifeboat fires.
23
32
  export const AUTH_DEATH_SLACK_CODES = new Set([
@@ -46,6 +55,37 @@ export function resetLifeboatThrottle() {
46
55
  lastLongFormAt = 0;
47
56
  }
48
57
 
58
+ /**
59
+ * Recovery advice for this platform and credential source, or null for the
60
+ * default macOS wording.
61
+ */
62
+ export function recoveryAdvice({ platformName, credentialSource }) {
63
+ if (credentialSource === "environment") {
64
+ return {
65
+ selfFix:
66
+ `Your Slack credentials come from the SLACK_TOKEN and SLACK_COOKIE environment variables, which take precedence over the file \`${SETUP_CMD}\` writes. Update both with fresh values from a signed-in browser session, or unset both and run \`${SETUP_CMD}\`. Full steps: ${README_ANCHOR_URL}`,
67
+ nextAction:
68
+ `Update SLACK_TOKEN and SLACK_COOKIE with fresh values, or unset both and run \`${SETUP_CMD}\`. Running setup alone won't help while they're set.`,
69
+ };
70
+ }
71
+ if (platformName !== "darwin") {
72
+ return {
73
+ selfFix:
74
+ `Auto-refresh only runs on macOS, not ${platformName}. Sign in to Slack in your browser, then run \`${SETUP_CMD}\` to save fresh tokens. Full steps: ${README_ANCHOR_URL}`,
75
+ nextAction: `Sign in to Slack in your browser, then run \`${SETUP_CMD}\`.`,
76
+ };
77
+ }
78
+ return null;
79
+ }
80
+
81
+ function currentCredentialSource() {
82
+ try {
83
+ return loadTokensReadOnly()?.source ?? null;
84
+ } catch {
85
+ return null;
86
+ }
87
+ }
88
+
49
89
  function upsellEnabled() {
50
90
  return process.env.SLACK_MCP_NO_UPSELL !== "1";
51
91
  }
@@ -108,9 +148,26 @@ export function buildLifeboatPayload(err, options = {}) {
108
148
  const now = options?.now ?? Date.now();
109
149
  const slackError = authDeathCode(err);
110
150
  const upsell = upsellEnabled();
151
+ const advice = recoveryAdvice({
152
+ platformName: options?.platformName ?? osPlatform(),
153
+ credentialSource: options?.credentialSource !== undefined
154
+ ? options.credentialSource
155
+ : currentCredentialSource(),
156
+ });
111
157
 
112
158
  const throttled = lastLongFormAt > 0 && now - lastLongFormAt < THROTTLE_WINDOW_MS;
113
159
 
160
+ if (throttled && advice) {
161
+ return {
162
+ status: "error",
163
+ code: "slack_auth_expired",
164
+ slack_error: slackError,
165
+ throttled: true,
166
+ message: `Slack session token is still expired or revoked. ${advice.nextAction}`,
167
+ next_action: advice.nextAction,
168
+ };
169
+ }
170
+
114
171
  if (throttled) {
115
172
  const message = upsell
116
173
  ? `Slack session token is still expired or revoked. Re-extract with \`${SETUP_CMD}\`. Permanent fix (hosted OAuth, free tier): ${HOSTED_SETUP_URL}`
@@ -143,12 +200,20 @@ export function buildLifeboatPayload(err, options = {}) {
143
200
  payload.extraction_error = err.extraction_error;
144
201
  }
145
202
 
203
+ if (advice) {
204
+ payload.self_fix = advice.selfFix;
205
+ }
206
+
146
207
  if (upsell) {
147
208
  payload.hosted_option =
148
209
  `To stop re-extracting every 1-2 weeks, switch to hosted OAuth (it never rotates): ${HOSTED_SETUP_URL} — free tier available, no credit card.`;
149
- payload.next_action = `Run \`${SETUP_CMD}\` to re-extract tokens, or switch to permanent hosted OAuth (see hosted_option).`;
210
+ payload.next_action = advice
211
+ ? `${advice.nextAction} Or switch to permanent hosted OAuth (see hosted_option).`
212
+ : `Run \`${SETUP_CMD}\` to re-extract tokens, or switch to permanent hosted OAuth (see hosted_option).`;
150
213
  } else {
151
- payload.next_action = `Run \`${SETUP_CMD}\` to re-extract tokens (macOS: call the slack_refresh_tokens tool).`;
214
+ payload.next_action = advice
215
+ ? advice.nextAction
216
+ : `Run \`${SETUP_CMD}\` to re-extract tokens (macOS: call the slack_refresh_tokens tool).`;
152
217
  }
153
218
 
154
219
  return payload;
@@ -51,6 +51,10 @@ export const SLACK_WRITE_ERRORS = Object.freeze({
51
51
  message: "The Slack session changed after the ownership check, so the tool didn't send the change.",
52
52
  next_action: "Run slack_health_check to confirm the signed-in user, then call the tool again."
53
53
  },
54
+ message_deleted: {
55
+ message: "The message was already deleted. Only Slack's \"This message was deleted.\" placeholder remains at that timestamp, above its thread replies.",
56
+ next_action: "Nothing to change. If you meant another message, read the thread with slack_get_thread to get its timestamp."
57
+ },
54
58
  lookup_incomplete: {
55
59
  message: "The tool couldn't finish searching the thread for this message, so it didn't make the change.",
56
60
  next_action: "Check the timestamp with slack_get_thread and call the tool again."
@@ -101,6 +105,10 @@ export const MAX_REPLY_PAGES = 50;
101
105
 
102
106
  const SLACK_TS_PATTERN = /^\d+\.\d+$/;
103
107
 
108
+ // Slack conversation IDs: C (channel), D (DM), or G (private channel or
109
+ // group DM), then at least 8 uppercase letters or digits.
110
+ export const SLACK_CONVERSATION_ID_PATTERN = /^[CDG][A-Z0-9]{8,}$/;
111
+
104
112
  /**
105
113
  * Build an invalid_argument error result for one input field.
106
114
  */
@@ -119,8 +127,8 @@ export function invalidArgument(field, message) {
119
127
  export function validateTargetArgs(args) {
120
128
  const input = args && typeof args === "object" ? args : {};
121
129
  const { channel_id: channelId, timestamp, expected_text: expectedText } = input;
122
- if (typeof channelId !== "string" || channelId.trim() === "" || /\s/.test(channelId)) {
123
- return invalidArgument("channel_id", "channel_id must be a non-empty channel or DM ID with no spaces.");
130
+ if (typeof channelId !== "string" || !SLACK_CONVERSATION_ID_PATTERN.test(channelId)) {
131
+ return invalidArgument("channel_id", "channel_id must be a Slack channel or DM ID, such as C0123456789 or D0123456789.");
124
132
  }
125
133
  if (typeof timestamp !== "string" || !SLACK_TS_PATTERN.test(timestamp)) {
126
134
  return invalidArgument("timestamp", "timestamp must be a Slack message timestamp such as \"1767368030.607599\".");
@@ -252,7 +260,15 @@ export function isGoneForSelf(message, selfId) {
252
260
  * Returns { ok: true, message, selfId, sessionToken } or
253
261
  * { ok: false, result } where result is a ready MCP error. Pass the result
254
262
  * to sessionChangedResult just before the write.
263
+ *
264
+ * `verified` says what Slack confirmed: the channel once conversations.history
265
+ * answered for it, and the timestamp once the message was found. It's absent
266
+ * for refusals made before any Slack call. The write log uses it so only
267
+ * Slack-confirmed IDs reach stderr.
255
268
  */
269
+ const CHANNEL_VERIFIED = Object.freeze({ channel: true, timestamp: false });
270
+ const MESSAGE_VERIFIED = Object.freeze({ channel: true, timestamp: true });
271
+
256
272
  export async function checkOwnMessage(channelId, timestamp, options = {}) {
257
273
  const {
258
274
  expectedText,
@@ -291,17 +307,23 @@ export async function checkOwnMessage(channelId, timestamp, options = {}) {
291
307
  ]);
292
308
  } catch (error) {
293
309
  if (error?.message === "lookup_incomplete") {
294
- return { ok: false, result: messageWriteError("lookup_incomplete", details) };
310
+ return { ok: false, verified: CHANNEL_VERIFIED, result: messageWriteError("lookup_incomplete", details) };
295
311
  }
296
312
  throw error;
297
313
  }
298
314
 
299
315
  if (!message) {
300
- return { ok: false, result: messageWriteError("message_not_found", details) };
316
+ return { ok: false, verified: CHANNEL_VERIFIED, result: messageWriteError("message_not_found", details) };
317
+ }
318
+ // A deleted thread parent leaves a tombstone at the same ts, authored by
319
+ // Slack rather than the user; report it as deleted, not as someone else's.
320
+ if (message.subtype === "tombstone") {
321
+ return { ok: false, verified: MESSAGE_VERIFIED, result: messageWriteError("message_deleted", details) };
301
322
  }
302
323
  if (message.user !== selfId) {
303
324
  return {
304
325
  ok: false,
326
+ verified: MESSAGE_VERIFIED,
305
327
  result: messageWriteError("not_own_message", {
306
328
  ...details,
307
329
  author: message.user || message.bot_id || null
@@ -314,13 +336,14 @@ export async function checkOwnMessage(channelId, timestamp, options = {}) {
314
336
  if (typeof expectedText !== "string" || (message.text ?? "").trim() !== expectedText.trim()) {
315
337
  return {
316
338
  ok: false,
339
+ verified: MESSAGE_VERIFIED,
317
340
  result: messageWriteError("text_mismatch", details, {
318
341
  message: "expected_text doesn't match the message's current text, so the tool won't change it.",
319
342
  next_action: "Read the message again with slack_conversations_history or slack_get_thread and confirm it's the one the user meant."
320
343
  })
321
344
  };
322
345
  }
323
- return { ok: true, message, selfId, sessionToken };
346
+ return { ok: true, verified: MESSAGE_VERIFIED, message, selfId, sessionToken };
324
347
  }
325
348
 
326
349
  /**
@@ -15,7 +15,9 @@ import {
15
15
  extractFromChrome,
16
16
  getLastExtractionError,
17
17
  saveAutoHealTelemetry,
18
+ isAutoRefreshAvailable,
18
19
  } from "./token-store.js";
20
+ import { platform as osPlatform } from "node:os";
19
21
 
20
22
  // ============ Configuration ============
21
23
 
@@ -97,11 +99,29 @@ const userCache = new LRUCache(USER_CACHE_MAX_SIZE, USER_CACHE_TTL);
97
99
  // ============ Token Health ============
98
100
 
99
101
  /**
100
- * Check token health and attempt proactive refresh if needed
102
+ * How to refresh the session token by hand, for platforms where Chrome
103
+ * auto-heal can't run.
101
104
  */
102
- export async function checkTokenHealth(logger = console) {
105
+ export function manualRefreshAdvice(platformName = osPlatform()) {
106
+ return `Auto-refresh only runs on macOS, not ${platformName}. To refresh by hand, sign in to Slack in your browser, then run bunx @uniquedivine/mcp-slack --setup, or update SLACK_TOKEN and SLACK_COOKIE.`;
107
+ }
108
+
109
+ /**
110
+ * Check token health and attempt proactive refresh if needed.
111
+ *
112
+ * Options (for tests): autoHealAvailable defaults to isAutoRefreshAvailable(),
113
+ * platformName to os.platform(), and creds to the stored credentials. Where auto-heal can't run, the check
114
+ * skips the Chrome refresh, never reports auto-heal as failing or stuck, and
115
+ * gives manual-refresh advice with the token-age warning.
116
+ */
117
+ export async function checkTokenHealth(logger = console, options = {}) {
118
+ const {
119
+ autoHealAvailable = isAutoRefreshAvailable(),
120
+ platformName = osPlatform(),
121
+ creds: injectedCreds
122
+ } = options;
103
123
  const silentLogger = { error: () => {}, warn: () => {}, log: () => {} };
104
- const creds = loadTokens(false, silentLogger, { autoExtract: false });
124
+ const creds = injectedCreds ?? loadTokens(false, silentLogger, { autoExtract: false });
105
125
 
106
126
  if (!creds) {
107
127
  return {
@@ -120,13 +140,15 @@ export async function checkTokenHealth(logger = console) {
120
140
  ? Math.round(tokenAge / (60 * 60 * 1000) * 10) / 10
121
141
  : null;
122
142
 
123
- // Read auto-heal telemetry (only populated when source is "file")
124
- let lastAutoHealAttempt = creds.lastAutoHealAttempt || null;
125
- let lastAutoHealError = creds.lastAutoHealError || null;
126
- let stuckSince = creds.stuckSince || null;
143
+ // Read auto-heal telemetry (only populated when source is "file"). Where
144
+ // auto-heal can't run, older telemetry such as unsupported_platform isn't
145
+ // a failure, so it's ignored.
146
+ let lastAutoHealAttempt = autoHealAvailable ? creds.lastAutoHealAttempt || null : null;
147
+ let lastAutoHealError = autoHealAvailable ? creds.lastAutoHealError || null : null;
148
+ let stuckSince = autoHealAvailable ? creds.stuckSince || null : null;
127
149
 
128
150
  // Attempt proactive refresh if token is getting old
129
- if (hasKnownAge && tokenAge > TOKEN_WARNING_AGE && Date.now() - lastRefreshAttempt > REFRESH_COOLDOWN) {
151
+ if (autoHealAvailable && hasKnownAge && tokenAge > TOKEN_WARNING_AGE && Date.now() - lastRefreshAttempt > REFRESH_COOLDOWN) {
130
152
  lastRefreshAttempt = Date.now();
131
153
  const attemptAt = new Date().toISOString();
132
154
  logger.error?.(`Token is ${ageHours}h old, attempting proactive refresh...`);
@@ -162,7 +184,8 @@ export async function checkTokenHealth(logger = console) {
162
184
  }
163
185
 
164
186
  const stuckSinceMs = stuckSince ? new Date(stuckSince).getTime() : Number.NaN;
165
- const isStuck = Number.isFinite(stuckSinceMs)
187
+ const isStuck = autoHealAvailable
188
+ && Number.isFinite(stuckSinceMs)
166
189
  && (Date.now() - stuckSinceMs) > STUCK_THRESHOLD_MS
167
190
  && !!lastAutoHealError;
168
191
 
@@ -187,14 +210,19 @@ export async function checkTokenHealth(logger = console) {
187
210
  last_auto_heal_attempt: lastAutoHealAttempt,
188
211
  last_auto_heal_error: lastAutoHealError,
189
212
  stuck_since: stuckSince,
213
+ auto_heal_available: autoHealAvailable,
190
214
  message: isStuck
191
215
  ? `Auto-heal has been failing since ${stuckSince} (last error: ${lastAutoHealError}). Open Chrome > View > Developer > Allow JavaScript from Apple Events, then run npm run tokens:auto.`
192
216
  : !hasKnownAge
193
217
  ? 'Token age unknown (missing timestamp) - auth can still be valid'
194
218
  : tokenAge > TOKEN_CRITICAL_AGE
195
- ? 'Token may expire soon - open Slack in Chrome'
219
+ ? (autoHealAvailable
220
+ ? 'Token may expire soon - open Slack in Chrome'
221
+ : `Token may expire soon. ${manualRefreshAdvice(platformName)}`)
196
222
  : tokenAge > TOKEN_WARNING_AGE
197
- ? 'Token is getting old - will auto-refresh if Slack tab is open'
223
+ ? (autoHealAvailable
224
+ ? 'Token is getting old - will auto-refresh if Slack tab is open'
225
+ : `Token is getting old. ${manualRefreshAdvice(platformName)}`)
198
226
  : 'Token is healthy'
199
227
  };
200
228
  }
@@ -295,6 +323,20 @@ export async function slackAPI(method, params = {}, options = {}) {
295
323
  }
296
324
 
297
325
  // Handle auth errors with auto-retry
326
+ if ((data.error === "invalid_auth" || data.error === "token_expired") && retryOnAuthFail && !isAutoRefreshAvailable()) {
327
+ // Chrome auto-heal can't run here, so don't try it or record it as a
328
+ // failure; point to the manual refresh instead.
329
+ const err = new Error(`Slack auth failed (${data.error}). ${manualRefreshAdvice()}`);
330
+ err.code = 'token_auth_failed';
331
+ err.slack_error = data.error;
332
+ err.extraction_error = {
333
+ code: 'unsupported_platform',
334
+ message: 'Chrome auto-extraction is only available on macOS.',
335
+ detail: null
336
+ };
337
+ err.next_action = manualRefreshAdvice();
338
+ throw err;
339
+ }
298
340
  if ((data.error === "invalid_auth" || data.error === "token_expired") && retryOnAuthFail) {
299
341
  logger.error?.("Token expired, attempting Chrome auto-extraction...");
300
342
  const attemptAt = new Date().toISOString();