slack-term 1.57.1 → 1.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/ts/cli.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env bun
2
+ import { asyncCommandArgs } from "./asyncArgs.ts";
2
3
  // Slack CLI entry — mirrors the Rust impl in src/main.rs.
3
4
 
4
5
  import { createHash } from "node:crypto";
@@ -10,7 +11,7 @@ import { dirname, join, resolve } from "node:path";
10
11
  import yargs, { type Options } from "yargs";
11
12
  import { hideBin } from "yargs/helpers";
12
13
  import { fixUrlBoundaries, guardUrlBoundaries } from "./urlGuard.ts";
13
- import { listProfiles, removeProfile, resolveBotToken, resolveCookie, resolveToken, useProfile, type Profile } from "./profiles.ts";
14
+ import { listProfiles, removeProfile, resolveBotToken, resolveCookie, resolveToken, tokenSource, useProfile, type Profile } from "./profiles.ts";
14
15
  import { diagnoseBotMessaging, formatDiagnosis } from "./botdoctor.ts";
15
16
  import { cmdAuthLogin, cmdAuthLoginChrome, cmdAuthChrome, cmdAuthFirefox, cmdAuthToken, cmdAuthApp, cmdAuthSave, cmdAuthTokens } from "./auth.ts";
16
17
  import { cmdTail, parseSince as parseDuration } from "./tail.ts";
@@ -54,6 +55,9 @@ import {
54
55
  type AskLang,
55
56
  ASK_POLL,
56
57
  askNextPollDelay,
58
+ askFormatTimeout,
59
+ askPositionalFlags,
60
+ parseAskTimeout,
57
61
  } from "./ask.ts";
58
62
  import { applyPrefix, findScope, initScope, isRestricted, listAliases, lookupAlias, readSettings, RestrictedError, setAlias, threadMismatch, unsetAlias, whoSubscribes, type MessagePlace, type Scope } from "./scope.ts";
59
63
  import { keepLanePrefix, tickText } from "./tick.ts";
@@ -135,6 +139,9 @@ import {
135
139
  savedDelete,
136
140
  savedList,
137
141
  savedUpdate,
142
+ setAuthSourceLabel,
143
+ enableReadCache,
144
+ fetchOrSay,
138
145
  } from "./slack.ts";
139
146
  import { isDone, messagePermalink, parseSavedItems, sortTodos, TODO_FILTERS, todoStatus, type TodoFilter, type TodoItem } from "./slackTodos.ts";
140
147
  import {
@@ -1466,11 +1473,8 @@ async function selfIdentity(token: string, cookie?: string): Promise<Self | null
1466
1473
  * needs it for the unreplied guard as well as the gate) — a command must never
1467
1474
  * pay for more than one lookup. */
1468
1475
  function selfLookup(token: string, cookie?: string): () => Promise<Self | null> {
1469
- let cache: Self | null | undefined;
1470
- return async () => {
1471
- if (cache === undefined) cache = await selfIdentity(token, cookie);
1472
- return cache;
1473
- };
1476
+ let pending: Promise<Self | null> | undefined;
1477
+ return () => pending ??= selfIdentity(token, cookie);
1474
1478
  }
1475
1479
 
1476
1480
  /** Who is sending, captured once per write: the Slack `metadata` to attach to
@@ -1532,7 +1536,7 @@ function fromLine(self: Self | null, opts: { asBot?: boolean | undefined; pad?:
1532
1536
  * "2026-06-11 08:05 @handle: head…". `headLen` bounds the text preview. */
