pi-quiver 6.13.2 → 6.14.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.
@@ -554,9 +554,9 @@ var init_fetch_core = __esm({
554
554
 
555
555
  // bin/pi-quiver.ts
556
556
  init_fetch_core();
557
- import { existsSync as existsSync3, readFileSync as readFileSync3, realpathSync } from "node:fs";
557
+ import { existsSync as existsSync3, readFileSync as readFileSync5, realpathSync } from "node:fs";
558
558
  import { homedir as homedir2 } from "node:os";
559
- import { join as join4, resolve as resolve3 } from "node:path";
559
+ import { dirname as dirname3, join as join6, resolve as resolve3 } from "node:path";
560
560
  import { fileURLToPath as fileURLToPath2 } from "node:url";
561
561
 
562
562
  // lib/doc-to-md-core.ts
@@ -2071,8 +2071,715 @@ async function inspectDocument(o, signal, seams) {
2071
2071
  }
2072
2072
  }
2073
2073
 
2074
+ // lib/slack-core.ts
2075
+ import { execFile as execFile2, execFileSync } from "node:child_process";
2076
+ import { createHash as createHash2 } from "node:crypto";
2077
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync4 } from "node:fs";
2078
+ import { tmpdir as tmpdir4 } from "node:os";
2079
+ import { dirname as dirname2, join as join5 } from "node:path";
2080
+
2081
+ // lib/settings-core.ts
2082
+ import { readFileSync as readFileSync3 } from "node:fs";
2083
+ import { join as join4 } from "node:path";
2084
+ function readSettings(path) {
2085
+ try {
2086
+ return JSON.parse(readFileSync3(path, "utf8"));
2087
+ } catch {
2088
+ return void 0;
2089
+ }
2090
+ }
2091
+ function settingsPathsFor(agentDir, cwd) {
2092
+ return [join4(agentDir, "settings.json"), join4(cwd, ".pi", "settings.json")];
2093
+ }
2094
+ var LEGACY_FLAT_KEYS = /* @__PURE__ */ new Set(["fastMode", "sessionAutoName", "swordHeader", "providerStallWatchdog"]);
2095
+ var QUIVER_CONFIG_KEYS = {
2096
+ fastMode: ["enabled"],
2097
+ sessionAutoName: ["enabled", "ghosttyTab", "herdrTab", "rules", "deny", "revisitFirstTurn", "revisitEveryTurns"],
2098
+ swordHeader: ["enabled"],
2099
+ providerStallWatchdog: ["enabled", "firstEventMs", "warningMs", "recoveryMs", "maxStallRetries", "models"],
2100
+ slack: ["enabled", "cachePath", "policyPath", "userTokenEnv", "userTokenCommand", "userTokenCommandTimeoutSeconds", "botTokenEnv", "uploadThresholdChars"],
2101
+ docToMd: DOC_TO_MD_OPTIONS.filter((o) => o.settable).map((o) => o.key)
2102
+ };
2103
+ var isPlainObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
2104
+ var emittedWarnings = /* @__PURE__ */ new Set();
2105
+ function emitWarning(warn, message) {
2106
+ if (!warn || emittedWarnings.has(message)) return;
2107
+ emittedWarnings.add(message);
2108
+ warn(message);
2109
+ }
2110
+ function lintSettings(settings) {
2111
+ const lines = [];
2112
+ for (const key of Object.keys(settings)) if (LEGACY_FLAT_KEYS.has(key)) lines.push(`"${key}" at top level - move under "quiver"`);
2113
+ const root = settings.quiver;
2114
+ if (root === void 0) return lines;
2115
+ if (!isPlainObject(root)) return [...lines, `"quiver" is not an object - ignored`];
2116
+ const fieldLines = [];
2117
+ for (const [block, value] of Object.entries(root)) {
2118
+ if (!Object.hasOwn(QUIVER_CONFIG_KEYS, block)) {
2119
+ lines.push(`"quiver.${block}" - unknown block; accepted: ${Object.keys(QUIVER_CONFIG_KEYS).join(", ")}`);
2120
+ continue;
2121
+ }
2122
+ if (!isPlainObject(value)) continue;
2123
+ const fields = QUIVER_CONFIG_KEYS[block];
2124
+ for (const field of Object.keys(value)) if (!fields.includes(field)) fieldLines.push(`"quiver.${block}.${field}" - unknown; accepted: ${fields.join(", ")}`);
2125
+ }
2126
+ return [...lines, ...fieldLines];
2127
+ }
2128
+ function formatLint(findings) {
2129
+ const tail2 = "unknown or misplaced keys - unknown ones fall back to defaults";
2130
+ if (findings.length === 1) {
2131
+ const [path, lines] = findings[0];
2132
+ return [`pi-quiver settings (${path}): ${tail2}`, ...lines.map((l) => ` ${l}`)].join("\n");
2133
+ }
2134
+ return [`pi-quiver settings: ${tail2}`, ...findings.flatMap(([path, lines]) => [` ${path}`, ...lines.map((l) => ` ${l}`)])].join("\n");
2135
+ }
2136
+ function resolveConfigFrom(paths, key, defaults, coerce2, warn) {
2137
+ const cfg = { ...defaults };
2138
+ const findings = [];
2139
+ for (const path of paths) {
2140
+ const settings = readSettings(path);
2141
+ if (!settings) continue;
2142
+ const lines = lintSettings(settings);
2143
+ if (lines.length > 0) findings.push([path, lines]);
2144
+ const nested = isPlainObject(settings.quiver) ? settings.quiver : void 0;
2145
+ const hasNested = nested !== void 0 && Object.hasOwn(nested, key);
2146
+ const hasFlat = Object.hasOwn(settings, key);
2147
+ if (!hasNested && !(hasFlat && LEGACY_FLAT_KEYS.has(key))) continue;
2148
+ const candidate = hasNested ? nested[key] : settings[key];
2149
+ const patch = coerce2(candidate, (message) => emitWarning(warn, message));
2150
+ if (patch) Object.assign(cfg, patch);
2151
+ else emitWarning(warn, `pi-quiver: "${key}" in ${path} has an unrecognized value; ignored.`);
2152
+ }
2153
+ if (findings.length > 0) emitWarning(warn, formatLint(findings));
2154
+ return cfg;
2155
+ }
2156
+
2157
+ // lib/slack-core.ts
2158
+ var DEFAULT_SLACK_CONFIG = {
2159
+ enabled: false,
2160
+ cachePath: void 0,
2161
+ policyPath: void 0,
2162
+ userTokenEnv: "SLACK_USER_TOKEN",
2163
+ userTokenCommand: void 0,
2164
+ userTokenCommandTimeoutSeconds: 10,
2165
+ botTokenEnv: "SLACK_BOT_TOKEN",
2166
+ uploadThresholdChars: 4e3
2167
+ };
2168
+ var SlackError = class extends Error {
2169
+ code;
2170
+ data;
2171
+ constructor(code, message, data) {
2172
+ super(message);
2173
+ this.code = code;
2174
+ this.data = data;
2175
+ }
2176
+ };
2177
+ var MAX_TIMER_SECONDS = 2147483647e-3;
2178
+ function coerce(raw, warn) {
2179
+ if (typeof raw === "boolean") return { enabled: raw };
2180
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return void 0;
2181
+ const o = raw;
2182
+ const patch = {};
2183
+ if (typeof o.enabled === "boolean") patch.enabled = o.enabled;
2184
+ if (typeof o.cachePath === "string") patch.cachePath = o.cachePath;
2185
+ if (typeof o.policyPath === "string") patch.policyPath = o.policyPath;
2186
+ if (typeof o.userTokenEnv === "string") patch.userTokenEnv = o.userTokenEnv;
2187
+ if (Array.isArray(o.userTokenCommand) && typeof o.userTokenCommand[0] === "string" && o.userTokenCommand[0].length > 0 && o.userTokenCommand.every((part) => typeof part === "string")) {
2188
+ patch.userTokenCommand = [...o.userTokenCommand];
2189
+ }
2190
+ if (o.userTokenCommandTimeoutSeconds !== void 0) {
2191
+ if (typeof o.userTokenCommandTimeoutSeconds === "number" && Number.isFinite(o.userTokenCommandTimeoutSeconds) && o.userTokenCommandTimeoutSeconds > 0 && o.userTokenCommandTimeoutSeconds <= MAX_TIMER_SECONDS) {
2192
+ patch.userTokenCommandTimeoutSeconds = o.userTokenCommandTimeoutSeconds;
2193
+ } else {
2194
+ warn?.(
2195
+ `pi-quiver: quiver.slack.userTokenCommandTimeoutSeconds must be a positive finite number no greater than ${MAX_TIMER_SECONDS}; ignored.`
2196
+ );
2197
+ }
2198
+ }
2199
+ if (typeof o.botTokenEnv === "string") patch.botTokenEnv = o.botTokenEnv;
2200
+ if (typeof o.uploadThresholdChars === "number" && Number.isInteger(o.uploadThresholdChars) && o.uploadThresholdChars > 0) {
2201
+ patch.uploadThresholdChars = o.uploadThresholdChars;
2202
+ }
2203
+ return patch;
2204
+ }
2205
+ var emittedEnvWarnings = /* @__PURE__ */ new Set();
2206
+ function emitEnvWarning(warn, key, message) {
2207
+ if (!warn || emittedEnvWarnings.has(key)) return;
2208
+ emittedEnvWarnings.add(key);
2209
+ warn(message);
2210
+ }
2211
+ function parseBooleanEnv(value) {
2212
+ if (value === "true" || value === "1") return true;
2213
+ if (value === "false" || value === "0") return false;
2214
+ return void 0;
2215
+ }
2216
+ function parsePositiveIntEnv(value) {
2217
+ if (!/^\d+$/.test(value)) return void 0;
2218
+ const n = Number.parseInt(value, 10);
2219
+ return n > 0 ? n : void 0;
2220
+ }
2221
+ function applyEnvOverrides(cfg, env, warn) {
2222
+ const result = { ...cfg };
2223
+ const enabledRaw = env.PI_QUIVER_SLACK_ENABLED;
2224
+ if (enabledRaw !== void 0 && enabledRaw !== "") {
2225
+ const parsed = parseBooleanEnv(enabledRaw);
2226
+ if (parsed !== void 0) result.enabled = parsed;
2227
+ else emitEnvWarning(warn, "PI_QUIVER_SLACK_ENABLED", `pi-quiver: env var PI_QUIVER_SLACK_ENABLED has an unrecognized value; ignored.`);
2228
+ }
2229
+ const cachePathRaw = env.PI_QUIVER_SLACK_CACHE_PATH;
2230
+ if (cachePathRaw !== void 0 && cachePathRaw !== "") result.cachePath = cachePathRaw;
2231
+ const userTokenEnvRaw = env.PI_QUIVER_SLACK_USER_TOKEN_ENV;
2232
+ if (userTokenEnvRaw !== void 0 && userTokenEnvRaw !== "") result.userTokenEnv = userTokenEnvRaw;
2233
+ const botTokenEnvRaw = env.PI_QUIVER_SLACK_BOT_TOKEN_ENV;
2234
+ if (botTokenEnvRaw !== void 0 && botTokenEnvRaw !== "") result.botTokenEnv = botTokenEnvRaw;
2235
+ const uploadThresholdRaw = env.PI_QUIVER_SLACK_UPLOAD_THRESHOLD_CHARS;
2236
+ if (uploadThresholdRaw !== void 0 && uploadThresholdRaw !== "") {
2237
+ const parsed = parsePositiveIntEnv(uploadThresholdRaw);
2238
+ if (parsed !== void 0) result.uploadThresholdChars = parsed;
2239
+ else
2240
+ emitEnvWarning(
2241
+ warn,
2242
+ "PI_QUIVER_SLACK_UPLOAD_THRESHOLD_CHARS",
2243
+ `pi-quiver: env var PI_QUIVER_SLACK_UPLOAD_THRESHOLD_CHARS has an unrecognized value; ignored.`
2244
+ );
2245
+ }
2246
+ return result;
2247
+ }
2248
+ function resolveSlackConfig(cwd, env, warn, agentDir) {
2249
+ return applyEnvOverrides(resolveConfigFrom(settingsPathsFor(agentDir, cwd), "slack", DEFAULT_SLACK_CONFIG, coerce, warn), env, warn);
2250
+ }
2251
+ function discoverRepoRoot(cwd) {
2252
+ try {
2253
+ return execFileSync("git", ["rev-parse", "--show-toplevel"], { cwd, encoding: "utf8" }).trim();
2254
+ } catch {
2255
+ return cwd;
2256
+ }
2257
+ }
2258
+ function primaryCheckoutRoot(cwd) {
2259
+ try {
2260
+ const gitCommonDir = execFileSync("git", ["rev-parse", "--path-format=absolute", "--git-common-dir"], {
2261
+ cwd,
2262
+ encoding: "utf8"
2263
+ }).trim();
2264
+ return dirname2(gitCommonDir);
2265
+ } catch {
2266
+ return void 0;
2267
+ }
2268
+ }
2269
+ function parseEnvFile(content) {
2270
+ const result = /* @__PURE__ */ new Map();
2271
+ for (const line of content.split(/\r?\n/)) {
2272
+ const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(line);
2273
+ if (!match) continue;
2274
+ const [, key, rawValue] = match;
2275
+ let value = rawValue;
2276
+ if (value.length >= 2) {
2277
+ const first = value[0];
2278
+ const last = value[value.length - 1];
2279
+ if (first === "'" && last === "'" || first === '"' && last === '"') {
2280
+ value = value.slice(1, -1);
2281
+ }
2282
+ }
2283
+ result.set(key, value);
2284
+ }
2285
+ return result;
2286
+ }
2287
+ function userConfigEnvPath(env, platform = process.platform) {
2288
+ if (platform === "win32") {
2289
+ return env.APPDATA ? join5(env.APPDATA, "pi-quiver", ".env") : void 0;
2290
+ }
2291
+ if (env.XDG_CONFIG_HOME) return join5(env.XDG_CONFIG_HOME, "pi-quiver", ".env");
2292
+ if (env.HOME) return join5(env.HOME, ".config", "pi-quiver", ".env");
2293
+ return void 0;
2294
+ }
2295
+ function readEnvFile(path) {
2296
+ try {
2297
+ return parseEnvFile(readFileSync4(path, "utf8"));
2298
+ } catch (err) {
2299
+ if (err?.code === "ENOENT") return void 0;
2300
+ throw err;
2301
+ }
2302
+ }
2303
+ function resolveToken(identity, cfg, env, repoRoot, platform = process.platform) {
2304
+ const envVar = identity === "user" ? cfg.userTokenEnv : cfg.botTokenEnv;
2305
+ const fromEnv = env[envVar];
2306
+ if (fromEnv) return fromEnv;
2307
+ const candidates = [join5(repoRoot, ".env")];
2308
+ const primaryRoot = primaryCheckoutRoot(repoRoot);
2309
+ if (primaryRoot !== void 0 && primaryRoot !== repoRoot) candidates.push(join5(primaryRoot, ".env"));
2310
+ const userPath = userConfigEnvPath(env, platform);
2311
+ if (userPath !== void 0) candidates.push(userPath);
2312
+ for (const path of candidates) {
2313
+ const parsed = readEnvFile(path);
2314
+ const value = parsed?.get(envVar);
2315
+ if (value) return value;
2316
+ }
2317
+ throw new SlackError(
2318
+ "missing_token",
2319
+ `No Slack ${identity} token: env var ${envVar} is empty and no entry found in ${candidates.join(", ")}.`
2320
+ );
2321
+ }
2322
+ function runCredentialCommand(command, timeoutMs) {
2323
+ return new Promise((resolve4, reject) => {
2324
+ const [file, ...args] = command;
2325
+ execFile2(file, args, { timeout: timeoutMs, killSignal: "SIGKILL", maxBuffer: 64 * 1024, encoding: "utf8" }, (err, stdout) => {
2326
+ if (err) {
2327
+ const childError = err;
2328
+ if (childError.killed) {
2329
+ reject(new SlackError("credential_command_failed", `Slack user credential command timed out after ${timeoutMs}ms.`));
2330
+ return;
2331
+ }
2332
+ const status = typeof childError.code === "number" ? ` (status ${childError.code})` : "";
2333
+ reject(new SlackError("credential_command_failed", `Slack user credential command failed${status}.`));
2334
+ return;
2335
+ }
2336
+ const token = stdout.trim();
2337
+ if (!token) {
2338
+ reject(new SlackError("missing_token", "Slack user credential command returned no token."));
2339
+ return;
2340
+ }
2341
+ resolve4(token);
2342
+ });
2343
+ });
2344
+ }
2345
+ async function resolveCredential(identity, cfg, env, repoRoot, platform = process.platform) {
2346
+ if (identity === "user" && cfg.userTokenCommand) {
2347
+ return runCredentialCommand(cfg.userTokenCommand, Math.ceil(cfg.userTokenCommandTimeoutSeconds * 1e3));
2348
+ }
2349
+ return resolveToken(identity, cfg, env, repoRoot, platform);
2350
+ }
2351
+ var REQUEST_TIMEOUT_MS = 2e4;
2352
+ var MAX_RETRY_AFTER_MS = 3e4;
2353
+ var RETRY_AFTER_DEFAULT_S = 2;
2354
+ var JSON_METHODS = /* @__PURE__ */ new Set(["chat.postMessage", "chat.update", "canvases.edit"]);
2355
+ var ERROR_HINTS = {
2356
+ channel_not_found: "check the name or run slack_cache_refresh",
2357
+ not_in_channel: "invite the bot to the channel",
2358
+ msg_too_long: "message exceeds Slack's length ceiling",
2359
+ is_archived: "the channel is archived",
2360
+ edit_window_closed: "Slack's edit window for this message has closed",
2361
+ already_pinned: "the message is already pinned",
2362
+ not_pinnable: "this message type cannot be pinned",
2363
+ too_many_pins: "the channel has reached Slack's pin limit"
2364
+ };
2365
+ function mapSlackApiError(data) {
2366
+ const code = typeof data.error === "string" ? data.error : "unknown_error";
2367
+ if (code === "missing_scope") {
2368
+ const needed = typeof data.needed === "string" ? data.needed : "unknown";
2369
+ return new SlackError(
2370
+ code,
2371
+ `missing_scope: the token passed to this call does not have the "${needed}" scope.`,
2372
+ data
2373
+ );
2374
+ }
2375
+ const hint = ERROR_HINTS[code];
2376
+ const message = hint ? `${code}: ${hint}` : code;
2377
+ return new SlackError(code, message, data);
2378
+ }
2379
+ function buildRequest(baseUrl, method, token, params) {
2380
+ const url = `${baseUrl}/api/${method}`;
2381
+ const headers = { authorization: `Bearer ${token}` };
2382
+ if (JSON_METHODS.has(method)) {
2383
+ headers["content-type"] = "application/json";
2384
+ return { url, init: { method: "POST", headers, body: JSON.stringify(params) } };
2385
+ }
2386
+ const body = new URLSearchParams();
2387
+ for (const [key, value] of Object.entries(params)) {
2388
+ if (value !== void 0) body.set(key, String(value));
2389
+ }
2390
+ headers["content-type"] = "application/x-www-form-urlencoded";
2391
+ return { url, init: { method: "POST", headers, body: body.toString() } };
2392
+ }
2393
+ async function defaultSleep(ms, signal) {
2394
+ if (signal?.aborted) throw signal.reason ?? new DOMException("Aborted", "AbortError");
2395
+ return new Promise((resolve4, reject) => {
2396
+ let timer;
2397
+ const onAbort = () => {
2398
+ clearTimeout(timer);
2399
+ reject(signal.reason ?? new DOMException("Aborted", "AbortError"));
2400
+ };
2401
+ timer = setTimeout(() => {
2402
+ signal?.removeEventListener("abort", onAbort);
2403
+ resolve4();
2404
+ }, ms);
2405
+ signal?.addEventListener("abort", onAbort, { once: true });
2406
+ });
2407
+ }
2408
+ async function fetchOrTransportError(url, init, callerSignal, timeoutMs, describe) {
2409
+ if (callerSignal?.aborted) throw new SlackError("aborted", "Request was cancelled.");
2410
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
2411
+ const signal = callerSignal ? AbortSignal.any([callerSignal, timeoutSignal]) : timeoutSignal;
2412
+ try {
2413
+ return await fetch(url, { ...init, signal });
2414
+ } catch (err) {
2415
+ if (callerSignal?.aborted) throw new SlackError("aborted", "Request was cancelled.");
2416
+ const detail = timeoutSignal.aborted ? `timed out after ${timeoutMs}ms` : err.message;
2417
+ throw new SlackError("transport", describe(detail));
2418
+ }
2419
+ }
2420
+ function makeApiCall(baseUrl = "https://slack.com", sleep = defaultSleep, timeoutMs = REQUEST_TIMEOUT_MS) {
2421
+ async function performCall(method, token, params, opts, isRetry) {
2422
+ const { url, init } = buildRequest(baseUrl, method, token, params);
2423
+ const res = await fetchOrTransportError(
2424
+ url,
2425
+ init,
2426
+ opts.signal,
2427
+ timeoutMs,
2428
+ (detail) => `Slack API request to ${method} failed: ${detail}`
2429
+ );
2430
+ if (res.status === 429) {
2431
+ const rawRetryAfter = Number(res.headers.get("retry-after") ?? String(RETRY_AFTER_DEFAULT_S));
2432
+ const retryAfterSec = Number.isFinite(rawRetryAfter) && rawRetryAfter > 0 ? rawRetryAfter : RETRY_AFTER_DEFAULT_S;
2433
+ if (opts.retry && !isRetry) {
2434
+ const waitMs = Math.min(retryAfterSec * 1e3, MAX_RETRY_AFTER_MS);
2435
+ await sleep(waitMs, opts.signal);
2436
+ return performCall(method, token, params, opts, true);
2437
+ }
2438
+ throw new SlackError("rate_limited", `Slack rate-limited ${method}; retry after ${retryAfterSec}s.`);
2439
+ }
2440
+ if (!res.ok) {
2441
+ throw new SlackError(`http_${res.status}`, `Slack API ${method} returned HTTP ${res.status}.`);
2442
+ }
2443
+ const data = await res.json();
2444
+ if (data.ok === false) throw mapSlackApiError(data);
2445
+ return data;
2446
+ }
2447
+ return (method, token, params, opts = {}) => performCall(method, token, params, opts, false);
2448
+ }
2449
+ var defaultApiCall = makeApiCall();
2450
+ var defaultUploadBytes = async (url, bytes, opts) => {
2451
+ const res = await fetchOrTransportError(
2452
+ url,
2453
+ { method: "POST", body: bytes },
2454
+ opts?.signal,
2455
+ REQUEST_TIMEOUT_MS,
2456
+ (detail) => `Upload request failed: ${detail}`
2457
+ );
2458
+ if (!res.ok) {
2459
+ throw new SlackError(`http_${res.status}`, `Upload returned HTTP ${res.status}.`);
2460
+ }
2461
+ };
2462
+ var MAX_TEXT_LENGTH = 4e3;
2463
+ function assertTextWithinLimit(text) {
2464
+ if (text !== void 0 && text.length > MAX_TEXT_LENGTH) {
2465
+ throw new SlackError(
2466
+ "text_too_long",
2467
+ `text is ${text.length} UTF-16 code units, over the ${MAX_TEXT_LENGTH} limit; use thread_body for announcements or slack_upload for documents.`
2468
+ );
2469
+ }
2470
+ }
2471
+ function requireResponseString(data, method, field) {
2472
+ const value = data[field];
2473
+ if (typeof value !== "string" || value === "") {
2474
+ throw new SlackError("unexpected_response", `${method} returned an unexpected response: missing "${field}".`);
2475
+ }
2476
+ return value;
2477
+ }
2478
+ async function withPermalink(deps, channel, ts) {
2479
+ try {
2480
+ const data = await deps.apiCall("chat.getPermalink", deps.token, { channel, message_ts: ts }, { retry: false, signal: deps.signal });
2481
+ return { permalink: typeof data.permalink === "string" ? data.permalink : void 0 };
2482
+ } catch (err) {
2483
+ const detail = err instanceof Error ? err.message : String(err);
2484
+ return { warning: `Could not fetch a permalink for this message: ${detail}` };
2485
+ }
2486
+ }
2487
+ async function postPlain(args, deps) {
2488
+ if (!(args.blocks && args.thread_ts !== void 0)) assertTextWithinLimit(args.text);
2489
+ const params = { channel: args.channel };
2490
+ if (args.text !== void 0) params.text = args.text;
2491
+ if (args.blocks !== void 0) params.blocks = args.blocks;
2492
+ if (args.thread_ts !== void 0) params.thread_ts = args.thread_ts;
2493
+ if (args.unfurl_links !== void 0) params.unfurl_links = args.unfurl_links;
2494
+ if (args.unfurl_media !== void 0) params.unfurl_media = args.unfurl_media;
2495
+ const data = await deps.apiCall("chat.postMessage", deps.token, params, { retry: true, signal: deps.signal });
2496
+ const channel = typeof data.channel === "string" ? data.channel : args.channel;
2497
+ const ts = requireResponseString(data, "chat.postMessage", "ts");
2498
+ const { permalink, warning } = await withPermalink(deps, channel, ts);
2499
+ return { channel, ts, permalink, warning };
2500
+ }
2501
+ async function uploadFile(args, deps) {
2502
+ const urlData = await deps.apiCall(
2503
+ "files.getUploadURLExternal",
2504
+ deps.token,
2505
+ { filename: args.filename, length: args.bytes.length },
2506
+ { retry: true, signal: deps.signal }
2507
+ );
2508
+ const uploadUrl = requireResponseString(urlData, "files.getUploadURLExternal", "upload_url");
2509
+ const fileId = requireResponseString(urlData, "files.getUploadURLExternal", "file_id");
2510
+ await deps.uploadBytes(uploadUrl, args.bytes, { signal: deps.signal });
2511
+ const fileEntry = { id: fileId };
2512
+ if (args.title !== void 0) fileEntry.title = args.title;
2513
+ const completeParams = {
2514
+ files: JSON.stringify([fileEntry]),
2515
+ channel_id: args.channel
2516
+ };
2517
+ if (args.thread_ts !== void 0) completeParams.thread_ts = args.thread_ts;
2518
+ if (args.initial_comment !== void 0) completeParams.initial_comment = args.initial_comment;
2519
+ const completeData = await deps.apiCall("files.completeUploadExternal", deps.token, completeParams, {
2520
+ retry: false,
2521
+ signal: deps.signal
2522
+ });
2523
+ const completedFiles = completeData.files;
2524
+ const permalink = typeof completedFiles?.[0]?.permalink === "string" ? completedFiles[0].permalink : void 0;
2525
+ const warning = permalink === void 0 ? "Could not find a permalink on the completed upload response." : void 0;
2526
+ return { channel: args.channel, fileId, permalink, warning };
2527
+ }
2528
+ var DETAIL_PENDING_MARKER = " _(detail pending)_";
2529
+ var DETAIL_INTRO = "Detail attached.";
2530
+ var DETAIL_FILENAME = "slack-detail.md";
2531
+ function linkCollapsedLength(text) {
2532
+ return text.replace(/<([^|>]+)\|([^>]+)>/g, "$2").replace(/<[^>]+>/g, "x").length;
2533
+ }
2534
+ function persistDetail(body, format = "md") {
2535
+ const dir = join5(tmpdir4(), "pi-slack");
2536
+ mkdirSync4(dir, { recursive: true });
2537
+ const hash = createHash2("sha256").update(body).digest("hex").slice(0, 8);
2538
+ const path = join5(dir, `${Date.now()}-${hash}-detail.${format}`);
2539
+ writeFileSync4(path, body, "utf8");
2540
+ return path;
2541
+ }
2542
+ function assertHeadline(text) {
2543
+ if (text.length === 0) {
2544
+ throw new SlackError("invalid_headline", "text is empty; announce requires a non-empty single-line headline.");
2545
+ }
2546
+ if (/\r?\n/.test(text)) {
2547
+ throw new SlackError("invalid_headline", "text must be a single line for an announce headline; use thread_body for the detail.");
2548
+ }
2549
+ assertTextWithinLimit(text);
2550
+ }
2551
+ async function deliverDetailUpload(channel, threadTs, body, deps) {
2552
+ const introData = await deps.apiCall(
2553
+ "chat.postMessage",
2554
+ deps.token,
2555
+ { channel, text: DETAIL_INTRO, thread_ts: threadTs },
2556
+ { retry: true, signal: deps.signal }
2557
+ );
2558
+ const detailTs = typeof introData.ts === "string" ? introData.ts : void 0;
2559
+ const bytes = new TextEncoder().encode(body);
2560
+ await uploadFile({ channel, bytes, filename: DETAIL_FILENAME, thread_ts: threadTs }, deps);
2561
+ return { detailTs };
2562
+ }
2563
+ function capitalize(s) {
2564
+ return s.length === 0 ? s : s.charAt(0).toUpperCase() + s.slice(1);
2565
+ }
2566
+ async function deliverDetailUploadOrPersist(channel, threadTs, body, deps) {
2567
+ try {
2568
+ return await deliverDetailUpload(channel, threadTs, body, deps);
2569
+ } catch (err) {
2570
+ const causeMessage = err instanceof Error ? err.message : String(err);
2571
+ const { detailPath, note } = persistOrDescribe(body, deps.persist ?? persistDetail);
2572
+ throw new SlackError(
2573
+ "detail_failed",
2574
+ `Threaded reply upload to ${channel} (thread_ts ${threadTs}) failed (${causeMessage}). ${capitalize(note)}.`,
2575
+ { channel, thread_ts: threadTs, ...detailPath ? { detailPath } : {} }
2576
+ );
2577
+ }
2578
+ }
2579
+ function persistOrDescribe(body, persist, format = "md", knownHeadline = true) {
2580
+ try {
2581
+ const detailPath = persist(body, format);
2582
+ const recovery = format === "json" ? `${knownHeadline ? "; recover with saved text as thread_body and saved blocks using the known thread_ts" : "; locate the headline in the channel and obtain its ts before recovering with saved text as thread_body and saved blocks using that thread_ts"}; correct rejected blocks before recovery, preserving the original artifact` : "";
2583
+ return { detailPath, note: `the full detail was saved to ${detailPath}${format === "json" ? " (json)" : ""}${recovery}` };
2584
+ } catch (err) {
2585
+ const msg = err instanceof Error ? err.message : String(err);
2586
+ return {
2587
+ note: `persisting the ${body.length}-char detail ${format === "json" ? "payload" : "body"} ALSO failed (${msg}) - the detail is unrecoverable`
2588
+ };
2589
+ }
2590
+ }
2591
+ async function recoverFromDetailFailure(causeMessage, headlineText, detailBody, channel, ts, permalink, deps, persist, format = "md") {
2592
+ const { detailPath, note } = persistOrDescribe(detailBody, persist, format);
2593
+ let markerFailureMessage;
2594
+ try {
2595
+ await deps.apiCall(
2596
+ "chat.update",
2597
+ deps.token,
2598
+ { channel, ts, text: `${headlineText}${DETAIL_PENDING_MARKER}` },
2599
+ { retry: true, signal: deps.signal }
2600
+ );
2601
+ } catch (markerErr) {
2602
+ markerFailureMessage = markerErr instanceof Error ? markerErr.message : String(markerErr);
2603
+ }
2604
+ const markerSuffix = markerFailureMessage ? ` The headline marker edit also failed: ${markerFailureMessage}.` : "";
2605
+ const data = { ts, channel, permalink };
2606
+ if (detailPath) data.detailPath = detailPath;
2607
+ throw new SlackError(
2608
+ "detail_failed",
2609
+ `Detail post to the thread failed (${causeMessage}); the headline was marked "detail pending" and ${note}.${markerSuffix}`,
2610
+ data
2611
+ );
2612
+ }
2613
+ async function announce(args, deps) {
2614
+ assertHeadline(args.text);
2615
+ const persist = deps.persist ?? persistDetail;
2616
+ const detailFormat = args.blocks ? "json" : "md";
2617
+ const detailBody = args.blocks ? JSON.stringify({ text: args.thread_body, blocks: args.blocks }) : args.thread_body;
2618
+ const unfurl = {};
2619
+ if (deps.unfurl_links !== void 0) unfurl.unfurl_links = deps.unfurl_links;
2620
+ if (deps.unfurl_media !== void 0) unfurl.unfurl_media = deps.unfurl_media;
2621
+ let headlineData;
2622
+ try {
2623
+ headlineData = await deps.apiCall("chat.postMessage", deps.token, { channel: args.channel, text: args.text, ...unfurl }, { retry: false, signal: deps.signal });
2624
+ } catch (err) {
2625
+ if (err instanceof SlackError && err.code === "transport") {
2626
+ const { detailPath, note } = persistOrDescribe(detailBody, persist, detailFormat, false);
2627
+ throw new SlackError(
2628
+ "outcome_unknown",
2629
+ `Headline post to ${args.channel} may or may not have reached Slack (${err.message}); check the channel before re-invoking slack_post. ${capitalize(note)}.`,
2630
+ { channel: args.channel, ...detailPath ? { detailPath } : {} }
2631
+ );
2632
+ }
2633
+ throw err;
2634
+ }
2635
+ const channel = typeof headlineData.channel === "string" ? headlineData.channel : args.channel;
2636
+ let ts;
2637
+ try {
2638
+ ts = requireResponseString(headlineData, "chat.postMessage", "ts");
2639
+ } catch (err) {
2640
+ const { detailPath, note } = persistOrDescribe(detailBody, persist, detailFormat, false);
2641
+ const detail = err instanceof Error ? err.message : String(err);
2642
+ throw new SlackError(
2643
+ "outcome_unknown",
2644
+ `Headline post to ${channel} WAS accepted by Slack (ok:true) but the response was unparseable (${detail}); ${args.blocks ? "do NOT repost the headline - recover only into its thread" : "do NOT re-invoke slack_post - thread the detail manually"}. ${capitalize(note)}.`,
2645
+ { channel, ...detailPath ? { detailPath } : {} }
2646
+ );
2647
+ }
2648
+ const { permalink, warning } = await withPermalink(deps, channel, ts);
2649
+ if (!args.blocks && linkCollapsedLength(args.thread_body) > deps.thresholdChars) {
2650
+ let detailTs2;
2651
+ try {
2652
+ ({ detailTs: detailTs2 } = await deliverDetailUpload(channel, ts, args.thread_body, deps));
2653
+ } catch (err) {
2654
+ const causeMessage = err instanceof Error ? err.message : String(err);
2655
+ return recoverFromDetailFailure(causeMessage, args.text, detailBody, channel, ts, permalink, deps, persist, detailFormat);
2656
+ }
2657
+ return { channel, ts, permalink, warning, detailTs: detailTs2, detailUploaded: true };
2658
+ }
2659
+ let detailData;
2660
+ try {
2661
+ detailData = await deps.apiCall(
2662
+ "chat.postMessage",
2663
+ deps.token,
2664
+ { channel, text: args.thread_body, thread_ts: ts, ...args.blocks ? { blocks: args.blocks } : {}, ...unfurl },
2665
+ { retry: true, signal: deps.signal }
2666
+ );
2667
+ } catch (err) {
2668
+ if (!args.blocks && err instanceof SlackError && err.code === "msg_too_long") {
2669
+ try {
2670
+ const { detailTs: detailTs2 } = await deliverDetailUpload(channel, ts, args.thread_body, deps);
2671
+ return { channel, ts, permalink, warning, detailTs: detailTs2, detailUploaded: true };
2672
+ } catch (uploadErr) {
2673
+ const causeMessage2 = uploadErr instanceof Error ? uploadErr.message : String(uploadErr);
2674
+ return recoverFromDetailFailure(causeMessage2, args.text, detailBody, channel, ts, permalink, deps, persist, detailFormat);
2675
+ }
2676
+ }
2677
+ const causeMessage = args.blocks && err instanceof SlackError && !err.message.startsWith(`${err.code}:`) ? `${err.code}: ${err.message}` : err instanceof Error ? err.message : String(err);
2678
+ return recoverFromDetailFailure(causeMessage, args.text, detailBody, channel, ts, permalink, deps, persist, detailFormat);
2679
+ }
2680
+ const detailTs = requireResponseString(detailData, "chat.postMessage", "ts");
2681
+ return { channel, ts, permalink, warning, detailTs };
2682
+ }
2683
+ async function postMessage(args, deps) {
2684
+ if (args.thread_body !== void 0 && args.thread_ts === void 0) {
2685
+ return announce(
2686
+ { channel: args.channel, text: args.text ?? "", thread_body: args.thread_body, blocks: args.blocks },
2687
+ { ...deps, unfurl_links: args.unfurl_links, unfurl_media: args.unfurl_media }
2688
+ );
2689
+ }
2690
+ if (args.thread_ts !== void 0) {
2691
+ if (args.blocks !== void 0) {
2692
+ return postPlain(
2693
+ {
2694
+ channel: args.channel,
2695
+ text: args.thread_body ?? args.text,
2696
+ blocks: args.blocks,
2697
+ thread_ts: args.thread_ts,
2698
+ unfurl_links: args.unfurl_links,
2699
+ unfurl_media: args.unfurl_media
2700
+ },
2701
+ deps
2702
+ );
2703
+ }
2704
+ const body = args.thread_body ?? args.text ?? "";
2705
+ if (linkCollapsedLength(body) > deps.thresholdChars) {
2706
+ const { detailTs } = await deliverDetailUploadOrPersist(args.channel, args.thread_ts, body, deps);
2707
+ return { channel: args.channel, ts: args.thread_ts, detailTs };
2708
+ }
2709
+ try {
2710
+ return await postPlain(
2711
+ { channel: args.channel, text: body, thread_ts: args.thread_ts, unfurl_links: args.unfurl_links, unfurl_media: args.unfurl_media },
2712
+ deps
2713
+ );
2714
+ } catch (err) {
2715
+ if (err instanceof SlackError && (err.code === "text_too_long" || err.code === "msg_too_long")) {
2716
+ const { detailTs } = await deliverDetailUploadOrPersist(args.channel, args.thread_ts, body, deps);
2717
+ return { channel: args.channel, ts: args.thread_ts, detailTs };
2718
+ }
2719
+ throw err;
2720
+ }
2721
+ }
2722
+ return postPlain(
2723
+ { channel: args.channel, text: args.text, blocks: args.blocks, unfurl_links: args.unfurl_links, unfurl_media: args.unfurl_media },
2724
+ deps
2725
+ );
2726
+ }
2727
+
2074
2728
  // bin/pi-quiver.ts
