slack-term 1.37.1 → 1.39.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
@@ -42,6 +42,7 @@ import {
42
42
  pollTally,
43
43
  } from "./poll.ts";
44
44
  import { seedReactionsInOrder } from "./reactionSeed.ts";
45
+ import { buildListSchema, cellValue, completedColumn, findColumn, parseColumnSpec, parseListSchema, parseSets, type ListColumn } from "./lists.ts";
45
46
  import { attributionEnabled, attributionMetadata, captureAttribution, parseSince, querySent, recordSent, SENT_LOG_UNAVAILABLE, sentDbPath, type RecordSent, type SentKind, type SentRow } from "./sentlog.ts";
46
47
  import {
47
48
  authTest,
@@ -61,6 +62,11 @@ import {
61
62
  filesInfo,
62
63
  filesList,
63
64
  listRecords,
65
+ slackListsAccessSet,
66
+ slackListsCreate,
67
+ slackListsItemsCreate,
68
+ slackListsItemsList,
69
+ slackListsItemsUpdate,
64
70
  history,
65
71
  listConversations,
66
72
  listConversationMembers,
@@ -76,6 +82,9 @@ import {
76
82
  search,
77
83
  searchAll,
78
84
  send as slackSend,
85
+ pinsAdd,
86
+ RateLimitError,
87
+ repliesCursor,
79
88
  type MessageMetadata,
80
89
  getPermalink,
81
90
  scheduleMessage,
@@ -104,9 +113,10 @@ import {
104
113
  type ProgressState,
105
114
  } from "./todo.ts";
106
115
  import { setCacheEnabled } from "./cache.ts";
107
- import { unescapeArg } from "./escapes.ts";
116
+ import { escapeArg, unescapeArg } from "./escapes.ts";
108
117
  import { dayLabel, encodeMentions, encodeMentionsDetailed, findUntaggedMentions, formatYmdHm, mentionWarnings, resolveDateMarkup, resolveMentions, type MentionEncodeResult } from "./format.ts";
109
118
  import { quietHoursNotice } from "./quietHours.ts";
119
+ import { LockBusyError, PINLOG_MARKER, acquireLock, composeHead, formatJst, headUpdatedAt, isPinlogHead, parsePinlogId, pinlogId, stripPinlogFooter } from "./pinlog.ts";
110
120
 
111
121
  function loadDotenv(path: string): void {
112
122
  if (!existsSync(path)) return;
@@ -876,6 +886,12 @@ const SCOPE_FOR_METHOD: Record<string, string> = {
876
886
  "chat.postMessage": "chat:write",
877
887
  "chat.update": "chat:write",
878
888
  "chat.delete": "chat:write",
889
+ "pins.add": "pins:write",
890
+ "slackLists.create": "lists:write",
891
+ "slackLists.items.create": "lists:write",
892
+ "slackLists.items.update": "lists:write",
893
+ "slackLists.items.list": "lists:read",
894
+ "slackLists.access.set": "lists:write",
879
895
  "conversations.replies": "channels:history (or groups:history)",
880
896
  "conversations.history": "channels:history (or groups:history)",
881
897
  };
@@ -1364,6 +1380,513 @@ async function cmdDelete(token: string, args: DeleteArgs): Promise<void> {
1364
1380
  console.log(`✓ Deleted (ts: ${ts})`);
1365
1381
  }
1366
1382
 
1383
+ // --- pinlog ---
1384
+ // A pinned status board: the pinned top-level message is the CURRENT state
1385
+ // (HEAD, edited in place — silent), and each change is one short thread reply
1386
+ // under it (the log — notifies). Pure helpers live in pinlog.ts; the commands
1387
+ // live here because they share the confirm gate with send/edit.
1388
+
1389
+ /** Single-quote `s` for a POSIX shell, for the retry commands we print. */
1390
+ function shQuote(s: string): string {
1391
+ return `'${s.replace(/'/g, `'\\''`)}'`;
1392
+ }
1393
+
1394
+ /** Which board a subcommand was pointed at: `C…:ts` (what `new` prints), or
1395
+ * the usual `#chan:ts` / permalink forms. A board IS its message — there is
1396
+ * no name and nothing local to look up. */
1397
+ async function resolvePinlogTarget(
1398
+ token: string, target: string, cookie?: string,
1399
+ ): Promise<{ channel: string; ts: string; ref: string }> {
1400
+ const id = parsePinlogId(target);
1401
+ if (id) return { ...id, ref: id.channel };
1402
+ const { ref, ts } = splitRefTs(target);
1403
+ if (!ts) {
1404
+ console.error(
1405
+ `Error: ${stripTerminalControls(target)} is a channel, not a board — pass the board's permalink, ` +
1406
+ `#chan:ts, or the id \`new\` printed (C…:ts). Boards in a channel: slack pinlog ls ${shQuote(target)}`,
1407
+ );
1408
+ process.exit(2);
1409
+ }
1410
+ return { channel: await resolveChannel(token, ref, cookie), ts, ref };
1411
+ }
1412
+
1413
+ /** The HEAD message itself, or a clean exit when there is none. */
1414
+ async function fetchPinlogHead(
1415
+ token: string, channel: string, ts: string, cookie?: string,
1416
+ ): Promise<Record<string, Json>> {
1417
+ const resp = asRecord((await replies(token, channel, ts, 1, cookie)) as Json);
1418
+ const head = asArray(resp.messages).map(asRecord).find((m) => String(m.ts) === ts);
1419
+ if (!head) {
1420
+ console.error(`Error: no message at ts=${ts} in ${channel}.`);
1421
+ process.exit(1);
1422
+ }
1423
+ return head;
1424
+ }
1425
+
1426
+ /** The state text for create/update: positional, or `--file` (`-` = stdin).
1427
+ * A board is many lines, and an agent quoting twenty lines into one argv
1428
+ * string is where a stray quote eats half of it. */
1429
+ function pinlogStateArg(positional: string | undefined, file: string | undefined): string | undefined {
1430
+ if (file !== undefined) {
1431
+ try {
1432
+ return readFileSync(file === "-" ? 0 : file, "utf8").replace(/\n+$/, "");
1433
+ } catch (e: unknown) {
1434
+ console.error(`Error: cannot read --file ${file}: ${e instanceof Error ? e.message : String(e)}`);
1435
+ process.exit(2);
1436
+ }
1437
+ }
1438
+ return positional === undefined ? undefined : unescapeArg(positional);
1439
+ }
1440
+
1441
+ /** Slack truncates `text` beyond 40,000 characters — which would cut the footer
1442
+ * off a board, after which `list` cannot find it and `update` refuses it. */
1443
+ const PINLOG_MAX_TEXT = 40_000;
1444
+ function pinlogCheckSize(what: string, text: string): void {
1445
+ if (text.length > PINLOG_MAX_TEXT) {
1446
+ console.error(`Error: the ${what} is ${text.length} characters; Slack truncates past ${PINLOG_MAX_TEXT}. Shorten it — move detail to a linked page.`);
1447
+ process.exit(2);
1448
+ }
1449
+ }
1450
+
1451
+ /** Did this failed write DEFINITELY not land? Only a Slack error response
1452
+ * names a rejection. A network failure, or Slack's own internal_error /
1453
+ * fatal_error (documented as possibly-partial), means the write MAY have
1454
+ * landed — and advising a blind retry would then duplicate a board or a
1455
+ * notifying log line. */
1456
+ function pinlogWriteRejected(e: unknown): boolean {
1457
+ const raw = e instanceof Error ? e.message : String(e);
1458
+ const m = raw.match(/Slack error on \S+: (\w+)/);
1459
+ if (e instanceof RateLimitError) return true;
1460
+ return !!m && !["internal_error", "fatal_error", "request_timeout", "service_unavailable"].includes(m[1]!);
1461
+ }
1462
+
1463
+ /** The quiet-hours line as a warning, or null outside them. The confirm gate
1464
+ * already prints the clock; this repeats it on the CONFIRMED run too, because
1465
+ * that is the run whose output an agent actually reads. */
1466
+ function pinlogQuietWarning(now: Date, what: string): string | null {
1467
+ const n = quietHoursNotice(now);
1468
+ return n && n.includes("QUIET HOURS") ? `⚠ Quiet hours (JST): ${what}.` : null;
1469
+ }
1470
+
1471
+ interface PinlogCreateArgs {
1472
+ target: string;
1473
+ /** `-w`, carried into the printed recovery commands. */
1474
+ workspace?: string;
1475
+ state: string;
1476
+ /** Optional first reason, posted as the new board's first thread reply. */
1477
+ log?: string;
1478
+ code?: string;
1479
+ cookie?: string;
1480
+ asBot?: boolean;
1481
+ allowUrlAdjacent?: boolean;
1482
+ }
1483
+
1484
+ async function cmdPinlogCreate(token: string, args: PinlogCreateArgs): Promise<void> {
1485
+ const { ref, ts } = splitRefTs(args.target);
1486
+ if (ts || parsePinlogId(args.target)) {
1487
+ console.error(
1488
+ "Error: `pinlog new` posts a NEW board — pass a channel (#chan or C…), not a message.\n" +
1489
+ ` To change an existing board: slack pinlog set ${shQuote(args.target)} '<new state>' '<reason>'`,
1490
+ );
1491
+ process.exit(2);
1492
+ }
1493
+ if (!args.state.trim()) {
1494
+ console.error("Error: the initial state is empty — a board has to say something.");
1495
+ process.exit(2);
1496
+ }
1497
+ guardUrlBoundaries(args.state, args.allowUrlAdjacent);
1498
+ if (args.log !== undefined) {
1499
+ guardUrlBoundaries(args.log, args.allowUrlAdjacent);
1500
+ pinlogCheckSize("reason", args.log);
1501
+ }
1502
+
1503
+ // Every recovery command printed below must act on the SAME workspace: a
1504
+ // `list` that silently checks the default one finds nothing, and the next
1505
+ // step is a duplicate board.
1506
+ const bot = `${args.workspace ? ` -w ${shQuote(args.workspace)}` : ""}${args.asBot ? " --as-bot" : ""}`;
1507
+ const getSelf = selfLookup(token, args.cookie);
1508
+ const channelId = await resolveChannel(token, ref, args.cookie);
1509
+ const self = await getSelf();
1510
+ // The clock is NOT in the hash: the footer's minute moves between preview and
1511
+ // confirm, and a code that expires every minute is a code people stop reading.
1512
+ const code = safetyCode("pinlog-create", channelId, args.state, args.log ?? "", self?.userId ?? "");
1513
+ const now = new Date();
1514
+ const head = composeHead(args.state, now);
1515
+ pinlogCheckSize("HEAD (state + footer)", head);
1516
+ if (args.code !== code) {
1517
+ const dest = await destLabel(token, channelId, ref, args.cookie);
1518
+ // The situation, not just the text: boards already here are the usual
1519
+ // sign that this should be a `set` on one of them, not a second board.
1520
+ const existing = (await pinlogsIn(token, channelId, 200, args.cookie)).found;
1521
+ requireCode(args.code, code, [
1522
+ `--- New pinlog -------------------------------`,
1523
+ fromLine(self, { asBot: args.asBot }),
1524
+ ` → ${dest} — NEW top-level message, then pinned`,
1525
+ ...(existing.length
1526
+ ? [`⚠ ${existing.length} board(s) already in this channel — to change one, use \`slack pinlog set <board> …\` instead:`,
1527
+ ...existing.slice(0, 5).map((m) => ` ${pinlogId(channelId, String(m.ts))} ${pinlogFirstLine(String(m.text))}`)]
1528
+ : [` (no other boards in the last 200 messages of this channel)`]),
1529
+ `--- State (the top-level message) ------------`,
1530
+ ...head.split("\n").map((l) => ` ${stripTerminalControls(l)}`),
1531
+ ...(args.log ? [`--- Reason (first thread reply — notifies) ---`, ...args.log.split("\n").map((l) => ` ${stripTerminalControls(l)}`)] : []),
1532
+ `---------------------------------------------`,
1533
+ ]);
1534
+ }
1535
+
1536
+ const attr = sentAttribution("send");
1537
+ let headTs: string;
1538
+ try {
1539
+ // plain: the HEAD must read back verbatim — `update` and `list` find the
1540
+ // footer in the stored text, which Slack rewrites when blocks are attached.
1541
+ headTs = await slackSend(token, channelId, head, undefined, false, args.cookie, true, attr.metadata);
1542
+ } catch (e: unknown) {
1543
+ if (pinlogWriteRejected(e)) {
1544
+ console.error(`✗ HEAD was NOT posted: ${friendlySlackError(e)}`);
1545
+ } else {
1546
+ console.error(
1547
+ `⚠ UNKNOWN whether the HEAD was posted: ${friendlySlackError(e)}\n` +
1548
+ ` Check before retrying, or you will have two boards: slack pinlog ls ${shQuote(args.target)}${bot}`,
1549
+ );
1550
+ }
1551
+ process.exit(1);
1552
+ }
1553
+ if (!headTs) {
1554
+ console.error("✗ Slack accepted the post but returned no ts — check the channel before retrying, it may have landed.");
1555
+ process.exit(1);
1556
+ }
1557
+ attr.record({ team: self?.team, channel: channelId, target: args.target, ts: headTs, text: head, asBot: args.asBot });
1558
+ const id = pinlogId(channelId, headTs);
1559
+ console.log(`✓ Posted HEAD: ${id}`);
1560
+ const quiet = pinlogQuietWarning(now, "this new top-level post notified everyone who follows the channel");
1561
+ if (quiet) console.error(quiet);
1562
+
1563
+ try {
1564
+ await pinsAdd(token, channelId, headTs, args.cookie);
1565
+ console.log("✓ Pinned");
1566
+ } catch (e: unknown) {
1567
+ // The board EXISTS now. Failing the command here would invite a retry of
1568
+ // `create`, i.e. a second board — so this is reported loudly, but the exit
1569
+ // code stays 0 and the id is already on stdout.
1570
+ const raw = e instanceof Error ? e.message : String(e);
1571
+ const why = /missing_scope/.test(raw)
1572
+ ? `the ${args.asBot ? "bot" : "user"} token lacks the pins:write scope`
1573
+ : friendlySlackError(e);
1574
+ console.error(`⚠ NOT pinned: ${why}.`);
1575
+ console.error(` The board works unpinned; pin it later with: slack pinlog pin ${id}${bot}`);
1576
+ }
1577
+
1578
+ if (args.log) {
1579
+ // The board exists either way: a failed first reason is reported with its
1580
+ // exact retry, never by failing `new` (a retry of that would be a 2nd board).
1581
+ try {
1582
+ const logTs = await slackSend(token, channelId, args.log, headTs, false, args.cookie, true);
1583
+ console.log(`✓ Reason posted in the thread (ts: ${logTs})`);
1584
+ } catch (e: unknown) {
1585
+ const noteCode = safetyCode("pinlog-log", channelId, headTs, args.log, self?.userId ?? "");
1586
+ console.error(
1587
+ `${pinlogWriteRejected(e) ? "✗ The reason was NOT posted" : "⚠ UNKNOWN whether the reason was posted"}: ${friendlySlackError(e)}\n` +
1588
+ ` The board IS posted. Retry just the reason (check the thread first):\n` +
1589
+ ` slack pinlog note ${id} ${shQuote(escapeArg(args.log))}${args.allowUrlAdjacent ? " --allow-url-adjacent" : ""}${bot} --code=${noteCode}`,
1590
+ );
1591
+ process.exit(1);
1592
+ }
1593
+ }
1594
+ }
1595
+
1596
+ interface PinlogUpdateArgs {
1597
+ target: string;
1598
+ state?: string;
1599
+ log: string;
1600
+ logOnly?: boolean;
1601
+ /** Turn an existing message (no footer yet) into a board: the explicit
1602
+ * opt-out of the marker check, for a board people already ran by hand. */
1603
+ adopt?: boolean;
1604
+ /** `-w`, carried into the printed retry so it acts on the same workspace. */
1605
+ workspace?: string;
1606
+ code?: string;
1607
+ cookie?: string;
1608
+ asBot?: boolean;
1609
+ allowUrlAdjacent?: boolean;
1610
+ }
1611
+
1612
+ async function cmdPinlogUpdate(token: string, args: PinlogUpdateArgs): Promise<void> {
1613
+ if (!args.log.trim()) {
1614
+ console.error("Error: the reason is required — one short line saying what changed. The thread log is the point of a pinlog.");
1615
+ process.exit(2);
1616
+ }
1617
+ if (!args.logOnly && (args.state === undefined || !args.state.trim())) {
1618
+ console.error("Error: the new state is required (positional or --file). To post only a reason: slack pinlog note <board> <reason>");
1619
+ process.exit(2);
1620
+ }
1621
+ guardUrlBoundaries(args.log, args.allowUrlAdjacent);
1622
+ if (args.state !== undefined) guardUrlBoundaries(args.state, args.allowUrlAdjacent);
1623
+ pinlogCheckSize("log line", args.log);
1624
+
1625
+ const getSelf = selfLookup(token, args.cookie);
1626
+ const { channel, ts, ref } = await resolvePinlogTarget(token, args.target, args.cookie);
1627
+ // Held from the HEAD fetch through the log post (released on exit): Slack has
1628
+ // no compare-and-swap on chat.update, so without it two confirmed updates can
1629
+ // both read the same HEAD and the second silently erases the first's change.
1630
+ try {
1631
+ acquireLock(`pinlog-${channel}-${ts}`);
1632
+ } catch (e: unknown) {
1633
+ if (!(e instanceof LockBusyError)) throw e;
1634
+ console.error(`Error: another update of ${pinlogId(channel, ts)} is running (${e.holder}). Re-run when it has finished — then re-read the board, it has changed.`);
1635
+ process.exit(1);
1636
+ }
1637
+ const head = await fetchPinlogHead(token, channel, ts, args.cookie);
1638
+ const currentText = typeof head.text === "string" ? head.text : "";
1639
+ if (args.adopt && args.logOnly) {
1640
+ console.error("Error: --adopt rewrites the state with a footer — it does not apply to note.");
1641
+ process.exit(2);
1642
+ }
1643
+ if (!isPinlogHead(currentText) && !args.adopt) {
1644
+ console.error(
1645
+ `Error: the message at ${pinlogId(channel, ts)} is not a pinlog HEAD (no "${PINLOG_MARKER}" footer).\n` +
1646
+ ` Refusing to overwrite it — check the id. To turn this message into a board on purpose, add --adopt.`,
1647
+ );
1648
+ process.exit(1);
1649
+ }
1650
+ const self = await getSelf();
1651
+ const id = pinlogId(channel, ts);
1652
+ const now = new Date();
1653
+ const bot = `${args.workspace ? ` -w ${shQuote(args.workspace)}` : ""}${args.asBot ? " --as-bot" : ""}`;
1654
+ // The retry command for a failed log post is printed with its code already
1655
+ // in it, so the hash for `note` must be computable here without a gate.
1656
+ const logOnlyCode = safetyCode("pinlog-log", channel, ts, args.log, self?.userId ?? "");
1657
+ const logOnlyRetry = `slack pinlog note ${id} ${shQuote(escapeArg(args.log))}${args.allowUrlAdjacent ? " --allow-url-adjacent" : ""}${bot} --code=${logOnlyCode}`;
1658
+
1659
+ const quiet = pinlogQuietWarning(now, "the log reply notified everyone following this thread — hold non-urgent updates until 08:00");
1660
+ if (args.logOnly) {
1661
+ if (args.code !== logOnlyCode) {
1662
+ const dest = await destLabel(token, channel, ref, args.cookie);
1663
+ requireCode(args.code, logOnlyCode, [
1664
+ `--- Pinlog log reply (HEAD unchanged) --------`,
1665
+ fromLine(self, { asBot: args.asBot }),
1666
+ ` → ${dest}, thread of ${id}`,
1667
+ ...args.log.split("\n").map((l) => ` ${stripTerminalControls(l)}`),
1668
+ `---------------------------------------------`,
1669
+ ]);
1670
+ }
1671
+ } else {
1672
+ const newHead = composeHead(args.state!, now);
1673
+ pinlogCheckSize("new HEAD (state + footer)", newHead);
1674
+ // The CURRENT text is in the hash: if someone else updated the board
1675
+ // between your preview and your confirm, the code you were shown no longer
1676
+ // matches, and you re-read before overwriting their change.
1677
+ const adopting = !isPinlogHead(currentText);
1678
+ const code = safetyCode("pinlog-update", channel, ts, currentText, args.state!, args.log, self?.userId ?? "");
1679
+ if (args.code !== code) {
1680
+ const dest = await destLabel(token, channel, ref, args.cookie);
1681
+ const unchanged = stripPinlogFooter(currentText).trim() === stripPinlogFooter(args.state!).trim();
1682
+ requireCode(args.code, code, [
1683
+ `--- Updating pinlog --------------------------`,
1684
+ fromLine(self, { asBot: args.asBot }),
1685
+ ` → ${dest}, ${id}`,
1686
+ `--- Current HEAD -----------------------------`,
1687
+ // Shown, not sent: the HEAD comes from Slack, and an escape sequence in
1688
+ // it could repaint this very preview.
1689
+ ...currentText.split("\n").map((l) => ` ${stripTerminalControls(l)}`),
1690
+ `--- New HEAD (edited in place — silent) ------`,
1691
+ ...newHead.split("\n").map((l) => ` ${stripTerminalControls(l)}`),
1692
+ `--- Log reply (in the thread — notifies) -----`,
1693
+ ...args.log.split("\n").map((l) => ` ${stripTerminalControls(l)}`),
1694
+ `---------------------------------------------`,
1695
+ ...(unchanged ? [`⚠ The state text is unchanged — only the footer time moves. Replies are for real changes.`] : []),
1696
+ ...(adopting ? [`⚠ Adopting: this message has no pinlog footer yet — it becomes a board now.`] : []),
1697
+ ]);
1698
+ }
1699
+
1700
+ const attrEdit = sentAttribution("edit");
1701
+ try {
1702
+ await editMessage(token, channel, ts, newHead, args.cookie, true, attrEdit.metadata);
1703
+ } catch (e: unknown) {
1704
+ const raw = e instanceof Error ? e.message : String(e);
1705
+ const hint = /cant_update_message/.test(raw)
1706
+ ? `\n Only the HEAD's author can edit it${args.asBot ? "" : " — if the bot created this board, add --as-bot"}.`
1707
+ : "";
1708
+ const what = pinlogWriteRejected(e)
1709
+ ? `✗ HEAD was NOT updated: ${friendlySlackError(e)}${hint}`
1710
+ : `⚠ UNKNOWN whether the HEAD was updated: ${friendlySlackError(e)}\n Check it first: slack pinlog get ${id}${bot}`;
1711
+ console.error(`${what}\n The log reply was NOT posted (a log line for a change the board may not show would be a lie).`);
1712
+ process.exit(1);
1713
+ }
1714
+ attrEdit.record({ team: self?.team, channel, target: args.target, ts, text: newHead, asBot: args.asBot });
1715
+ console.log(`✓ HEAD updated: ${id}`);
1716
+ }
1717
+
1718
+ const attrLog = sentAttribution("send");
1719
+ let logTs: string;
1720
+ try {
1721
+ logTs = await slackSend(token, channel, args.log, ts, false, args.cookie, true, attrLog.metadata);
1722
+ } catch (e: unknown) {
1723
+ const rejected = pinlogWriteRejected(e);
1724
+ console.error(
1725
+ (rejected
1726
+ ? `✗ Log reply was NOT posted: ${friendlySlackError(e)}\n`
1727
+ : `⚠ UNKNOWN whether the log reply was posted: ${friendlySlackError(e)}\n`) +
1728
+ (args.logOnly ? "" : ` The HEAD IS updated — only the log line ${rejected ? "is" : "may be"} missing.\n`) +
1729
+ (rejected ? "" : ` Check the thread first (retrying a reply that landed notifies everyone twice): slack pinlog get ${id}${bot}\n`) +
1730
+ ` Retry just the log line${rejected ? "" : " (only if it is not there)"}:\n ${logOnlyRetry}`,
1731
+ );
1732
+ process.exit(1);
1733
+ }
1734
+ attrLog.record({ team: self?.team, channel, target: args.target, ts: logTs, text: args.log, asBot: args.asBot });
1735
+ console.log(`✓ Logged (ts: ${logTs})`);
1736
+ if (quiet) console.error(quiet);
1737
+ }
1738
+
1739
+ /** Slack stores `&`, `<`, `>` escaped; `show` is for reading, so undo that. */
1740
+ function slackUnescape(s: string): string {
1741
+ return s.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
1742
+ }
1743
+
1744
+ /** `2026-10-08 15:10 JST` for a Slack ts. */
1745
+ function tsJst(ts: string): string {
1746
+ return formatJst(new Date(Number(ts.split(".")[0]) * 1000));
1747
+ }
1748
+
1749
+ async function pinlogAuthor(token: string, m: Record<string, Json>, cache: Map<string, string>, cookie?: string): Promise<string> {
1750
+ if (typeof m.user === "string") {
1751
+ const hit = cache.get(m.user);
1752
+ if (hit !== undefined) return hit;
1753
+ let name: string;
1754
+ try {
1755
+ name = await userName(token, m.user, cookie);
1756
+ } catch {
1757
+ name = m.user;
1758
+ }
1759
+ cache.set(m.user, name);
1760
+ return name;
1761
+ }
1762
+ const prof = asRecord(m.bot_profile);
1763
+ if (typeof prof.name === "string") return prof.name;
1764
+ return typeof m.username === "string" ? m.username : "bot";
1765
+ }
1766
+
1767
+ async function cmdPinlogShow(token: string, target: string, cookie?: string, json?: boolean): Promise<void> {
1768
+ const { channel, ts } = await resolvePinlogTarget(token, target, cookie);
1769
+ // Page through the whole thread. Slack returns the oldest replies first, so a
1770
+ // single page silently drops the NEWEST log entries — the ones a reader came
1771
+ // for. Bounded; past the bound, `complete` says so.
1772
+ const msgs: Record<string, Json>[] = [];
1773
+ let cursor: string | undefined;
1774
+ let pages = 0;
1775
+ do {
1776
+ const page = asRecord((await repliesCursor(token, channel, ts, cursor, 200, cookie)) as Json);
1777
+ for (const m of asArray(page.messages).map(asRecord)) {
1778
+ // Every page repeats the parent; keep it once.
1779
+ if (String(m.ts) === ts && msgs.some((x) => String(x.ts) === ts)) continue;
1780
+ msgs.push(m);
1781
+ }
1782
+ const next = asRecord(page.response_metadata).next_cursor;
1783
+ cursor = typeof next === "string" && next ? next : undefined;
1784
+ pages++;
1785
+ } while (cursor && pages < 50);
1786
+ const complete = cursor === undefined;
1787
+ const head = msgs.find((m) => String(m.ts) === ts);
1788
+ if (!head) {
1789
+ console.error(`Error: no message at ts=${ts} in ${channel}.`);
1790
+ process.exit(1);
1791
+ }
1792
+ const text = typeof head.text === "string" ? head.text : "";
1793
+ const log = msgs.filter((m) => String(m.ts) !== ts);
1794
+ if (json) {
1795
+ console.log(JSON.stringify({
1796
+ id: pinlogId(channel, ts),
1797
+ isPinlog: isPinlogHead(text),
1798
+ updated: headUpdatedAt(text),
1799
+ complete,
1800
+ head: text,
1801
+ log: log.map((m) => ({ ts: String(m.ts), user: m.user ?? null, text: typeof m.text === "string" ? m.text : "" })),
1802
+ }));
1803
+ return;
1804
+ }
1805
+ if (!isPinlogHead(text)) {
1806
+ console.error(`⚠ ${pinlogId(channel, ts)} has no "${PINLOG_MARKER}" footer — showing it anyway, but it is not a pinlog HEAD.`);
1807
+ }
1808
+ console.log(`=== HEAD ${pinlogId(channel, ts)} ===`);
1809
+ for (const l of slackUnescape(text).split("\n")) console.log(stripTerminalControls(l));
1810
+ const more = complete ? "" : " — INCOMPLETE: the newest entries are not shown";
1811
+ console.log(`=== log (${log.length}${more}) ===`);
1812
+ // One lookup per author, not per entry: a board is mostly one writer.
1813
+ const authors = new Map<string, string>();
1814
+ for (const m of log) {
1815
+ const body = typeof m.text === "string" ? m.text : "";
1816
+ const author = stripTerminalControls(await pinlogAuthor(token, m, authors, cookie));
1817
+ const lines = slackUnescape(body).split("\n").map((l) => stripTerminalControls(l));
1818
+ console.log(`${tsJst(String(m.ts))} @${author}: ${lines[0] ?? ""}`);
1819
+ for (const l of lines.slice(1)) console.log(` ${l}`);
1820
+ }
1821
+ }
1822
+
1823
+ /** Boards among the last `limit` messages of a channel, newest first — found
1824
+ * by their footer, which is the only place a board is recorded. */
1825
+ async function pinlogsIn(
1826
+ token: string, channelId: string, limit: number, cookie?: string,
1827
+ ): Promise<{ found: Record<string, Json>[]; scanned: number }> {
1828
+ let scanned = 0;
1829
+ let cursor: string | undefined;
1830
+ const found: Record<string, Json>[] = [];
1831
+ do {
1832
+ const page = asRecord((await history(token, channelId, Math.min(200, limit - scanned), undefined, cursor, cookie)) as Json);
1833
+ const msgs = asArray(page.messages).map(asRecord);
1834
+ scanned += msgs.length;
1835
+ for (const m of msgs) if (typeof m.text === "string" && isPinlogHead(m.text)) found.push(m);
1836
+ const next = asRecord(page.response_metadata).next_cursor;
1837
+ cursor = typeof next === "string" && next ? next : undefined;
1838
+ } while (cursor && scanned < limit);
1839
+ return { found, scanned };
1840
+ }
1841
+
1842
+ /** A board's first non-empty state line, for one-line listings. */
1843
+ function pinlogFirstLine(text: string): string {
1844
+ return stripTerminalControls(stripPinlogFooter(text).split("\n").find((l) => l.trim()) ?? "").slice(0, 80);
1845
+ }
1846
+
1847
+ async function cmdPinlogList(token: string, target: string, limit: number, cookie?: string): Promise<void> {
1848
+ const { ref, ts } = splitRefTs(target);
1849
+ if (ts || parsePinlogId(target)) {
1850
+ console.error(`Error: \`pinlog ls\` takes a channel. For one board: slack pinlog get ${shQuote(target)}`);
1851
+ process.exit(2);
1852
+ }
1853
+ const channelId = await resolveChannel(token, ref, cookie);
1854
+ const { found, scanned } = await pinlogsIn(token, channelId, limit, cookie);
1855
+
1856
+ const dest = await destLabel(token, channelId, ref, cookie);
1857
+ if (found.length === 0) {
1858
+ // "None in what we looked at" — not "none exist". Say how far we looked.
1859
+ console.log(`No pinlogs in the last ${scanned} messages of ${dest}.${scanned >= limit ? ` (Older ones: --limit ${limit * 2})` : ""}`);
1860
+ return;
1861
+ }
1862
+ for (const m of found) {
1863
+ const ts = String(m.ts);
1864
+ const id = pinlogId(channelId, ts);
1865
+ const text = String(m.text);
1866
+ const pinned = asArray(m.pinned_to).some((c) => c === channelId) ? "📌" : " ";
1867
+ const first = pinlogFirstLine(text);
1868
+ const replies = typeof m.reply_count === "number" ? m.reply_count : 0;
1869
+ console.log(`${pinned} ${id} updated ${headUpdatedAt(text) ?? "?"} log ${replies}`);
1870
+ console.log(` ${first}`);
1871
+ }
1872
+ }
1873
+
1874
+ async function cmdPinlogPin(token: string, target: string, cookie?: string): Promise<void> {
1875
+ const { channel, ts } = await resolvePinlogTarget(token, target, cookie);
1876
+ try {
1877
+ await pinsAdd(token, channel, ts, cookie);
1878
+ console.log(`✓ Pinned ${pinlogId(channel, ts)}`);
1879
+ } catch (e: unknown) {
1880
+ const raw = e instanceof Error ? e.message : String(e);
1881
+ if (/already_pinned/.test(raw)) {
1882
+ console.log(`✓ Already pinned: ${pinlogId(channel, ts)}`);
1883
+ return;
1884
+ }
1885
+ console.error(`✗ NOT pinned: ${friendlySlackError(e)}`);
1886
+ process.exit(1);
1887
+ }
1888
+ }
1889
+
1367
1890
  // --- react ---
1368
1891
  interface ReactArgs {
1369
1892
  target: string;
@@ -3219,7 +3742,7 @@ async function cmdLists(
3219
3742
  token: string,
3220
3743
  cookie: string | undefined,
3221
3744
  ref: string,
3222
- opts: { limit: number; format: string },
3745
+ opts: { limit: number; format: string; asBot?: boolean },
3223
3746
  ): Promise<void> {
3224
3747
  const listId = parseListId(ref);
3225
3748
  if (!listId) {
@@ -3233,7 +3756,11 @@ async function cmdLists(
3233
3756
  do {
3234
3757
  const listOpts: { limit: number; cursor?: string } = { limit: 200 };
3235
3758
  if (cursor) listOpts.cursor = cursor;
3236
- const resp = asRecord((await listRecords(token, listId, listOpts, cookie)) as Json);
3759
+ // --as-bot reads through the public slackLists.items.list (bot token,
3760
+ // lists:read) — for lanes that hold only a bot token, no user session.
3761
+ const resp = opts.asBot
3762
+ ? await slackListsItemsList(listsBotToken(), listId, listOpts)
3763
+ : asRecord((await listRecords(token, listId, listOpts, cookie)) as Json);
3237
3764
  for (const it of asArray(resp.items ?? resp.records)) records.push(asRecord(it));
3238
3765
  const next = asRecord(resp.response_metadata).next_cursor;
3239
3766
  cursor = typeof next === "string" && next ? next : undefined;
@@ -3258,6 +3785,173 @@ async function cmdLists(
3258
3785
  }
3259
3786
  }
3260
3787
 
3788
+ // --- lists create / add / set — gated writes via the public slackLists.* API ---
3789
+ // The public API rejects the xoxc desktop token, so these act as the BOT
3790
+ // (SLACK_BOT_TOKEN, needs lists:write). Same two-step --code gate as `send`.
3791
+
3792
+ function listsBotToken(): string {
3793
+ const bot = resolveBotToken();
3794
+ if (!bot) {
3795
+ console.error(
3796
+ "Error: Slack List writes go through the public slackLists.* API, which needs a bot token (xoxb-) — none was found.\n" +
3797
+ " Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).",
3798
+ );
3799
+ process.exit(1);
3800
+ }
3801
+ return bot;
3802
+ }
3803
+
3804
+ /** Fail early, before any gate, when the bot lacks lists:write — the gate would
3805
+ * otherwise mint a code for a write that can only fail. */
3806
+ async function requireListsWrite(bot: string): Promise<void> {
3807
+ let scopes: string[] = [];
3808
+ try {
3809
+ scopes = (await authScopes(bot)).scopes;
3810
+ } catch {
3811
+ return; // scope lookup is best-effort; the write itself reports missing_scope
3812
+ }
3813
+ if (scopes.length && !scopes.includes("lists:write")) {
3814
+ console.error(
3815
+ "Error: the bot token lacks the lists:write scope (needed for slackLists.* writes).\n" +
3816
+ " Add it under OAuth & Permissions → Bot Token Scopes in the Slack app config, then reinstall the app.",
3817
+ );
3818
+ process.exit(1);
3819
+ }
3820
+ }
3821
+
3822
+ async function listUrl(bot: string, listId: string): Promise<string> {
3823
+ try {
3824
+ const a = await authTest(bot);
3825
+ if (a.url && a.teamId) return `${a.url.replace(/\/$/, "")}/lists/${a.teamId}/${listId}`;
3826
+ } catch {
3827
+ // fall through to the bare id
3828
+ }
3829
+ return listId;
3830
+ }
3831
+
3832
+ async function listColumns(bot: string, listId: string): Promise<ListColumn[]> {
3833
+ const resp = await slackListsItemsList(bot, listId, { limit: 1, includeList: true });
3834
+ const cols = parseListSchema(asRecord(resp.list));
3835
+ if (!cols.length) throw new Error(`could not read the column schema of list ${listId}`);
3836
+ return cols;
3837
+ }
3838
+
3839
+ function listWriteFail(e: unknown): never {
3840
+ console.error(friendlySlackError(e));
3841
+ process.exit(1);
3842
+ }
3843
+
3844
+ async function cmdListsCreate(args: { name: string; cols: string[]; todo: boolean; code?: string }): Promise<void> {
3845
+ const specs = args.cols.map(parseColumnSpec);
3846
+ const schema = buildListSchema(specs);
3847
+ const bot = listsBotToken();
3848
+ await requireListsWrite(bot);
3849
+ const self = await selfIdentity(bot);
3850
+ const code = safetyCode("lists-create", args.name, JSON.stringify(schema), String(args.todo), self?.userId ?? "");
3851
+ if (args.code !== code) requireCode(args.code, code, [
3852
+ `--- Creating Slack List ----------------------`,
3853
+ fromLine(self, { asBot: true, pad: 9 }),
3854
+ ` name: ${args.name}`,
3855
+ ...specs.map((c, i) => ` column: ${c.name} (${c.type}${c.choices ? `: ${c.choices.join("/")}` : ""})${i === 0 ? " [primary]" : ""}`),
3856
+ ` todo: ${args.todo ? "on (adds Completed / Assignee / Due date)" : "off"}`,
3857
+ `--------------------------------────────────`,
3858
+ ]);
3859
+ let resp: Record<string, Json>;
3860
+ try {
3861
+ resp = await slackListsCreate(bot, args.name, schema, args.todo);
3862
+ } catch (e: unknown) {
3863
+ listWriteFail(e);
3864
+ }
3865
+ const listId = String(resp.list_id ?? asRecord(resp.list).id ?? "");
3866
+ console.log(`✓ Created list ${args.name} (${listId})`);
3867
+ console.log(await listUrl(bot, listId));
3868
+ }
3869
+
3870
+ async function cmdListsAdd(args: { list: string; text: string; sets: string[]; code?: string }): Promise<void> {
3871
+ const listId = parseListId(args.list);
3872
+ if (!listId) throw new Error(`Not a list ID or list URL: ${args.list}`);
3873
+ const bot = listsBotToken();
3874
+ await requireListsWrite(bot);
3875
+ const cols = await listColumns(bot, listId);
3876
+ const primary = cols.find((c) => c.type === "text") ?? cols[0]!;
3877
+ const pairs = [{ col: primary, value: args.text }, ...parseSets(args.sets).map((p) => ({ col: findColumn(cols, p.col), value: p.value }))];
3878
+ const fields = pairs.map((p) => ({ column_id: p.col.id, ...cellValue(p.col, p.value) }));
3879
+ const self = await selfIdentity(bot);
3880
+ const code = safetyCode("lists-add", listId, JSON.stringify(fields), self?.userId ?? "");
3881
+ if (args.code !== code) requireCode(args.code, code, [
3882
+ `--- Adding a row to Slack List ---------------`,
3883
+ fromLine(self, { asBot: true, pad: 9 }),
3884
+ ` list: ${listId}`,
3885
+ ...pairs.map((p) => ` ${(p.col.name || p.col.key).padEnd(8)} ${p.value}`),
3886
+ `--------------------------------────────────`,
3887
+ ]);
3888
+ let resp: Record<string, Json>;
3889
+ try {
3890
+ resp = await slackListsItemsCreate(bot, listId, fields);
3891
+ } catch (e: unknown) {
3892
+ listWriteFail(e);
3893
+ }
3894
+ console.log(`✓ Added row ${String(asRecord(resp.item).id ?? "")} ${args.text}`);
3895
+ }
3896
+
3897
+ async function cmdListsSet(args: { list: string; row: string; sets: string[]; done?: boolean; code?: string }): Promise<void> {
3898
+ const listId = parseListId(args.list);
3899
+ if (!listId) throw new Error(`Not a list ID or list URL: ${args.list}`);
3900
+ const bot = listsBotToken();
3901
+ await requireListsWrite(bot);
3902
+ const cols = await listColumns(bot, listId);
3903
+ const pairs = parseSets(args.sets).map((p) => ({ col: findColumn(cols, p.col), value: p.value }));
3904
+ if (args.done !== undefined) {
3905
+ const completed = completedColumn(cols);
3906
+ if (!completed) throw new Error(`list ${listId} has no Completed column — it was not created with todo mode`);
3907
+ pairs.push({ col: { ...completed, type: "checkbox" }, value: String(args.done) });
3908
+ }
3909
+ if (!pairs.length) throw new Error("nothing to set — pass --set name=value and/or --done / --no-done");
3910
+ const cells = pairs.map((p) => ({ row_id: args.row, column_id: p.col.id, ...cellValue(p.col, p.value) }));
3911
+ const self = await selfIdentity(bot);
3912
+ const code = safetyCode("lists-set", listId, args.row, JSON.stringify(cells), self?.userId ?? "");
3913
+ if (args.code !== code) requireCode(args.code, code, [
3914
+ `--- Updating Slack List row -----------------`,
3915
+ fromLine(self, { asBot: true, pad: 9 }),
3916
+ ` list: ${listId}`,
3917
+ ` row: ${args.row}`,
3918
+ ...pairs.map((p) => ` ${(p.col.name || p.col.key).padEnd(8)} ${p.value}`),
3919
+ `--------------------------------────────────`,
3920
+ ]);
3921
+ try {
3922
+ await slackListsItemsUpdate(bot, listId, cells);
3923
+ } catch (e: unknown) {
3924
+ listWriteFail(e);
3925
+ }
3926
+ console.log(`✓ Updated row ${args.row}`);
3927
+ }
3928
+
3929
+ async function cmdListsShare(args: { list: string; users: string[]; channels: string[]; level: "read" | "write" | "owner"; code?: string }): Promise<void> {
3930
+ const listId = parseListId(args.list);
3931
+ if (!listId) throw new Error(`Not a list ID or list URL: ${args.list}`);
3932
+ if (!args.users.length === !args.channels.length) throw new Error("pass --user or --channel (Slack takes one kind per call, not both)");
3933
+ if (args.level === "owner" && args.channels.length) throw new Error("only a user can be made owner");
3934
+ const bot = listsBotToken();
3935
+ await requireListsWrite(bot);
3936
+ const who = args.users.length ? args.users : args.channels;
3937
+ const self = await selfIdentity(bot);
3938
+ const code = safetyCode("lists-share", listId, args.level, who.join(","), self?.userId ?? "");
3939
+ if (args.code !== code) requireCode(args.code, code, [
3940
+ `--- Sharing Slack List ----------------------`,
3941
+ fromLine(self, { asBot: true, pad: 9 }),
3942
+ ` list: ${listId}`,
3943
+ ` ${args.users.length ? "users: " : "channels:"} ${who.join(", ")}`,
3944
+ ` access: ${args.level}${args.level === "owner" ? " ⚠ transfers ownership" : ""}`,
3945
+ `--------------------------------────────────`,
3946
+ ]);
3947
+ try {
3948
+ await slackListsAccessSet(bot, listId, args.level, args.users.length ? { userIds: args.users } : { channelIds: args.channels });
3949
+ } catch (e: unknown) {
3950
+ listWriteFail(e);
3951
+ }
3952
+ console.log(`✓ Granted ${args.level} on ${listId} to ${who.join(", ")}`);
3953
+ }
3954
+
3261
3955
  // --- download <ref> [dest] — fetch an attachment's bytes to disk (read-only) ---
3262
3956
  // ref: a file ID (F…) or a Slack file permalink (…/files/<UID>/<FID>/<name>).
3263
3957
  function parseFileId(ref: string): string | undefined {
@@ -4294,6 +4988,179 @@ async function main(): Promise<void> {
4294
4988
  await cmdDelete(deleteToken, args);
4295
4989
  },
4296
4990
  )
4991
+ .command(
4992
+ "pinlog",
4993
+ "Pinned status board: the pinned top-level message is the current state (edited in place, silent); each change is one thread reply (the log, notifies)",
4994
+ (y) => {
4995
+ // Every pinlog subcommand acts as ONE identity for both reads and
4996
+ // writes: the bot can only edit what the bot posted, and reading with a
4997
+ // different token than the one that will write is how a preview shows
4998
+ // a message the write then cannot touch.
4999
+ const asBotOpt = { type: "boolean", default: false, describe: "Act via the bot token (xoxb / SLACK_BOT_TOKEN). A board the bot created can only be updated --as-bot: Slack lets a token edit only its own messages." } as const;
5000
+ const pick = async (argv: W & { "as-bot"?: boolean }): Promise<{ token: string; cookie?: string; asBot: boolean }> => {
5001
+ if (argv["as-bot"]) {
5002
+ const bot = requireBotToken();
5003
+ // The bot token is SLACK_BOT_TOKEN whatever -w says. A -w naming a
5004
+ // different workspace would read and write there with the wrong
5005
+ // identity — or in the wrong workspace altogether — so refuse it.
5006
+ if (typeof argv.workspace === "string") {
5007
+ const cookie = ck(argv);
5008
+ const [u, b] = await Promise.all([authScopes(tok(argv), cookie), authScopes(bot)]);
5009
+ if (u.url !== b.url) {
5010
+ console.error(
5011
+ `Error: --as-bot acts with SLACK_BOT_TOKEN, which belongs to ${b.url}, but -w ${argv.workspace} is ${u.url}.\n` +
5012
+ " Drop -w, or set SLACK_BOT_TOKEN to that workspace's bot token.",
5013
+ );
5014
+ process.exit(2);
5015
+ }
5016
+ }
5017
+ return { token: bot, asBot: true };
5018
+ }
5019
+ const cookie = ck(argv);
5020
+ return { token: tok(argv), ...(cookie ? { cookie } : {}), asBot: false };
5021
+ };
5022
+ const fail = (e: unknown): never => {
5023
+ console.error(friendlySlackError(e));
5024
+ process.exit(1);
5025
+ };
5026
+ return y
5027
+ .command(
5028
+ "new <channel> [state] [reason]",
5029
+ "Post a NEW board in a channel and pin it — the state is the top-level message; prints the board's id (C…:ts)",
5030
+ (y2) => y2
5031
+ .positional("channel", { type: "string", demandOption: true, describe: "#chan or channel ID" })
5032
+ .positional("state", { type: "string", describe: "The whole state (\\n for newlines), or use --file" })
5033
+ .positional("reason", { type: "string", describe: "Optional: why the board exists — its first thread reply" })
5034
+ .option("file", { type: "string", describe: "Read the state from a file (- = stdin); then the only positional after <channel> is the reason" })
5035
+ .option("code", { type: "string", describe: "Safety hash to confirm (printed by the preview)" })
5036
+ .option("allow-url-adjacent", { type: "boolean", default: false, describe: "Warn instead of refusing ambiguous bare URL boundaries" })
5037
+ .option("as-bot", asBotOpt)
5038
+ .example('slack pinlog new "#gtm" "販売ブロッカー\\n1. 見積テンプレ — 未"', "preview, then rerun with --code"),
5039
+ async (argv) => {
5040
+ // As with `set`: with --file the state comes from the file, so the
5041
+ // one positional after <channel> is the reason.
5042
+ const fromFile = argv.file !== undefined;
5043
+ if (fromFile && argv.state !== undefined && argv.reason !== undefined) {
5044
+ console.error("Error: with --file, pass only the reason after <channel> (the state comes from the file).");
5045
+ process.exit(2);
5046
+ }
5047
+ const state = fromFile ? pinlogStateArg(undefined, argv.file) : pinlogStateArg(argv.state, undefined);
5048
+ const reason = fromFile ? argv.state : argv.reason;
5049
+ if (state === undefined) {
5050
+ console.error("Error: the state is required (positional or --file).");
5051
+ process.exit(2);
5052
+ }
5053
+ const t = await pick(argv as W & { "as-bot"?: boolean });
5054
+ const args: PinlogCreateArgs = { target: argv.channel!, state, asBot: t.asBot, allowUrlAdjacent: argv["allow-url-adjacent"] };
5055
+ if (reason !== undefined) args.log = unescapeArg(reason);
5056
+ if (t.cookie) args.cookie = t.cookie;
5057
+ if (typeof argv.workspace === "string") args.workspace = argv.workspace;
5058
+ if (argv.code) args.code = argv.code;
5059
+ await cmdPinlogCreate(t.token, args).catch(fail);
5060
+ },
5061
+ )
5062
+ .command(
5063
+ "set <board> [state] [reason]",
5064
+ "Change a board: replace its state (silent edit) AND post the reason in its thread (notifies)",
5065
+ (y2) => y2
5066
+ .positional("board", { type: "string", demandOption: true, describe: "The board: permalink, #chan:ts, or the id `new` printed" })
5067
+ .positional("state", { type: "string", describe: "The WHOLE new state, not a diff (or --file)" })
5068
+ .positional("reason", { type: "string", describe: "One short line: what changed and why (required)" })
5069
+ .option("file", { type: "string", describe: "Read the state from a file (- = stdin); then the only positional after <board> is the reason" })
5070
+ .option("adopt", { type: "boolean", default: false, describe: "Allow a message WITHOUT the pinlog footer: turn a hand-run board into one" })
5071
+ .option("code", { type: "string", describe: "Safety hash to confirm (printed by the preview)" })
5072
+ .option("allow-url-adjacent", { type: "boolean", default: false, describe: "Warn instead of refusing ambiguous bare URL boundaries" })
5073
+ .option("as-bot", asBotOpt)
5074
+ .example('slack pinlog set <board-link> "販売ブロッカー\\n1. 見積テンプレ — 済" "見積テンプレ: 未 → 済"', "")
5075
+ .example('slack pinlog set <board-link> --file board.md "見積テンプレ: 未 → 済"', "state from a file"),
5076
+ async (argv) => {
5077
+ // With --file the state comes from the file, so the one positional
5078
+ // after <board> is the reason.
5079
+ const fromFile = argv.file !== undefined;
5080
+ if (fromFile && argv.state !== undefined && argv.reason !== undefined) {
5081
+ console.error("Error: with --file, pass only the reason after <board> (the state comes from the file).");
5082
+ process.exit(2);
5083
+ }
5084
+ const state = fromFile ? pinlogStateArg(undefined, argv.file) : pinlogStateArg(argv.state, undefined);
5085
+ const reasonRaw = fromFile ? argv.state : argv.reason;
5086
+ if (state === undefined || reasonRaw === undefined) {
5087
+ console.error(
5088
+ "Error: `pinlog set` needs the whole new state AND the reason: slack pinlog set <board> '<state>' '<reason>'\n" +
5089
+ " Only a reason, state unchanged: slack pinlog note <board> '<reason>'",
5090
+ );
5091
+ process.exit(2);
5092
+ }
5093
+ const t = await pick(argv as W & { "as-bot"?: boolean });
5094
+ const args: PinlogUpdateArgs = {
5095
+ target: argv.board!, state, log: unescapeArg(reasonRaw), adopt: argv.adopt, asBot: t.asBot,
5096
+ allowUrlAdjacent: argv["allow-url-adjacent"],
5097
+ };
5098
+ if (typeof argv.workspace === "string") args.workspace = argv.workspace;
5099
+ if (t.cookie) args.cookie = t.cookie;
5100
+ if (argv.code) args.code = argv.code;
5101
+ await cmdPinlogUpdate(t.token, args).catch(fail);
5102
+ },
5103
+ )
5104
+ .command(
5105
+ "note <board> <reason>",
5106
+ "Post only a reason in a board's thread (notifies); the state stays as is",
5107
+ (y2) => y2
5108
+ .positional("board", { type: "string", demandOption: true, describe: "The board: permalink, #chan:ts, or the id `new` printed" })
5109
+ .positional("reason", { type: "string", demandOption: true, describe: "One short line, e.g. still blocked — chased X" })
5110
+ .option("code", { type: "string", describe: "Safety hash to confirm (printed by the preview)" })
5111
+ .option("allow-url-adjacent", { type: "boolean", default: false, describe: "Warn instead of refusing ambiguous bare URL boundaries" })
5112
+ .option("as-bot", asBotOpt),
5113
+ async (argv) => {
5114
+ const t = await pick(argv as W & { "as-bot"?: boolean });
5115
+ const args: PinlogUpdateArgs = {
5116
+ target: argv.board!, log: unescapeArg(argv.reason!), logOnly: true, asBot: t.asBot,
5117
+ allowUrlAdjacent: argv["allow-url-adjacent"],
5118
+ };
5119
+ if (typeof argv.workspace === "string") args.workspace = argv.workspace;
5120
+ if (t.cookie) args.cookie = t.cookie;
5121
+ if (argv.code) args.code = argv.code;
5122
+ await cmdPinlogUpdate(t.token, args).catch(fail);
5123
+ },
5124
+ )
5125
+ .command(
5126
+ ["get <board>", "show <board>"],
5127
+ "Show a board's state and its log (read-only)",
5128
+ (y2) => y2
5129
+ .positional("board", { type: "string", demandOption: true, describe: "The board: permalink, #chan:ts, or C…:ts" })
5130
+ .option("json", { type: "boolean", default: false, describe: "One JSON object: {id, isPinlog, updated, head, log[]}" })
5131
+ .option("as-bot", asBotOpt),
5132
+ async (argv) => {
5133
+ const t = await pick(argv as W & { "as-bot"?: boolean });
5134
+ await cmdPinlogShow(t.token, argv.board!, t.cookie, argv.json).catch(fail);
5135
+ },
5136
+ )
5137
+ .command(
5138
+ ["ls <channel>", "list <channel>"],
5139
+ "List the boards in a channel, found by their footer (read-only)",
5140
+ (y2) => y2
5141
+ .positional("channel", { type: "string", demandOption: true })
5142
+ .option("limit", { alias: "n", type: "number", default: 500, describe: "How many recent channel messages to scan" })
5143
+ .option("as-bot", asBotOpt),
5144
+ async (argv) => {
5145
+ const t = await pick(argv as W & { "as-bot"?: boolean });
5146
+ await cmdPinlogList(t.token, argv.channel!, argv.limit, t.cookie).catch(fail);
5147
+ },
5148
+ )
5149
+ .command(
5150
+ "pin <board>",
5151
+ false as unknown as string, // recovery only: `new` prints it when pinning failed
5152
+ (y2) => y2
5153
+ .positional("board", { type: "string", demandOption: true })
5154
+ .option("as-bot", asBotOpt),
5155
+ async (argv) => {
5156
+ const t = await pick(argv as W & { "as-bot"?: boolean });
5157
+ await cmdPinlogPin(t.token, argv.board!, t.cookie).catch(fail);
5158
+ },
5159
+ )
5160
+ .demandCommand(1, "Pick one: ls | get | new | set | note");
5161
+ },
5162
+ () => {},
5163
+ )
4297
5164
  .command(
4298
5165
  "react <target> <emoji>",
4299
5166
  "Add (or --remove) an emoji reaction — a lightweight ack that doesn't grow the thread",
@@ -4483,22 +5350,111 @@ async function main(): Promise<void> {
4483
5350
  () => {},
4484
5351
  )
4485
5352
  .command(
4486
- "lists <ref>",
4487
- "Read a Slack List's rows (by list URL or F-id) — read-only",
5353
+ "lists",
5354
+ "Slack Lists — read rows (lists <ref>), or create / add / set (gated, as the bot)",
4488
5355
  (y) => y
4489
- .positional("ref", { type: "string", demandOption: true, describe: "List URL (…/lists/<TEAM>/<F-id>) or bare F-id" })
4490
- .option("limit", { alias: "l", type: "number", default: 100, describe: "Max rows to show" })
4491
- .option("format", { type: "string", choices: ["text", "jsonl"], default: "text" })
4492
- .option("json", { type: "boolean", default: false, describe: "Alias for --format=jsonl (raw records)" }),
4493
- async (argv) => {
4494
- const format = argv.json ? "jsonl" : (argv.format as string);
4495
- try {
4496
- await cmdLists(tok(argv as W), ck(argv as W), argv.ref!, { limit: argv.limit as number, format });
4497
- } catch (e: unknown) {
4498
- console.error(friendlySlackError(e));
4499
- process.exit(1);
4500
- }
4501
- },
5356
+ .command(
5357
+ "create <name>",
5358
+ "Create a Slack List (confirm-hash safety gate; bot token, lists:write)",
5359
+ (y2) => y2
5360
+ .positional("name", { type: "string", demandOption: true, describe: "List name" })
5361
+ .option("col", { type: "string", array: true, default: [], describe: "Column name:type (text|select|user|link|date|number|checkbox); select takes name:select:a,b,c. First is the primary text column. Repeatable" })
5362
+ .option("todo", { type: "boolean", default: false, describe: "Todo mode: adds Completed / Assignee / Due date columns" })
5363
+ .option("code", { type: "string", describe: "Safety hash to confirm create" }),
5364
+ async (argv) => {
5365
+ try {
5366
+ const a: { name: string; cols: string[]; todo: boolean; code?: string } = { name: argv.name!, cols: argv.col as string[], todo: argv.todo === true };
5367
+ if (argv.code !== undefined) a.code = argv.code;
5368
+ await cmdListsCreate(a);
5369
+ } catch (e: unknown) {
5370
+ console.error(friendlySlackError(e));
5371
+ process.exit(1);
5372
+ }
5373
+ },
5374
+ )
5375
+ .command(
5376
+ "add <list> <text>",
5377
+ "Add a row to a Slack List (confirm-hash safety gate; bot token)",
5378
+ (y2) => y2
5379
+ .positional("list", { type: "string", demandOption: true, describe: "List URL or F-id" })
5380
+ .positional("text", { type: "string", demandOption: true, describe: "Primary (first text) column value" })
5381
+ .option("set", { type: "string", array: true, default: [], describe: "Other cells: column=value (repeatable)" })
5382
+ .option("code", { type: "string", describe: "Safety hash to confirm add" }),
5383
+ async (argv) => {
5384
+ try {
5385
+ const a: { list: string; text: string; sets: string[]; code?: string } = { list: argv.list!, text: argv.text!, sets: argv.set as string[] };
5386
+ if (argv.code !== undefined) a.code = argv.code;
5387
+ await cmdListsAdd(a);
5388
+ } catch (e: unknown) {
5389
+ console.error(friendlySlackError(e));
5390
+ process.exit(1);
5391
+ }
5392
+ },
5393
+ )
5394
+ .command(
5395
+ "set <list> <row>",
5396
+ "Update cells of a Slack List row; --done checks it off (confirm-hash safety gate; bot token)",
5397
+ (y2) => y2
5398
+ .positional("list", { type: "string", demandOption: true, describe: "List URL or F-id" })
5399
+ .positional("row", { type: "string", demandOption: true, describe: "Row id (Rec…), as printed by lists add / lists <ref>" })
5400
+ .option("set", { type: "string", array: true, default: [], describe: "column=value (repeatable)" })
5401
+ .option("done", { type: "boolean", describe: "Check the row off (--no-done to uncheck); needs a todo-mode list" })
5402
+ .option("code", { type: "string", describe: "Safety hash to confirm update" }),
5403
+ async (argv) => {
5404
+ try {
5405
+ const a: { list: string; row: string; sets: string[]; done?: boolean; code?: string } = { list: argv.list!, row: argv.row!, sets: argv.set as string[] };
5406
+ if (argv.done !== undefined) a.done = argv.done;
5407
+ if (argv.code !== undefined) a.code = argv.code;
5408
+ await cmdListsSet(a);
5409
+ } catch (e: unknown) {
5410
+ console.error(friendlySlackError(e));
5411
+ process.exit(1);
5412
+ }
5413
+ },
5414
+ )
5415
+ .command(
5416
+ "share <list>",
5417
+ "Grant users or channels access to a Slack List (confirm-hash safety gate; bot token)",
5418
+ (y2) => y2
5419
+ .positional("list", { type: "string", demandOption: true, describe: "List URL or F-id" })
5420
+ .option("user", { type: "string", array: true, default: [], describe: "User ID (U…), repeatable" })
5421
+ .option("channel", { type: "string", array: true, default: [], describe: "Channel ID (C…), repeatable" })
5422
+ .option("level", { type: "string", choices: ["read", "write", "owner"] as const, default: "write" })
5423
+ .option("code", { type: "string", describe: "Safety hash to confirm share" }),
5424
+ async (argv) => {
5425
+ try {
5426
+ const a: { list: string; users: string[]; channels: string[]; level: "read" | "write" | "owner"; code?: string } = {
5427
+ list: argv.list!, users: argv.user as string[], channels: argv.channel as string[], level: argv.level as "read" | "write" | "owner",
5428
+ };
5429
+ if (argv.code !== undefined) a.code = argv.code;
5430
+ await cmdListsShare(a);
5431
+ } catch (e: unknown) {
5432
+ console.error(friendlySlackError(e));
5433
+ process.exit(1);
5434
+ }
5435
+ },
5436
+ )
5437
+ .command(
5438
+ "$0 <ref>",
5439
+ "Read a Slack List's rows (by list URL or F-id) — read-only",
5440
+ (y2) => y2
5441
+ .positional("ref", { type: "string", demandOption: true, describe: "List URL (…/lists/<TEAM>/<F-id>) or bare F-id" })
5442
+ .option("limit", { alias: "l", type: "number", default: 100, describe: "Max rows to show" })
5443
+ .option("format", { type: "string", choices: ["text", "jsonl"], default: "text" })
5444
+ .option("json", { type: "boolean", default: false, describe: "Alias for --format=jsonl (raw records)" })
5445
+ .option("as-bot", { type: "boolean", default: false, describe: "Read with the bot token (SLACK_BOT_TOKEN, lists:read) via the public API instead of the user session" }),
5446
+ async (argv) => {
5447
+ const format = argv.json ? "jsonl" : (argv.format as string);
5448
+ try {
5449
+ // --as-bot never touches the user token: a bot-only lane may have none.
5450
+ const asBot = argv.asBot === true;
5451
+ await cmdLists(asBot ? "" : tok(argv as W), asBot ? undefined : ck(argv as W), argv.ref!, { limit: argv.limit as number, format, asBot });
5452
+ } catch (e: unknown) {
5453
+ console.error(friendlySlackError(e));
5454
+ process.exit(1);
5455
+ }
5456
+ },
5457
+ ),
4502
5458
  )
4503
5459
  .command(
4504
5460
  "download <ref> [dest]",