pi-quiver 6.13.2 → 6.14.1

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,718 @@ 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
+ var SLACK_TEXT_HARD_LIMIT = 4e4;
2464
+ function assertTextWithinLimit(text, limit = MAX_TEXT_LENGTH) {
2465
+ if (text !== void 0 && text.length > limit) {
2466
+ throw new SlackError(
2467
+ "text_too_long",
2468
+ `text is ${text.length} UTF-16 code units, over the ${limit} limit; use thread_body for announcements or slack_upload for documents.`
2469
+ );
2470
+ }
2471
+ }
2472
+ function requireResponseString(data, method, field) {
2473
+ const value = data[field];
2474
+ if (typeof value !== "string" || value === "") {
2475
+ throw new SlackError("unexpected_response", `${method} returned an unexpected response: missing "${field}".`);
2476
+ }
2477
+ return value;
2478
+ }
2479
+ async function withPermalink(deps, channel, ts) {
2480
+ try {
2481
+ const data = await deps.apiCall("chat.getPermalink", deps.token, { channel, message_ts: ts }, { retry: false, signal: deps.signal });
2482
+ return { permalink: typeof data.permalink === "string" ? data.permalink : void 0 };
2483
+ } catch (err) {
2484
+ const detail = err instanceof Error ? err.message : String(err);
2485
+ return { warning: `Could not fetch a permalink for this message: ${detail}` };
2486
+ }
2487
+ }
2488
+ async function postPlain(args, deps) {
2489
+ if (deps.identity === "bot") assertTextWithinLimit(args.text, SLACK_TEXT_HARD_LIMIT);
2490
+ else if (!(args.blocks && args.thread_ts !== void 0)) assertTextWithinLimit(args.text);
2491
+ const params = { channel: args.channel };
2492
+ if (args.text !== void 0) params.text = args.text;
2493
+ if (args.blocks !== void 0) params.blocks = args.blocks;
2494
+ if (args.thread_ts !== void 0) params.thread_ts = args.thread_ts;
2495
+ if (args.unfurl_links !== void 0) params.unfurl_links = args.unfurl_links;
2496
+ if (args.unfurl_media !== void 0) params.unfurl_media = args.unfurl_media;
2497
+ const data = await deps.apiCall("chat.postMessage", deps.token, params, { retry: true, signal: deps.signal });
2498
+ const channel = typeof data.channel === "string" ? data.channel : args.channel;
2499
+ const ts = requireResponseString(data, "chat.postMessage", "ts");
2500
+ const { permalink, warning } = await withPermalink(deps, channel, ts);
2501
+ return { channel, ts, permalink, warning };
2502
+ }
2503
+ async function uploadFile(args, deps) {
2504
+ const urlData = await deps.apiCall(
2505
+ "files.getUploadURLExternal",
2506
+ deps.token,
2507
+ { filename: args.filename, length: args.bytes.length },
2508
+ { retry: true, signal: deps.signal }
2509
+ );
2510
+ const uploadUrl = requireResponseString(urlData, "files.getUploadURLExternal", "upload_url");
2511
+ const fileId = requireResponseString(urlData, "files.getUploadURLExternal", "file_id");
2512
+ await deps.uploadBytes(uploadUrl, args.bytes, { signal: deps.signal });
2513
+ const fileEntry = { id: fileId };
2514
+ if (args.title !== void 0) fileEntry.title = args.title;
2515
+ const completeParams = {
2516
+ files: JSON.stringify([fileEntry]),
2517
+ channel_id: args.channel
2518
+ };
2519
+ if (args.thread_ts !== void 0) completeParams.thread_ts = args.thread_ts;
2520
+ if (args.initial_comment !== void 0) completeParams.initial_comment = args.initial_comment;
2521
+ const completeData = await deps.apiCall("files.completeUploadExternal", deps.token, completeParams, {
2522
+ retry: false,
2523
+ signal: deps.signal
2524
+ });
2525
+ const completedFiles = completeData.files;
2526
+ const permalink = typeof completedFiles?.[0]?.permalink === "string" ? completedFiles[0].permalink : void 0;
2527
+ const warning = permalink === void 0 ? "Could not find a permalink on the completed upload response." : void 0;
2528
+ return { channel: args.channel, fileId, permalink, warning };
2529
+ }
2530
+ var DETAIL_PENDING_MARKER = " _(detail pending)_";
2531
+ var DETAIL_INTRO = "Detail attached.";
2532
+ var DETAIL_FILENAME = "slack-detail.md";
2533
+ function linkCollapsedLength(text) {
2534
+ return text.replace(/<([^|>]+)\|([^>]+)>/g, "$2").replace(/<[^>]+>/g, "x").length;
2535
+ }
2536
+ function persistDetail(body, format = "md") {
2537
+ const dir = join5(tmpdir4(), "pi-slack");
2538
+ mkdirSync4(dir, { recursive: true });
2539
+ const hash = createHash2("sha256").update(body).digest("hex").slice(0, 8);
2540
+ const path = join5(dir, `${Date.now()}-${hash}-detail.${format}`);
2541
+ writeFileSync4(path, body, "utf8");
2542
+ return path;
2543
+ }
2544
+ function assertHeadline(text) {
2545
+ if (text.length === 0) {
2546
+ throw new SlackError("invalid_headline", "text is empty; announce requires a non-empty single-line headline.");
2547
+ }
2548
+ if (/\r?\n/.test(text)) {
2549
+ throw new SlackError("invalid_headline", "text must be a single line for an announce headline; use thread_body for the detail.");
2550
+ }
2551
+ assertTextWithinLimit(text);
2552
+ }
2553
+ async function deliverDetailUpload(channel, threadTs, body, deps) {
2554
+ const introData = await deps.apiCall(
2555
+ "chat.postMessage",
2556
+ deps.token,
2557
+ { channel, text: DETAIL_INTRO, thread_ts: threadTs },
2558
+ { retry: true, signal: deps.signal }
2559
+ );
2560
+ const detailTs = typeof introData.ts === "string" ? introData.ts : void 0;
2561
+ const bytes = new TextEncoder().encode(body);
2562
+ await uploadFile({ channel, bytes, filename: DETAIL_FILENAME, thread_ts: threadTs }, deps);
2563
+ return { detailTs };
2564
+ }
2565
+ function capitalize(s) {
2566
+ return s.length === 0 ? s : s.charAt(0).toUpperCase() + s.slice(1);
2567
+ }
2568
+ async function deliverDetailUploadOrPersist(channel, threadTs, body, deps) {
2569
+ try {
2570
+ return await deliverDetailUpload(channel, threadTs, body, deps);
2571
+ } catch (err) {
2572
+ const causeMessage = err instanceof Error ? err.message : String(err);
2573
+ const { detailPath, note } = persistOrDescribe(body, deps.persist ?? persistDetail);
2574
+ throw new SlackError(
2575
+ "detail_failed",
2576
+ `Threaded reply upload to ${channel} (thread_ts ${threadTs}) failed (${causeMessage}). ${capitalize(note)}.`,
2577
+ { channel, thread_ts: threadTs, ...detailPath ? { detailPath } : {} }
2578
+ );
2579
+ }
2580
+ }
2581
+ function persistOrDescribe(body, persist, format = "md", knownHeadline = true) {
2582
+ try {
2583
+ const detailPath = persist(body, format);
2584
+ 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` : "";
2585
+ return { detailPath, note: `the full detail was saved to ${detailPath}${format === "json" ? " (json)" : ""}${recovery}` };
2586
+ } catch (err) {
2587
+ const msg = err instanceof Error ? err.message : String(err);
2588
+ return {
2589
+ note: `persisting the ${body.length}-char detail ${format === "json" ? "payload" : "body"} ALSO failed (${msg}) - the detail is unrecoverable`
2590
+ };
2591
+ }
2592
+ }
2593
+ async function recoverFromDetailFailure(causeMessage, headlineText, detailBody, channel, ts, permalink, deps, persist, format = "md") {
2594
+ const { detailPath, note } = persistOrDescribe(detailBody, persist, format);
2595
+ let markerFailureMessage;
2596
+ try {
2597
+ await deps.apiCall(
2598
+ "chat.update",
2599
+ deps.token,
2600
+ { channel, ts, text: `${headlineText}${DETAIL_PENDING_MARKER}` },
2601
+ { retry: true, signal: deps.signal }
2602
+ );
2603
+ } catch (markerErr) {
2604
+ markerFailureMessage = markerErr instanceof Error ? markerErr.message : String(markerErr);
2605
+ }
2606
+ const markerSuffix = markerFailureMessage ? ` The headline marker edit also failed: ${markerFailureMessage}.` : "";
2607
+ const data = { ts, channel, permalink };
2608
+ if (detailPath) data.detailPath = detailPath;
2609
+ throw new SlackError(
2610
+ "detail_failed",
2611
+ `Detail post to the thread failed (${causeMessage}); the headline was marked "detail pending" and ${note}.${markerSuffix}`,
2612
+ data
2613
+ );
2614
+ }
2615
+ async function announce(args, deps) {
2616
+ assertHeadline(args.text);
2617
+ const persist = deps.persist ?? persistDetail;
2618
+ const detailFormat = args.blocks ? "json" : "md";
2619
+ const detailBody = args.blocks ? JSON.stringify({ text: args.thread_body, blocks: args.blocks }) : args.thread_body;
2620
+ const unfurl = {};
2621
+ if (deps.unfurl_links !== void 0) unfurl.unfurl_links = deps.unfurl_links;
2622
+ if (deps.unfurl_media !== void 0) unfurl.unfurl_media = deps.unfurl_media;
2623
+ let headlineData;
2624
+ try {
2625
+ headlineData = await deps.apiCall("chat.postMessage", deps.token, { channel: args.channel, text: args.text, ...unfurl }, { retry: false, signal: deps.signal });
2626
+ } catch (err) {
2627
+ if (err instanceof SlackError && err.code === "transport") {
2628
+ const { detailPath, note } = persistOrDescribe(detailBody, persist, detailFormat, false);
2629
+ throw new SlackError(
2630
+ "outcome_unknown",
2631
+ `Headline post to ${args.channel} may or may not have reached Slack (${err.message}); check the channel before re-invoking slack_post. ${capitalize(note)}.`,
2632
+ { channel: args.channel, ...detailPath ? { detailPath } : {} }
2633
+ );
2634
+ }
2635
+ throw err;
2636
+ }
2637
+ const channel = typeof headlineData.channel === "string" ? headlineData.channel : args.channel;
2638
+ let ts;
2639
+ try {
2640
+ ts = requireResponseString(headlineData, "chat.postMessage", "ts");
2641
+ } catch (err) {
2642
+ const { detailPath, note } = persistOrDescribe(detailBody, persist, detailFormat, false);
2643
+ const detail = err instanceof Error ? err.message : String(err);
2644
+ throw new SlackError(
2645
+ "outcome_unknown",
2646
+ `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)}.`,
2647
+ { channel, ...detailPath ? { detailPath } : {} }
2648
+ );
2649
+ }
2650
+ const { permalink, warning } = await withPermalink(deps, channel, ts);
2651
+ if (!args.blocks && linkCollapsedLength(args.thread_body) > deps.thresholdChars) {
2652
+ let detailTs2;
2653
+ try {
2654
+ ({ detailTs: detailTs2 } = await deliverDetailUpload(channel, ts, args.thread_body, deps));
2655
+ } catch (err) {
2656
+ const causeMessage = err instanceof Error ? err.message : String(err);
2657
+ return recoverFromDetailFailure(causeMessage, args.text, detailBody, channel, ts, permalink, deps, persist, detailFormat);
2658
+ }
2659
+ return { channel, ts, permalink, warning, detailTs: detailTs2, detailUploaded: true };
2660
+ }
2661
+ let detailData;
2662
+ try {
2663
+ detailData = await deps.apiCall(
2664
+ "chat.postMessage",
2665
+ deps.token,
2666
+ { channel, text: args.thread_body, thread_ts: ts, ...args.blocks ? { blocks: args.blocks } : {}, ...unfurl },
2667
+ { retry: true, signal: deps.signal }
2668
+ );
2669
+ } catch (err) {
2670
+ if (!args.blocks && err instanceof SlackError && err.code === "msg_too_long") {
2671
+ try {
2672
+ const { detailTs: detailTs2 } = await deliverDetailUpload(channel, ts, args.thread_body, deps);
2673
+ return { channel, ts, permalink, warning, detailTs: detailTs2, detailUploaded: true };
2674
+ } catch (uploadErr) {
2675
+ const causeMessage2 = uploadErr instanceof Error ? uploadErr.message : String(uploadErr);
2676
+ return recoverFromDetailFailure(causeMessage2, args.text, detailBody, channel, ts, permalink, deps, persist, detailFormat);
2677
+ }
2678
+ }
2679
+ const causeMessage = args.blocks && err instanceof SlackError && !err.message.startsWith(`${err.code}:`) ? `${err.code}: ${err.message}` : err instanceof Error ? err.message : String(err);
2680
+ return recoverFromDetailFailure(causeMessage, args.text, detailBody, channel, ts, permalink, deps, persist, detailFormat);
2681
+ }
2682
+ const detailTs = requireResponseString(detailData, "chat.postMessage", "ts");
2683
+ return { channel, ts, permalink, warning, detailTs };
2684
+ }
2685
+ async function postMessage(args, deps) {
2686
+ if (deps.identity === "bot" && args.thread_body === void 0) return postPlain(args, deps);
2687
+ if (args.thread_body !== void 0 && args.thread_ts === void 0) {
2688
+ return announce(
2689
+ { channel: args.channel, text: args.text ?? "", thread_body: args.thread_body, blocks: args.blocks },
2690
+ { ...deps, unfurl_links: args.unfurl_links, unfurl_media: args.unfurl_media }
2691
+ );
2692
+ }
2693
+ if (args.thread_ts !== void 0) {
2694
+ if (args.blocks !== void 0) {
2695
+ return postPlain(
2696
+ {
2697
+ channel: args.channel,
2698
+ text: args.thread_body ?? args.text,
2699
+ blocks: args.blocks,
2700
+ thread_ts: args.thread_ts,
2701
+ unfurl_links: args.unfurl_links,
2702
+ unfurl_media: args.unfurl_media
2703
+ },
2704
+ deps
2705
+ );
2706
+ }
2707
+ const body = args.thread_body ?? args.text ?? "";
2708
+ if (linkCollapsedLength(body) > deps.thresholdChars) {
2709
+ const { detailTs } = await deliverDetailUploadOrPersist(args.channel, args.thread_ts, body, deps);
2710
+ return { channel: args.channel, ts: args.thread_ts, detailTs };
2711
+ }
2712
+ try {
2713
+ return await postPlain(
2714
+ { channel: args.channel, text: body, thread_ts: args.thread_ts, unfurl_links: args.unfurl_links, unfurl_media: args.unfurl_media },
2715
+ deps
2716
+ );
2717
+ } catch (err) {
2718
+ if (err instanceof SlackError && (err.code === "text_too_long" || err.code === "msg_too_long")) {
2719
+ const { detailTs } = await deliverDetailUploadOrPersist(args.channel, args.thread_ts, body, deps);
2720
+ return { channel: args.channel, ts: args.thread_ts, detailTs };
2721
+ }
2722
+ throw err;
2723
+ }
2724
+ }
2725
+ return postPlain(
2726
+ { channel: args.channel, text: args.text, blocks: args.blocks, unfurl_links: args.unfurl_links, unfurl_media: args.unfurl_media },
2727
+ deps
2728
+ );
2729
+ }
2730
+
2074
2731
  // 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)';
2732
+ 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]
2733
+ pi-quiver slack reply --channel <id> --thread-ts <ts> (--text <t> | --text-file <path>) [--no-unfurl] [--as user|bot] [--token-from-env] [--dry-run]
2734
+ pi-quiver slack dm --user <id> (--text <t> | --text-file <path>) [--blocks-file <path>] [--no-unfurl] [--as user|bot] [--token-from-env] [--dry-run]
2735
+ pi-quiver slack canvas --id <id> --markdown-file <path> [--as user|bot] [--token-from-env] [--dry-run]
2736
+ User post text must be a one-line headline; bot post text may be multi-line. Dry-run validates credentials without network calls.
2737
+ Exit codes: 0 sent, 1 runtime error, 2 usage, 3 credential unavailable, 4 definitive failure, 5 outcome unknown.`;
2738
+ 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;
2739
+ function parseSlack(rest) {
2740
+ if (rest.length === 1 && rest[0] === "--help") return { ok: true, cmd: "slack-help" };
2741
+ const sub = rest[0];
2742
+ if (sub !== "post" && sub !== "reply" && sub !== "dm" && sub !== "canvas") return { ok: false, error: `unknown Slack command: ${sub ?? "(none)"}` };
2743
+ const allowed = {
2744
+ post: ["channel", "text", "detail", "detail-file", "blocks-file"],
2745
+ reply: ["channel", "thread-ts", "text", "text-file"],
2746
+ dm: ["user", "text", "text-file", "blocks-file"],
2747
+ canvas: ["id", "markdown-file"]
2748
+ }[sub];
2749
+ const booleans = {};
2750
+ const values = {};
2751
+ for (let i = 1; i < rest.length; i++) {
2752
+ const flag = rest[i];
2753
+ const key = flag.slice(2);
2754
+ if (flag === "--token-from-env") {
2755
+ booleans.tokenFromEnv = true;
2756
+ continue;
2757
+ }
2758
+ if (flag === "--dry-run") {
2759
+ booleans.dryRun = true;
2760
+ continue;
2761
+ }
2762
+ if (flag === "--no-unfurl" && sub !== "canvas") {
2763
+ booleans.noUnfurl = true;
2764
+ continue;
2765
+ }
2766
+ if (!flag.startsWith("--") || !(key === "as" || allowed.includes(key))) return { ok: false, error: `unexpected Slack argument: ${flag}` };
2767
+ const value = rest[++i];
2768
+ if (value === void 0 || value.startsWith("--")) return { ok: false, error: `${flag} requires a value` };
2769
+ values[key] = value;
2770
+ }
2771
+ if (values.as !== void 0 && values.as !== "user" && values.as !== "bot") return { ok: false, error: "--as must be user or bot" };
2772
+ for (const pair of [["text", "text-file"], ["detail", "detail-file"]]) {
2773
+ if (pair.every((k) => values[k] !== void 0)) return { ok: false, error: `--${pair[0]} and --${pair[1]} are exclusive` };
2774
+ }
2775
+ const required = sub === "post" ? ["channel", "text"] : sub === "reply" ? ["channel", "thread-ts"] : sub === "dm" ? ["user"] : ["id", "markdown-file"];
2776
+ for (const key of required) if (values[key] === void 0 || key !== "text" && !values[key]) return { ok: false, error: `missing --${key}` };
2777
+ if ((sub === "reply" || sub === "dm") && values.text === void 0 && values["text-file"] === void 0) return { ok: false, error: "missing --text or --text-file" };
2778
+ if (values.channel !== void 0 && !/^[CDG][A-Z0-9]+$/.test(values.channel)) return { ok: false, error: "--channel requires a raw channel ID" };
2779
+ if (values.user !== void 0 && !/^U[A-Z0-9]+$/.test(values.user)) return { ok: false, error: "--user requires a raw user ID" };
2780
+ const result = { ok: true, cmd: "slack", sub, as: values.as === "bot" ? "bot" : "user", ...booleans };
2781
+ for (const key of allowed) {
2782
+ if (values[key] !== void 0) Object.assign(result, { [key.replace(/-([a-z])/g, (_match, c) => c.toUpperCase())]: values[key] });
2783
+ }
2784
+ return result;
2785
+ }
2076
2786
  function parseDocToMd(rest) {
2077
2787
  if (rest.includes("--help") || rest.includes("-h")) return { ok: true, cmd: "doc-to-md-help" };
2078
2788
  const json = rest.includes("--json");
@@ -2113,18 +2823,18 @@ function cliAgentDir(env) {
2113
2823
  const home = env.HOME ?? env.USERPROFILE ?? homedir2();
2114
2824
  if (raw && raw.length > 0) {
2115
2825
  if (raw === "~") return home;
2116
- if (raw.startsWith("~/") || process.platform === "win32" && raw.startsWith("~\\")) return join4(home, raw.slice(2));
2826
+ if (raw.startsWith("~/") || process.platform === "win32" && raw.startsWith("~\\")) return join6(home, raw.slice(2));
2117
2827
  return raw;
2118
2828
  }
2119
- return join4(home, ".pi", "agent");
2829
+ return join6(home, ".pi", "agent");
2120
2830
  }
2121
2831
  function readCliSettings(cwd, env, warn) {
2122
2832
  const out = {};
2123
- for (const file of [join4(cliAgentDir(env), "settings.json"), join4(cwd, ".pi", "settings.json")]) {
2833
+ for (const file of [join6(cliAgentDir(env), "settings.json"), join6(cwd, ".pi", "settings.json")]) {
2124
2834
  if (!existsSync3(file)) continue;
2125
2835
  let raw;
2126
2836
  try {
2127
- raw = JSON.parse(readFileSync3(file, "utf8")).quiver?.docToMd;
2837
+ raw = JSON.parse(readFileSync5(file, "utf8")).quiver?.docToMd;
2128
2838
  } catch {
2129
2839
  warn(`pi-quiver: ${file} is not valid JSON; ignored.`);
2130
2840
  continue;
@@ -2141,6 +2851,8 @@ function readCliSettings(cwd, env, warn) {
2141
2851
  return out;
2142
2852
  }
2143
2853
  function parseCliArgs(argv) {
2854
+ if (argv.length === 1 && argv[0] === "--version") return { ok: true, cmd: "version" };
2855
+ if (argv[0] === "slack") return parseSlack(argv.slice(1));
2144
2856
  if (argv[0] === "doc-to-md") return parseDocToMd(argv.slice(1));
2145
2857
  if (argv[0] !== "fetch") return { ok: false, error: `unknown command: ${argv[0] ?? "(none)"}` };
2146
2858
  const rest = argv.slice(1);
@@ -2188,14 +2900,211 @@ function parseCliArgs(argv) {
2188
2900
  if (timeoutMs !== void 0) opts.timeoutMs = timeoutMs;
2189
2901
  return { ok: true, cmd: "fetch", opts };
2190
2902
  }
2903
+ function slackFailureCode(err, mutationStarted, method) {
2904
+ if (err instanceof SlackError) {
2905
+ if (err.code === "missing_token" || err.code === "credential_command_failed") return 3;
2906
+ if (err.code === "detail_failed") return 4;
2907
+ if (err.code === "outcome_unknown") return 5;
2908
+ if ((err.code === "transport" || err.code === "unexpected_response") && mutationStarted) return 5;
2909
+ if (method === "canvases.edit" && (err.code === "internal_error" || err.code === "fatal_error")) return 5;
2910
+ return 4;
2911
+ }
2912
+ return mutationStarted ? 5 : 1;
2913
+ }
2914
+ async function runSlack(parsed, deps) {
2915
+ let token;
2916
+ const redact = (text2) => token ? text2.split(token).join("<redacted>") : text2;
2917
+ const stdout = (text2) => deps.stdout(redact(text2));
2918
+ const stderr = (text2) => deps.stderr(redact(text2));
2919
+ let text = parsed.text;
2920
+ let detail = parsed.detail;
2921
+ let markdown;
2922
+ let blocks;
2923
+ const read = (path) => {
2924
+ try {
2925
+ return readFileSync5(resolve3(deps.cwd, path), "utf8");
2926
+ } catch {
2927
+ throw new Error(`cannot read file: ${path}`);
2928
+ }
2929
+ };
2930
+ try {
2931
+ if (parsed.textFile !== void 0) text = read(parsed.textFile);
2932
+ if (parsed.detailFile !== void 0) detail = read(parsed.detailFile);
2933
+ if (parsed.markdownFile !== void 0) markdown = read(parsed.markdownFile);
2934
+ if (parsed.blocksFile !== void 0) {
2935
+ const content = read(parsed.blocksFile);
2936
+ let value;
2937
+ try {
2938
+ value = JSON.parse(content);
2939
+ } catch {
2940
+ throw new Error(`invalid JSON array in --blocks-file: ${parsed.blocksFile}`);
2941
+ }
2942
+ if (!Array.isArray(value)) throw new Error(`--blocks-file must contain a JSON array: ${parsed.blocksFile}`);
2943
+ blocks = value;
2944
+ }
2945
+ if (parsed.sub === "post" && parsed.as === "user") assertHeadline(text ?? "");
2946
+ if (parsed.sub !== "canvas" && !text) throw new Error("text must not be empty");
2947
+ if (parsed.dryRun && (parsed.sub === "post" || parsed.sub === "dm" || parsed.sub === "reply" && parsed.as === "bot")) {
2948
+ assertTextWithinLimit(text, parsed.as === "bot" ? SLACK_TEXT_HARD_LIMIT : MAX_TEXT_LENGTH);
2949
+ }
2950
+ } catch (err) {
2951
+ stderr(`usage: ${err instanceof Error ? err.message : String(err)}
2952
+ ${USAGE}
2953
+ `);
2954
+ return 2;
2955
+ }
2956
+ let acknowledgedParent;
2957
+ let mutationStarted = false;
2958
+ let method;
2959
+ const trackedApiCall = async (name, credential, params, opts) => {
2960
+ method = name;
2961
+ if (["chat.postMessage", "canvases.edit", "files.getUploadURLExternal", "files.completeUploadExternal"].includes(name)) mutationStarted = true;
2962
+ return deps.apiCall(name, credential, params, opts);
2963
+ };
2964
+ const warnings = [];
2965
+ const flushWarnings = () => {
2966
+ for (const warning of warnings.splice(0)) stderr(`${warning}
2967
+ `);
2968
+ };
2969
+ try {
2970
+ const cfg = resolveSlackConfig(deps.cwd, deps.env, (message) => warnings.push(message), cliAgentDir(deps.env));
2971
+ if (parsed.tokenFromEnv) {
2972
+ const key = parsed.as === "user" ? cfg.userTokenEnv : cfg.botTokenEnv;
2973
+ token = deps.env[key];
2974
+ if (!token) throw new SlackError("missing_token", `No Slack ${parsed.as} token in process environment key ${key}`);
2975
+ } else {
2976
+ const repoRoot = discoverRepoRoot(deps.cwd);
2977
+ token = await resolveCredential(parsed.as, cfg, deps.env, repoRoot);
2978
+ }
2979
+ flushWarnings();
2980
+ if (parsed.dryRun) return 0;
2981
+ if (parsed.sub === "canvas") {
2982
+ await trackedApiCall("canvases.edit", token, {
2983
+ canvas_id: parsed.id,
2984
+ changes: [{ operation: "replace", document_content: { type: "markdown", markdown } }]
2985
+ }, { retry: true });
2986
+ stdout(`canvas=${parsed.id}
2987
+ `);
2988
+ return 0;
2989
+ }
2990
+ let channel = parsed.channel;
2991
+ if (parsed.sub === "dm") {
2992
+ const opened = await trackedApiCall("conversations.open", token, { users: parsed.user }, { retry: true });
2993
+ const id = opened.channel?.id;
2994
+ if (typeof id !== "string" || !id) throw new SlackError("unexpected_response", "conversations.open returned no channel.id");
2995
+ channel = id;
2996
+ }
2997
+ const unfurl = parsed.noUnfurl ? { unfurl_links: false, unfurl_media: false } : {};
2998
+ const coreDeps = { apiCall: trackedApiCall, uploadBytes: deps.uploadBytes, token, identity: parsed.as, thresholdChars: cfg.uploadThresholdChars };
2999
+ let result;
3000
+ if (parsed.sub === "post" && parsed.as === "bot" && /\r?\n/.test(text) && detail !== void 0) {
3001
+ const parent = await postMessage({ channel, text, ...unfurl }, coreDeps);
3002
+ acknowledgedParent = parent.ts;
3003
+ if (parent.warning) stderr(`${parent.warning}
3004
+ `);
3005
+ let detailFailure;
3006
+ const detailApiCall = async (...args) => {
3007
+ try {
3008
+ return await trackedApiCall(...args);
3009
+ } catch (error) {
3010
+ detailFailure = { error };
3011
+ throw error;
3012
+ }
3013
+ };
3014
+ const detailUploadBytes = async (...args) => {
3015
+ try {
3016
+ return await deps.uploadBytes(...args);
3017
+ } catch (error) {
3018
+ detailFailure = { error };
3019
+ throw error;
3020
+ }
3021
+ };
3022
+ let child;
3023
+ try {
3024
+ child = await postMessage({ channel: parent.channel, text: detail, thread_ts: parent.ts, ...blocks !== void 0 ? { blocks } : {}, ...unfurl }, { ...coreDeps, identity: void 0, apiCall: detailApiCall, uploadBytes: detailUploadBytes });
3025
+ } catch (error) {
3026
+ throw error instanceof SlackError && error.code === "detail_failed" && detailFailure ? detailFailure.error : error;
3027
+ }
3028
+ result = { ...parent, detailTs: child.detailTs ?? child.ts, warning: child.warning };
3029
+ } else result = await postMessage({
3030
+ channel,
3031
+ text,
3032
+ ...unfurl,
3033
+ ...blocks !== void 0 ? { blocks } : {},
3034
+ ...detail !== void 0 ? { thread_body: detail } : {},
3035
+ ...parsed.threadTs !== void 0 ? { thread_ts: parsed.threadTs } : {}
3036
+ }, coreDeps);
3037
+ if (result.warning) stderr(`${result.warning}
3038
+ `);
3039
+ 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");
3040
+ return 0;
3041
+ } catch (err) {
3042
+ flushWarnings();
3043
+ const code = slackFailureCode(err, mutationStarted, method);
3044
+ if (err instanceof SlackError) {
3045
+ let message = err.message.includes(err.code) ? err.message : `${err.code}: ${err.message}`;
3046
+ const hint = ERROR_HINTS[err.code];
3047
+ if (hint && !message.includes(hint)) message += `; ${hint}`;
3048
+ if (typeof err.data?.channel === "string") message += ` channel=${err.data.channel}`;
3049
+ stderr(`${message}
3050
+ `);
3051
+ if (code === 4) {
3052
+ const parent = acknowledgedParent ?? (err.code === "detail_failed" && typeof err.data?.ts === "string" ? err.data.ts : void 0);
3053
+ stdout(`${parent !== void 0 ? `ts=${parent} ` : ""}error=${err.code}
3054
+ `);
3055
+ }
3056
+ } else stderr(`slack failed: ${err instanceof Error ? err.message : String(err)}
3057
+ `);
3058
+ if (code === 5) stderr("Check the channel before retrying.\n");
3059
+ return code;
3060
+ }
3061
+ }
3062
+ function packageVersion() {
3063
+ let dir = dirname3(fileURLToPath2(import.meta.url));
3064
+ while (true) {
3065
+ const path = join6(dir, "package.json");
3066
+ if (existsSync3(path)) return JSON.parse(readFileSync5(path, "utf8")).version;
3067
+ const parent = dirname3(dir);
3068
+ if (parent === dir) throw new Error("No ancestor package.json found");
3069
+ dir = parent;
3070
+ }
3071
+ }
2191
3072
  async function main() {
2192
3073
  const parsed = parseCliArgs(process.argv.slice(2));
2193
3074
  if (!parsed.ok) {
2194
- process.stderr.write(`${parsed.error}
3075
+ process.stderr.write(`${process.argv[2] === "slack" ? "usage: " : ""}${parsed.error}
2195
3076
  ${USAGE}
2196
3077
  `);
2197
3078
  return 2;
2198
3079
  }
3080
+ if (parsed.cmd === "slack-help") {
3081
+ process.stdout.write(`${SLACK_HELP}
3082
+ `);
3083
+ return 0;
3084
+ }
3085
+ if (parsed.cmd === "version") {
3086
+ try {
3087
+ process.stdout.write(`${packageVersion()}
3088
+ `);
3089
+ return 0;
3090
+ } catch (err) {
3091
+ process.stderr.write(`${err instanceof Error ? err.message : String(err)}
3092
+ `);
3093
+ return 1;
3094
+ }
3095
+ }
3096
+ if (parsed.cmd === "slack") return runSlack(parsed, {
3097
+ env: process.env,
3098
+ cwd: process.cwd(),
3099
+ apiCall: defaultApiCall,
3100
+ uploadBytes: defaultUploadBytes,
3101
+ stdout: (text) => {
3102
+ process.stdout.write(text);
3103
+ },
3104
+ stderr: (text) => {
3105
+ process.stderr.write(text);
3106
+ }
3107
+ });
2199
3108
  if (parsed.cmd === "doc-to-md-help") {
2200
3109
  process.stdout.write(`${renderHelp()}
2201
3110
  `);
@@ -2266,5 +3175,6 @@ if (isMainEntry()) {
2266
3175
  export {
2267
3176
  cliAgentDir,
2268
3177
  parseCliArgs,
2269
- readCliSettings
3178
+ readCliSettings,
3179
+ runSlack
2270
3180
  };