1533
1537
  async function threadMsgLine(token: string, m: Record<string, Json>, headLen = 60, cookie?: string): Promise<string> {
1534
1538
  const author = typeof m.user === "string"
1535
- ? await userName(token, m.user, cookie)
1539
+ ? (process.stdout.isTTY ? await userName(token, m.user, cookie) : m.user)
1536
1540
  : typeof m.username === "string"
1537
1541
  ? m.username
1538
1542
  : "?";
@@ -2478,19 +2482,29 @@ async function cmdSend(token: string, args: SendArgs): Promise<void> {
2478
2482
  // Identity of the token that will actually post — the bot token under
2479
2483
  // --as-bot, the user token otherwise.
2480
2484
  const getSelf = selfLookup(token, cookie);
2485
+ const selfPending = getSelf();
2481
2486
 
2482
2487
  let channelId: string;
2483
2488
  if (args.channelId) channelId = args.channelId;
2484
2489
  else if (args.userId) channelId = await openDm(token, args.userId, cookie);
2485
2490
  else channelId = await resolveChannel(token, ref, cookie);
2486
2491
 
2492
+ // Independent metadata and context requests overlap mention processing.
2493
+ // The shared lookup cache collapses DM metadata/identity reads below.
2494
+ const recipientTzPending = recipientTzFor(token, channelId, cookie);
2495
+ const destPending = args.code === undefined ? destLabel(token, channelId, ref, cookie) : undefined;
2496
+ const contextPending = (threadTs
2497
+ ? replies(token, channelId, threadTs, 100, cookie)
2498
+ : history(token, channelId, 1, undefined, undefined, cookie)
2499
+ ).catch(() => null);
2500
+
2487
2501
  // Self-DM footgun: Slack never notifies you about a message you sent, so a DM
2488
2502
  // to yourself is delivered and then silently never surfaces — the worst shape
2489
2503
  // for an escalation ("I told you" / nobody saw it). Checked after resolution
2490
2504
  // so it fires however the DM was addressed: @me, a handle, a display name,
2491
2505
  // --user-id, --channel-id, or a permalink. --as-bot is exempt: that posts as
2492
2506
  // the app, a different identity, which does notify you.
2493
- if (!args.asBot && await isSelfDmChannel(token, channelId, (await getSelf())?.userId, cookie)) {
2507
+ if (!args.asBot && await isSelfDmChannel(token, channelId, (await selfPending)?.userId, cookie)) {
2494
2508
  console.error(
2495
2509
  `Warning: "${args.target}" is a DM to yourself — Slack will NOT notify you of your own message.\n` +
2496
2510
  ` To reach yourself with a notification, send as the bot: slack send '${args.target}' '...' --as-bot`,
@@ -2557,7 +2571,7 @@ async function cmdSend(token: string, args: SendArgs): Promise<void> {
2557
2571
  // Fetch a generous window and preview its tail. conversations.replies is
2558
2572
  // oldest-first from the parent, so a very long thread's true tail may lie
2559
2573
  // beyond this window — 100 covers essentially all real threads.
2560
- const resp = (await replies(token, channelId, threadTs, 100, cookie)) as Record<string, Json>;
2574
+ const resp = (await contextPending) as Record<string, Json>;
2561
2575
  threadMsgs = asArray(resp.messages).map(asRecord);
2562
2576
  const lastMsg = threadMsgs[threadMsgs.length - 1];
2563
2577
  // Bind the hash to the thread's most recent message: if someone replies
@@ -2571,7 +2585,7 @@ async function cmdSend(token: string, args: SendArgs): Promise<void> {
2571
2585
  }
2572
2586
  } else {
2573
2587
  try {
2574
- const ctx = (await history(token, channelId, 1, undefined, undefined, cookie)) as Record<string, Json>;
2588
+ const ctx = (await contextPending) as Record<string, Json>;
2575
2589
  // limit=1 already narrows this to exactly the channel's true last message
2576
2590
  // (subtype or not) — take it raw for the ownership check below. The
2577
2591
  // subtype filter is only for the human-readable preview text/author: it
@@ -2683,20 +2697,22 @@ async function cmdSend(token: string, args: SendArgs): Promise<void> {
2683
2697
  const self = await getSelf();
2684
2698
  // Resolved before the gate so the clock can name the recipient's zone. DM
2685
2699
  // only; null means "unknown" and the label says so rather than guessing.
2686
- const recipientTz = await recipientTzFor(token, channelId, cookie);
2700
+ const recipientTz = await recipientTzPending;
2687
2701
  const code = safetyCode(channelId, threadTs ?? "", lastText, message, self?.userId ?? "");
2688
2702
 
2689
2703
  if (args.code !== code) {
2690
- const dest = await destLabel(token, channelId, ref, cookie);
2704
+ const dest = await (destPending ?? destLabel(token, channelId, ref, cookie));
2691
2705
  const from = fromLine(self, { asBot: args.asBot });
2692
2706
  if (threadTs) {
2693
- const parentLine = await threadParentLine(token, threadTs, threadMsgs, cookie);
2694
2707
  // Preview the tail of the thread (up to 3 most recent messages) so the
2695
2708
  // sender can see what's already been said and avoid repeating it.
2696
2709
  const recent = threadMsgs.slice(-3);
2697
- const recentLines = recent.length
2698
- ? await Promise.all(recent.map(async (m) => ` ${await threadMsgLine(token, m, 60, cookie)}`))
2699
- : [" (thread context unavailable)"];
2710
+ const [parentLine, recentLines] = await Promise.all([
2711
+ threadParentLine(token, threadTs, threadMsgs, cookie),
2712
+ recent.length
2713
+ ? Promise.all(recent.map(async (m) => ` ${await threadMsgLine(token, m, 60, cookie)}`))
2714
+ : Promise.resolve([" (thread context unavailable)"]),
2715
+ ]);
2700
2716
  requireCode(args.code, code, [
2701
2717
  `--- Recent messages in thread ----------------`,
2702
2718
  ...recentLines,
@@ -3662,7 +3678,7 @@ async function askWaitForAnswer(token: string, ctx: AskWaitCtx): Promise<never>
3662
3678
  if (timeout === 0) {
3663
3679
  console.error(`No answer yet: ${shown}`);
3664
3680
  } else {
3665
- console.error(`Error: no answer within ${timeout}s (the message is left in place)`);
3681
+ console.error(`Error: no answer within ${askFormatTimeout(timeout)} (the message is left in place)`);
3666
3682
  console.error(` ${shown}`);
3667
3683
  console.error(` To collect later: ${askResumeCommand(shown, ctx.asBot, ctx.after)}`);
3668
3684
  }
@@ -3933,7 +3949,7 @@ async function cmdAsk(token: string, args: AskArgs): Promise<void> {
3933
3949
  }
3934
3950
 
3935
3951
  const timeout = args.timeout ?? 3600;
3936
- console.error(` Waiting for an answer (up to ${timeout}s)… Ctrl-C to stop`);
3952
+ console.error(` Waiting for an answer (up to ${askFormatTimeout(timeout)})… Ctrl-C to stop`);
3937
3953
 
3938
3954
  const ctx: AskWaitCtx = {
3939
3955
  channelId,
@@ -5913,7 +5929,7 @@ async function cmdDownload(token: string, cookie: string | undefined, ref: strin
5913
5929
 
5914
5930
  const headers: Record<string, string> = { Authorization: `Bearer ${token}` };
5915
5931
  if (cookie) headers.Cookie = `d=${cookie}`;
5916
- const res = await fetch(url, { headers });
5932
+ const res = await fetchOrSay("the download", url, { headers });
5917
5933
  if (!res.ok) throw new Error(`Download failed: HTTP ${res.status} ${res.statusText}`);
5918
5934
  const buf = Buffer.from(await res.arrayBuffer());
5919
5935
 
@@ -5935,9 +5951,43 @@ async function main(): Promise<void> {
5935
5951
  if (notice) console.error(notice);
5936
5952
 
5937
5953
  type W = { workspace?: string };
5938
- const tok = (a: W) => resolveToken(a.workspace);
5954
+ let tokenNoteShown = false;
5955
+ const tok = (a: W) => {
5956
+ const t = resolveToken(a.workspace);
5957
+ const src = tokenSource();
5958
+ if (src) {
5959
+ // Name the source, never the value. An identity (`slack @who …`) put the
5960
+ // token in the env on purpose, so that is labelled as the identity.
5961
+ const id = process.env.SLACK_HUB_IDENTITY;
5962
+ const file = src.kind === "env" ? dotenvSource.get("SLACK_TOKEN") : undefined;
5963
+ const label = id && src.kind === "env" ? `identity @${id}` : file ? `${src.name} in ${file}` : src.name;
5964
+ setAuthSourceLabel(label);
5965
+ if (!id && src.kind === "env" && src.shadowed.length > 0 && !tokenNoteShown) {
5966
+ tokenNoteShown = true;
5967
+ const cookieNote = process.env.SLACK_COOKIE ? " (and SLACK_COOKIE)" : "";
5968
+ console.error(`note: using ${label}${cookieNote}, which overrides profiles.json (${src.shadowed.join(", ")}); unset it or pass --workspace <name> to use a profile`);
5969
+ }
5970
+ }
5971
+ return t;
5972
+ };
5939
5973
  const ck = (a: W) => resolveCookie(a.workspace);
5940
5974
 
5975
+ const channelWriteIdentity = async (argv: W & { "as-bot"?: boolean }): Promise<{ token: string; cookie?: string; asBot: boolean }> => {
5976
+ if (argv["as-bot"]) {
5977
+ const token = requireBotToken();
5978
+ if (argv.workspace) {
5979
+ const [selected, bot] = await Promise.all([authScopes(tok(argv), ck(argv)), authScopes(token)]);
5980
+ if (selected.url !== bot.url) {
5981
+ console.error("Error: --as-bot token belongs to a different workspace than -w; select that workspace's bot token.");
5982
+ process.exit(2);
5983
+ }
5984
+ }
5985
+ return { token, asBot: true };
5986
+ }
5987
+ const cookie = ck(argv);
5988
+ return { token: tok(argv), ...(cookie ? { cookie } : {}), asBot: false };
5989
+ };
5990
+
5941
5991
  /** The `send` handler, shared with `reply` (which resolves its own target,
5942
5992
  * prefix and thread check first). */
5943
5993
  type SendCli = {
@@ -6120,8 +6170,26 @@ async function main(): Promise<void> {
6120
6170
  await cmdTodoLs(tok(argv), opts);
6121
6171
  };
6122
6172
 
6173
+ // One command asks the same lookups several times (gate, guards, preview).
6174
+ enableReadCache();
6175
+ if (hubEnv("TIMING") === "1") process.on("exit", () => console.error(`slack-hub timing: ${(performance.now() / 1000).toFixed(2)}s exit`));
6176
+
6123
6177
  // `slack @<who> <command> …`: act as a named identity (ts/identity.ts).
6124
- const { who, rest: cliArgs } = splitWho(hideBin(process.argv));
6178
+ const { who, rest: whoRest } = splitWho(hideBin(process.argv));
6179
+ // `ask --choices "A|B"`: an alias for the positional choices, taken out
6180
+ // before yargs (see askPositionalFlags for why yargs cannot be left to it).
6181
+ let cliArgs = whoRest;
6182
+ let askChoicesFlag: string[] = [];
6183
+ const askAt = whoRest.findIndex((a) => !a.startsWith("-"));
6184
+ if (askAt >= 0 && whoRest[askAt] === "ask") {
6185
+ const f = askPositionalFlags(whoRest.slice(askAt + 1));
6186
+ if ("error" in f) {
6187
+ console.error(`Error: ${f.error}`);
6188
+ process.exit(ASK_EXIT_ERROR);
6189
+ }
6190
+ cliArgs = [...whoRest.slice(0, askAt + 1), ...f.rest];
6191
+ askChoicesFlag = f.choices;
6192
+ }
6125
6193
  let whoKind: "bot" | "user" | undefined;
6126
6194
  if (who) {
6127
6195
  const r = applyIdentity(who);
@@ -6132,8 +6200,74 @@ async function main(): Promise<void> {
6132
6200
  whoKind = r.kind;
6133
6201
  }
6134
6202
 
6203
+ const queuedArgs = asyncCommandArgs(whoRest);
6204
+ if (queuedArgs.enabled) {
6205
+ const fs = await import("node:fs");
6206
+ const path = await import("node:path");
6207
+ const os = await import("node:os");
6208
+ const { spawn } = await import("node:child_process");
6209
+ const { callback, args: forwardArgs } = queuedArgs;
6210
+ // `-` reads stdin, but the detached worker has none: read it here and
6211
+ // hand it over in the job.
6212
+ const stdin = forwardArgs.includes("-") && !process.stdin.isTTY ? fs.readFileSync(0, "utf8") : undefined;
6213
+ const jobId = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
6214
+ const jobsDir = path.join(os.homedir(), ".local", "state", "slack-post", "jobs");
6215
+ fs.mkdirSync(jobsDir, { recursive: true, mode: 0o700 });
6216
+ fs.chmodSync(jobsDir, 0o700);
6217
+ fs.chmodSync(path.dirname(jobsDir), 0o700);
6218
+ const lastFailedFile = path.join(os.homedir(), ".local", "state", "slack-post", "last-failed.json");
6219
+ let lastFailed: Record<string, unknown> | undefined;
6220
+ if (fs.existsSync(lastFailedFile)) {
6221
+ try { lastFailed = JSON.parse(fs.readFileSync(lastFailedFile, "utf8")); } catch {}
6222
+ }
6223
+ const inFlight: { jobId: string; status: string; target?: string }[] = [];
6224
+ try {
6225
+ for (const f of fs.readdirSync(jobsDir)) {
6226
+ if (!f.endsWith(".json")) continue;
6227
+ try {
6228
+ const j = JSON.parse(fs.readFileSync(path.join(jobsDir, f), "utf8"));
6229
+ if (j.status === "queued" || j.status === "running") {
6230
+ inFlight.push({ jobId: j.jobId, status: j.status, target: j.target });
6231
+ }
6232
+ } catch {}
6233
+ }
6234
+ } catch {}
6235
+ const jobFile = path.join(jobsDir, `${jobId}.json`);
6236
+ const job = {
6237
+ jobId,
6238
+ status: "queued",
6239
+ target: forwardArgs.join(" "),
6240
+ createdAt: new Date().toISOString(),
6241
+ callback,
6242
+ forwardArgs,
6243
+ ...(who ? { who } : {}),
6244
+ ...(stdin !== undefined ? { stdin } : {}),
6245
+ };
6246
+ fs.writeFileSync(jobFile, JSON.stringify(job, null, 2), { mode: 0o600 });
6247
+ const worker = spawn(process.execPath, [process.argv[1]!, "_post-worker", jobFile], {
6248
+ detached: true,
6249
+ stdio: "ignore",
6250
+ });
6251
+ worker.unref();
6252
+ if (forwardArgs.includes("--json")) {
6253
+ console.log(JSON.stringify({ ok: true, queued: true, jobId, statusFile: jobFile, ...(lastFailed ? { lastFailed } : {}), ...(inFlight.length ? { inFlight } : {}) }));
6254
+ } else {
6255
+ if (lastFailed) {
6256
+ console.error(`⚠ Last post failed (job: ${lastFailed.jobId}, target: ${lastFailed.target}): ${lastFailed.error}`);
6257
+ }
6258
+ if (inFlight.length) {
6259
+ console.error(`⏳ In-flight posts (${inFlight.length}): ${inFlight.map((j) => `${j.jobId}[${j.status}]`).join(", ")}`);
6260
+ }
6261
+ console.log(`✓ Queued (job: ${jobId}) · check: slack jobs ${jobId}`);
6262
+ }
6263
+ return;
6264
+ }
6265
+
6135
6266
  await yargs(cliArgs)
6136
6267
  .scriptName("slack")
6268
+ // yargs' own lookup finds no package.json next to the bundled dist/cli.js
6269
+ // and prints "unknown"; the imported one is bundled in.
6270
+ .version(pkgJson.version)
6137
6271
  // A thrown handler error (e.g. a Slack API failure) is a runtime error, not a usage
6138
6272
  // mistake — print just the clean one-line message, never the command's --help block or a
6139
6273
  // minified source stack. Reserve the usage/help output for actual argument-parse errors
@@ -6161,7 +6295,7 @@ async function main(): Promise<void> {
6161
6295
  }
6162
6296
  // `sent` reads only the local log — no token, no network. `relay` writes
6163
6297
  // local files (init) or talks to the user's own relay (health): no Slack token.
6164
- if (!cmd || cmd === "auth" || cmd === "login" || cmd === "agent" || cmd === "sent" || cmd === "relay") return;
6298
+ if (!cmd || ["auth", "login", "agent", "sent", "relay", "jobs", "_post-worker"].includes(cmd)) return;
6165
6299
  try {
6166
6300
  const active = resolveToken((argv as W).workspace);
6167
6301
  const bot = resolveBotToken();
@@ -6286,10 +6420,10 @@ async function main(): Promise<void> {
6286
6420
  (yy) => yy
6287
6421
  .positional("channel", { type: "string", demandOption: true, describe: "#name, channel id, or permalink" })
6288
6422
  .positional("users", { type: "string", array: true, demandOption: true, describe: "@handle or U… ids" })
6289
- .option("code", { type: "string", describe: "Safety hash to confirm" }),
6423
+ .option("code", { type: "string", describe: "Safety hash to confirm" })
6424
+ .option("as-bot", { type: "boolean", default: false, describe: "Invite via the bot token, without a user-session cookie" }),
6290
6425
  async (argv) => {
6291
- const token = tok(argv as W);
6292
- const cookie = ck(argv as W);
6426
+ const { token, cookie, asBot } = await channelWriteIdentity(argv as W & { "as-bot"?: boolean });
6293
6427
  let channel: string;
6294
6428
  const ids: string[] = [];
6295
6429
  try {
@@ -6304,7 +6438,7 @@ async function main(): Promise<void> {
6304
6438
  const code = safetyCode("channel-invite", channel, ids.join(","), self?.userId ?? "");
6305
6439
  if (argv.code !== code) requireCode(argv.code, code, [
6306
6440
  `--- Inviting to a channel --------------------`,
6307
- fromLine(self, { pad: 9 }),
6441
+ fromLine(self, { pad: 9, asBot }),
6308
6442
  ` channel: ${label}`,
6309
6443
  ` users: ${ids.join(", ")}`,
6310
6444
  `--------------------------------────────────`,
@@ -6329,10 +6463,10 @@ async function main(): Promise<void> {
6329
6463
  .positional("name", { type: "string", demandOption: true, describe: "Channel name (Slack lowercases it; no spaces)" })
6330
6464
  .option("private", { type: "boolean", default: false, describe: "Create a private channel" })
6331
6465
  .option("invite", { type: "string", array: true, default: [], describe: "Users to invite after creating (@handle or Uxxxx, repeatable)" })
6332
- .option("code", { type: "string", describe: "Safety hash to confirm create" }),
6466
+ .option("code", { type: "string", describe: "Safety hash to confirm create" })
6467
+ .option("as-bot", { type: "boolean", default: false, describe: "Create and invite via the bot token, without a user-session cookie" }),
6333
6468
  async (argv) => {
6334
- const token = tok(argv as W);
6335
- const cookie = ck(argv as W);
6469
+ const { token, cookie, asBot } = await channelWriteIdentity(argv as W & { "as-bot"?: boolean });
6336
6470
  // Slack lowercases and strips the leading #; normalize for preview + code.
6337
6471
  const name = argv.name!.replace(/^#/, "").toLowerCase();
6338
6472
  const isPrivate = argv.private === true;
@@ -6343,7 +6477,7 @@ async function main(): Promise<void> {
6343
6477
  const code = safetyCode(name, String(isPrivate), invites.join(","), self?.userId ?? "");
6344
6478
  if (argv.code !== code) requireCode(argv.code, code, [
6345
6479
  `--- Creating channel -------------------------`,
6346
- fromLine(self, { pad: 9 }),
6480
+ fromLine(self, { pad: 9, asBot }),
6347
6481
  ` name: ${isPrivate ? "🔒 " : "#"}${name}`,
6348
6482
  ` private: ${isPrivate}`,
6349
6483
  ...(invites.length ? [` invite: ${invites.join(", ")}`] : []),
@@ -6695,6 +6829,110 @@ async function main(): Promise<void> {
6695
6829
  await runSend(argv);
6696
6830
  },
6697
6831
  )
6832
+ .command(
6833
+ "jobs [jobId]",
6834
+ "Background `--async` sends: list recent jobs, or show one (status, permalink, error output)",
6835
+ (y) => y
6836
+ .positional("jobId", { type: "string", describe: "A job id from `--async`; omit to list recent jobs" })
6837
+ .option("limit", { type: "number", default: 20, describe: "Jobs to list" })
6838
+ .option("json", { type: "boolean", default: false }),
6839
+ async (argv) => {
6840
+ const fs = await import("node:fs");
6841
+ const path = await import("node:path");
6842
+ const os = await import("node:os");
6843
+ const jobsDir = path.join(os.homedir(), ".local", "state", "slack-post", "jobs");
6844
+ type Job = { jobId: string; status: string; target?: string; createdAt?: string; startedAt?: string; finishedAt?: string; permalink?: string; error?: string; who?: string };
6845
+ if (argv.jobId) {
6846
+ const jobFile = path.join(jobsDir, `${argv.jobId}.json`);
6847
+ if (!/^[0-9a-z-]+$/.test(argv.jobId) || !fs.existsSync(jobFile)) {
6848
+ console.error(`Error: job not found: ${argv.jobId} (list them: slack jobs)`);
6849
+ process.exit(1);
6850
+ }
6851
+ const j = JSON.parse(fs.readFileSync(jobFile, "utf8")) as Job & { stdin?: string };
6852
+ delete j.stdin;
6853
+ if (argv.json) { console.log(JSON.stringify(j)); return; }
6854
+ console.log(`job ${j.jobId}: ${j.status}${j.who ? ` as @${j.who}` : ""}`);
6855
+ console.log(` command: slack ${stripTerminalControls(j.target ?? "")}`);
6856
+ for (const k of ["createdAt", "startedAt", "finishedAt", "permalink"] as const) if (j[k]) console.log(` ${k}: ${j[k]}`);
6857
+ if (j.error) console.log(` output:\n${stripTerminalControls(j.error).split("\n").map((l) => ` ${l}`).join("\n")}`);
6858
+ return;
6859
+ }
6860
+ let jobs: Job[] = [];
6861
+ try {
6862
+ for (const f of fs.readdirSync(jobsDir)) {
6863
+ if (!f.endsWith(".json")) continue;
6864
+ try { jobs.push(JSON.parse(fs.readFileSync(path.join(jobsDir, f), "utf8")) as Job); } catch { /* half-written */ }
6865
+ }
6866
+ } catch { /* no jobs yet */ }
6867
+ jobs = jobs.sort((x, y) => (y.createdAt ?? "").localeCompare(x.createdAt ?? "")).slice(0, Math.max(1, argv.limit));
6868
+ if (argv.json) { for (const j of jobs) console.log(JSON.stringify({ jobId: j.jobId, status: j.status, createdAt: j.createdAt, finishedAt: j.finishedAt, permalink: j.permalink, error: j.error })); return; }
6869
+ if (!jobs.length) { console.log("No --async jobs yet."); return; }
6870
+ for (const j of jobs) {
6871
+ const when = (j.createdAt ?? "").replace("T", " ").slice(0, 19);
6872
+ const what = j.status === "done" ? j.permalink ?? "" : j.status === "failed" ? (j.error ?? "").split("\n").pop() ?? "" : "";
6873
+ console.log(`${when} ${j.jobId} ${j.status.padEnd(7)} ${stripTerminalControls(what).slice(0, 120)}`);
6874
+ }
6875
+ },
6876
+ )
6877
+ .command(
6878
+ "_post-worker <jobFile>",
6879
+ false,
6880
+ (y) => y.positional("jobFile", { type: "string", demandOption: true }),
6881
+ async (argv) => {
6882
+ const fs = await import("node:fs");
6883
+ const path = await import("node:path");
6884
+ const { spawnSync } = await import("node:child_process");
6885
+ const jobFile = argv.jobFile!;
6886
+ const lastFailedFile = path.join(path.dirname(path.dirname(jobFile)), "last-failed.json");
6887
+ const job = JSON.parse(fs.readFileSync(jobFile, "utf8"));
6888
+ job.status = "running";
6889
+ job.startedAt = new Date().toISOString();
6890
+ fs.writeFileSync(jobFile, JSON.stringify(job, null, 2), { mode: 0o600 });
6891
+ fs.chmodSync(jobFile, 0o600);
6892
+ // The same identity the job was queued as, and the stdin it was given.
6893
+ const res = spawnSync(process.execPath, [process.argv[1]!, ...(job.who ? [`@${job.who}`] : []), ...job.forwardArgs], {
6894
+ encoding: "utf8",
6895
+ ...(typeof job.stdin === "string" ? { input: job.stdin } : {}),
6896
+ });
6897
+ delete job.stdin; // the message is not kept once it is sent
6898
+ job.finishedAt = new Date().toISOString();
6899
+ if (res.status === 0) {
6900
+ try {
6901
+ const out = JSON.parse(res.stdout.trim().split("\n").pop() || "{}");
6902
+ job.status = "done";
6903
+ job.ts = out.ts;
6904
+ job.permalink = out.permalink;
6905
+ } catch {
6906
+ job.status = "done";
6907
+ }
6908
+ try { fs.unlinkSync(lastFailedFile); } catch {}
6909
+ } else {
6910
+ job.status = "failed";
6911
+ job.error = (res.stderr || res.stdout || `exit ${res.status}`).trim().slice(-500);
6912
+ fs.writeFileSync(lastFailedFile, JSON.stringify({
6913
+ jobId: job.jobId,
6914
+ target: job.target,
6915
+ error: job.error,
6916
+ finishedAt: job.finishedAt,
6917
+ }, null, 2), { mode: 0o600 });
6918
+ fs.chmodSync(lastFailedFile, 0o600);
6919
+ }
6920
+ fs.writeFileSync(jobFile, JSON.stringify(job, null, 2), { mode: 0o600 });
6921
+ fs.chmodSync(jobFile, 0o600);
6922
+ if (job.callback) {
6923
+ spawnSync("bash", ["-lc", job.callback], {
6924
+ env: {
6925
+ ...process.env,
6926
+ SLACK_POST_JOB_ID: job.jobId,
6927
+ SLACK_POST_STATUS: job.status,
6928
+ SLACK_POST_TS: job.ts || "",
6929
+ SLACK_POST_PERMALINK: job.permalink || "",
6930
+ SLACK_POST_ERROR: job.error || "",
6931
+ },
6932
+ });
6933
+ }
6934
+ },
6935
+ )
6698
6936
  .command(
6699
6937
  "init [dir]",
6700
6938
  "Create .slack-hub/ in a directory: aliases, settings, inbox/outbox (never committed)",
@@ -7083,7 +7321,7 @@ async function main(): Promise<void> {
7083
7321
  (y) => y
7084
7322
  .positional("target", { type: "string", describe: "#chan, @user, #chan:thread_ts, or permalink (omit with --waitFor)" })
7085
7323
  .positional("question", { type: "string", describe: "The question. Must @tag whoever may answer (@alice), or the whole channel (@here / @channel / @everyone) — only their answer counts. In a 1:1 DM the other party counts automatically." })
7086
- .positional("choices", { type: "string", array: true, describe: "Up to 10 choices, seeded as 1️⃣..🔟 reactions. Beyond 10 they are listed but answerable only by text. With none, the question asks for a free-text reply." })
7324
+ .positional("choices", { type: "string", array: true, describe: "Up to 10 choices, seeded as 1️⃣..🔟 reactions. Beyond 10 they are listed but answerable only by text. With none, the question asks for a free-text reply. Also accepted as --choices \"A|B|C\" (split on |)." })
7087
7325
  .option("code", { type: "string", describe: "Safety hash to confirm the ask" })
7088
7326
  .option("allow-url-adjacent", { type: "boolean", default: false, describe: "Warn instead of refusing ambiguous bare URL boundaries" })
7089
7327
  .option("body", { type: "string", describe: "Extra context shown under the question" })
@@ -7096,7 +7334,7 @@ async function main(): Promise<void> {
7096
7334
  .option("edit", { type: "string", describe: "Change an open question you posted: --edit=<permalink> [\"new question\" [choices…]] [--body …]. Rebuilt with the ask layout so collect still reads it. Options can change only while nobody has answered (then: --void=<link> --reask). Same --code gate." })
7097
7335
  .option("ls", { type: "boolean", default: false, describe: "List the questions you posted (local sent-log) with their LIVE state: --state open|answered|void|all (default open), --stale 24h, --channel, --json. With --stale it prints the --void command that would retire them." })
7098
7336
  .option("pending", { type: "boolean", default: false, describe: "List questions THIS machine asked (local sent-log) that somebody answered but nobody collected, grouped by the asking session, with whether that agent is still alive and the --waitFor line that collects each. Read-only unless --push: --since 7d, --channel, --json. Never waits out a rate limit: a throttled pass says how many it skipped." })
7099
- .option("push", { type: "boolean", default: false, describe: "With --pending: send each answer to the agent that asked (ay send to the pid in the sent-log, or up to 3 of its parents), then collect a decision (✅, off this list); a free-text reply is marked delivered, the question stays open. A gone asker's answer goes to the newest live agent in the same directory (a restarted lane), else it stays listed. Each answer is pushed once." })
7337
+ .option("push", { type: "boolean", default: false, describe: "With --pending: send each answer to the agent that asked (ay send to the pid in the sent-log, or up to 3 of its parents), then collect a decision (✅, off this list); a free-text reply is marked delivered, the question stays open. A gone asker's answer goes to the unique live agent in the same directory (a restarted lane), else it stays listed. Each answer is pushed once." })
7100
7338
  .option("undelivered", { type: "boolean", default: false, describe: "With --pending: the sweep — only answers that have reached nobody yet. With --push, also why (asker gone and no live agent in its directory, or ay refused)." })
7101
7339
  .option("watch", { type: "boolean", default: false, describe: "With --pending --push: keep running — a pass every --interval, and one for a question as soon as the relay rings for it (SLACK_RELAY_URL / SLACK_RELAY_TOKEN). Prints only what it pushed." })
7102
7340
  .option("interval", { type: "number", default: 10, describe: "With --watch: minutes between full passes" })
@@ -7110,11 +7348,12 @@ async function main(): Promise<void> {
7110
7348
  .option("explain", { type: "boolean", describe: "Also offer an ℹ️ 'explain' pill (seeded after ➕): pressing it asks YOU to explain the question in its thread and is never an answer — the question stays open. --wait/--waitFor report it on stderr (and as `explain` in --json), and post one thread note per question. Default: $SLACK_HUB_ASK_EXPLAIN=1 turns it on; --no-explain turns it off." })
7111
7349
  .option("explain-exit", { type: "boolean", default: false, describe: "With --wait / --waitFor: exit 7 (stdout empty; --json status \"explain\") when someone presses ℹ️ — once per question, on the run that posts the thread note. The question stays open: explain, then collect again." })
7112
7350
  .option("json", { type: "boolean", default: false, describe: "With --pending: one JSON object per answered question (sender, answer, collect command). With --wait / --waitFor: print ONE JSON object on stdout — {status, answer, how, who, notes:[{ts,user,text,permalink}], cursor, permalink} — instead of the bare answer. `notes` are the audience's replies that are not the answer (thread replies; plain replies too in a 1:1 DM). Exit codes unchanged." })
7113
- .option("timeout", { type: "number", default: 3600, describe: "Overall limit for --wait / --waitFor, in seconds (0 with --waitFor = check once)" })
7351
+ .option("timeout", { type: "string", default: "3600", describe: "Overall limit for --wait / --waitFor: seconds or a duration (90s, 30m, 2h, 1d), or `forever`. 0 with --waitFor = check once. Running out exits 2 (stdout empty) — never mistaken for an answer" })
7114
7352
  .option("channel-id", { type: "string", describe: "Raw channel ID" })
7115
7353
  .option("user-id", { type: "string", describe: "Raw user ID (opens DM)" })
7116
7354
  .option("as-bot", { type: "boolean", default: false, describe: "Ask via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient. @tags and an @user target then resolve with the bot token too (needs users:read)." }),
7117
7355
  async (argv) => {
7356
+ if (askChoicesFlag.length) argv.choices = [...((argv.choices as string[] | undefined) ?? []), ...askChoicesFlag];
7118
7357
  // Verbs. A target is always #chan / @user / a permalink / a raw ID, so a
7119
7358
  // bare word here cannot be one — `slack ask void …` is unambiguous.
7120
7359
  // slack ask void <link…> [--reason …] [--superseded-by <link>] 無効化
@@ -7322,11 +7561,11 @@ async function main(): Promise<void> {
7322
7561
  argv.question = undefined;
7323
7562
  }
7324
7563
  const waitFor = argv.waitFor ? String(argv.waitFor) : "";
7325
- const timeout = Number(argv.timeout);
7564
+ const timeout = parseAskTimeout(argv.timeout);
7326
7565
  // 0 is a real value only for --waitFor ("look once"). For --wait it would
7327
7566
  // mean "give up before asking", which is never what anyone meant.
7328
- if (!Number.isFinite(timeout) || timeout < 0 || (timeout === 0 && !waitFor)) {
7329
- console.error("Error: --timeout must be a positive number of seconds");
7567
+ if (timeout === undefined || (timeout === 0 && !waitFor)) {
7568
+ console.error(`Error: --timeout must be a positive number of seconds, a duration (90s, 30m, 2h, 1d) or \`forever\` (got ${stripTerminalControls(String(argv.timeout))})`);
7330
7569
  process.exit(ASK_EXIT_ERROR);
7331
7570
  }
7332
7571
  if (waitFor) {
package/ts/profiles.ts CHANGED
@@ -248,6 +248,18 @@ export function useProfile(name: string, global = false): void {
248
248
  }
249
249
  }
250
250
 
251
+ /** Where the last resolveToken() answer came from — a NAME (env var or
252
+ * profile), never the value. `shadowed` lists the profiles an env token won
253
+ * over, which is the case worth telling the user about: a stale exported
254
+ * SLACK_TOKEN otherwise reads as a broken profile. */
255
+ export type TokenSource = { kind: "env" | "profile"; name: string; shadowed: string[] };
256
+ let lastTokenSource: TokenSource | undefined;
257
+ export function tokenSource(): TokenSource | undefined { return lastTokenSource; }
258
+ function srcd(token: string, name: string, kind: TokenSource["kind"], shadowed: string[] = []): string {
259
+ lastTokenSource = { kind, name, shadowed };
260
+ return token;
261
+ }
262
+
251
263
  export function resolveToken(workspaceFlag?: string): string {
252
264
  const store = load();
253
265
  const profiles = store.profiles;
@@ -259,16 +271,16 @@ export function resolveToken(workspaceFlag?: string): string {
259
271
  if (!profile) {
260
272
  throw new Error(`Workspace "${workspaceFlag}" not found. Available: ${names.join(", ") || "(none)"}`);
261
273
  }
262
- return profile.token;
274
+ return srcd(profile.token, `profile "${workspaceFlag}" (--workspace)`, "profile");
263
275
  }
264
276
 
265
277
  // SLACK_TOKEN always wins — intended as an explicit per-project override.
266
- if (process.env.SLACK_TOKEN) return process.env.SLACK_TOKEN;
278
+ if (process.env.SLACK_TOKEN) return srcd(process.env.SLACK_TOKEN, "SLACK_TOKEN", "env", names);
267
279
 
268
280
  // SLACK_BOT_TOKEN and SLACK_MCP_XOXP_TOKEN: only used when no profiles exist.
269
281
  // Bot tokens in shell env or .env files must not shadow workspace profiles.
270
282
  const legacyEnvToken = process.env.SLACK_BOT_TOKEN ?? process.env.SLACK_MCP_XOXP_TOKEN;
271
- if (legacyEnvToken && names.length === 0) return legacyEnvToken;
283
+ if (legacyEnvToken && names.length === 0) return srcd(legacyEnvToken, process.env.SLACK_BOT_TOKEN ? "SLACK_BOT_TOKEN" : "SLACK_MCP_XOXP_TOKEN", "env");
272
284
  // A bot token (xoxb-) belongs in SLACK_BOT_TOKEN: it is how `slack ask` / --as-bot send, and
273
285
  // ~/.config/slack-cli/.env is its documented home. It never stands in for the user token, so it is
274
286
  // no conflict; warn only about a *user* token parked in the legacy variables.
@@ -292,7 +304,7 @@ export function resolveToken(workspaceFlag?: string): string {
292
304
  // Dir walk: only SLACK_TOKEN from env files can override profiles.
293
305
  // SLACK_BOT_TOKEN in .env files yields to profiles (same as shell env).
294
306
  const walked = walkDirEnv(process.cwd(), ["SLACK_TOKEN"]);
295
- if (walked) return walked;
307
+ if (walked) return srcd(walked, "SLACK_TOKEN (from an env file above the current directory)", "env", names);
296
308
 
297
309
  // profiles.json via SLACK_WORKSPACE env var or lockfiles
298
310
  const selected = process.env.SLACK_WORKSPACE;
@@ -301,21 +313,21 @@ export function resolveToken(workspaceFlag?: string): string {
301
313
  if (!profile) {
302
314
  throw new Error(`Workspace "${selected}" not found. Available: ${names.join(", ") || "(none)"}`);
303
315
  }
304
- return profile.token;
316
+ return srcd(profile.token, `profile "${selected}" (SLACK_WORKSPACE)`, "profile");
305
317
  }
306
318
 
307
319
  const localName = readLockfile(localLockfilePath());
308
320
  if (localName) {
309
321
  const profile = profiles[localName];
310
322
  if (!profile) throw new Error(`Workspace "${localName}" (from .slack-cli/workspace) not found in profiles.`);
311
- return profile.token;
323
+ return srcd(profile.token, `profile "${localName}" (.slack-cli/workspace)`, "profile");
312
324
  }
313
325
 
314
326
  const globalName = readLockfile(globalLockfilePath());
315
327
  if (globalName) {
316
328
  const profile = profiles[globalName];
317
329
  if (!profile) throw new Error(`Workspace "${globalName}" (from ~/.slack-cli/workspace) not found in profiles.`);
318
- return profile.token;
330
+ return srcd(profile.token, `profile "${globalName}" (~/.slack-cli/workspace)`, "profile");
319
331
  }
320
332
 
321
333
  if (names.length > 0) {