2075
- var USAGE = 'Usage: pi-quiver fetch <url> [--method GET|HEAD|POST] [--header "K: V"]... [--body <str>] [--raw] [--timeout-ms <n>]\n pi-quiver doc-to-md [--json] [--info] [--page-images] [--words] [--pages <spec>] [--output-dir <dir>] [--overwrite] [--ocr] [--ocr-mode textless|all] [tunable flags] <path> (--help for all flags)';
2729
+ var SLACK_HELP = `pi-quiver slack post --channel <id> --text <text> [--detail <text> | --detail-file <path>] [--blocks-file <path>] [--no-unfurl] [--as user|bot] [--token-from-env] [--dry-run]
2730
+ pi-quiver slack reply --channel <id> --thread-ts <ts> (--text <t> | --text-file <path>) [--no-unfurl] [--as user|bot] [--token-from-env] [--dry-run]
2731
+ pi-quiver slack dm --user <id> (--text <t> | --text-file <path>) [--blocks-file <path>] [--no-unfurl] [--as user|bot] [--token-from-env] [--dry-run]
2732
+ pi-quiver slack canvas --id <id> --markdown-file <path> [--as user|bot] [--token-from-env] [--dry-run]
2733
+ User post text must be a one-line headline; bot post text may be multi-line. Dry-run validates credentials without network calls.
2734
+ Exit codes: 0 sent, 1 runtime error, 2 usage, 3 credential unavailable, 4 definitive failure, 5 outcome unknown.`;
2735
+ var USAGE = 'Usage: pi-quiver fetch <url> [--method GET|HEAD|POST] [--header "K: V"]... [--body <str>] [--raw] [--timeout-ms <n>]\n pi-quiver doc-to-md [--json] [--info] [--page-images] [--words] [--pages <spec>] [--output-dir <dir>] [--overwrite] [--ocr] [--ocr-mode textless|all] [tunable flags] <path> (--help for all flags)\n' + SLACK_HELP;
2736
+ function parseSlack(rest) {
2737
+ if (rest.length === 1 && rest[0] === "--help") return { ok: true, cmd: "slack-help" };
2738
+ const sub = rest[0];
2739
+ if (sub !== "post" && sub !== "reply" && sub !== "dm" && sub !== "canvas") return { ok: false, error: `unknown Slack command: ${sub ?? "(none)"}` };
2740
+ const allowed = {
2741
+ post: ["channel", "text", "detail", "detail-file", "blocks-file"],
2742
+ reply: ["channel", "thread-ts", "text", "text-file"],
2743
+ dm: ["user", "text", "text-file", "blocks-file"],
2744
+ canvas: ["id", "markdown-file"]
2745
+ }[sub];
2746
+ const booleans = {};
2747
+ const values = {};
2748
+ for (let i = 1; i < rest.length; i++) {
2749
+ const flag = rest[i];
2750
+ const key = flag.slice(2);
2751
+ if (flag === "--token-from-env") {
2752
+ booleans.tokenFromEnv = true;
2753
+ continue;
2754
+ }
2755
+ if (flag === "--dry-run") {
2756
+ booleans.dryRun = true;
2757
+ continue;
2758
+ }
2759
+ if (flag === "--no-unfurl" && sub !== "canvas") {
2760
+ booleans.noUnfurl = true;
2761
+ continue;
2762
+ }
2763
+ if (!flag.startsWith("--") || !(key === "as" || allowed.includes(key))) return { ok: false, error: `unexpected Slack argument: ${flag}` };
2764
+ const value = rest[++i];
2765
+ if (value === void 0 || value.startsWith("--")) return { ok: false, error: `${flag} requires a value` };
2766
+ values[key] = value;
2767
+ }
2768
+ if (values.as !== void 0 && values.as !== "user" && values.as !== "bot") return { ok: false, error: "--as must be user or bot" };
2769
+ for (const pair of [["text", "text-file"], ["detail", "detail-file"]]) {
2770
+ if (pair.every((k) => values[k] !== void 0)) return { ok: false, error: `--${pair[0]} and --${pair[1]} are exclusive` };
2771
+ }
2772
+ const required = sub === "post" ? ["channel", "text"] : sub === "reply" ? ["channel", "thread-ts"] : sub === "dm" ? ["user"] : ["id", "markdown-file"];
2773
+ for (const key of required) if (values[key] === void 0 || key !== "text" && !values[key]) return { ok: false, error: `missing --${key}` };
2774
+ if ((sub === "reply" || sub === "dm") && values.text === void 0 && values["text-file"] === void 0) return { ok: false, error: "missing --text or --text-file" };
2775
+ if (values.channel !== void 0 && !/^[CDG][A-Z0-9]+$/.test(values.channel)) return { ok: false, error: "--channel requires a raw channel ID" };
2776
+ if (values.user !== void 0 && !/^U[A-Z0-9]+$/.test(values.user)) return { ok: false, error: "--user requires a raw user ID" };
2777
+ const result = { ok: true, cmd: "slack", sub, as: values.as === "bot" ? "bot" : "user", ...booleans };
2778
+ for (const key of allowed) {
2779
+ if (values[key] !== void 0) Object.assign(result, { [key.replace(/-([a-z])/g, (_match, c) => c.toUpperCase())]: values[key] });
2780
+ }
2781
+ return result;
2782
+ }
2076
2783
  function parseDocToMd(rest) {
2077
2784
  if (rest.includes("--help") || rest.includes("-h")) return { ok: true, cmd: "doc-to-md-help" };
2078
2785
  const json = rest.includes("--json");
@@ -2113,18 +2820,18 @@ function cliAgentDir(env) {
2113
2820
  const home = env.HOME ?? env.USERPROFILE ?? homedir2();
2114
2821
  if (raw && raw.length > 0) {
2115
2822
  if (raw === "~") return home;
2116
- if (raw.startsWith("~/") || process.platform === "win32" && raw.startsWith("~\\")) return join4(home, raw.slice(2));
2823
+ if (raw.startsWith("~/") || process.platform === "win32" && raw.startsWith("~\\")) return join6(home, raw.slice(2));
2117
2824
  return raw;
2118
2825
  }
2119
- return join4(home, ".pi", "agent");
2826
+ return join6(home, ".pi", "agent");
2120
2827
  }
2121
2828
  function readCliSettings(cwd, env, warn) {
2122
2829
  const out = {};
2123
- for (const file of [join4(cliAgentDir(env), "settings.json"), join4(cwd, ".pi", "settings.json")]) {
2830
+ for (const file of [join6(cliAgentDir(env), "settings.json"), join6(cwd, ".pi", "settings.json")]) {
2124
2831
  if (!existsSync3(file)) continue;
2125
2832
  let raw;
2126
2833
  try {
2127
- raw = JSON.parse(readFileSync3(file, "utf8")).quiver?.docToMd;
2834
+ raw = JSON.parse(readFileSync5(file, "utf8")).quiver?.docToMd;
2128
2835
  } catch {
2129
2836
  warn(`pi-quiver: ${file} is not valid JSON; ignored.`);
2130
2837
  continue;
@@ -2141,6 +2848,8 @@ function readCliSettings(cwd, env, warn) {
2141
2848
  return out;
2142
2849
  }
2143
2850
  function parseCliArgs(argv) {
2851
+ if (argv.length === 1 && argv[0] === "--version") return { ok: true, cmd: "version" };
2852
+ if (argv[0] === "slack") return parseSlack(argv.slice(1));
2144
2853
  if (argv[0] === "doc-to-md") return parseDocToMd(argv.slice(1));
2145
2854
  if (argv[0] !== "fetch") return { ok: false, error: `unknown command: ${argv[0] ?? "(none)"}` };
2146
2855
  const rest = argv.slice(1);
@@ -2188,14 +2897,209 @@ function parseCliArgs(argv) {
2188
2897
  if (timeoutMs !== void 0) opts.timeoutMs = timeoutMs;
2189
2898
  return { ok: true, cmd: "fetch", opts };
2190
2899
  }
2900
+ function slackFailureCode(err, mutationStarted, method) {
2901
+ if (err instanceof SlackError) {
2902
+ if (err.code === "missing_token" || err.code === "credential_command_failed") return 3;
2903
+ if (err.code === "detail_failed") return 4;
2904
+ if (err.code === "outcome_unknown") return 5;
2905
+ if ((err.code === "transport" || err.code === "unexpected_response") && mutationStarted) return 5;
2906
+ if (method === "canvases.edit" && (err.code === "internal_error" || err.code === "fatal_error")) return 5;
2907
+ return 4;
2908
+ }
2909
+ return mutationStarted ? 5 : 1;
2910
+ }
2911
+ async function runSlack(parsed, deps) {
2912
+ let token;
2913
+ const redact = (text2) => token ? text2.split(token).join("<redacted>") : text2;
2914
+ const stdout = (text2) => deps.stdout(redact(text2));
2915
+ const stderr = (text2) => deps.stderr(redact(text2));
2916
+ let text = parsed.text;
2917
+ let detail = parsed.detail;
2918
+ let markdown;
2919
+ let blocks;
2920
+ const read = (path) => {
2921
+ try {
2922
+ return readFileSync5(resolve3(deps.cwd, path), "utf8");
2923
+ } catch {
2924
+ throw new Error(`cannot read file: ${path}`);
2925
+ }
2926
+ };
2927
+ try {
2928
+ if (parsed.textFile !== void 0) text = read(parsed.textFile);
2929
+ if (parsed.detailFile !== void 0) detail = read(parsed.detailFile);
2930
+ if (parsed.markdownFile !== void 0) markdown = read(parsed.markdownFile);
2931
+ if (parsed.blocksFile !== void 0) {
2932
+ const content = read(parsed.blocksFile);
2933
+ let value;
2934
+ try {
2935
+ value = JSON.parse(content);
2936
+ } catch {
2937
+ throw new Error(`invalid JSON array in --blocks-file: ${parsed.blocksFile}`);
2938
+ }
2939
+ if (!Array.isArray(value)) throw new Error(`--blocks-file must contain a JSON array: ${parsed.blocksFile}`);
2940
+ blocks = value;
2941
+ }
2942
+ if (parsed.sub === "post" && parsed.as === "user") assertHeadline(text ?? "");
2943
+ if (parsed.sub !== "canvas" && !text) throw new Error("text must not be empty");
2944
+ if (parsed.dryRun && (parsed.sub === "post" || parsed.sub === "dm")) assertTextWithinLimit(text);
2945
+ } catch (err) {
2946
+ stderr(`usage: ${err instanceof Error ? err.message : String(err)}
2947
+ ${USAGE}
2948
+ `);
2949
+ return 2;
2950
+ }
2951
+ let acknowledgedParent;
2952
+ let mutationStarted = false;
2953
+ let method;
2954
+ const trackedApiCall = async (name, credential, params, opts) => {
2955
+ method = name;
2956
+ if (["chat.postMessage", "canvases.edit", "files.getUploadURLExternal", "files.completeUploadExternal"].includes(name)) mutationStarted = true;
2957
+ return deps.apiCall(name, credential, params, opts);
2958
+ };
2959
+ const warnings = [];
2960
+ const flushWarnings = () => {
2961
+ for (const warning of warnings.splice(0)) stderr(`${warning}
2962
+ `);
2963
+ };
2964
+ try {
2965
+ const cfg = resolveSlackConfig(deps.cwd, deps.env, (message) => warnings.push(message), cliAgentDir(deps.env));
2966
+ if (parsed.tokenFromEnv) {
2967
+ const key = parsed.as === "user" ? cfg.userTokenEnv : cfg.botTokenEnv;
2968
+ token = deps.env[key];
2969
+ if (!token) throw new SlackError("missing_token", `No Slack ${parsed.as} token in process environment key ${key}`);
2970
+ } else {
2971
+ const repoRoot = discoverRepoRoot(deps.cwd);
2972
+ token = await resolveCredential(parsed.as, cfg, deps.env, repoRoot);
2973
+ }
2974
+ flushWarnings();
2975
+ if (parsed.dryRun) return 0;
2976
+ if (parsed.sub === "canvas") {
2977
+ await trackedApiCall("canvases.edit", token, {
2978
+ canvas_id: parsed.id,
2979
+ changes: [{ operation: "replace", document_content: { type: "markdown", markdown } }]
2980
+ }, { retry: true });
2981
+ stdout(`canvas=${parsed.id}
2982
+ `);
2983
+ return 0;
2984
+ }
2985
+ let channel = parsed.channel;
2986
+ if (parsed.sub === "dm") {
2987
+ const opened = await trackedApiCall("conversations.open", token, { users: parsed.user }, { retry: true });
2988
+ const id = opened.channel?.id;
2989
+ if (typeof id !== "string" || !id) throw new SlackError("unexpected_response", "conversations.open returned no channel.id");
2990
+ channel = id;
2991
+ }
2992
+ const unfurl = parsed.noUnfurl ? { unfurl_links: false, unfurl_media: false } : {};
2993
+ const coreDeps = { apiCall: trackedApiCall, uploadBytes: deps.uploadBytes, token, thresholdChars: cfg.uploadThresholdChars };
2994
+ let result;
2995
+ if (parsed.sub === "post" && parsed.as === "bot" && /\r?\n/.test(text) && detail !== void 0) {
2996
+ const parent = await postMessage({ channel, text, ...unfurl }, coreDeps);
2997
+ acknowledgedParent = parent.ts;
2998
+ if (parent.warning) stderr(`${parent.warning}
2999
+ `);
3000
+ let detailFailure;
3001
+ const detailApiCall = async (...args) => {
3002
+ try {
3003
+ return await trackedApiCall(...args);
3004
+ } catch (error) {
3005
+ detailFailure = { error };
3006
+ throw error;
3007
+ }
3008
+ };
3009
+ const detailUploadBytes = async (...args) => {
3010
+ try {
3011
+ return await deps.uploadBytes(...args);
3012
+ } catch (error) {
3013
+ detailFailure = { error };
3014
+ throw error;
3015
+ }
3016
+ };
3017
+ let child;
3018
+ try {
3019
+ child = await postMessage({ channel: parent.channel, text: detail, thread_ts: parent.ts, ...blocks !== void 0 ? { blocks } : {}, ...unfurl }, { ...coreDeps, apiCall: detailApiCall, uploadBytes: detailUploadBytes });
3020
+ } catch (error) {
3021
+ throw error instanceof SlackError && error.code === "detail_failed" && detailFailure ? detailFailure.error : error;
3022
+ }
3023
+ result = { ...parent, detailTs: child.detailTs ?? child.ts, warning: child.warning };
3024
+ } else result = await postMessage({
3025
+ channel,
3026
+ text,
3027
+ ...unfurl,
3028
+ ...blocks !== void 0 ? { blocks } : {},
3029
+ ...detail !== void 0 ? { thread_body: detail } : {},
3030
+ ...parsed.threadTs !== void 0 ? { thread_ts: parsed.threadTs } : {}
3031
+ }, coreDeps);
3032
+ if (result.warning) stderr(`${result.warning}
3033
+ `);
3034
+ stdout([result.ts !== void 0 ? `ts=${result.ts}` : void 0, result.permalink !== void 0 ? `permalink=${result.permalink}` : void 0, result.detailTs !== void 0 ? `detail_ts=${result.detailTs}` : void 0].filter((s) => s !== void 0).join(" ") + "\n");
3035
+ return 0;
3036
+ } catch (err) {
3037
+ flushWarnings();
3038
+ const code = slackFailureCode(err, mutationStarted, method);
3039
+ if (err instanceof SlackError) {
3040
+ let message = err.message.includes(err.code) ? err.message : `${err.code}: ${err.message}`;
3041
+ const hint = ERROR_HINTS[err.code];
3042
+ if (hint && !message.includes(hint)) message += `; ${hint}`;
3043
+ if (typeof err.data?.channel === "string") message += ` channel=${err.data.channel}`;
3044
+ stderr(`${message}
3045
+ `);
3046
+ if (code === 4) {
3047
+ const parent = acknowledgedParent ?? (err.code === "detail_failed" && typeof err.data?.ts === "string" ? err.data.ts : void 0);
3048
+ stdout(`${parent !== void 0 ? `ts=${parent} ` : ""}error=${err.code}
3049
+ `);
3050
+ }
3051
+ } else stderr(`slack failed: ${err instanceof Error ? err.message : String(err)}
3052
+ `);
3053
+ if (code === 5) stderr("Check the channel before retrying.\n");
3054
+ return code;
3055
+ }
3056
+ }
3057
+ function packageVersion() {
3058
+ let dir = dirname3(fileURLToPath2(import.meta.url));
3059
+ while (true) {
3060
+ const path = join6(dir, "package.json");
3061
+ if (existsSync3(path)) return JSON.parse(readFileSync5(path, "utf8")).version;
3062
+ const parent = dirname3(dir);
3063
+ if (parent === dir) throw new Error("No ancestor package.json found");
3064
+ dir = parent;
3065
+ }
3066
+ }
2191
3067
  async function main() {
2192
3068
  const parsed = parseCliArgs(process.argv.slice(2));
2193
3069
  if (!parsed.ok) {
2194
- process.stderr.write(`${parsed.error}
3070
+ process.stderr.write(`${process.argv[2] === "slack" ? "usage: " : ""}${parsed.error}
2195
3071
  ${USAGE}
2196
3072
  `);
2197
3073
  return 2;
2198
3074
  }
3075
+ if (parsed.cmd === "slack-help") {
3076
+ process.stdout.write(`${SLACK_HELP}
3077
+ `);
3078
+ return 0;
3079
+ }
3080
+ if (parsed.cmd === "version") {
3081
+ try {
3082
+ process.stdout.write(`${packageVersion()}
3083
+ `);
3084
+ return 0;
3085
+ } catch (err) {
3086
+ process.stderr.write(`${err instanceof Error ? err.message : String(err)}
3087
+ `);
3088
+ return 1;
3089
+ }
3090
+ }
3091
+ if (parsed.cmd === "slack") return runSlack(parsed, {
3092
+ env: process.env,
3093
+ cwd: process.cwd(),
3094
+ apiCall: defaultApiCall,
3095
+ uploadBytes: defaultUploadBytes,
3096
+ stdout: (text) => {
3097
+ process.stdout.write(text);
3098
+ },
3099
+ stderr: (text) => {
3100
+ process.stderr.write(text);
3101
+ }
3102
+ });
2199
3103
  if (parsed.cmd === "doc-to-md-help") {
2200
3104
  process.stdout.write(`${renderHelp()}
2201
3105
  `);
@@ -2266,5 +3170,6 @@ if (isMainEntry()) {
2266
3170
  export {
2267
3171
  cliAgentDir,
2268
3172
  parseCliArgs,
2269
- readCliSettings
3173
+ readCliSettings,
3174
+ runSlack
2270
3175
  };