pi-quiver 6.17.1 → 6.18.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.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,15 @@
3
3
  Format follows sibling pi packages (e.g. [`pi-condense`](https://github.com/jjuraszek/pi-condense/blob/main/CHANGELOG.md)):
4
4
  one entry per `vX.Y.Z` tag, newest first, terse bullets, dated.
5
5
 
6
+ ## v6.18.1 - 2026-12-01
7
+
8
+ - `slack_thread` shows cached authors as `@Display Name` in compact thread lines. Uncached authors keep their user IDs. (#49)
9
+
10
+ ## v6.18.0 - 2026-11-26
11
+
12
+ - `slack_thread` lists attachment names and file IDs on their message lines. `slack_download` saves one file by ID or Slack file link to a fresh temp folder or a directory you choose. (#47)
13
+ - On Windows, `doc_to_md` retries briefly locked staging deletes on Node 24.21.0 or later in the 24.x line and on Node 26.8.0 or later, so timed-out PDF conversions can fall back to text extraction. On older supported Node versions, the first locked delete fails the conversion.
14
+
6
15
  ## v6.17.1 - 2026-11-22
7
16
 
8
17
  - `message-timestamps` shows times as `2026-11-22 15:24` (`YYYY-MM-DD HH:mm`, local time zone, same for every system language) in the footer and the transcript. The footer no longer prefixes the time with `last message`.
package/README.md CHANGED
@@ -71,7 +71,7 @@ A 300 KB changelog page never touches your context window - you get a preview an
71
71
  | `extensions/sword-header.ts` | `/builtin-header` | Themed ASCII startup header replacing pi's default logo. OFF by default. |
72
72
  | `extensions/fast-mode.ts` | `/fast` | Inject Anthropic fast-mode (`speed: "fast"`, plus `anthropic-beta: fast-mode-2026-02-01` where the model needs it) into every Claude Fable 5.2 / Mythos 5.2 / Opus 5.5 / Opus 5 / Opus 4.8 request, any thinking level. `--fast` flag + `/fast [on\|off\|status]`. OFF by default. |
73
73
  | `extensions/provider-stall-watchdog.ts` | - | Opt-in provider-stall recovery, in two tiers: a pre-first-event deadline (`firstEventMs`, 20s) on every provider request in every mode, and the mid-stream pair (warn at 2 min, recover at 4 min) in TUI runs only. Each stall is aborted; while pi's `retry.enabled` is true and the stall retry budget (`maxStallRetries`, default = `retry.maxRetries`) remains, its aborted attempt is hidden from the model and re-driven by the watchdog after pi's backoff; behavior guide: [doc/provider-stall-watchdog.md](doc/provider-stall-watchdog.md). OFF by default. |
74
- | `extensions/slack.ts` | `slack_search`, `slack_thread`, `slack_post`, `slack_update`, `slack_delete`, `slack_pin`, `slack_upload`, `slack_cache_refresh` | Context-safe Slack search/threads/posting with dual `user`/`bot` token identities, Block Kit flattening and optional raw JSON output for threads, a workspace-keyed channel/user name->ID cache, DM targets by `@name` / user ID, fetch-style output size gating, and a transactional headline+detail-thread announce protocol with a documented recovery path. Pi registration is OFF by default. Behavior lives in `lib/slack-core.ts` and `lib/slack-cache.ts`; the [Slack CLI](doc/slack.md#cli) exposes `post`, `reply`, `dm`, and `canvas` without enabling pi registration. |
74
+ | `extensions/slack.ts` | `slack_search`, `slack_thread`, `slack_download`, `slack_post`, `slack_update`, `slack_delete`, `slack_pin`, `slack_upload`, `slack_cache_refresh` | Context-safe Slack search/threads/posting with dual `user`/`bot` token identities, Block Kit flattening and optional raw JSON output for threads, a workspace-keyed channel/user name->ID cache, DM targets by `@name` / user ID, fetch-style output size gating, and a transactional headline+detail-thread announce protocol with a documented recovery path. Pi registration is OFF by default. Behavior lives in `lib/slack-core.ts` and `lib/slack-cache.ts`; the [Slack CLI](doc/slack.md#cli) exposes `post`, `reply`, `dm`, and `canvas` without enabling pi registration. |
75
75
  | `prompts/rebase-worktree.md` | `/rebase-worktree [base]` | Prompt template, pi only. Rebases the current worktree onto `origin/<base>` (default `main`), resolves conflicts inline with the authorization stated in the prompt, runs only the tests that cover the resolved files, and reports the resolutions and fix commits. Never pushes; it syncs the branch so a later CI run or `/skill:gatekeep-pr` sees current `main`. |
76
76
  | `prompts/elevator.md` | `/elevator [ticket\|PR\|path\|topic\|free text]` | Outcome-first PM explanations and frank judgment. Takes a free-text subject or question; omitting it uses the prior discussion. Claude Code counterpart: `/quiver:elevator`, user-invoked only. |
77
77
 
@@ -104,7 +104,7 @@ Full routing rules, size-gate mechanics, and config: [doc/fetch.md](doc/fetch.md
104
104
 
105
105
  Published to npm as the unscoped `pi-quiver` package. Requires Node `^24.15.0 || >=26.0.0` (the floor `jsdom` 31 and `unpdf` 2 declare).
106
106
 
107
- Pi 0.99.0 or later is required for typed results from `doc_to_md`, `fetch`, `slack_thread`, and `slack_search`, and for the script-only cache refresh. With codemode enabled, scripts receive structured objects instead of rendered text. When Slack is enabled, refresh is reachable from codemode scripts only via `await tools.slack_cache_refresh({})`, not as a direct model tool. With `codemode.mode: "only"`, the host's inline catalog (default `codemode.inlineBudget`: 3000 tokens) does not have room for `doc_to_md` and `slack_post`; they stay callable, and a script can read their declaration with `await describeTool("doc_to_md")` or find them with `searchTools`. In the default mode `"on"`, nothing is omitted because direct tools are not listed in that catalog. The `pi-quiver` CLI does not require Pi.
107
+ Pi 0.99.0 or later is required for typed results from `doc_to_md`, `fetch`, `slack_thread`, `slack_search`, and `slack_download`, and for the script-only cache refresh. With codemode enabled, scripts receive structured objects instead of rendered text. When Slack is enabled, refresh is reachable from codemode scripts only via `await tools.slack_cache_refresh({})`, not as a direct model tool. With `codemode.mode: "only"`, the host's inline catalog (default `codemode.inlineBudget`: 3000 tokens) does not have room for `doc_to_md`, `slack_post`, and `slack_update`; they stay callable, and a script can read their declaration with `await describeTool("doc_to_md")` or find them with `searchTools`. In the default mode `"on"`, nothing is omitted because direct tools are not listed in that catalog. The `pi-quiver` CLI does not require Pi.
108
108
 
109
109
  **User scope** (all repos under your pi profile):
110
110
 
@@ -286,7 +286,7 @@ Operational notes:
286
286
  - **A watchdog abort that the provider ignores escalates after a fixed 10s.** Any post-abort stream event re-arms that deadline (bytes prove only that the connection was alive at that instant), so a stream that emits a straggler and then wedges still escalates 10s after its last event. This reduces the hang; it cannot force the provider to stop, and undici's timeouts remain the final backstop.
287
287
  - **Headless runs report on stderr.** In `print`/`json` mode pi binds a no-op UI, so watchdog notices go out via `console.warn`. Nothing is ever written to stdout, which `json` mode uses for its protocol. In TUI and RPC the notices render as main-window notifications, not the bottom status line.
288
288
 
289
- `slack` is OFF by default and, once enabled, adds eight `slack_*` tools (search, thread, post, update, delete, pin, upload, cache refresh) covering context-safe Slack search/threads/posting under dual `user`/`bot` token identities. Nested-only from day one (no legacy flat form):
289
+ `slack` is OFF by default and, once enabled, adds nine `slack_*` tools (search, thread, download, post, update, delete, pin, upload, cache refresh) covering context-safe Slack search/threads/posting under dual `user`/`bot` token identities. Nested-only from day one (no legacy flat form):
290
290
 
291
291
  ```json
292
292
  {
@@ -277,8 +277,8 @@ function binaryExtension(contentType) {
277
277
  return sub || "bin";
278
278
  }
279
279
  function writeChunk(stream, b) {
280
- return new Promise((resolve4, reject) => {
281
- stream.write(b, (err) => err ? reject(err) : resolve4());
280
+ return new Promise((resolve5, reject) => {
281
+ stream.write(b, (err) => err ? reject(err) : resolve5());
282
282
  });
283
283
  }
284
284
  async function pumpToFile(stream, reader, prefix, exhausted) {
@@ -302,7 +302,7 @@ async function pumpToFile(stream, reader, prefix, exhausted) {
302
302
  await writeChunk(stream, chunk);
303
303
  bytes += chunk.length;
304
304
  }
305
- await new Promise((resolve4, reject) => stream.end((err) => err ? reject(err) : resolve4()));
305
+ await new Promise((resolve5, reject) => stream.end((err) => err ? reject(err) : resolve5()));
306
306
  return { bytes, truncated };
307
307
  }
308
308
  async function collectBody(res, contentType, raw) {
@@ -562,7 +562,7 @@ var init_fetch_core = __esm({
562
562
  init_fetch_core();
563
563
  import { existsSync as existsSync3, readFileSync as readFileSync5, realpathSync } from "node:fs";
564
564
  import { homedir as homedir2 } from "node:os";
565
- import { dirname as dirname3, join as join6, resolve as resolve3 } from "node:path";
565
+ import { dirname as dirname3, join as join6, resolve as resolve4 } from "node:path";
566
566
  import { fileURLToPath as fileURLToPath2 } from "node:url";
567
567
 
568
568
  // lib/doc-to-md-core.ts
@@ -674,6 +674,9 @@ function openBundle(root, requested, overwrite) {
674
674
  throw e;
675
675
  }
676
676
  }
677
+ function removeStaging(path) {
678
+ fs.rmSync(path, { recursive: true, force: true, ...process.platform === "win32" ? { maxRetries: 3 } : {} });
679
+ }
677
680
  function publishStaged(b) {
678
681
  const out = /* @__PURE__ */ new Map();
679
682
  if (!existsSync(b.stagingDir)) return out;
@@ -682,7 +685,7 @@ function publishStaged(b) {
682
685
  if (!m) continue;
683
686
  const pageDir = join2(b.stagingDir, dir);
684
687
  if (!existsSync(join2(pageDir, ".done"))) {
685
- rmSync(pageDir, { recursive: true, force: true });
688
+ removeStaging(pageDir);
686
689
  continue;
687
690
  }
688
691
  const page = Number(m[1]);
@@ -703,7 +706,7 @@ function publishStaged(b) {
703
706
  names.push(name);
704
707
  });
705
708
  if (meta.native) meta.native = { ...meta.native, file: names[files.indexOf(meta.native.file)] ?? meta.native.file };
706
- rmSync(pageDir, { recursive: true, force: true });
709
+ removeStaging(pageDir);
707
710
  out.set(page, { files: names, meta });
708
711
  }
709
712
  return out;
@@ -738,7 +741,7 @@ function publishPageImages(b, pageCount) {
738
741
  b.pageManifest.add(name);
739
742
  b.sourceMap.set(`pages/${f}`, `pages/${name}`);
740
743
  }
741
- rmSync(b.pagesStagingDir, { recursive: true, force: true });
744
+ removeStaging(b.pagesStagingDir);
742
745
  }
743
746
  function writePageStats(b, stats) {
744
747
  writeFileSync2(b.pageStatsPath, `${JSON.stringify(stats, null, 2)}
@@ -776,7 +779,7 @@ function publishSidecars(b) {
776
779
  wordSidecars.set(Number(m[1]), join2(b.ocrDir, wfile));
777
780
  }
778
781
  }
779
- rmSync(b.ocrStagingDir, { recursive: true, force: true });
782
+ removeStaging(b.ocrStagingDir);
780
783
  return { sidecars, wordSidecars };
781
784
  }
782
785
  function publishAttachments(b) {
@@ -789,7 +792,7 @@ function publishAttachments(b) {
789
792
  b.attachmentManifest.add(name);
790
793
  b.sourceMap.set(`attachments/${f}`, `attachments/${name}`);
791
794
  }
792
- rmSync(b.attachmentsStagingDir, { recursive: true, force: true });
795
+ removeStaging(b.attachmentsStagingDir);
793
796
  }
794
797
  function rewriteLinks(md, sourceMap) {
795
798
  const images = md.replace(IMG_LINK_RE, (whole, mdAngle, mdPlain, htmlDouble, htmlSingle, htmlUnquoted) => {
@@ -821,23 +824,23 @@ function commitBundle(b, markdown) {
821
824
  writeFileSync2(tmp, markdown, "utf8");
822
825
  renameSync(tmp, b.mdPath);
823
826
  try {
824
- fs.rmSync(b.stagingDir, { recursive: true, force: true });
827
+ removeStaging(b.stagingDir);
825
828
  } catch {
826
829
  }
827
830
  try {
828
- fs.rmSync(b.sheetsStagingDir, { recursive: true, force: true });
831
+ removeStaging(b.sheetsStagingDir);
829
832
  } catch {
830
833
  }
831
834
  try {
832
- fs.rmSync(b.pagesStagingDir, { recursive: true, force: true });
835
+ removeStaging(b.pagesStagingDir);
833
836
  } catch {
834
837
  }
835
838
  try {
836
- fs.rmSync(b.attachmentsStagingDir, { recursive: true, force: true });
839
+ removeStaging(b.attachmentsStagingDir);
837
840
  } catch {
838
841
  }
839
842
  try {
840
- fs.rmSync(b.ocrStagingDir, { recursive: true, force: true });
843
+ removeStaging(b.ocrStagingDir);
841
844
  } catch {
842
845
  }
843
846
  try {
@@ -851,14 +854,14 @@ function abortBundle(b) {
851
854
  for (const f of b.pageManifest) rmSync(join2(b.pagesDir, f), { force: true });
852
855
  for (const f of b.attachmentManifest) rmSync(join2(b.attachmentsDir, f), { force: true });
853
856
  for (const f of b.ocrManifest) rmSync(join2(b.ocrDir, f), { force: true });
854
- rmSync(b.ocrStagingDir, { recursive: true, force: true });
857
+ removeStaging(b.ocrStagingDir);
855
858
  rmSync(b.pageStatsPath, { force: true });
856
859
  rmSync(b.wordsPath, { force: true });
857
860
  rmSync(`${b.mdPath}.tmp`, { force: true });
858
- rmSync(b.stagingDir, { recursive: true, force: true });
859
- rmSync(b.sheetsStagingDir, { recursive: true, force: true });
860
- rmSync(b.pagesStagingDir, { recursive: true, force: true });
861
- rmSync(b.attachmentsStagingDir, { recursive: true, force: true });
861
+ removeStaging(b.stagingDir);
862
+ removeStaging(b.sheetsStagingDir);
863
+ removeStaging(b.pagesStagingDir);
864
+ removeStaging(b.attachmentsStagingDir);
862
865
  rmSync(b.lockPath, { force: true });
863
866
  }
864
867
  function tempBundleRoot() {
@@ -1667,7 +1670,7 @@ var docxRemedy = `Remedy: install uv, or ${DOCX_PIP} into a Python that already
1667
1670
  var backendState = (b, missing) => b.kind === "none" ? b.reason : missing;
1668
1671
  var lacksDocx = (b) => b.kind === "none" || !b.docx;
1669
1672
  var clearStaging = (b) => {
1670
- for (const f of readdirSync2(b.stagingDir)) rmSync2(join3(b.stagingDir, f), { recursive: true, force: true });
1673
+ for (const f of readdirSync2(b.stagingDir)) removeStaging(join3(b.stagingDir, f));
1671
1674
  };
1672
1675
  var EXCEL_REMEDY = "Remedy: install uv, or pip install openpyxl xlrd pillow";
1673
1676
  function resolveUnpdfWorker(candidates, exists) {
@@ -1975,7 +1978,7 @@ async function convertDocument(o, signal, seams) {
1975
1978
  else {
1976
1979
  if (signal?.aborted) throw new Error("aborted");
1977
1980
  const keepPages = Object.fromEntries([...kept.entries()].map(([k, v]) => [String(k), v.files]));
1978
- rmSync2(b.pagesStagingDir, { recursive: true, force: true });
1981
+ removeStaging(b.pagesStagingDir);
1979
1982
  const f = await s.runTier("pdf-fallback", { ...pdfBase, keepPages }, b, signal, o.fallbackTimeoutMs, backend);
1980
1983
  publishStaged(b);
1981
1984
  if (f.ok && f.json.pageImages?.length) publishPageImages(b, f.json.pageCount ?? 0);
@@ -2088,7 +2091,7 @@ import { execFile as execFile2, execFileSync } from "node:child_process";
2088
2091
  import { createHash as createHash2 } from "node:crypto";
2089
2092
  import { mkdirSync as mkdirSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync4 } from "node:fs";
2090
2093
  import { tmpdir as tmpdir4 } from "node:os";
2091
- import { dirname as dirname2, join as join5 } from "node:path";
2094
+ import { dirname as dirname2, extname as extname4, join as join5, resolve as resolve3 } from "node:path";
2092
2095
 
2093
2096
  // lib/settings-core.ts
2094
2097
  import { readFileSync as readFileSync3 } from "node:fs";
@@ -2333,7 +2336,7 @@ function resolveToken(identity, cfg, env, repoRoot, platform = process.platform)
2333
2336
  );
2334
2337
  }
2335
2338
  function runCredentialCommand(command, timeoutMs) {
2336
- return new Promise((resolve4, reject) => {
2339
+ return new Promise((resolve5, reject) => {
2337
2340
  const [file, ...args] = command;
2338
2341
  execFile2(file, args, { timeout: timeoutMs, killSignal: "SIGKILL", maxBuffer: 64 * 1024, encoding: "utf8" }, (err, stdout) => {
2339
2342
  if (err) {
@@ -2351,7 +2354,7 @@ function runCredentialCommand(command, timeoutMs) {
2351
2354
  reject(new SlackError("missing_token", "Slack user credential command returned no token."));
2352
2355
  return;
2353
2356
  }
2354
- resolve4(token);
2357
+ resolve5(token);
2355
2358
  });
2356
2359
  });
2357
2360
  }
@@ -2404,7 +2407,7 @@ function buildRequest(baseUrl, method, token, params) {
2404
2407
  }
2405
2408
  async function defaultSleep(ms, signal) {
2406
2409
  if (signal?.aborted) throw signal.reason ?? new DOMException("Aborted", "AbortError");
2407
- return new Promise((resolve4, reject) => {
2410
+ return new Promise((resolve5, reject) => {
2408
2411
  let timer;
2409
2412
  const onAbort = () => {
2410
2413
  clearTimeout(timer);
@@ -2412,7 +2415,7 @@ async function defaultSleep(ms, signal) {
2412
2415
  };
2413
2416
  timer = setTimeout(() => {
2414
2417
  signal?.removeEventListener("abort", onAbort);
2415
- resolve4();
2418
+ resolve5();
2416
2419
  }, ms);
2417
2420
  signal?.addEventListener("abort", onAbort, { once: true });
2418
2421
  });
@@ -2934,7 +2937,7 @@ async function runSlack(parsed, deps) {
2934
2937
  let blocks;
2935
2938
  const read = (path) => {
2936
2939
  try {
2937
- return readFileSync5(resolve3(deps.cwd, path), "utf8");
2940
+ return readFileSync5(resolve4(deps.cwd, path), "utf8");
2938
2941
  } catch {
2939
2942
  throw new Error(`cannot read file: ${path}`);
2940
2943
  }
@@ -3128,7 +3131,7 @@ ${USAGE}
3128
3131
  const settings = readCliSettings(process.cwd(), process.env, (m) => process.stderr.write(`${m}
3129
3132
  `));
3130
3133
  const pc = parsed.perCall;
3131
- o = resolveOptions({ ...pc, path: resolve3(process.cwd(), pc.path), ...pc.outputDir ? { outputDir: resolve3(process.cwd(), pc.outputDir) } : {} }, settings, process.env);
3134
+ o = resolveOptions({ ...pc, path: resolve4(process.cwd(), pc.path), ...pc.outputDir ? { outputDir: resolve4(process.cwd(), pc.outputDir) } : {} }, settings, process.env);
3132
3135
  } catch (err) {
3133
3136
  if (err instanceof UsageError) {
3134
3137
  process.stderr.write(`${err.message}
@@ -3173,7 +3176,7 @@ ${USAGE}
3173
3176
  function isMainEntry() {
3174
3177
  if (!process.argv[1]) return false;
3175
3178
  try {
3176
- return realpathSync(fileURLToPath2(import.meta.url)) === realpathSync(resolve3(process.argv[1]));
3179
+ return realpathSync(fileURLToPath2(import.meta.url)) === realpathSync(resolve4(process.argv[1]));
3177
3180
  } catch {
3178
3181
  return false;
3179
3182
  }
@@ -1,23 +1,26 @@
1
1
  /**
2
2
  * Slack extension: opt-in, default-off. On `session_start` resolves
3
3
  * `quiver.slack`; if not enabled, registers zero tools (no `.env` read, no
4
- * network, no cache I/O). If enabled, registers the eight `slack_*` tools as
4
+ * network, no cache I/O). If enabled, registers the nine `slack_*` tools as
5
5
  * thin wrappers over lib/slack-core.ts and lib/slack-cache.ts.
6
6
  *
7
7
  * Toggling takes effect at the next session (registration-time gate, same
8
8
  * convention as the other opt-in extensions).
9
9
  */
10
10
 
11
- import { getAgentDir, type ExtensionAPI, type ExtensionContext, type Theme } from "@earendil-works/pi-coding-agent";
11
+ import { formatSize, getAgentDir, type ExtensionAPI, type ExtensionContext, type Theme } from "@earendil-works/pi-coding-agent";
12
12
  import { Text } from "@earendil-works/pi-tui";
13
13
  import { Type } from "@sinclair/typebox";
14
14
  import type { JsonValue } from "@earendil-works/pi-ai";
15
15
  import { createHash } from "node:crypto";
16
16
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
17
17
  import { tmpdir } from "node:os";
18
- import { basename, isAbsolute, join } from "node:path";
18
+ import { basename, isAbsolute, join, resolve } from "node:path";
19
19
  import {
20
20
  defaultApiCall,
21
+ defaultDownloadBytes,
22
+ downloadFile,
23
+ parseFileRef,
21
24
  defaultUploadBytes,
22
25
  INLINE_MAX_BYTES,
23
26
  INLINE_MAX_LINES,
@@ -346,7 +349,7 @@ export default function slackExtension(pi: ExtensionAPI) {
346
349
  Type.Object({ file: Type.String(), ...threadFields }),
347
350
  ]),
348
351
  description:
349
- 'Read a Slack thread via conversations.replies. Always uses the "user" identity (no `as` param). Provide either `channel` (#name, channel ID, @name, or user ID (DM)) plus `ts`, or a `permalink` (parsed for channel+ts). Paginates by cursor until Slack reports no more replies or a cap of 50 pages / 5,000 messages is hit; the result carries a `complete` flag and a resumable `next_cursor` when capped. Caveat: since 2025-05-29, conversations.replies is rate-limited to ~1 request/minute (limit capped at 15) for apps that are neither Marketplace-listed nor classified internal - hitting that throttle mid-pagination returns the messages collected so far plus a caveat and a resumable cursor instead of spinning. Default output is one line per message; messages with Block Kit blocks render those blocks flattened (blocks joined by " / ") instead of the text fallback. Compact lines render cached user mentions as `@Display Name` and labeled groups as `@handle`. Uncached user tokens keep their original text, including any label; an uncached rich-text user renders as `<@ID>`. `raw: true` changes only the text to a pure JSON array for block extraction and slack_update round-trips. Structured results carry `messages` (raw Slack objects) or `file` (a JSON array spill), plus `complete`, `next_cursor` when capped, `message_count`, and `caveat` when throttled, in either mode. Resume a capped read by passing `next_cursor` as `cursor`. Text and structured results are size-gated independently at 32KB/1000 lines; over the cap each writes its own temp file.',
352
+ 'Read a Slack thread as the user. Pass `permalink` or `channel` plus `ts`. Paginates to 50 pages / 5,000 messages; capped reads return a resumable cursor. A `files:` suffix lists each attachment by name and ID; slack_download saves one. Caveat: since 2025-05-29, conversations.replies is rate-limited to ~1 request/minute (limit capped at 15) for apps that are neither Marketplace-listed nor classified internal - hitting that throttle mid-pagination returns the messages collected so far plus a caveat and a resumable cursor instead of spinning. Default output is one line per message; messages with Block Kit blocks render those blocks flattened (blocks joined by " / ") instead of the text fallback. Compact lines render cached user mentions as `@Display Name` and labeled groups as `@handle`. Uncached user tokens keep their original text, including any label; an uncached rich-text user renders as `<@ID>`. `raw: true` changes only the text to a pure JSON array for block extraction and slack_update round-trips. Structured results carry `messages` (raw Slack objects) or `file` (a JSON array spill), plus `complete`, `next_cursor` when capped, `message_count`, and `caveat` when throttled, in either mode. Resume a capped read by passing `next_cursor` as `cursor`. Text and structured results are size-gated independently at 32KB/1000 lines; over the cap each writes its own temp file.',
350
353
  parameters: Type.Object({
351
354
  channel: Type.Optional(Type.String({ description: "#name, channel ID, @name, or user ID (DM)" })),
352
355
  ts: Type.Optional(Type.String({ description: "Thread parent timestamp" })),
@@ -380,6 +383,36 @@ export default function slackExtension(pi: ExtensionAPI) {
380
383
  renderResult: renderToolResult,
381
384
  });
382
385
 
386
+ pi.registerTool({
387
+ name: "slack_download",
388
+ label: "Slack Download",
389
+ promptSnippet: "Save a Slack attachment by file ID or link",
390
+ description: "Save one Slack-hosted file as the user. Pass a file ID from slack_thread or a Slack file link. Open the saved path with a file-read tool; contents are never inlined.",
391
+ parameters: Type.Object({
392
+ file: Type.String({ description: "Slack file ID or file link" }),
393
+ dir: Type.Optional(Type.String({ description: "Destination directory, relative to cwd or absolute. Defaults to a new temp directory." })),
394
+ }),
395
+ outputSchema: Type.Object({
396
+ path: Type.String(), file_id: Type.String(), name: Type.String(), mimetype: Type.Optional(Type.String()), size: Type.Number(),
397
+ }),
398
+ async execute(_toolCallId, params, signal) {
399
+ return guarded(async () => {
400
+ const fileId = parseFileRef(params.file);
401
+ const { deps } = await resolveCall("user", cfg, ctx, signal, repoRoot);
402
+ const dir = params.dir === undefined ? undefined : resolve(ctx.cwd, params.dir);
403
+ const result = await downloadFile({ fileId, dir }, { ...deps, downloadBytes: defaultDownloadBytes });
404
+ const name = result.name.replace(/[\s\p{Cc}]+/gu, " ");
405
+ const escapeLineBreaks = (value: string) => value.replace(/[\n\r\v\f\u0085\u2028\u2029]/g,
406
+ (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`);
407
+ const type = result.mimetype ? `, ${escapeLineBreaks(result.mimetype)}` : "";
408
+ const text = `Saved ${name} (${fileId}${type}, ${formatSize(result.size)}) to ${escapeLineBreaks(result.path)}`;
409
+ return { content: [{ type: "text" as const, text }], structuredContent: result, details: result };
410
+ }, "user");
411
+ },
412
+ renderCall: (_args, theme) => oneLine(theme, "slack_download", ""),
413
+ renderResult: renderToolResult,
414
+ });
415
+
383
416
  pi.registerTool({
384
417
  name: "slack_post",
385
418
  label: "Slack Post",
@@ -112,6 +112,11 @@ export function openBundle(root: string, requested: string, overwrite: boolean):
112
112
  export interface DoneMeta { native?: { file: string; width: number; height: number }; dpi?: number; requestedDpi?: number }
113
113
  export interface StagedPage { files: string[]; meta: DoneMeta }
114
114
 
115
+ export function removeStaging(path: string): void {
116
+ // Windows can still hold staging handles after the child tree is killed.
117
+ fs.rmSync(path, { recursive: true, force: true, ...(process.platform === "win32" ? { maxRetries: 3 } : {}) });
118
+ }
119
+
115
120
  /** Publish completed pages, retaining metadata with native filenames renamed; discard partial pages. */
116
121
  export function publishStaged(b: Bundle): Map<number, StagedPage> {
117
122
  const out = new Map<number, StagedPage>();
@@ -120,7 +125,7 @@ export function publishStaged(b: Bundle): Map<number, StagedPage> {
120
125
  const m = dir.match(/^p(\d+)$/);
121
126
  if (!m) continue;
122
127
  const pageDir = join(b.stagingDir, dir);
123
- if (!existsSync(join(pageDir, ".done"))) { rmSync(pageDir, { recursive: true, force: true }); continue; }
128
+ if (!existsSync(join(pageDir, ".done"))) { removeStaging(pageDir); continue; }
124
129
  const page = Number(m[1]);
125
130
  const raw = readFileSync(join(pageDir, ".done"), "utf8").trim();
126
131
  let meta: DoneMeta = {};
@@ -138,7 +143,7 @@ export function publishStaged(b: Bundle): Map<number, StagedPage> {
138
143
  names.push(name);
139
144
  });
140
145
  if (meta.native) meta.native = { ...meta.native, file: names[files.indexOf(meta.native.file)] ?? meta.native.file };
141
- rmSync(pageDir, { recursive: true, force: true });
146
+ removeStaging(pageDir);
142
147
  out.set(page, { files: names, meta });
143
148
  }
144
149
  return out;
@@ -178,7 +183,7 @@ export function publishPageImages(b: Bundle, pageCount: number): void {
178
183
  b.pageManifest.add(name);
179
184
  b.sourceMap.set(`pages/${f}`, `pages/${name}`);
180
185
  }
181
- rmSync(b.pagesStagingDir, { recursive: true, force: true });
186
+ removeStaging(b.pagesStagingDir);
182
187
  }
183
188
 
184
189
  export function writePageStats(b: Bundle, stats: PageStat[]): void {
@@ -220,7 +225,7 @@ export function publishSidecars(b: Bundle): { sidecars: Map<number, string>; wor
220
225
  wordSidecars.set(Number(m[1]), join(b.ocrDir, wfile));
221
226
  }
222
227
  }
223
- rmSync(b.ocrStagingDir, { recursive: true, force: true });
228
+ removeStaging(b.ocrStagingDir);
224
229
  return { sidecars, wordSidecars };
225
230
  }
226
231
 
@@ -234,7 +239,7 @@ export function publishAttachments(b: Bundle): void {
234
239
  b.attachmentManifest.add(name);
235
240
  b.sourceMap.set(`attachments/${f}`, `attachments/${name}`);
236
241
  }
237
- rmSync(b.attachmentsStagingDir, { recursive: true, force: true });
242
+ removeStaging(b.attachmentsStagingDir);
238
243
  }
239
244
 
240
245
  export function rewriteLinks(md: string, sourceMap: Map<string, string>): string {
@@ -268,11 +273,11 @@ export function commitBundle(b: Bundle, markdown: string): void {
268
273
  const tmp = `${b.mdPath}.tmp`;
269
274
  writeFileSync(tmp, markdown, "utf8");
270
275
  renameSync(tmp, b.mdPath);
271
- try { fs.rmSync(b.stagingDir, { recursive: true, force: true }); } catch { /* Markdown is published; cleanup is best-effort. */ }
272
- try { fs.rmSync(b.sheetsStagingDir, { recursive: true, force: true }); } catch { /* best-effort */ }
273
- try { fs.rmSync(b.pagesStagingDir, { recursive: true, force: true }); } catch { /* best-effort */ }
274
- try { fs.rmSync(b.attachmentsStagingDir, { recursive: true, force: true }); } catch { /* best-effort */ }
275
- try { fs.rmSync(b.ocrStagingDir, { recursive: true, force: true }); } catch { /* best-effort */ }
276
+ try { removeStaging(b.stagingDir); } catch { /* Markdown is published; cleanup is best-effort. */ }
277
+ try { removeStaging(b.sheetsStagingDir); } catch { /* best-effort */ }
278
+ try { removeStaging(b.pagesStagingDir); } catch { /* best-effort */ }
279
+ try { removeStaging(b.attachmentsStagingDir); } catch { /* best-effort */ }
280
+ try { removeStaging(b.ocrStagingDir); } catch { /* best-effort */ }
276
281
  try { fs.rmSync(b.lockPath, { force: true }); } catch { /* Markdown is published; cleanup is best-effort. */ }
277
282
  }
278
283
 
@@ -282,14 +287,14 @@ export function abortBundle(b: Bundle): void {
282
287
  for (const f of b.pageManifest) rmSync(join(b.pagesDir, f), { force: true });
283
288
  for (const f of b.attachmentManifest) rmSync(join(b.attachmentsDir, f), { force: true });
284
289
  for (const f of b.ocrManifest) rmSync(join(b.ocrDir, f), { force: true });
285
- rmSync(b.ocrStagingDir, { recursive: true, force: true });
290
+ removeStaging(b.ocrStagingDir);
286
291
  rmSync(b.pageStatsPath, { force: true });
287
292
  rmSync(b.wordsPath, { force: true });
288
293
  rmSync(`${b.mdPath}.tmp`, { force: true });
289
- rmSync(b.stagingDir, { recursive: true, force: true });
290
- rmSync(b.sheetsStagingDir, { recursive: true, force: true });
291
- rmSync(b.pagesStagingDir, { recursive: true, force: true });
292
- rmSync(b.attachmentsStagingDir, { recursive: true, force: true });
294
+ removeStaging(b.stagingDir);
295
+ removeStaging(b.sheetsStagingDir);
296
+ removeStaging(b.pagesStagingDir);
297
+ removeStaging(b.attachmentsStagingDir);
293
298
  rmSync(b.lockPath, { force: true });
294
299
  }
295
300
 
@@ -12,7 +12,7 @@ import { type ChildProcess, spawn } from "node:child_process";
12
12
  import { homedir, tmpdir } from "node:os";
13
13
  import { basename, dirname, extname, isAbsolute, join, resolve } from "node:path";
14
14
  import { fileURLToPath, pathToFileURL } from "node:url";
15
- import { type StagedPage, type Bundle, abortBundle, commitBundle, openBundle, publishAttachments, publishSidecars, publishWords, writePageStats, publishPageImages, publishSheetCsvs, publishSheetImages, publishStaged, rewriteLinks, tempBundleRoot, validateImageLinks } from "./doc-to-md-bundle.ts";
15
+ import { type StagedPage, type Bundle, abortBundle, commitBundle, openBundle, publishAttachments, publishSidecars, publishWords, writePageStats, publishPageImages, publishSheetCsvs, publishSheetImages, publishStaged, removeStaging, rewriteLinks, tempBundleRoot, validateImageLinks } from "./doc-to-md-bundle.ts";
16
16
  import { type BackendKind, type NativeImage, type Engine, type HandleData, type InfoData, type OcrInfo, type PageStat, type Tier, formatHandle, formatInfoHandle, scanOutline, type SheetInfo, type TocEntry } from "./doc-to-md-handle.ts";
17
17
  import { type DocToMdOptions, type InputType, IMAGE_EXTS, TUNABLE_DEFAULTS, UsageError, classifyInput, sanitizeStem } from "./doc-to-md-options.ts";
18
18
 
@@ -472,7 +472,7 @@ export const DOCX_PAGES_OFFICE = `--pages on a DOCX needs the Python DOCX backen
472
472
  const docxRemedy = `Remedy: install uv, or ${DOCX_PIP} into a Python that already has pymupdf4llm`;
473
473
  const backendState = (b: Backend, missing: string) => b.kind === "none" ? b.reason : missing;
474
474
  const lacksDocx = (b: Backend) => b.kind === "none" || !b.docx;
475
- const clearStaging = (b: Pick<Bundle, "stagingDir">) => { for (const f of readdirSync(b.stagingDir)) rmSync(join(b.stagingDir, f), { recursive: true, force: true }); };
475
+ const clearStaging = (b: Pick<Bundle, "stagingDir">) => { for (const f of readdirSync(b.stagingDir)) removeStaging(join(b.stagingDir, f)); };
476
476
  export const EXCEL_REMEDY = "Remedy: install uv, or pip install openpyxl xlrd pillow";
477
477
 
478
478
  export type Mode = "html" | "image" | "info" | "pdf-primary" | "pdf-fallback" | "xlsx" | "pdf-text" | "render-pages" | "docx" | "email" | "ocr-pages";
@@ -762,7 +762,7 @@ export async function convertDocument(o: DocToMdOptions, signal?: AbortSignal, s
762
762
  else {
763
763
  if (signal?.aborted) throw new Error("aborted");
764
764
  const keepPages = Object.fromEntries([...kept.entries()].map(([k, v]) => [String(k), v.files]));
765
- rmSync(b.pagesStagingDir, { recursive: true, force: true });
765
+ removeStaging(b.pagesStagingDir);
766
766
  const f = await s.runTier("pdf-fallback", { ...pdfBase, keepPages }, b, signal, o.fallbackTimeoutMs, backend);
767
767
  publishStaged(b);
768
768
  if (f.ok && f.json.pageImages?.length) publishPageImages(b, f.json.pageCount ?? 0);
package/lib/slack-core.ts CHANGED
@@ -12,8 +12,10 @@
12
12
  import { execFile, execFileSync } from "node:child_process";
13
13
  import { createHash } from "node:crypto";
14
14
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
15
+ import { lstat, mkdir, mkdtemp, open, rm, rmdir } from "node:fs/promises";
15
16
  import { tmpdir } from "node:os";
16
- import { dirname, join } from "node:path";
17
+ import { dirname, extname, join, resolve } from "node:path";
18
+ import { ReadableStream } from "node:stream/web";
17
19
  import { resolveConfigFrom, settingsPathsFor } from "./settings-core.ts";
18
20
 
19
21
  export interface SlackConfig {
@@ -283,8 +285,7 @@ export async function resolveCredential(
283
285
  }
284
286
 
285
287
  /**
286
- * Data-plane transport: every Slack API call and file upload funnels through
287
- * these two injectable functions so tests script responses without network.
288
+ * The JSON and byte transports are injectable so tests can script responses without network.
288
289
  * Retry policy lives with the caller (`opts.retry`), not the transport.
289
290
  */
290
291
 
@@ -306,6 +307,15 @@ export type ApiCall = (
306
307
 
307
308
  export type UploadBytes = (url: string, bytes: Uint8Array, opts?: { signal?: AbortSignal }) => Promise<void>;
308
309
 
310
+ export const DOWNLOAD_MAX_BYTES = 50_000_000;
311
+ export const DOWNLOAD_TIMEOUT_MS = 120_000;
312
+
313
+ export type DownloadBytes = (url: string, token: string, opts?: { signal?: AbortSignal }) => Promise<{
314
+ contentType: string | undefined;
315
+ body: AsyncIterable<Uint8Array>;
316
+ cancel: () => Promise<void>;
317
+ }>;
318
+
309
319
  const JSON_METHODS = new Set(["chat.postMessage", "chat.update", "canvases.edit"]);
310
320
 
311
321
  export const ERROR_HINTS: Record<string, string> = {
@@ -451,6 +461,43 @@ export const defaultUploadBytes: UploadBytes = async (url, bytes, opts) => {
451
461
  }
452
462
  };
453
463
 
464
+ export const defaultDownloadBytes: DownloadBytes = async (url, token, opts) => {
465
+ const res = await fetchOrTransportError(
466
+ url, { method: "GET", headers: { authorization: `Bearer ${token}` }, redirect: "manual" },
467
+ opts?.signal, DOWNLOAD_TIMEOUT_MS, () => "Slack file request failed or timed out.",
468
+ );
469
+ const stream = res.body ?? ReadableStream.from<Uint8Array>([]);
470
+ let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
471
+ const cancel = async () => {
472
+ const cancelling = reader ? reader.cancel() : stream.cancel();
473
+ reader?.releaseLock();
474
+ reader = undefined;
475
+ await cancelling.catch(() => {});
476
+ };
477
+ if (res.status !== 200) {
478
+ await cancel();
479
+ if (res.status >= 300 && res.status < 400) {
480
+ const location = res.headers.get("location");
481
+ const host = location ? URL.parse(location, url)?.host : undefined;
482
+ throw new SlackError("file_auth_redirect", `Slack file host returned a redirect${host ? ` to ${host}` : ""}.`);
483
+ }
484
+ throw new SlackError(`http_${res.status}`, `Slack file host returned HTTP ${res.status}.`);
485
+ }
486
+ const body = (async function* () {
487
+ reader = stream.getReader();
488
+ try {
489
+ while (reader) {
490
+ const chunk = await reader.read();
491
+ if (chunk.done) return;
492
+ yield chunk.value;
493
+ }
494
+ } finally {
495
+ await cancel();
496
+ }
497
+ })();
498
+ return { contentType: res.headers.get("content-type") ?? undefined, body, cancel };
499
+ };
500
+
454
501
  /**
455
502
  * Size gating for slack_search / slack_thread output: same thresholds as
456
503
  * fetch-core, defined locally to avoid a cross-module dependency. Output
@@ -687,12 +734,25 @@ export function renderBlocks(blocks: unknown[], userNames?: UserNames): string {
687
734
  .replace(/\r?\n/g, " ");
688
735
  }
689
736
 
737
+ function threadFilesSuffix(files: unknown): string {
738
+ if (!Array.isArray(files)) return "";
739
+ const labels: string[] = [];
740
+ for (const file of files) {
741
+ if (typeof file?.id !== "string" || !file.id) continue;
742
+ const name = [file.name, file.title].find((s) => typeof s === "string" && s.length > 0) ?? "untitled";
743
+ labels.push(`${name.replace(/[\s\p{Cc}]+/gu, " ")} (${file.id})`);
744
+ }
745
+ return labels.length ? ` | files: ${labels.join(", ")}` : "";
746
+ }
747
+
690
748
  function renderThreadLine(message: Record<string, unknown>, userNames?: UserNames): string {
691
- const author = typeof message.user === "string" ? message.user : String(message.username ?? "unknown");
749
+ const author = typeof message.user === "string"
750
+ ? compactUserMention(message.user, userNames, message.user).replace(/[\s\p{Cc}]+/gu, " ")
751
+ : String(message.username ?? "unknown");
692
752
  const ts = String(message.ts ?? "");
693
753
  const flattened = Array.isArray(message.blocks) ? renderBlocks(message.blocks, userNames) : "";
694
754
  const body = flattened || compactMessageText(message, userNames);
695
- return `${author} | ${ts} | ${body}`;
755
+ return `${author} | ${ts} | ${body}${threadFilesSuffix(message.files)}`;
696
756
  }
697
757
 
698
758
  export async function readThread(
@@ -876,6 +936,133 @@ export async function pinMessage(args: { channel: string; ts: string }, deps: Co
876
936
  return { channel: args.channel, ts: args.ts, permalink, warning };
877
937
  }
878
938
 
939
+ export function parseFileRef(input: string): string {
940
+ const ref = input.trim();
941
+ if (/^F[A-Z0-9]+$/.test(ref)) return ref;
942
+ const url = URL.parse(ref);
943
+ if (url?.protocol === "https:") {
944
+ const path = url.pathname;
945
+ if (url.host === "slack.com" || url.host.endsWith(".slack.com")) {
946
+ const id = /^\/files\/[^/]+\/(F[A-Z0-9]+)(?:\/|$)/.exec(path)?.[1]
947
+ ?? /^\/files-pri\/[^/-]+-(F[A-Z0-9]+)(?:\/|$)/.exec(path)?.[1];
948
+ if (id) return id;
949
+ } else if (url.host === "slack-files.com") {
950
+ const id = /^\/[^/-]+-(F[A-Z0-9]+)-[^/]+/.exec(path)?.[1];
951
+ if (id) return id;
952
+ }
953
+ }
954
+ throw new SlackError("invalid_file_ref", "Expected a Slack file ID or file link. For a message permalink, use slack_thread first.");
955
+ }
956
+
957
+ function checkedFileUrl(file: Record<string, unknown>): string {
958
+ const refuse = (reason: string): never => {
959
+ const permalink = file.permalink;
960
+ const page = typeof permalink === "string" && URL.canParse(permalink) ? ` (${permalink})` : "";
961
+ throw new SlackError("file_not_downloadable", `${reason}${page}`);
962
+ };
963
+ if (file.mode === "external" || file.is_external === true) refuse("Slack does not host this external file.");
964
+ if (file.is_hidden_by_limit) refuse("Slack hides this file under the workspace plan limit.");
965
+ const address = [file.url_private_download, file.url_private].find((v): v is string => typeof v === "string" && v.length > 0);
966
+ if (!address) return refuse("Slack returned no content address.");
967
+ const url = URL.parse(address);
968
+ if (url?.protocol !== "https:" || url.host !== "files.slack.com" || url.username || url.password) {
969
+ return refuse(`Expected HTTPS on files.slack.com, got ${url?.host || "an invalid address"}.`);
970
+ }
971
+ return url.href;
972
+ }
973
+
974
+ function safeDownloadName(name: string, id: string): string {
975
+ const segment = name.replace(/[/\\<>:"|?*\p{Cc}]/gu, "_").replace(/[. ]+$/, "");
976
+ // Windows device names stay reserved even with an extension.
977
+ return !segment || /^(?:CON|PRN|AUX|NUL|(?:COM|LPT)[1-9\u00b9\u00b2\u00b3])(?:\.|$)/i.test(segment) ? id : segment;
978
+ }
979
+
980
+ function writeError(err: unknown): SlackError {
981
+ return new SlackError("write_failed", `Could not save Slack file: ${(err as Error).message}`);
982
+ }
983
+
984
+ async function createDownload(dir: string, name: string, id: string) {
985
+ const ext = extname(name);
986
+ for (const filename of [name, `${name.slice(0, name.length - ext.length)}-${id}${ext}`]) {
987
+ const path = join(dir, filename);
988
+ try {
989
+ return { path, handle: await open(path, "wx", 0o600) };
990
+ } catch (err) {
991
+ if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw writeError(err);
992
+ }
993
+ }
994
+ throw new SlackError("file_exists", "Both download names are taken. Choose another dir.");
995
+ }
996
+
997
+ export async function downloadFile(
998
+ args: { fileId: string; dir?: string }, deps: CoreDeps & { downloadBytes: DownloadBytes },
999
+ ) {
1000
+ const { fileId } = args;
1001
+ const data = await deps.apiCall("files.info", deps.token, { file: fileId }, { retry: true, signal: deps.signal });
1002
+ const file = (data.file ?? {}) as Record<string, unknown>;
1003
+ const url = checkedFileUrl(file);
1004
+ const tooLarge = () => new SlackError("file_too_large", `Slack file exceeds ${DOWNLOAD_MAX_BYTES} bytes.`);
1005
+ if (typeof file.size === "number" && file.size > DOWNLOAD_MAX_BYTES) throw tooLarge();
1006
+ const name = [file.name, file.title].find((v): v is string => typeof v === "string" && v.length > 0) ?? fileId;
1007
+ const mimetype = typeof file.mimetype === "string" ? file.mimetype : undefined;
1008
+ let dir = args.dir ?? resolve(tmpdir(), "pi-slack");
1009
+ try {
1010
+ if (args.dir === undefined) {
1011
+ try {
1012
+ await mkdir(dir, { mode: 0o700 });
1013
+ } catch (err) {
1014
+ if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err;
1015
+ }
1016
+ const parent = await lstat(dir);
1017
+ if (!parent.isDirectory() || (process.getuid && (parent.uid !== process.getuid() || (parent.mode & 0o002) !== 0))) {
1018
+ throw new Error(`Unsafe temp parent: ${dir} must be a real directory and, on POSIX, owned by the current user and not world-writable.`);
1019
+ }
1020
+ dir = await mkdtemp(join(dir, "download-"));
1021
+ } else {
1022
+ await mkdir(dir, { recursive: true });
1023
+ }
1024
+ } catch (err) {
1025
+ throw new SlackError("invalid_dir", `Cannot create download directory: ${(err as Error).message}`);
1026
+ }
1027
+
1028
+ let response: Awaited<ReturnType<DownloadBytes>> | undefined;
1029
+ let completeBody = false;
1030
+ let ownedPath: string | undefined;
1031
+ try {
1032
+ response = await deps.downloadBytes(url, deps.token, { signal: deps.signal });
1033
+ const isHtml = (type?: string) => type?.split(";", 1)[0].trim().toLowerCase() === "text/html";
1034
+ if (isHtml(response.contentType) && !isHtml(mimetype)) {
1035
+ throw new SlackError("file_auth_redirect", "Slack returned an HTML page instead of the requested file.");
1036
+ }
1037
+ const { path, handle } = await createDownload(dir, safeDownloadName(name, fileId), fileId);
1038
+ ownedPath = path;
1039
+ let size = 0;
1040
+ try {
1041
+ for await (const chunk of response.body) {
1042
+ size += chunk.byteLength;
1043
+ if (size > DOWNLOAD_MAX_BYTES) throw tooLarge();
1044
+ await handle.writeFile(chunk).catch((err) => { throw writeError(err); });
1045
+ }
1046
+ completeBody = true;
1047
+ } catch (err) {
1048
+ if (err instanceof SlackError) throw err;
1049
+ if (deps.signal?.aborted) throw new SlackError("aborted", "Request was cancelled.");
1050
+ throw new SlackError("transport", "Slack file transfer failed or timed out.");
1051
+ } finally {
1052
+ await handle.close().catch((err) => { throw writeError(err); });
1053
+ }
1054
+ if (typeof file.size === "number" && Number.isInteger(file.size) && file.size >= 0 && size !== file.size) {
1055
+ throw new SlackError("transport", `Expected ${file.size} bytes, received ${size}.`);
1056
+ }
1057
+ return { path, file_id: fileId, name, ...(mimetype !== undefined ? { mimetype } : {}), size };
1058
+ } catch (err) {
1059
+ if (!completeBody && response) await response.cancel();
1060
+ if (ownedPath) await rm(ownedPath, { force: true });
1061
+ if (args.dir === undefined) await rmdir(dir);
1062
+ throw err;
1063
+ }
1064
+ }
1065
+
879
1066
  export async function uploadFile(
880
1067
  args: { channel: string; bytes: Uint8Array; filename: string; title?: string; thread_ts?: string; initial_comment?: string },
881
1068
  deps: CoreDeps & { uploadBytes: UploadBytes },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-quiver",
3
- "version": "6.17.1",
3
+ "version": "6.18.1",
4
4
  "description": "Personal pack of Pi coding-agent extensions: context-safe fetch, doc_to_md PDF/DOCX/PPTX-to-Markdown conversion, session naming, a themed ASCII startup header, Anthropic fast mode, and a provider-stall watchdog.",
5
5
  "author": "Jacek Juraszek",
6
6
  "license": "MIT",