@capybara-hq/plugin-slack 0.1.0-rc.1 → 0.1.0-rc.10

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/dist/index.mjs CHANGED
@@ -7345,25 +7345,25 @@ var require_infra = __commonJS({
7345
7345
  return input;
7346
7346
  }
7347
7347
  var nonASCIIRegex = /[^\x00-\x7F]/;
7348
- function asciiLowercase(str5) {
7349
- return nonASCIIRegex.test(str5) ? str5.replace(/[A-Z]+/g, (upper) => upper.toLowerCase()) : str5.toLowerCase();
7348
+ function asciiLowercase(str6) {
7349
+ return nonASCIIRegex.test(str6) ? str6.replace(/[A-Z]+/g, (upper) => upper.toLowerCase()) : str6.toLowerCase();
7350
7350
  }
7351
7351
  function parseJSONFromBytes(bytes) {
7352
7352
  return JSON.parse(utf8DecodeBytes(bytes));
7353
7353
  }
7354
- function removeASCIIWhitespace(str5, leading = true, trailing = true) {
7355
- return removeChars(str5, leading, trailing, isASCIIWhitespace);
7354
+ function removeASCIIWhitespace(str6, leading = true, trailing = true) {
7355
+ return removeChars(str6, leading, trailing, isASCIIWhitespace);
7356
7356
  }
7357
- function removeChars(str5, leading, trailing, predicate) {
7358
- let lead = 0;
7359
- let trail = str5.length - 1;
7357
+ function removeChars(str6, leading, trailing, predicate) {
7358
+ let lead2 = 0;
7359
+ let trail = str6.length - 1;
7360
7360
  if (leading) {
7361
- while (lead < str5.length && predicate(str5.charCodeAt(lead))) lead++;
7361
+ while (lead2 < str6.length && predicate(str6.charCodeAt(lead2))) lead2++;
7362
7362
  }
7363
7363
  if (trailing) {
7364
- while (trail >= lead && predicate(str5.charCodeAt(trail))) trail--;
7364
+ while (trail >= lead2 && predicate(str6.charCodeAt(trail))) trail--;
7365
7365
  }
7366
- return lead === 0 && trail === str5.length - 1 ? str5 : str5.slice(lead, trail + 1);
7366
+ return lead2 === 0 && trail === str6.length - 1 ? str6 : str6.slice(lead2, trail + 1);
7367
7367
  }
7368
7368
  function serializeJavascriptValueToJSONString(value) {
7369
7369
  const result = JSON.stringify(value);
@@ -7615,8 +7615,8 @@ var require_data_url = __commonJS({
7615
7615
  function isHTTPWhiteSpace(char) {
7616
7616
  return char === 13 || char === 10 || char === 9 || char === 32;
7617
7617
  }
7618
- function removeHTTPWhitespace(str5, leading = true, trailing = true) {
7619
- return removeChars(str5, leading, trailing, isHTTPWhiteSpace);
7618
+ function removeHTTPWhitespace(str6, leading = true, trailing = true) {
7619
+ return removeChars(str6, leading, trailing, isHTTPWhiteSpace);
7620
7620
  }
7621
7621
  function minimizeSupportedMimeType(mimeType) {
7622
7622
  switch (mimeType.essence) {
@@ -9664,11 +9664,11 @@ var require_request2 = __commonJS({
9664
9664
  } else if (typeof val[i] === "object") {
9665
9665
  throw new InvalidArgumentError(`invalid ${key} header`);
9666
9666
  } else {
9667
- const str5 = `${val[i]}`;
9668
- if (!isValidHeaderValue(str5)) {
9667
+ const str6 = `${val[i]}`;
9668
+ if (!isValidHeaderValue(str6)) {
9669
9669
  throw new InvalidArgumentError(`invalid ${key} header`);
9670
9670
  }
9671
- arr.push(str5);
9671
+ arr.push(str6);
9672
9672
  }
9673
9673
  }
9674
9674
  val = arr;
@@ -13737,15 +13737,15 @@ var require_formdata_parser = __commonJS({
13737
13737
  return input.subarray(position.position, position.position = start);
13738
13738
  }
13739
13739
  function removeChars(buf, leading, trailing, predicate) {
13740
- let lead = 0;
13740
+ let lead2 = 0;
13741
13741
  let trail = buf.length - 1;
13742
13742
  if (leading) {
13743
- while (lead < buf.length && predicate(buf[lead])) lead++;
13743
+ while (lead2 < buf.length && predicate(buf[lead2])) lead2++;
13744
13744
  }
13745
13745
  if (trailing) {
13746
13746
  while (trail > 0 && predicate(buf[trail])) trail--;
13747
13747
  }
13748
- return lead === 0 && trail === buf.length - 1 ? buf : buf.subarray(lead, trail + 1);
13748
+ return lead2 === 0 && trail === buf.length - 1 ? buf : buf.subarray(lead2, trail + 1);
13749
13749
  }
13750
13750
  function bufferStartsWith(buffer, start, position) {
13751
13751
  if (buffer.length < start.length) {
@@ -13877,7 +13877,7 @@ var require_body = __commonJS({
13877
13877
  const boundary = getFormDataBoundary(object);
13878
13878
  const prefix = `--${boundary}\r
13879
13879
  Content-Disposition: form-data`;
13880
- const formdataEscape = (str5) => str5.replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22");
13880
+ const formdataEscape = (str6) => str6.replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22");
13881
13881
  const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, "\r\n");
13882
13882
  const blobParts = [];
13883
13883
  const rn = new Uint8Array([13, 10]);
@@ -25872,9 +25872,9 @@ var require_cache_handler = __commonJS({
25872
25872
  function appendConnectionHeaderTokens(headersToRemove, connectionHeader) {
25873
25873
  const values = Array.isArray(connectionHeader) ? connectionHeader : [connectionHeader];
25874
25874
  for (let i = 0; i < values.length; i++) {
25875
- const tokens = values[i].split(",");
25876
- for (let j = 0; j < tokens.length; j++) {
25877
- headersToRemove.push(trimOWS(tokens[j]).toLowerCase());
25875
+ const tokens2 = values[i].split(",");
25876
+ for (let j = 0; j < tokens2.length; j++) {
25877
+ headersToRemove.push(trimOWS(tokens2[j]).toLowerCase());
25878
25878
  }
25879
25879
  }
25880
25880
  }
@@ -28418,9 +28418,9 @@ var require_sqlite_cache_store = __commonJS({
28418
28418
  let compressed = null;
28419
28419
  let storedBody = body;
28420
28420
  if (body && hasZstd && (size > this.#compressThreshold || isCompressibleContentType(getContentType(value.headers)))) {
28421
- const candidate = zstdCompressSync(body);
28422
- if (candidate.byteLength < body.byteLength) {
28423
- storedBody = candidate;
28421
+ const candidate2 = zstdCompressSync(body);
28422
+ if (candidate2.byteLength < body.byteLength) {
28423
+ storedBody = candidate2;
28424
28424
  compressed = "zstd";
28425
28425
  }
28426
28426
  }
@@ -32641,7 +32641,7 @@ var require_cookies = __commonJS({
32641
32641
  if (!cookies) {
32642
32642
  return [];
32643
32643
  }
32644
- return cookies.map((pair) => parseSetCookie(pair));
32644
+ return cookies.map((pair2) => parseSetCookie(pair2));
32645
32645
  }
32646
32646
  function parseCookie(cookie) {
32647
32647
  cookie = webidl.converters.DOMString(cookie);
@@ -32651,9 +32651,9 @@ var require_cookies = __commonJS({
32651
32651
  webidl.argumentLengthCheck(arguments, 2, "setCookie");
32652
32652
  brandCheckHeaders(headers);
32653
32653
  cookie = webidl.converters.Cookie(cookie);
32654
- const str5 = stringify(cookie);
32655
- if (str5) {
32656
- headers.append("set-cookie", str5, true);
32654
+ const str6 = stringify(cookie);
32655
+ if (str6) {
32656
+ headers.append("set-cookie", str6, true);
32657
32657
  }
32658
32658
  }
32659
32659
  webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([
@@ -33157,8 +33157,8 @@ var require_util5 = __commonJS({
33157
33157
  const position = { position: 0 };
33158
33158
  const extensionList = /* @__PURE__ */ new Map();
33159
33159
  while (position.position < extensions.length) {
33160
- const pair = collectASequenceOfCodePointsFast(";", extensions, position);
33161
- const [name, value = ""] = pair.split("=", 2);
33160
+ const pair2 = collectASequenceOfCodePointsFast(";", extensions, position);
33161
+ const [name, value = ""] = pair2.split("=", 2);
33162
33162
  extensionList.set(
33163
33163
  removeHTTPWhitespace(name, true, false),
33164
33164
  removeHTTPWhitespace(value, false, true)
@@ -36822,7 +36822,8 @@ var import_web_api = __toESM(require_dist4(), 1);
36822
36822
  import { createHash } from "node:crypto";
36823
36823
  import {
36824
36824
  ChannelSendError as ChannelSendError3,
36825
- secret as secret2
36825
+ secret as secret2,
36826
+ ui as ui2
36826
36827
  } from "@capybara-hq/plugin-sdk";
36827
36828
  import { z as z2 } from "zod";
36828
36829
 
@@ -36947,9 +36948,106 @@ function parseBlockActions(payload) {
36947
36948
  import {
36948
36949
  ChannelSendError,
36949
36950
  questionRenderableInline,
36951
+ questionStateLabel,
36952
+ questionTextReplyHint,
36950
36953
  renderCardAsText
36951
36954
  } from "@capybara-hq/plugin-sdk";
36952
36955
 
36956
+ // src/tables.ts
36957
+ var FENCE = /^\s*(```|~~~)/;
36958
+ var DELIM_CELL = /^:?-+:?$/;
36959
+ function splitRow(line) {
36960
+ let s = line.trim();
36961
+ if (!/(^|[^\\])\|/.test(s)) return void 0;
36962
+ if (s.startsWith("|")) s = s.slice(1);
36963
+ if (s.endsWith("|") && !s.endsWith("\\|")) s = s.slice(0, -1);
36964
+ const cells = [];
36965
+ let cur = "";
36966
+ for (let i = 0; i < s.length; i++) {
36967
+ const c = s[i];
36968
+ if (c === "\\" && s[i + 1] === "|") {
36969
+ cur += "|";
36970
+ i++;
36971
+ } else if (c === "|") {
36972
+ cells.push(cur.trim());
36973
+ cur = "";
36974
+ } else cur += c;
36975
+ }
36976
+ cells.push(cur.trim());
36977
+ return cells;
36978
+ }
36979
+ var candidate = (line) => !/^\s{4,}/.test(line) && !/^\s*>/.test(line);
36980
+ function delimiterRow(line, width) {
36981
+ if (line === void 0 || !candidate(line)) return false;
36982
+ const cells = splitRow(line);
36983
+ return cells !== void 0 && cells.length === width && cells.every((c) => DELIM_CELL.test(c));
36984
+ }
36985
+ var fit = (cells, width) => Array.from({ length: width }, (_, i) => cells[i] ?? "");
36986
+ function segmentTables(md2) {
36987
+ const lines = md2.replace(/\r\n?/g, "\n").split("\n");
36988
+ const out = [];
36989
+ let text = [];
36990
+ const flushText = () => {
36991
+ if (text.length > 0) out.push({ kind: "text", lines: text });
36992
+ text = [];
36993
+ };
36994
+ let inFence = false;
36995
+ for (let i = 0; i < lines.length; i++) {
36996
+ const line = lines[i];
36997
+ if (FENCE.test(line)) {
36998
+ inFence = !inFence;
36999
+ text.push(line);
37000
+ continue;
37001
+ }
37002
+ const header = !inFence && candidate(line) ? splitRow(line) : void 0;
37003
+ if (!header || !delimiterRow(lines[i + 1], header.length)) {
37004
+ text.push(line);
37005
+ continue;
37006
+ }
37007
+ const rows = [];
37008
+ let j = i + 2;
37009
+ for (; j < lines.length; j++) {
37010
+ const l = lines[j];
37011
+ if (l.trim() === "" || FENCE.test(l) || !candidate(l)) break;
37012
+ const cells = splitRow(l);
37013
+ if (!cells) break;
37014
+ rows.push(fit(cells, header.length));
37015
+ }
37016
+ flushText();
37017
+ out.push({ kind: "table", table: { header, rows } });
37018
+ i = j - 1;
37019
+ }
37020
+ flushText();
37021
+ return out;
37022
+ }
37023
+ var BR = /<br\s*\/?>/gi;
37024
+ var CJK_END = /[⺀-鿿가-힯豈-﫿＀-￯]$/u;
37025
+ var INDENT = " ";
37026
+ var pair = (h, v) => h === "" ? v : `${h}${CJK_END.test(h) ? ":" : ": "}${v}`;
37027
+ var lead = (cell2) => /`|\*\*|__/.test(cell2) ? cell2 : `**${cell2}**`;
37028
+ function tableToListMarkdown(t) {
37029
+ const clean = (s) => s.replace(BR, " / ").trim();
37030
+ const header = t.header.map(clean);
37031
+ if (t.rows.length === 0) return [header.filter((h) => h !== "").join(" · ")];
37032
+ const out = [];
37033
+ for (const raw of t.rows) {
37034
+ const [first = "", ...rest] = raw.map(clean);
37035
+ const head = first === "" ? "" : lead(first);
37036
+ const items = rest.flatMap((v, i) => v === "" ? [] : [pair(header[i + 1] ?? "", v)]);
37037
+ if (head === "" && items.length === 0) continue;
37038
+ if (header.length === 2) {
37039
+ out.push(`- ${[head, rest[0] ?? ""].filter((s) => s !== "").join(" — ")}`);
37040
+ continue;
37041
+ }
37042
+ out.push(`- ${head === "" ? items.shift() ?? "" : head}`);
37043
+ for (const it of items) out.push(`${INDENT}${it}`);
37044
+ }
37045
+ return out;
37046
+ }
37047
+ function tablesToLists(md2) {
37048
+ return segmentTables(md2).flatMap((s) => s.kind === "text" ? s.lines : tableToListMarkdown(s.table)).join("\n");
37049
+ }
37050
+
36953
37051
  // src/mrkdwn.ts
36954
37052
  var esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
36955
37053
  var safeUrl = (url) => url.replace(/&/g, "&amp;").replace(/</g, "%3C").replace(/>/g, "%3E").replace(/\|/g, "%7C");
@@ -36995,7 +37093,7 @@ function convertLine(line) {
36995
37093
  function markdownToMrkdwn(md2) {
36996
37094
  const out = [];
36997
37095
  let inFence = false;
36998
- for (const line of md2.replace(/\r\n?/g, "\n").split("\n")) {
37096
+ for (const line of tablesToLists(md2).split("\n")) {
36999
37097
  if (/^\s*(```|~~~)/.test(line)) {
37000
37098
  out.push("```");
37001
37099
  inFence = !inFence;
@@ -37065,6 +37163,103 @@ function splitMrkdwn(text, limit) {
37065
37163
  return out;
37066
37164
  }
37067
37165
 
37166
+ // src/table-block.ts
37167
+ var TABLE_MAX_ROWS = 100;
37168
+ var TABLE_MAX_COLUMNS = 20;
37169
+ var TABLE_MAX_CHARS = 1e4;
37170
+ var EMPTY = " ";
37171
+ function withStyle(e, style) {
37172
+ return Object.keys(style).length === 0 ? e : { ...e, style: { ...e.style, ...style } };
37173
+ }
37174
+ var EMPHASIS = /\*\*\*(\S(?:.*?\S)?)\*\*\*|\*\*(\S(?:.*?\S)?)\*\*|(?<!\w)__(\S(?:.*?\S)?)__(?!\w)|(?<![\w*])\*(?=[^\s*])([^*]*?[^\s*])\*(?![\w*])|(?<![\w_])_(?=[^\s_])([^_]*?[^\s_])_(?![\w_])|~~(\S(?:.*?\S)?)~~/;
37175
+ function emphasis(s, style) {
37176
+ const out = [];
37177
+ let rest = s;
37178
+ while (rest !== "") {
37179
+ const m = EMPHASIS.exec(rest);
37180
+ if (!m) break;
37181
+ if (m.index > 0)
37182
+ out.push(withStyle({ type: "text", text: rest.slice(0, m.index) }, style));
37183
+ const [, bi, b, b2, i, i2, st] = m;
37184
+ if (bi !== void 0) out.push(...emphasis(bi, { ...style, bold: true, italic: true }));
37185
+ else if (b !== void 0 || b2 !== void 0)
37186
+ out.push(...emphasis(b ?? b2, { ...style, bold: true }));
37187
+ else if (i !== void 0 || i2 !== void 0)
37188
+ out.push(...emphasis(i ?? i2, { ...style, italic: true }));
37189
+ else out.push(...emphasis(st, { ...style, strike: true }));
37190
+ rest = rest.slice(m.index + m[0].length);
37191
+ }
37192
+ if (rest !== "") out.push(withStyle({ type: "text", text: rest }, style));
37193
+ return out;
37194
+ }
37195
+ var LINK = /\[([^\]\n]+)\]\(((?:https?:\/\/|mailto:)[^\s)]+)\)|<((?:https?:\/\/|mailto:)[^>\s]+)>/;
37196
+ function links(s) {
37197
+ const out = [];
37198
+ let rest = s;
37199
+ for (let m = LINK.exec(rest); m; m = LINK.exec(rest)) {
37200
+ out.push(...emphasis(rest.slice(0, m.index), {}));
37201
+ const url = m[2] ?? m[3];
37202
+ if (m[1] === void 0) out.push({ type: "link", url, text: url });
37203
+ else
37204
+ for (const e of emphasis(m[1], {})) {
37205
+ const { code: _code, ...style } = e.style ?? {};
37206
+ out.push(withStyle({ type: "link", url, text: e.text }, style));
37207
+ }
37208
+ rest = rest.slice(m.index + m[0].length);
37209
+ }
37210
+ out.push(...emphasis(rest, {}));
37211
+ return out;
37212
+ }
37213
+ function cellElements(md2) {
37214
+ const out = [];
37215
+ let last = 0;
37216
+ for (const m of md2.matchAll(/`([^`\n]+)`/g)) {
37217
+ out.push(...links(md2.slice(last, m.index)));
37218
+ out.push({ type: "text", text: m[1], style: { code: true } });
37219
+ last = m.index + m[0].length;
37220
+ }
37221
+ out.push(...links(md2.slice(last)));
37222
+ return out.filter((e) => e.text !== "");
37223
+ }
37224
+ var cellText = (md2) => cellElements(md2.replace(/<br\s*\/?>/gi, "\n")).map((e) => e.text).join("");
37225
+ function cell(md2, header) {
37226
+ const els = cellElements(md2.replace(/<br\s*\/?>/gi, "\n")).map(
37227
+ (e) => header ? withStyle(e, { bold: true }) : e
37228
+ );
37229
+ if (els.length === 0) return { type: "raw_text", text: EMPTY };
37230
+ if (els.every((e) => e.type === "text" && e.style === void 0)) {
37231
+ return { type: "raw_text", text: els.map((e) => e.text).join("") };
37232
+ }
37233
+ return { type: "rich_text", elements: [{ type: "rich_text_section", elements: els }] };
37234
+ }
37235
+ var rowChars = (row) => row.reduce((n, c) => n + Math.max(cellText(c).length, 1), 0);
37236
+ function tableBlocks(t) {
37237
+ const width = t.header.length;
37238
+ if (width > TABLE_MAX_COLUMNS || t.rows.length === 0) return void 0;
37239
+ const headChars = rowChars(t.header);
37240
+ const groups = [];
37241
+ let cur = [];
37242
+ let chars = headChars;
37243
+ for (const row of t.rows) {
37244
+ const n = rowChars(row);
37245
+ if (headChars + n > TABLE_MAX_CHARS) return void 0;
37246
+ if (cur.length > 0 && (cur.length + 1 >= TABLE_MAX_ROWS || chars + n > TABLE_MAX_CHARS)) {
37247
+ groups.push(cur);
37248
+ cur = [];
37249
+ chars = headChars;
37250
+ }
37251
+ cur.push(row);
37252
+ chars += n;
37253
+ }
37254
+ groups.push(cur);
37255
+ const column_settings = Array.from({ length: width }, () => ({ is_wrapped: true }));
37256
+ return groups.map((rows) => ({
37257
+ type: "table",
37258
+ column_settings,
37259
+ rows: [t.header.map((c) => cell(c, true)), ...rows.map((r) => r.map((c) => cell(c, false)))]
37260
+ }));
37261
+ }
37262
+
37068
37263
  // src/blocks.ts
37069
37264
  var TEXT_LIMIT = 4e3;
37070
37265
  var SECTION_TEXT_LIMIT = 3e3;
@@ -37077,7 +37272,7 @@ var T = {
37077
37272
  question: "Question",
37078
37273
  tool: "Tool",
37079
37274
  agent: "Agent",
37080
- input: "Input",
37275
+ summary: "Summary",
37081
37276
  status: "Status",
37082
37277
  reason: "Reason",
37083
37278
  expires: "Expires",
@@ -37100,11 +37295,13 @@ var T = {
37100
37295
  approved: "Approved",
37101
37296
  denied: "Denied",
37102
37297
  expired: "Expired",
37103
- cancelled: "Cancelled"
37298
+ cancelled: "Cancelled",
37299
+ skipped: "Skipped (replied instead)"
37104
37300
  },
37105
37301
  questionStates: {
37106
37302
  pending: "Pending",
37107
37303
  answered: "Answered",
37304
+ skipped: "Skipped (replied instead)",
37108
37305
  expired: "Expired",
37109
37306
  cancelled: "Cancelled"
37110
37307
  }
@@ -37115,7 +37312,7 @@ var T = {
37115
37312
  question: "提问",
37116
37313
  tool: "工具",
37117
37314
  agent: "Agent",
37118
- input: "输入",
37315
+ summary: "摘要",
37119
37316
  status: "状态",
37120
37317
  reason: "原因",
37121
37318
  expires: "过期时间",
@@ -37134,11 +37331,13 @@ var T = {
37134
37331
  approved: "已批准",
37135
37332
  denied: "已拒绝",
37136
37333
  expired: "已过期",
37137
- cancelled: "已取消"
37334
+ cancelled: "已取消",
37335
+ skipped: "已跳过(已直接回复)"
37138
37336
  },
37139
37337
  questionStates: {
37140
37338
  pending: "待回答",
37141
37339
  answered: "已回答",
37340
+ skipped: "已跳过(已直接回复)",
37142
37341
  expired: "已过期",
37143
37342
  cancelled: "已取消"
37144
37343
  }
@@ -37229,12 +37428,14 @@ ${esc2(c.agentName)}`, FIELD_LIMIT)
37229
37428
  }
37230
37429
  ];
37231
37430
  if (c.inputPreview !== "") {
37232
- const head = `*${t.input}*
37233
- \`\`\`
37234
- `;
37235
- const tail = "\n```";
37236
- const body = trunc(esc2(c.inputPreview), SECTION_TEXT_LIMIT - head.length - tail.length);
37237
- blocks.push(section(`${head}${body}${tail}`));
37431
+ blocks.push({
37432
+ type: "section",
37433
+ text: {
37434
+ type: "plain_text",
37435
+ text: trunc(`${t.summary}${t.sep}${c.inputPreview}`, SECTION_TEXT_LIMIT),
37436
+ emoji: false
37437
+ }
37438
+ });
37238
37439
  }
37239
37440
  if (c.state !== "pending") {
37240
37441
  const state = t.approvalStates[c.state];
@@ -37275,7 +37476,8 @@ function questionInputs(c, locale) {
37275
37476
  const t = T[locale];
37276
37477
  const web = link("cap_link_web", t.answerOnWeb, c.webUrl);
37277
37478
  const f = c.form.fields[0];
37278
- if (!questionRenderableInline(c.form) || !f || !("enum" in f.schema)) return [actions([web])];
37479
+ const inline2 = questionRenderableInline(c.form, { textReply: c.textReply !== void 0 });
37480
+ if (!inline2 || !f || !("enum" in f.schema)) return [actions([web])];
37279
37481
  const options = f.schema.enum;
37280
37482
  try {
37281
37483
  if (!f.multiSelect) {
@@ -37309,6 +37511,10 @@ function questionInputs(c, locale) {
37309
37511
  return [actions([web])];
37310
37512
  }
37311
37513
  }
37514
+ function questionState(state, locale) {
37515
+ const states = T[locale].questionStates;
37516
+ return states[state] ?? esc2(questionStateLabel(state, locale));
37517
+ }
37312
37518
  function questionBlocks(c, locale) {
37313
37519
  const t = T[locale];
37314
37520
  const title = textOf(c.form.title, locale);
@@ -37320,8 +37526,13 @@ function questionBlocks(c, locale) {
37320
37526
  if (f.description !== void 0) lines.push(`_${esc2(textOf(f.description, locale))}_`);
37321
37527
  }
37322
37528
  const blocks = [section(lines.join("\n"))];
37323
- if (c.state === "pending") return [...blocks, ...questionInputs(c, locale)];
37324
- const status = `${t.status}${t.sep}${t.questionStates[c.state]}`;
37529
+ if (c.state === "pending") {
37530
+ blocks.push(...questionInputs(c, locale));
37531
+ if (c.textReply !== void 0)
37532
+ blocks.push(context(esc2(questionTextReplyHint(c.textReply, locale))));
37533
+ return blocks;
37534
+ }
37535
+ const status = `${t.status}${t.sep}${questionState(c.state, locale)}`;
37325
37536
  const answer = c.answerSummary ? `
37326
37537
  ${t.answer}${t.sep}${esc2(c.answerSummary)}` : "";
37327
37538
  blocks.push(context(`${status}${answer}`));
@@ -37360,16 +37571,50 @@ function cardHeadline(card, locale) {
37360
37571
  }
37361
37572
  }
37362
37573
  function renderSend(message2, locale) {
37363
- const mrkdwn = markdownToMrkdwn(message2.text);
37364
- const cards = message2.cards ?? [];
37574
+ const posts = [];
37575
+ let pending = [];
37576
+ for (const seg of segmentTables(message2.text)) {
37577
+ const tables = seg.kind === "table" ? tableBlocks(seg.table) : void 0;
37578
+ if (seg.kind === "text" || !tables) {
37579
+ pending.push(...seg.kind === "text" ? seg.lines : tableToListMarkdown(seg.table));
37580
+ continue;
37581
+ }
37582
+ const list = markdownToMrkdwn(tableToListMarkdown(seg.table).join("\n"));
37583
+ tables.forEach((table2, i) => {
37584
+ const lead2 = i === 0 ? markdownToMrkdwn(trimBlank(pending).join("\n")) : "";
37585
+ const chunks = lead2.trim() === "" ? [] : splitMrkdwn(lead2, SECTION_TEXT_LIMIT);
37586
+ const last = chunks.pop();
37587
+ posts.push(...chunks.map((text) => ({ text })));
37588
+ const full = [last, list].filter((t) => t !== void 0 && t.trim() !== "").join("\n\n");
37589
+ posts.push({
37590
+ text: trunc(full, TEXT_LIMIT),
37591
+ blocks: [...last !== void 0 ? [section(last)] : [], table2],
37592
+ fallback: splitMrkdwn(full, TEXT_LIMIT).map((text) => ({ text }))
37593
+ });
37594
+ });
37595
+ pending = [];
37596
+ }
37597
+ const rest = (posts.length > 0 ? trimBlank(pending) : pending).join("\n");
37598
+ const trailing = posts.length > 0 ? rest : message2.text;
37599
+ return [...posts, ...renderText(rest, trailing, message2.cards ?? [], locale, posts.length > 0)];
37600
+ }
37601
+ function trimBlank(lines) {
37602
+ let a = 0;
37603
+ let b = lines.length;
37604
+ while (a < b && (lines[a] ?? "").trim() === "") a++;
37605
+ while (b > a && (lines[b - 1] ?? "").trim() === "") b--;
37606
+ return lines.slice(a, b);
37607
+ }
37608
+ function renderText(md2, headlineText, cards, locale, afterTable) {
37609
+ const mrkdwn = markdownToMrkdwn(md2);
37365
37610
  if (cards.length === 0) {
37366
- if (mrkdwn.trim() === "") return [{ text: "…" }];
37611
+ if (mrkdwn.trim() === "") return afterTable ? [] : [{ text: "…" }];
37367
37612
  return splitMrkdwn(mrkdwn, TEXT_LIMIT).map((text) => ({ text }));
37368
37613
  }
37369
37614
  const chunks = mrkdwn.trim() === "" ? [] : splitMrkdwn(mrkdwn, SECTION_TEXT_LIMIT);
37370
37615
  const last = chunks.pop();
37371
37616
  const posts = chunks.map((text) => ({ text }));
37372
- const dup = cards.some((c) => cardHeadline(c, locale)?.trim() === message2.text.trim());
37617
+ const dup = cards.some((c) => cardHeadline(c, locale)?.trim() === headlineText.trim());
37373
37618
  const blocks = last !== void 0 && !dup ? [section(last)] : [];
37374
37619
  cards.forEach((c, i) => {
37375
37620
  if (i > 0) blocks.push({ type: "divider" });
@@ -37391,6 +37636,49 @@ function renderUpdate(message2, locale) {
37391
37636
  return only;
37392
37637
  }
37393
37638
 
37639
+ // src/commands.ts
37640
+ var str2 = (v) => typeof v === "string" && v !== "" ? v : void 0;
37641
+ var GENERIC_COMMAND = "/capybara";
37642
+ function parseSlashCommand(body) {
37643
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return null;
37644
+ const b = body;
37645
+ const command = str2(b.command);
37646
+ const userId = str2(b.user_id);
37647
+ const channelId = str2(b.channel_id);
37648
+ const teamId = str2(b.team_id);
37649
+ const triggerId = str2(b.trigger_id);
37650
+ if (!command?.startsWith("/") || !userId || !channelId || !teamId || !triggerId) return null;
37651
+ return {
37652
+ command,
37653
+ text: typeof b.text === "string" ? b.text : "",
37654
+ userId,
37655
+ userName: str2(b.user_name),
37656
+ channelId,
37657
+ teamId,
37658
+ triggerId
37659
+ };
37660
+ }
37661
+ var unescapeSlack = (s) => s.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
37662
+ function slashCommandText(command, text) {
37663
+ const args = unescapeSlack(text).trim();
37664
+ const name = command.toLowerCase();
37665
+ if (name === "/new" || name === "/env") return args === "" ? name : `${name} ${args}`;
37666
+ const rest = args.replace(/^\/+/, "");
37667
+ return rest === "" ? null : `/${rest}`;
37668
+ }
37669
+ var escapeSlack = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
37670
+ var typedCommand = (c) => c.text.trim() === "" ? c.command : `${c.command} ${unescapeSlack(c.text).trim()}`;
37671
+ var ephemeral = (text) => ({
37672
+ response_type: "ephemeral",
37673
+ text
37674
+ });
37675
+ var SLASH_REPLIES = {
37676
+ usage: `Usage: ${GENERIC_COMMAND} <skill> [args] · 用法:${GENERIC_COMMAND} <技能> [参数]`,
37677
+ wrongDm: "Run Capybara commands in your direct message with the app, or in a channel it is in. · 请在与 Capybara 应用的私聊里,或在它所在的频道里使用命令。",
37678
+ notInChannel: "Invite the Capybara app to this channel first (/invite), then run the command again. · 请先把 Capybara 应用邀请进这个频道,再运行命令。",
37679
+ failed: "Slack could not take this command right now; try again in a moment. · Slack 暂时无法处理这条命令,请稍后再试。"
37680
+ };
37681
+
37394
37682
  // src/config.ts
37395
37683
  import { secret, ui } from "@capybara-hq/plugin-sdk";
37396
37684
  import { z } from "zod";
@@ -37409,10 +37697,22 @@ var SlackDeployment = z.object({
37409
37697
  var SlackDirectoryConfig = z.object({
37410
37698
  teamId: ui(
37411
37699
  z.string().regex(/^T[A-Z0-9]+$/, "must be a Slack workspace team id such as T0123ABCD").optional(),
37412
- { label: { zh: "工作区 ID", en: "Workspace ID" } }
37700
+ {
37701
+ label: { zh: "工作区 ID", en: "Workspace ID" },
37702
+ help: {
37703
+ zh: "选填:和机器人令牌一起用于把 Slack 成员同步到组织;只用机器人收发消息时不用填。",
37704
+ en: "Optional: used with the bot token to sync Slack members into the org. Leave empty if you only use the bot for chat."
37705
+ },
37706
+ placeholder: "T0123ABCD"
37707
+ }
37413
37708
  ),
37414
37709
  botToken: ui(secret(z.string().regex(/^xoxb-/, "must be a bot token starting with xoxb-")), {
37415
- label: { zh: "机器人令牌", en: "Bot token" }
37710
+ label: { zh: "机器人令牌", en: "Bot token" },
37711
+ help: {
37712
+ zh: "选填,仅用于成员同步;聊天用的令牌在新建渠道连接时填。",
37713
+ en: "Optional, only for member sync. The tokens for chat go into the channel connection you create under Channels."
37714
+ },
37715
+ placeholder: "xoxb-…"
37416
37716
  }).optional()
37417
37717
  });
37418
37718
  var SLACK_ISSUER = "https://slack.com";
@@ -37493,11 +37793,16 @@ function toChannelSendError(e) {
37493
37793
  return new ChannelSendError2("Slack API call failed", { retryable: true, cause: e });
37494
37794
  }
37495
37795
  }
37796
+ function blocksRejected(e) {
37797
+ const cause = e instanceof ChannelSendError2 ? e.cause : e;
37798
+ const code = platformErrorCode(cause);
37799
+ return code === "invalid_blocks" || code === "invalid_blocks_format" || code === "invalid_attachments";
37800
+ }
37496
37801
 
37497
37802
  // src/inbound.ts
37498
37803
  var obj2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : void 0;
37499
- var str2 = (v) => typeof v === "string" && v !== "" ? v : void 0;
37500
- var unescapeSlack = (s) => s.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
37804
+ var str3 = (v) => typeof v === "string" && v !== "" ? v : void 0;
37805
+ var unescapeSlack2 = (s) => s.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
37501
37806
  function stripBotMention(text, botUserId) {
37502
37807
  const id = botUserId.replace(/[^A-Za-z0-9]/g, "");
37503
37808
  return text.replace(new RegExp(`[ \\t]*<@${id}(\\|[^>]*)?>[ \\t]*`, "g"), (m, _label, at, s) => {
@@ -37512,8 +37817,8 @@ var mentions = (text, botUserId) => new RegExp(`<@${botUserId.replace(/[^A-Za-z0
37512
37817
  function profileOf(p) {
37513
37818
  const o = obj2(p);
37514
37819
  if (!o) return void 0;
37515
- const displayName = str2(o.display_name) ?? str2(o.real_name) ?? str2(o.name);
37516
- const avatarUrl = str2(o.image_72) ?? str2(o.image_48) ?? str2(o.image_192);
37820
+ const displayName = str3(o.display_name) ?? str3(o.real_name) ?? str3(o.name);
37821
+ const avatarUrl = str3(o.image_72) ?? str3(o.image_48) ?? str3(o.image_192);
37517
37822
  if (displayName === void 0 && avatarUrl === void 0) return void 0;
37518
37823
  return {
37519
37824
  ...displayName !== void 0 && { displayName },
@@ -37524,7 +37829,7 @@ function eventToInbound(body, botUserId) {
37524
37829
  const b = obj2(body);
37525
37830
  const e = obj2(b?.event);
37526
37831
  if (!b || !e) return null;
37527
- const teamId = str2(b.team_id);
37832
+ const teamId = str3(b.team_id);
37528
37833
  const type = e.type;
37529
37834
  if (type === "team_join" || type === "user_change") {
37530
37835
  if (!teamId) return null;
@@ -37536,19 +37841,19 @@ function eventToInbound(body, botUserId) {
37536
37841
  }
37537
37842
  if (e.bot_id !== void 0 || e.bot_profile !== void 0) return null;
37538
37843
  if (type === "app_mention" && e.edited !== void 0) return null;
37539
- const user = str2(e.user);
37540
- const channel = str2(e.channel);
37541
- const ts = str2(e.ts);
37844
+ const user = str3(e.user);
37845
+ const channel = str3(e.channel);
37846
+ const ts = str3(e.ts);
37542
37847
  const raw = typeof e.text === "string" ? e.text : "";
37543
37848
  if (!user || !channel || !ts || user === botUserId) return null;
37544
- const tenantId = str2(e.user_team) ?? str2(e.team) ?? teamId;
37849
+ const tenantId = str3(e.user_team) ?? str3(e.team) ?? teamId;
37545
37850
  if (!tenantId) return null;
37546
37851
  const mentioned = type === "app_mention" || mentions(raw, botUserId);
37547
- const threadTs = str2(e.thread_ts);
37852
+ const threadTs = str3(e.thread_ts);
37548
37853
  const inThread = threadTs !== void 0 && threadTs !== ts;
37549
37854
  const dm = type === "message" ? e.channel_type === "im" : channel.startsWith("D");
37550
37855
  if (!dm && type === "message" && (mentioned || !inThread)) return null;
37551
- const text = unescapeSlack(stripBotMention(raw, botUserId));
37856
+ const text = unescapeSlack2(stripBotMention(raw, botUserId));
37552
37857
  if (text === "") return null;
37553
37858
  const target = dm ? { chatId: channel, chatType: "dm" } : {
37554
37859
  chatId: channel,
@@ -37569,6 +37874,19 @@ function eventToInbound(body, botUserId) {
37569
37874
  }
37570
37875
  };
37571
37876
  }
37877
+ function userInfoProfile(u) {
37878
+ const o = obj2(u);
37879
+ if (!o) return void 0;
37880
+ const base = profileOf(o.profile) ?? profileOf({ real_name: o.real_name, name: o.name });
37881
+ const timeZone = str3(o.tz);
37882
+ const locale = str3(o.locale);
37883
+ if (base === void 0 && timeZone === void 0 && locale === void 0) return void 0;
37884
+ return {
37885
+ ...base,
37886
+ ...timeZone !== void 0 && { timeZone },
37887
+ ...locale !== void 0 && { locale }
37888
+ };
37889
+ }
37572
37890
 
37573
37891
  // src/webhook.ts
37574
37892
  import { createHmac, timingSafeEqual } from "node:crypto";
@@ -37589,6 +37907,11 @@ function verifySlackSignature(h, body, signingSecret, nowMs) {
37589
37907
  const got = Buffer.from(sig2);
37590
37908
  return got.length === want.length && timingSafeEqual(got, want);
37591
37909
  }
37910
+ var slackJsonAck = (body) => ({
37911
+ status: 200,
37912
+ headers: { "content-type": "application/json; charset=utf-8" },
37913
+ body: JSON.stringify(body)
37914
+ });
37592
37915
  function readSlackWebhook(config, request) {
37593
37916
  if (config.signingSecret === void 0) return { kind: "reject", status: 401 };
37594
37917
  if (!verifySlackSignature(request.headers, request.body, config.signingSecret, request.receivedAt)) {
@@ -37597,8 +37920,12 @@ function readSlackWebhook(config, request) {
37597
37920
  const text = new TextDecoder().decode(request.body);
37598
37921
  const type = (request.headers["content-type"] ?? "").split(";")[0]?.trim().toLowerCase();
37599
37922
  if (type === "application/x-www-form-urlencoded") {
37600
- const payload = new URLSearchParams(text).get("payload");
37601
- if (payload === null) return { kind: "ignore" };
37923
+ const form = new URLSearchParams(text);
37924
+ const payload = form.get("payload");
37925
+ if (payload === null) {
37926
+ if (form.get("command") === null) return { kind: "ignore" };
37927
+ return { kind: "command", body: Object.fromEntries(form) };
37928
+ }
37602
37929
  let parsed2;
37603
37930
  try {
37604
37931
  parsed2 = JSON.parse(payload);
@@ -37636,6 +37963,11 @@ async function handleSlackWebhook(args) {
37636
37963
  const r = readSlackWebhook(args.config, args.request);
37637
37964
  if (r.kind === "respond" || r.kind === "reject") return r;
37638
37965
  if (r.kind === "ignore") return { kind: "events", events: [], ack: SLACK_WEBHOOK_ACK };
37966
+ if (r.kind === "command") {
37967
+ const { event: event2, response } = await args.command(r.body);
37968
+ const ack = response !== void 0 ? slackJsonAck(response) : SLACK_WEBHOOK_ACK;
37969
+ return event2 ? { kind: "events", events: [event2], ack } : { kind: "respond", response: ack };
37970
+ }
37639
37971
  const bot = r.envelope.type === "events_api" ? await args.botUserId() : "";
37640
37972
  const event = await args.toEvent(r.envelope, bot);
37641
37973
  return { kind: "events", events: event ? [event] : [], ack: SLACK_WEBHOOK_ACK };
@@ -37643,11 +37975,36 @@ async function handleSlackWebhook(args) {
37643
37975
 
37644
37976
  // src/channel.ts
37645
37977
  var SlackConnection = z2.object({
37646
- appToken: secret2(
37647
- z2.string().regex(/^xapp-/, "must be an app-level token starting with xapp-").optional()
37978
+ appToken: ui2(
37979
+ secret2(
37980
+ z2.string().regex(/^xapp-/, "must be an app-level token starting with xapp-").optional()
37981
+ ),
37982
+ {
37983
+ label: { zh: "应用令牌", en: "App-level token" },
37984
+ help: {
37985
+ zh: "xapp-…,Socket Mode 必填(Basic Information → App-Level Tokens,权限 connections:write)。",
37986
+ en: "xapp-…, required for Socket Mode (Basic Information → App-Level Tokens, scope connections:write)."
37987
+ },
37988
+ placeholder: "xapp-…",
37989
+ inboundModes: ["long_connection"]
37990
+ }
37648
37991
  ),
37649
- botToken: secret2(z2.string().regex(/^xoxb-/, "must be a bot token starting with xoxb-")),
37650
- signingSecret: secret2(z2.string().min(1).optional())
37992
+ botToken: ui2(secret2(z2.string().regex(/^xoxb-/, "must be a bot token starting with xoxb-")), {
37993
+ label: { zh: "机器人令牌", en: "Bot token" },
37994
+ help: {
37995
+ zh: "xoxb-…(Install App → Bot User OAuth Token)。",
37996
+ en: "xoxb-… (Install App → Bot User OAuth Token)."
37997
+ },
37998
+ placeholder: "xoxb-…"
37999
+ }),
38000
+ signingSecret: ui2(secret2(z2.string().min(1).optional()), {
38001
+ label: { zh: "签名密钥", en: "Signing secret" },
38002
+ help: {
38003
+ zh: "Basic Information → App Credentials → Signing Secret,用来校验 Slack 发来的每个请求。",
38004
+ en: "Basic Information → App Credentials → Signing Secret; every request from Slack is verified with it."
38005
+ },
38006
+ inboundModes: ["webhook"]
38007
+ })
37651
38008
  });
37652
38009
  var SOCKET_MODE_NEEDS_APP_TOKEN = "Socket Mode needs an app-level token (xapp-…); set one or switch this connection to webhook mode";
37653
38010
  var BOT_USER_CACHE_TTL_SECONDS = 3600;
@@ -37655,9 +38012,11 @@ var MIN_EDIT_INTERVAL_MS = 2500;
37655
38012
  var SHORT_LIVED_MS = 1e4;
37656
38013
  var MAX_SHORT_LIVED = 5;
37657
38014
  var MAX_RECONNECT_DELAY_MS = 3e4;
37658
- var PROFILE_TTL_MS = 10 * 6e4;
37659
- var PROFILE_CACHE_MAX = 1e3;
38015
+ var PROFILE_CACHE_TTL_SECONDS = 600;
37660
38016
  var PROFILE_TIMEOUT_MS = 1500;
38017
+ var BOT_DM_CACHE_TTL_SECONDS = 86400;
38018
+ var COMMAND_ECHO_TTL_SECONDS = 3600;
38019
+ var COMMAND_CALL_TIMEOUT_MS = 1500;
37661
38020
  var pause = (ms, signal) => new Promise((resolve) => {
37662
38021
  const s = AbortSignal.any([signal, AbortSignal.timeout(ms)]);
37663
38022
  if (s.aborted) resolve();
@@ -37727,44 +38086,55 @@ function createSlackChannel(opts) {
37727
38086
  });
37728
38087
  };
37729
38088
  const parse = (config) => SlackConnection.parse(config);
37730
- const profiles = /* @__PURE__ */ new Map();
37731
- const lookupProfile = async (botToken, scope, userId, signal) => {
37732
- const key = `${scope}\0${userId}`;
37733
- const hit = profiles.get(key);
37734
- if (hit && Date.now() - hit.at < PROFILE_TTL_MS) return hit.profile;
38089
+ const lookupProfile = async (botToken, teamId, userId, signal) => {
38090
+ const key = `profile/${teamId}/${userId}`;
38091
+ const hit = await opts.kv?.get(key).catch(() => null);
38092
+ if (hit) {
38093
+ try {
38094
+ const cached = JSON.parse(hit);
38095
+ return Object.keys(cached).length > 0 ? cached : void 0;
38096
+ } catch {
38097
+ }
38098
+ }
37735
38099
  let profile;
37736
38100
  try {
37737
38101
  const s = AbortSignal.any([signal, AbortSignal.timeout(PROFILE_TIMEOUT_MS)]);
37738
- const r = await web(botToken, s).apiCall("users.info", { user: userId });
37739
- profile = profileOf(r.user?.profile) ?? profileOf({ real_name: r.user?.real_name, name: r.user?.name });
38102
+ const r = await web(botToken, s).apiCall("users.info", {
38103
+ user: userId,
38104
+ include_locale: true
38105
+ });
38106
+ profile = userInfoProfile(r.user);
37740
38107
  } catch (e) {
37741
- const code = platformErrorCode(e);
37742
- if (code !== "user_not_found") return void 0;
37743
- }
37744
- profiles.delete(key);
37745
- profiles.set(key, { at: Date.now(), profile });
37746
- if (profiles.size > PROFILE_CACHE_MAX) {
37747
- const oldest = profiles.keys().next().value;
37748
- if (oldest !== void 0) profiles.delete(oldest);
38108
+ if (platformErrorCode(e) !== "user_not_found") return void 0;
37749
38109
  }
38110
+ await opts.kv?.set(key, JSON.stringify(profile ?? {}), { ttlSeconds: PROFILE_CACHE_TTL_SECONDS }).catch(() => {
38111
+ });
37750
38112
  return profile;
37751
38113
  };
37752
38114
  const withProfile = (sender, p) => ({
37753
38115
  ...sender,
37754
38116
  ...p?.displayName !== void 0 && { displayName: p.displayName },
37755
- ...p?.avatarUrl !== void 0 && { avatarUrl: p.avatarUrl }
38117
+ ...p?.avatarUrl !== void 0 && { avatarUrl: p.avatarUrl },
38118
+ ...p?.timeZone !== void 0 && { timeZone: p.timeZone },
38119
+ ...p?.locale !== void 0 && { locale: p.locale }
37756
38120
  });
37757
- const toEvent = async (c, connectionId, botUserId, { type, body }, signal) => {
38121
+ const toEvent = async (c, botUserId, { type, body }, signal) => {
37758
38122
  if (type === "events_api") {
37759
38123
  const cand = eventToInbound(body, botUserId);
37760
38124
  if (!cand) return null;
37761
38125
  if (cand.kind === "directory") return cand.event;
37762
- const p2 = cand.profile ?? await lookupProfile(c.botToken, connectionId, cand.userId, signal);
38126
+ const looked = await lookupProfile(
38127
+ c.botToken,
38128
+ cand.event.sender.tenantId,
38129
+ cand.userId,
38130
+ signal
38131
+ );
38132
+ const p2 = looked || cand.profile ? { ...looked, ...cand.profile } : void 0;
37763
38133
  return { ...cand.event, sender: withProfile(cand.event.sender, p2) };
37764
38134
  }
37765
38135
  const a = parseBlockActions(body);
37766
38136
  if (!a) return null;
37767
- const p = await lookupProfile(c.botToken, connectionId, a.sender.externalId, signal) ?? (a.username !== void 0 ? { displayName: a.username } : void 0);
38137
+ const p = await lookupProfile(c.botToken, a.sender.tenantId, a.sender.externalId, signal) ?? (a.username !== void 0 ? { displayName: a.username } : void 0);
37768
38138
  return {
37769
38139
  type: "card_action",
37770
38140
  messageId: a.messageId,
@@ -37792,6 +38162,101 @@ function createSlackChannel(opts) {
37792
38162
  await rememberBotUser(connectionId, botToken, id);
37793
38163
  return id;
37794
38164
  };
38165
+ const isBotDm = async (c, connectionId, userId, channelId, signal) => {
38166
+ const key = `dm/${connectionId}/${userId}`;
38167
+ const hit = await opts.kv?.get(key).catch(() => null);
38168
+ if (hit) return hit === channelId;
38169
+ try {
38170
+ const s = AbortSignal.any([signal, AbortSignal.timeout(COMMAND_CALL_TIMEOUT_MS)]);
38171
+ const r = await web(c.botToken, s).apiCall("conversations.open", { users: userId });
38172
+ const id = r.channel?.id;
38173
+ if (!id) return true;
38174
+ await opts.kv?.set(key, id, { ttlSeconds: BOT_DM_CACHE_TTL_SECONDS }).catch(() => {
38175
+ });
38176
+ return id === channelId;
38177
+ } catch (e) {
38178
+ log.warn("slack: could not look up the bot's DM for a slash command; assuming it is", {
38179
+ connectionId,
38180
+ error: describe(e, "conversations.open").message
38181
+ });
38182
+ return true;
38183
+ }
38184
+ };
38185
+ const postEcho = async (c, connectionId, channelId, triggerId, text, signal) => {
38186
+ const key = `cmd-echo/${connectionId}/${createHash("sha256").update(triggerId).digest("hex").slice(0, 32)}`;
38187
+ const hit = await opts.kv?.get(key).catch(() => null);
38188
+ if (hit) return { ts: hit };
38189
+ try {
38190
+ const s = AbortSignal.any([signal, AbortSignal.timeout(COMMAND_CALL_TIMEOUT_MS)]);
38191
+ const r = await web(c.botToken, s).apiCall("chat.postMessage", {
38192
+ channel: channelId,
38193
+ text
38194
+ });
38195
+ if (!r.ts) return { error: "no_ts" };
38196
+ await opts.kv?.set(key, r.ts, { ttlSeconds: COMMAND_ECHO_TTL_SECONDS }).catch(() => {
38197
+ });
38198
+ return { ts: r.ts };
38199
+ } catch (e) {
38200
+ return { error: platformErrorCode(e) ?? "request_failed" };
38201
+ }
38202
+ };
38203
+ const toCommand = async (c, connectionId, body, signal) => {
38204
+ const cmd = parseSlashCommand(body);
38205
+ if (!cmd) return { event: null, response: void 0 };
38206
+ const text = slashCommandText(cmd.command, cmd.text);
38207
+ if (text === null) return { event: null, response: ephemeral(SLASH_REPLIES.usage) };
38208
+ const profile = lookupProfile(c.botToken, cmd.teamId, cmd.userId, signal).then(
38209
+ (p2) => p2 ?? (cmd.userName !== void 0 ? { displayName: cmd.userName } : void 0)
38210
+ );
38211
+ const sender = { externalId: cmd.userId, tenantId: cmd.teamId };
38212
+ if (cmd.channelId.startsWith("D")) {
38213
+ const [own, p2] = await Promise.all([
38214
+ isBotDm(c, connectionId, cmd.userId, cmd.channelId, signal),
38215
+ profile
38216
+ ]);
38217
+ if (!own) return { event: null, response: ephemeral(SLASH_REPLIES.wrongDm) };
38218
+ return {
38219
+ event: {
38220
+ type: "message",
38221
+ messageId: `${cmd.channelId}:cmd-${cmd.triggerId}`,
38222
+ target: { chatId: cmd.channelId, chatType: "dm" },
38223
+ sender: withProfile(sender, p2),
38224
+ text,
38225
+ mentionsBot: false
38226
+ },
38227
+ response: ephemeral(escapeSlack(typedCommand(cmd)))
38228
+ };
38229
+ }
38230
+ const echoText = `<@${cmd.userId}>: ${escapeSlack(typedCommand(cmd))}`;
38231
+ const [echo, p] = await Promise.all([
38232
+ postEcho(c, connectionId, cmd.channelId, cmd.triggerId, echoText, signal),
38233
+ profile
38234
+ ]);
38235
+ if ("error" in echo) {
38236
+ const gone = ["not_in_channel", "channel_not_found", "is_archived"].includes(echo.error);
38237
+ if (!gone) {
38238
+ log.warn("slack: could not post a slash command's echo", {
38239
+ connectionId,
38240
+ error: echo.error
38241
+ });
38242
+ }
38243
+ return {
38244
+ event: null,
38245
+ response: ephemeral(gone ? SLASH_REPLIES.notInChannel : SLASH_REPLIES.failed)
38246
+ };
38247
+ }
38248
+ return {
38249
+ event: {
38250
+ type: "message",
38251
+ messageId: `${cmd.channelId}:${echo.ts}`,
38252
+ target: { chatId: cmd.channelId, chatType: "group" },
38253
+ sender: withProfile(sender, p),
38254
+ text,
38255
+ mentionsBot: true
38256
+ },
38257
+ response: void 0
38258
+ };
38259
+ };
37795
38260
  return {
37796
38261
  connectionSchema: SlackConnection,
37797
38262
  features: { cards: true, edit: true, threads: true, minEditIntervalMs: MIN_EDIT_INTERVAL_MS },
@@ -37824,9 +38289,12 @@ function createSlackChannel(opts) {
37824
38289
  await rememberBotUser(connectionId, c.botToken, botUserId);
37825
38290
  const handle = async ({ ack, type, body }) => {
37826
38291
  let event = null;
38292
+ let response;
37827
38293
  try {
37828
38294
  if (type === "events_api" || type === "interactive") {
37829
- event = await toEvent(c, connectionId, botUserId, { type, body }, signal);
38295
+ event = await toEvent(c, botUserId, { type, body }, signal);
38296
+ } else if (type === "slash_commands") {
38297
+ ({ event, response } = await toCommand(c, connectionId, body, signal));
37830
38298
  }
37831
38299
  } catch (e) {
37832
38300
  log.warn("slack: could not read an event; acknowledging and skipping it", {
@@ -37846,7 +38314,7 @@ function createSlackChannel(opts) {
37846
38314
  return;
37847
38315
  }
37848
38316
  }
37849
- await ack().catch((e) => {
38317
+ await ack(response).catch((e) => {
37850
38318
  log.warn("slack: acknowledging an event failed; Slack will redeliver it", {
37851
38319
  connectionId,
37852
38320
  error: e instanceof Error ? e.message : String(e)
@@ -37934,9 +38402,20 @@ function createSlackChannel(opts) {
37934
38402
  config: c,
37935
38403
  request,
37936
38404
  botUserId: () => botUserIdOf(connectionId, c.botToken, signal),
38405
+ command: async (body) => {
38406
+ try {
38407
+ return await toCommand(c, connectionId, body, signal);
38408
+ } catch (e) {
38409
+ log.warn("slack: could not read a webhook slash command; skipping it", {
38410
+ connectionId,
38411
+ error: e instanceof Error ? e.message : String(e)
38412
+ });
38413
+ return { event: null, response: ephemeral(SLASH_REPLIES.failed) };
38414
+ }
38415
+ },
37937
38416
  toEvent: async (envelope, botUserId) => {
37938
38417
  try {
37939
- return await toEvent(c, connectionId, botUserId, envelope, signal);
38418
+ return await toEvent(c, botUserId, envelope, signal);
37940
38419
  } catch (e) {
37941
38420
  log.warn("slack: could not read a webhook event; acknowledging and skipping it", {
37942
38421
  connectionId,
@@ -37957,10 +38436,9 @@ function createSlackChannel(opts) {
37957
38436
  const client = web(c.botToken, signal);
37958
38437
  const threadTs = threadTsOf(target);
37959
38438
  let last;
37960
- for (const p of renderSend(message2, locale)) {
37961
- let r;
38439
+ const post = async (p) => {
37962
38440
  try {
37963
- r = await client.apiCall("chat.postMessage", {
38441
+ return await client.apiCall("chat.postMessage", {
37964
38442
  channel: target.chatId,
37965
38443
  text: p.text,
37966
38444
  ...p.blocks !== void 0 && { blocks: p.blocks },
@@ -37969,13 +38447,27 @@ function createSlackChannel(opts) {
37969
38447
  } catch (e) {
37970
38448
  throw toChannelSendError(e);
37971
38449
  }
37972
- if (!r.ts) {
37973
- throw new ChannelSendError3("Slack returned no message ts", {
37974
- retryable: false,
37975
- reason: "rejected"
38450
+ };
38451
+ for (const p of renderSend(message2, locale)) {
38452
+ const sent = [];
38453
+ try {
38454
+ sent.push(await post(p));
38455
+ } catch (e) {
38456
+ if (!p.fallback || !blocksRejected(e)) throw e;
38457
+ log.warn("slack: Slack rejected a table block; the table is sent as a list", {
38458
+ error: e instanceof Error ? e.message : String(e)
37976
38459
  });
38460
+ for (const f of p.fallback) sent.push(await post(f));
38461
+ }
38462
+ for (const r of sent) {
38463
+ if (!r.ts) {
38464
+ throw new ChannelSendError3("Slack returned no message ts", {
38465
+ retryable: false,
38466
+ reason: "rejected"
38467
+ });
38468
+ }
38469
+ last = `${r.channel ?? target.chatId}:${r.ts}`;
37977
38470
  }
37978
- last = `${r.channel ?? target.chatId}:${r.ts}`;
37979
38471
  }
37980
38472
  if (last === void 0) throw new ChannelSendError3("nothing to send", { retryable: false });
37981
38473
  return { messageId: last };
@@ -37984,15 +38476,33 @@ function createSlackChannel(opts) {
37984
38476
  const p = renderUpdate(message2, locale);
37985
38477
  const { channel, ts } = parseMessageId(messageId);
37986
38478
  const c = parse(config);
38479
+ const edit = async (q) => {
38480
+ try {
38481
+ await web(c.botToken, signal).apiCall("chat.update", {
38482
+ channel,
38483
+ ts,
38484
+ text: q.text,
38485
+ ...q.blocks !== void 0 && { blocks: q.blocks }
38486
+ });
38487
+ } catch (e) {
38488
+ throw toChannelSendError(e);
38489
+ }
38490
+ };
37987
38491
  try {
37988
- await web(c.botToken, signal).apiCall("chat.update", {
37989
- channel,
37990
- ts,
37991
- text: p.text,
37992
- ...p.blocks !== void 0 && { blocks: p.blocks }
37993
- });
38492
+ await edit(p);
37994
38493
  } catch (e) {
37995
- throw toChannelSendError(e);
38494
+ if (!p.fallback || !blocksRejected(e)) throw e;
38495
+ const only = p.fallback.length === 1 ? p.fallback[0] : void 0;
38496
+ if (!only) {
38497
+ throw new ChannelSendError3("message too long for a single Slack message", {
38498
+ retryable: false,
38499
+ reason: "too_large"
38500
+ });
38501
+ }
38502
+ log.warn("slack: Slack rejected a table block; the table is sent as a list", {
38503
+ error: e instanceof Error ? e.message : String(e)
38504
+ });
38505
+ await edit(only);
37996
38506
  }
37997
38507
  }
37998
38508
  };
@@ -38000,7 +38510,7 @@ function createSlackChannel(opts) {
38000
38510
 
38001
38511
  // src/directory.ts
38002
38512
  var obj4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : void 0;
38003
- var str3 = (v) => typeof v === "string" && v !== "" ? v : void 0;
38513
+ var str4 = (v) => typeof v === "string" && v !== "" ? v : void 0;
38004
38514
  var pause2 = (ms, signal) => new Promise((resolve, reject) => {
38005
38515
  if (signal.aborted) return reject(signal.reason);
38006
38516
  const timer = AbortSignal.timeout(ms);
@@ -38052,7 +38562,7 @@ function createSlackDirectory(opts) {
38052
38562
  }
38053
38563
  const body = obj4(await res.json().catch(() => void 0));
38054
38564
  if (body?.ok !== true) {
38055
- throw new Error(`Slack ${method} failed: ${str3(body?.error) ?? "malformed response"}`);
38565
+ throw new Error(`Slack ${method} failed: ${str4(body?.error) ?? "malformed response"}`);
38056
38566
  }
38057
38567
  return body;
38058
38568
  }
@@ -38072,7 +38582,7 @@ function createSlackDirectory(opts) {
38072
38582
  const teamId = c.teamId;
38073
38583
  const budget = { leftMs: maxWait };
38074
38584
  const auth = await call("auth.test", c.botToken, {}, signal, budget);
38075
- const tokenTeam = str3(auth.team_id);
38585
+ const tokenTeam = str4(auth.team_id);
38076
38586
  const problem = workspaceTokenProblem(auth);
38077
38587
  if (problem !== void 0) throw new Error(problem);
38078
38588
  if (tokenTeam !== teamId) {
@@ -38097,23 +38607,23 @@ function createSlackDirectory(opts) {
38097
38607
  const members = [];
38098
38608
  for (const raw of page.members) {
38099
38609
  const u = obj4(raw);
38100
- const id = str3(u?.id);
38610
+ const id = str4(u?.id);
38101
38611
  if (!u || !id || id === SLACKBOT || u.is_bot === true) continue;
38102
38612
  if (u.is_restricted === true || u.is_ultra_restricted === true) continue;
38103
- const ownTeam = str3(u.team_id);
38613
+ const ownTeam = str4(u.team_id);
38104
38614
  if (ownTeam !== void 0 && ownTeam !== teamId) continue;
38105
38615
  const profile = obj4(u.profile);
38106
- const email = str3(profile?.email);
38616
+ const email = str4(profile?.email);
38107
38617
  members.push({
38108
38618
  externalId: id,
38109
38619
  tenantId: teamId,
38110
38620
  ...email !== void 0 && { email },
38111
38621
  emailVerified: false,
38112
- displayName: str3(profile?.display_name) ?? str3(profile?.real_name) ?? str3(u.real_name) ?? str3(u.name) ?? id,
38622
+ displayName: str4(profile?.display_name) ?? str4(profile?.real_name) ?? str4(u.real_name) ?? str4(u.name) ?? id,
38113
38623
  active: u.deleted !== true
38114
38624
  });
38115
38625
  }
38116
- const next = str3(obj4(page.response_metadata)?.next_cursor);
38626
+ const next = str4(obj4(page.response_metadata)?.next_cursor);
38117
38627
  return { members, ...next !== void 0 && { next } };
38118
38628
  }
38119
38629
  };
@@ -38606,9 +39116,9 @@ var checkFailed = "check_failed";
38606
39116
  function invalidDuration() {
38607
39117
  throw new TypeError("Invalid time period format");
38608
39118
  }
38609
- function secs(str5) {
38610
- typeof str5 != "string" && invalidDuration();
38611
- const matched = REGEX.exec(str5);
39119
+ function secs(str6) {
39120
+ typeof str6 != "string" && invalidDuration();
39121
+ const matched = REGEX.exec(str6);
38612
39122
  (!matched || matched[4] && matched[1]) && invalidDuration();
38613
39123
  const value = parseFloat(matched[2]), numericDate2 = Math.round(value * multipliers[matched[3][0].toLowerCase()]);
38614
39124
  return Number.isFinite(numericDate2) || invalidDuration(), matched[1] === "-" || matched[4] === "ago" ? -numericDate2 : numericDate2;
@@ -38840,7 +39350,7 @@ var SLACK_OIDC_SCOPES = "openid email profile";
38840
39350
  var TEAM_CLAIM = "https://slack.com/team_id";
38841
39351
  var USER_CLAIM = "https://slack.com/user_id";
38842
39352
  var REQUEST_TIMEOUT_MS = 1e4;
38843
- var str4 = (v) => typeof v === "string" && v !== "" ? v : void 0;
39353
+ var str5 = (v) => typeof v === "string" && v !== "" ? v : void 0;
38844
39354
  var isHttpUrl2 = (v) => /^https?:\/\//i.test(v);
38845
39355
  function loginConfig(config) {
38846
39356
  const c = SlackDeployment.parse(config ?? {});
@@ -38872,7 +39382,7 @@ async function slackPost(apiUrl, method, form, signal, token) {
38872
39382
  }
38873
39383
  const body = await res.json().catch(() => void 0);
38874
39384
  if (body?.ok !== true) {
38875
- throw new Error(`Slack ${method} failed: ${str4(body?.error) ?? "malformed response"}`);
39385
+ throw new Error(`Slack ${method} failed: ${str5(body?.error) ?? "malformed response"}`);
38876
39386
  }
38877
39387
  return body;
38878
39388
  }
@@ -38918,8 +39428,8 @@ function createSlackIdentitySource() {
38918
39428
  },
38919
39429
  signal
38920
39430
  );
38921
- const accessToken = str4(token.access_token);
38922
- const idToken = str4(token.id_token);
39431
+ const accessToken = str5(token.access_token);
39432
+ const idToken = str5(token.id_token);
38923
39433
  if (!accessToken || !idToken) {
38924
39434
  throw new Error("Slack openid.connect.token failed: no access_token / id_token");
38925
39435
  }
@@ -38937,49 +39447,378 @@ function createSlackIdentitySource() {
38937
39447
  }
38938
39448
  signal.throwIfAborted();
38939
39449
  if (claims.nonce !== nonce) throw new Error("Slack ID token rejected: nonce mismatch");
38940
- const teamId = str4(claims[TEAM_CLAIM]);
38941
- const userId = str4(claims[USER_CLAIM]) ?? str4(claims.sub);
39450
+ const teamId = str5(claims[TEAM_CLAIM]);
39451
+ const userId = str5(claims[USER_CLAIM]) ?? str5(claims.sub);
38942
39452
  if (!teamId || !userId) throw new Error("Slack ID token rejected: no team / user id");
38943
39453
  const info = await slackPost(c.apiUrl, "openid.connect.userInfo", {}, signal, accessToken);
38944
- const infoUser = str4(info[USER_CLAIM]) ?? str4(info.sub);
38945
- if (infoUser !== userId || str4(info[TEAM_CLAIM]) !== teamId) {
39454
+ const infoUser = str5(info[USER_CLAIM]) ?? str5(info.sub);
39455
+ if (infoUser !== userId || str5(info[TEAM_CLAIM]) !== teamId) {
38946
39456
  throw new Error("Slack userInfo does not match the ID token (user / team)");
38947
39457
  }
38948
- const email = str4(info.email);
38949
- const picture = str4(info.picture);
39458
+ const email = str5(info.email);
39459
+ const picture = str5(info.picture);
38950
39460
  return {
38951
39461
  source: `slack:${teamId}`,
38952
39462
  externalId: userId,
38953
39463
  tenantId: teamId,
38954
39464
  ...email !== void 0 && { email },
38955
39465
  emailVerified: email !== void 0 && info.email_verified === true,
38956
- displayName: str4(info.name) ?? str4(info.given_name) ?? userId,
39466
+ displayName: str5(info.name) ?? str5(info.given_name) ?? userId,
38957
39467
  ...picture !== void 0 && isHttpUrl2(picture) && { avatarUrl: picture }
38958
39468
  };
38959
39469
  }
38960
39470
  };
38961
39471
  }
38962
39472
 
39473
+ // src/setup-checks.ts
39474
+ var REQUIRED_BOT_SCOPES = [
39475
+ "chat:write",
39476
+ "commands",
39477
+ "im:write",
39478
+ "im:history",
39479
+ "app_mentions:read",
39480
+ "channels:history",
39481
+ "groups:history",
39482
+ "users:read",
39483
+ "users:read.email"
39484
+ ];
39485
+ var ERROR_CODE_RE = /^[a-z][a-z0-9_.]{0,63}$/;
39486
+ async function slackCall(apiUrl, method, token, signal) {
39487
+ let res;
39488
+ try {
39489
+ res = await fetch(new URL(method, apiUrl), {
39490
+ method: "POST",
39491
+ headers: {
39492
+ "content-type": "application/x-www-form-urlencoded",
39493
+ authorization: `Bearer ${token}`
39494
+ },
39495
+ body: "",
39496
+ redirect: "manual",
39497
+ signal
39498
+ });
39499
+ } catch {
39500
+ return { kind: "network" };
39501
+ }
39502
+ if (res.status !== 200) {
39503
+ await res.body?.cancel().catch(() => void 0);
39504
+ return { kind: "http", status: res.status };
39505
+ }
39506
+ let body;
39507
+ try {
39508
+ body = await res.json();
39509
+ } catch {
39510
+ return { kind: "network" };
39511
+ }
39512
+ if (typeof body !== "object" || body === null) return { kind: "error", code: "invalid_response" };
39513
+ const b = body;
39514
+ if (b.ok === true) return { kind: "ok", body: b, headers: res.headers };
39515
+ const code = typeof b.error === "string" && ERROR_CODE_RE.test(b.error) ? b.error : "unknown_error";
39516
+ return { kind: "error", code };
39517
+ }
39518
+ var unknown = (reason) => ({ status: "unknown", reason });
39519
+ var failing = (reason, fix) => ({ status: "failing", reason, fix });
39520
+ var TRANSIENT = /* @__PURE__ */ new Set([
39521
+ "ratelimited",
39522
+ "rate_limited",
39523
+ "internal_error",
39524
+ "fatal_error",
39525
+ "service_unavailable",
39526
+ "request_timeout"
39527
+ ]);
39528
+ var REFUSED = /* @__PURE__ */ new Set([
39529
+ "invalid_auth",
39530
+ "not_authed",
39531
+ "token_revoked",
39532
+ "token_expired",
39533
+ "account_inactive",
39534
+ "no_permission",
39535
+ "ekm_access_denied"
39536
+ ]);
39537
+ function notAnswered(r) {
39538
+ if (r.kind === "network")
39539
+ return unknown({
39540
+ en: "Could not reach Slack (network error or timeout); check again later.",
39541
+ zh: "无法连接 Slack(网络错误或超时),请稍后再检查。"
39542
+ });
39543
+ if (r.kind === "http") {
39544
+ if (r.status === 429)
39545
+ return unknown({
39546
+ en: "Slack is rate limiting requests; check again in a minute.",
39547
+ zh: "Slack 正在限流,请一分钟后再检查。"
39548
+ });
39549
+ return unknown({
39550
+ en: `Slack answered HTTP ${r.status}; check again later.`,
39551
+ zh: `Slack 返回 HTTP ${r.status},请稍后再检查。`
39552
+ });
39553
+ }
39554
+ if (r.code === "ratelimited" || r.code === "rate_limited")
39555
+ return unknown({
39556
+ en: "Slack is rate limiting requests; check again in a minute.",
39557
+ zh: "Slack 正在限流,请一分钟后再检查。"
39558
+ });
39559
+ if (TRANSIENT.has(r.code))
39560
+ return unknown({
39561
+ en: `Slack is temporarily unavailable (${r.code}); check again later.`,
39562
+ zh: `Slack 暂时不可用(${r.code}),请稍后再检查。`
39563
+ });
39564
+ return unknown({
39565
+ en: `Slack answered ${r.code}; the check could not tell whether the setup is right.`,
39566
+ zh: `Slack 返回 ${r.code},无法判断设置是否正确。`
39567
+ });
39568
+ }
39569
+ var BOT_TOKEN_FIX = {
39570
+ en: "Under Install App, reinstall the app to the workspace and copy the new Bot User OAuth Token (xoxb-…) into the Bot token field.",
39571
+ zh: "在 Install App 中把应用重新安装到工作区,再把新的 Bot User OAuth Token(xoxb-…)填进「机器人令牌」。"
39572
+ };
39573
+ var MANIFEST_FIX = {
39574
+ en: "Open the app at https://api.slack.com/apps, paste the manifest from this guide under App Manifest, save, then reinstall the app under Install App.",
39575
+ zh: "在 https://api.slack.com/apps 打开该应用,在 App Manifest 粘贴本指南中的 manifest 并保存,然后在 Install App 中重新安装应用。"
39576
+ };
39577
+ function botTokenRefused(code) {
39578
+ if (REFUSED.has(code))
39579
+ return failing(
39580
+ {
39581
+ en: `Slack refused the bot token (${code}); it may have been revoked or the app uninstalled.`,
39582
+ zh: `Slack 拒绝了机器人令牌(${code}),令牌可能已被撤销或应用已被卸载。`
39583
+ },
39584
+ BOT_TOKEN_FIX
39585
+ );
39586
+ if (code === "not_allowed_token_type")
39587
+ return failing(
39588
+ {
39589
+ en: "The Bot token field holds a token of the wrong type (not_allowed_token_type).",
39590
+ zh: "「机器人令牌」中的令牌类型不对(not_allowed_token_type)。"
39591
+ },
39592
+ {
39593
+ en: "Copy the Bot User OAuth Token (xoxb-…) from Install App, not a user or app-level token.",
39594
+ zh: "从 Install App 复制 Bot User OAuth Token(xoxb-…),不要用用户令牌或应用级令牌。"
39595
+ }
39596
+ );
39597
+ if (code === "missing_scope")
39598
+ return failing(
39599
+ {
39600
+ en: "Slack refused the call for a missing scope (missing_scope).",
39601
+ zh: "Slack 因缺少权限拒绝了调用(missing_scope)。"
39602
+ },
39603
+ MANIFEST_FIX
39604
+ );
39605
+ return void 0;
39606
+ }
39607
+ function plain2(s, max = 80) {
39608
+ if (typeof s !== "string") return void 0;
39609
+ const t = s.replace(/[\p{C}\p{Zl}\p{Zp}]/gu, "").trim().slice(0, max);
39610
+ return t === "" ? void 0 : t;
39611
+ }
39612
+ function tokens(args) {
39613
+ if (args.target.kind !== "channel-connection") return void 0;
39614
+ const c = args.target.config;
39615
+ if (typeof c !== "object" || c === null) return {};
39616
+ const x = c;
39617
+ return {
39618
+ ...typeof x.botToken === "string" && x.botToken !== "" && { botToken: x.botToken },
39619
+ ...typeof x.appToken === "string" && x.appToken !== "" && { appToken: x.appToken }
39620
+ };
39621
+ }
39622
+ var NOT_A_CONNECTION = unknown({
39623
+ en: "This check applies to Slack channel connections only.",
39624
+ zh: "此检查只适用于 Slack 渠道连接。"
39625
+ });
39626
+ var NO_BOT_TOKEN = failing(
39627
+ { en: "No bot token is set on this connection.", zh: "这个渠道连接还没有填写机器人令牌。" },
39628
+ {
39629
+ en: "Install the app under Install App and copy the Bot User OAuth Token (xoxb-…) into the Bot token field.",
39630
+ zh: "在 Install App 安装应用,把 Bot User OAuth Token(xoxb-…)填进「机器人令牌」。"
39631
+ }
39632
+ );
39633
+ function botTokenCheck(opts) {
39634
+ return {
39635
+ place: "channel-connection",
39636
+ async run(args) {
39637
+ const t = tokens(args);
39638
+ if (t === void 0) return NOT_A_CONNECTION;
39639
+ if (t.botToken === void 0) return NO_BOT_TOKEN;
39640
+ const r = await slackCall(opts.apiUrl(), "auth.test", t.botToken, args.signal);
39641
+ if (r.kind !== "ok") {
39642
+ return r.kind === "error" && botTokenRefused(r.code) || notAnswered(r);
39643
+ }
39644
+ const problem = workspaceTokenProblem(r.body);
39645
+ if (problem !== void 0)
39646
+ return failing(
39647
+ {
39648
+ en: `${problem}.`,
39649
+ zh: "这个机器人令牌不是工作区令牌(来自组织级安装或企业 ID)。"
39650
+ },
39651
+ {
39652
+ en: "Install the app to one workspace (not org-wide) and copy that workspace's Bot User OAuth Token.",
39653
+ zh: "把应用安装到单个工作区(不要组织级安装),再复制该工作区的 Bot User OAuth Token。"
39654
+ }
39655
+ );
39656
+ if (typeof r.body.bot_id !== "string" || r.body.bot_id === "")
39657
+ return failing(
39658
+ {
39659
+ en: "Slack accepted the token, but it is not a bot token.",
39660
+ zh: "Slack 接受了该令牌,但它不是机器人令牌。"
39661
+ },
39662
+ {
39663
+ en: "Copy the Bot User OAuth Token (xoxb-…) from Install App into the Bot token field.",
39664
+ zh: "从 Install App 复制 Bot User OAuth Token(xoxb-…)填进「机器人令牌」。"
39665
+ }
39666
+ );
39667
+ const teamId = plain2(r.body.team_id, 32) ?? "";
39668
+ const team = plain2(r.body.team);
39669
+ const where = team !== void 0 ? `${team} (${teamId})` : teamId;
39670
+ return {
39671
+ status: "ok",
39672
+ reason: {
39673
+ en: `Slack accepted the bot token for workspace ${where}.`,
39674
+ zh: `Slack 接受了工作区 ${where} 的机器人令牌。`
39675
+ }
39676
+ };
39677
+ }
39678
+ };
39679
+ }
39680
+ function botScopesCheck(opts) {
39681
+ return {
39682
+ place: "channel-connection",
39683
+ async run(args) {
39684
+ const t = tokens(args);
39685
+ if (t === void 0) return NOT_A_CONNECTION;
39686
+ if (t.botToken === void 0)
39687
+ return unknown({
39688
+ en: "No bot token is set yet, so the scopes cannot be read.",
39689
+ zh: "还没有填写机器人令牌,无法读取权限。"
39690
+ });
39691
+ const r = await slackCall(opts.apiUrl(), "auth.test", t.botToken, args.signal);
39692
+ if (r.kind !== "ok") {
39693
+ if (r.kind === "error" && (REFUSED.has(r.code) || r.code === "not_allowed_token_type"))
39694
+ return unknown({
39695
+ en: `Slack refused the bot token (${r.code}), so the scopes cannot be read; see the bot token row.`,
39696
+ zh: `Slack 拒绝了机器人令牌(${r.code}),无法读取权限;请看「机器人令牌」一行。`
39697
+ });
39698
+ return notAnswered(r);
39699
+ }
39700
+ const header = r.headers.get("x-oauth-scopes");
39701
+ if (header === null)
39702
+ return unknown({
39703
+ en: "Slack did not report the token's scopes; check again later.",
39704
+ zh: "Slack 没有返回令牌的权限,请稍后再检查。"
39705
+ });
39706
+ const granted = new Set(
39707
+ header.split(",").map((s) => s.trim()).filter((s) => s !== "")
39708
+ );
39709
+ const missing = REQUIRED_BOT_SCOPES.filter((s) => !granted.has(s));
39710
+ if (missing.length > 0)
39711
+ return failing(
39712
+ {
39713
+ en: `The app is missing the bot scopes ${missing.join(", ")}.`,
39714
+ zh: `应用缺少机器人权限 ${missing.join("、")}。`
39715
+ },
39716
+ MANIFEST_FIX
39717
+ );
39718
+ return {
39719
+ status: "ok",
39720
+ reason: {
39721
+ en: `The bot token has all ${REQUIRED_BOT_SCOPES.length} scopes the manifest asks for.`,
39722
+ zh: `机器人令牌具备 manifest 要求的全部 ${REQUIRED_BOT_SCOPES.length} 项权限。`
39723
+ }
39724
+ };
39725
+ }
39726
+ };
39727
+ }
39728
+ var APP_TOKEN_FIX = {
39729
+ en: "Under Basic Information → App-Level Tokens choose Generate Token and Scopes, add the scope connections:write and copy the xapp-… token into the App-level token field.",
39730
+ zh: "在 Basic Information → App-Level Tokens 选择 Generate Token and Scopes,添加权限 connections:write,把 xapp-… 令牌填进「应用令牌」。"
39731
+ };
39732
+ function appTokenCheck(opts) {
39733
+ return {
39734
+ place: "channel-connection",
39735
+ async run(args) {
39736
+ const t = tokens(args);
39737
+ if (t === void 0) return NOT_A_CONNECTION;
39738
+ if (args.mode !== null && args.mode !== "long_connection")
39739
+ return unknown({
39740
+ en: "Webhook mode does not use an app-level token.",
39741
+ zh: "Webhook 模式不使用应用级令牌。"
39742
+ });
39743
+ if (t.appToken === void 0)
39744
+ return failing(
39745
+ {
39746
+ en: "No app-level token is set; Socket Mode needs one.",
39747
+ zh: "还没有填写应用令牌,Socket Mode 需要它。"
39748
+ },
39749
+ APP_TOKEN_FIX
39750
+ );
39751
+ const r = await slackCall(opts.apiUrl(), "apps.connections.open", t.appToken, args.signal);
39752
+ if (r.kind === "ok")
39753
+ return {
39754
+ status: "ok",
39755
+ reason: {
39756
+ en: "Slack accepted the app-level token and offered a Socket Mode connection.",
39757
+ zh: "Slack 接受了应用令牌,并提供了 Socket Mode 连接。"
39758
+ }
39759
+ };
39760
+ if (r.kind === "error") {
39761
+ if (REFUSED.has(r.code))
39762
+ return failing(
39763
+ {
39764
+ en: `Slack refused the app-level token (${r.code}); it may have been revoked.`,
39765
+ zh: `Slack 拒绝了应用令牌(${r.code}),令牌可能已被撤销。`
39766
+ },
39767
+ APP_TOKEN_FIX
39768
+ );
39769
+ if (r.code === "not_allowed_token_type")
39770
+ return failing(
39771
+ {
39772
+ en: "The App-level token field holds a token of the wrong type (not_allowed_token_type).",
39773
+ zh: "「应用令牌」中的令牌类型不对(not_allowed_token_type)。"
39774
+ },
39775
+ APP_TOKEN_FIX
39776
+ );
39777
+ if (r.code === "missing_scope")
39778
+ return failing(
39779
+ {
39780
+ en: "The app-level token lacks the scope connections:write (missing_scope).",
39781
+ zh: "应用令牌缺少权限 connections:write(missing_scope)。"
39782
+ },
39783
+ APP_TOKEN_FIX
39784
+ );
39785
+ }
39786
+ return notAnswered(r);
39787
+ }
39788
+ };
39789
+ }
39790
+
38963
39791
  // src/index.ts
38964
39792
  var index_default = defineExtension({
38965
39793
  name: "slack",
38966
- version: "0.1.0-rc.1",
39794
+ version: "0.1.0-rc.10",
38967
39795
  sdk: "^0.1.0-rc.0",
38968
39796
  provides: [CHANNEL_EXTENSION_POINT, IDENTITY_SOURCE_EXTENSION_POINT, DIRECTORY_EXTENSION_POINT],
38969
- permissions: { network: ["slack.com", "wss-primary.slack.com"] },
39797
+ permissions: {
39798
+ network: ["slack.com", "wss-primary.slack.com"],
39799
+ setupChecks: ["bot-token", "bot-scopes", "app-token"]
39800
+ },
38970
39801
  config: { deployment: SlackDeployment, org: SlackDirectoryConfig },
38971
39802
  setup(ctx) {
38972
39803
  const { apiUrl } = SlackDeployment.parse(ctx.config ?? {});
38973
39804
  ctx.provide(CHANNEL_EXTENSION_POINT, createSlackChannel({ apiUrl, log: ctx.log, kv: ctx.kv }));
38974
39805
  ctx.provide(IDENTITY_SOURCE_EXTENSION_POINT, createSlackIdentitySource());
38975
39806
  ctx.provide(DIRECTORY_EXTENSION_POINT, createSlackDirectory({ apiUrl }));
39807
+ const checks = { apiUrl: () => SlackDeployment.parse(ctx.config ?? {}).apiUrl };
39808
+ ctx.setup.check("bot-token", botTokenCheck(checks));
39809
+ ctx.setup.check("bot-scopes", botScopesCheck(checks));
39810
+ ctx.setup.check("app-token", appTokenCheck(checks));
38976
39811
  }
38977
39812
  });
38978
39813
  export {
38979
39814
  MIN_EDIT_INTERVAL_MS,
39815
+ REQUIRED_BOT_SCOPES,
38980
39816
  SlackConnection,
38981
39817
  SlackDeployment,
38982
39818
  SlackDirectoryConfig,
39819
+ appTokenCheck,
39820
+ botScopesCheck,
39821
+ botTokenCheck,
38983
39822
  createSlackChannel,
38984
39823
  createSlackDirectory,
38985
39824
  createSlackIdentitySource,