pi-quiver 6.15.2 → 6.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -8,6 +8,14 @@ Published to npm as `pi-quiver` (`pi install npm:pi-quiver`). Pushing a
8
8
  via OIDC trusted publishing. The release helper at
9
9
  `.agents/skills/release/scripts/release.sh` cuts the tag; CI publishes.
10
10
 
11
+ ## v6.16.0 - 2026-11-08
12
+
13
+ - Typed results: `doc_to_md`, `fetch`, `slack_thread`, and `slack_search` declare `outputSchema` and return `structuredContent` to codemode scripts, without changing direct-call text or CLI output. Slack reads keep pagination metadata alongside inline message arrays or a separate JSON spill file.
14
+ - Script-only refresh: `slack_cache_refresh` is callable as `await tools.slack_cache_refresh({})` from codemode scripts, not as a direct model tool. Pi's `channel_not_found` hint names that call; the CLI instead asks callers to check the channel ID and token-user membership. These host APIs require Pi 0.99.0 or later.
15
+ - Description diet: `slack_post` and `slack_update` no longer repeat formatting guidance in `description`; it stays in `promptGuidelines`, with the native-list example last. `doc_to_md` keeps only call-shaping sentences in its tool description and uses compact `toolHelp` for `pages`, `outputDir`, `words`, `ocrMode`, and `hideAnnotations`; `pi-quiver doc-to-md --help` and the generated Claude Code skill keep the long form. `test/tool-descriptions.test.ts` pins per-tool declaration ceilings using the host's own codemode renderer and asserts the default-mode catalog lists every non-direct tool.
16
+
17
+ - Dependencies move to current: `jsdom` ^31, `unpdf` ^2.1, `turndown` ^7.2.5 at runtime; `@earendil-works/pi-*` ^1.5.0, TypeScript ^7, `@types/jsdom` ^30, `@types/node` ^26.6 for development. `engines.node` is `^24.15.0 || >=26.0.0` (the intersection of `unpdf` 2's `>=24` and `jsdom` 31's `^22.22.2 || ^24.15.0 || >=26`); the README install section states the floor; the README watchdog section is verified against Pi 1.5.0.
18
+
11
19
  ## v6.15.2 - 2026-11-03
12
20
 
13
21
  - `/elevator` and `/quiver:elevator` ask for a PM elevator talk in prose instead of five numbered answers, with a short-answer release valve. The checkout-only `eval/elevator/` target replays the body through pi-gauntlet at commit `d0a2cadacf20cd4b530ae651fcd2b536cbea07ad` (`--root` support and runner-owned judge).
package/README.md CHANGED
@@ -101,7 +101,9 @@ Full routing rules, size-gate mechanics, and config: [doc/fetch.md](doc/fetch.md
101
101
 
102
102
  ## Install
103
103
 
104
- Published to npm as the unscoped `pi-quiver` package.
104
+ 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).
105
+
106
+ 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.
105
107
 
106
108
  **User scope** (all repos under your pi profile):
107
109
 
@@ -258,7 +260,7 @@ not a pi-quiver setting and is never nested):
258
260
 
259
261
  **Leave pi's own `httpIdleTimeoutMs` (default `300000`) at its default.** It is the transport backstop, and a single value drives undici's `headersTimeout` *and* `bodyTimeout` - lowering it to get fast pre-stream failure also truncates legitimate mid-stream gaps. `firstEventMs` is the knob for pre-stream silence.
260
262
 
261
- Verified with Pi 0.87.1: each eligible stall is aborted, its message omitted from the model's context, and the request re-driven by the watchdog after pi's backoff (`retry.baseDelayMs`, capped at `retry.maxAgentDelayMs`) until `maxStallRetries` conversions are used; further stalls stop for manual resubmission. Both tiers draw on that one budget. `maxStallRetries` defaults to the layered `retry.maxRetries` (Pi default 3, an explicit `0` honoured); `0` is valid and means "detect and stop, never auto-retry". A successful assistant turn resets the stall counter (mirroring Pi's own retry counter). pi's `retry.enabled: false` disables the re-drive and degrades to manual resubmission without omitting the aborted message. Pending steering or follow-ups return to the editor and are excluded from automatic continuation. Invalid merged watchdog config fails closed. Print/json await pi's backoff before re-driving; TUI/RPC show a timer-path countdown that a new prompt cancels. Why the watchdog re-drives instead of pi, the hidden re-drive message, and the wait behavior: [doc/provider-stall-watchdog.md](doc/provider-stall-watchdog.md).
263
+ Verified with Pi 1.5.0: each eligible stall is aborted, its message omitted from the model's context, and the request re-driven by the watchdog after pi's backoff (`retry.baseDelayMs`, capped at `retry.maxAgentDelayMs`) until `maxStallRetries` conversions are used; further stalls stop for manual resubmission. Both tiers draw on that one budget. `maxStallRetries` defaults to the layered `retry.maxRetries` (Pi default 3, an explicit `0` honoured); `0` is valid and means "detect and stop, never auto-retry". A successful assistant turn resets the stall counter (mirroring Pi's own retry counter). pi's `retry.enabled: false` disables the re-drive and degrades to manual resubmission without omitting the aborted message. Pending steering or follow-ups return to the editor and are excluded from automatic continuation. Invalid merged watchdog config fails closed. Print/json await pi's backoff before re-driving; TUI/RPC show a timer-path countdown that a new prompt cancels. Why the watchdog re-drives instead of pi, the hidden re-drive message, and the wait behavior: [doc/provider-stall-watchdog.md](doc/provider-stall-watchdog.md).
262
264
 
263
265
  Operational notes:
264
266
 
@@ -132,6 +132,7 @@ ${failedLogs.trimEnd()}` : stdout.trimEnd();
132
132
  Source: gh ${buildGhLogArgs(target).join(" ")}` : `Source: ${ghSourceLine(target, ref)}`;
133
133
  if (!spill) {
134
134
  return {
135
+ body,
135
136
  output: [source, "", body].join("\n"),
136
137
  details: { ...baseDetails, spilled: false }
137
138
  };
@@ -139,6 +140,7 @@ Source: gh ${buildGhLogArgs(target).join(" ")}` : `Source: ${ghSourceLine(target
139
140
  const spillUrl = target.kind === "repo" ? `https://github.com/${target.slug}` : target.url;
140
141
  const file = spillToFile(spillUrl, body, "md");
141
142
  return {
143
+ body: "",
142
144
  output: [
143
145
  source,
144
146
  `Body: ${formatSize(bytes)} across ${lines} lines \u2014 written to file (too large to inline)`,
@@ -394,15 +396,16 @@ async function fetchUrl(opts) {
394
396
  ];
395
397
  if (!res.body || (opts.method ?? "GET") === "HEAD") {
396
398
  return {
399
+ body: "",
397
400
  output: [...header, "Length: 0 (no body)"].join("\n"),
398
- details: { url: res.url, status: res.status, contentType: ct, charset, bytes: 0 }
401
+ details: { url: res.url, status: res.status, ...res.headers.has("content-type") ? { contentType: ct } : {}, charset, bytes: 0 }
399
402
  };
400
403
  }
401
404
  const collected = await collectBody(res, ct, opts.raw ?? false);
402
405
  const baseDetails = {
403
406
  url: res.url,
404
407
  status: res.status,
405
- contentType: ct,
408
+ ...res.headers.has("content-type") ? { contentType: ct } : {},
406
409
  charset,
407
410
  bytes: collected.bytes,
408
411
  truncated: collected.truncated,
@@ -411,6 +414,7 @@ async function fetchUrl(opts) {
411
414
  if (collected.category === "binary") {
412
415
  const note = collected.truncated ? " (truncated to 50MB)" : "";
413
416
  return {
417
+ body: "",
414
418
  output: [
415
419
  ...header,
416
420
  `Body: ${formatSize(collected.bytes)}${note} binary (${mimeType(ct) || "unknown"}) \u2014 saved untouched for processing`,
@@ -444,6 +448,7 @@ async function fetchUrl(opts) {
444
448
  baseDetails.lines = lineCount;
445
449
  if (!spill) {
446
450
  return {
451
+ body,
447
452
  output: [...header, lengthLine, "", body + truncNote].join("\n"),
448
453
  details: { ...baseDetails, spilled: false }
449
454
  };
@@ -452,6 +457,7 @@ async function fetchUrl(opts) {
452
457
  const file = spillToFile(res.url, body, ext);
453
458
  const grepHint = effectiveCategory === "markdown" ? "Read slices of this file with the read tool (offset/limit) or grep it; do not read the whole file unless you must. Markdown is grep-able by heading (^#)." : "Read slices of this file with the read tool (offset/limit) or grep it; do not read the whole file unless you must.";
454
459
  return {
460
+ body: "",
455
461
  output: [
456
462
  ...header,
457
463
  lengthLine,
@@ -862,6 +868,10 @@ function tempBundleRoot() {
862
868
  }
863
869
 
864
870
  // lib/doc-to-md-handle.ts
871
+ function publicHandle(details) {
872
+ const { path, backend, pymupdfVersion, inputType, file, outputDir, ...handle } = details;
873
+ return handle;
874
+ }
865
875
  var TITLE_MAX = 80;
866
876
  var NOTE_MAX_LINES = 5;
867
877
  var NOTE_MAX_CHARS = 200;
@@ -1033,12 +1043,12 @@ var IMAGE_EXTS = [".png", ".jpg", ".jpeg", ".tif", ".tiff", ".bmp", ".gif"];
1033
1043
  var DOC_TO_MD_OPTIONS = [
1034
1044
  { key: "path", flag: null, type: "string", default: null, settable: false, help: "Local .pdf .docx .doc .pptx .xlsx .xlsm .xls .msg .eml .html .htm .png .jpg .jpeg .tif .tiff .bmp .gif file" },
1035
1045
  { key: "info", flag: "--info", type: "bool", default: false, settable: false, help: "Inspect only (page count, metadata, TOC or sheet inventory); no bundle" },
1036
- { key: "pages", flag: "--pages", type: "pages", default: null, settable: false, help: 'Inclusive 1-based pages, e.g. "12-15" or "3,7,10-12" (PDF/DOCX/DOC/PPTX only); default all; "" means all pages. DOCX: selects explicit-page-break segments; rejected when the file has none' },
1037
- { key: "outputDir", flag: "--output-dir", type: "string", default: null, settable: false, help: "Bundle root for <stem>.md + images/; default a per-call temp dir. <stem> = basename without extension with [^A-Za-z0-9._-]+ -> _ (empty -> document); a second call on the same stem writes <stem>-2.md" },
1046
+ { key: "pages", toolHelp: 'Inclusive 1-based pages, e.g. "12-15" or "3,7,10-12" (PDF/DOCX/DOC/PPTX); default all; "" means all pages; DOCX selects explicit-page-break segments, rejected when the file has none.', flag: "--pages", type: "pages", default: null, settable: false, help: 'Inclusive 1-based pages, e.g. "12-15" or "3,7,10-12" (PDF/DOCX/DOC/PPTX only); default all; "" means all pages. DOCX: selects explicit-page-break segments; rejected when the file has none' },
1047
+ { key: "outputDir", toolHelp: "Bundle root for <stem>.md + images/; default a per-call temp dir.", flag: "--output-dir", type: "string", default: null, settable: false, help: "Bundle root for <stem>.md + images/; default a per-call temp dir. <stem> = basename without extension with [^A-Za-z0-9._-]+ -> _ (empty -> document); a second call on the same stem writes <stem>-2.md" },
1038
1048
  { key: "overwrite", flag: "--overwrite", type: "bool", default: false, settable: false, help: "Replace an existing completed <stem>.md bundle" },
1039
1049
  { key: "pageImages", flag: "--page-images", type: "bool", default: false, settable: false, help: "Also render every selected page to pages/<stem>-pNNN.<imageFormat> at imageDpi (PDF, PPTX, .doc, DOCX via LibreOffice); off by default" },
1040
- { key: "words", flag: "--words", type: "bool", default: false, settable: false, help: 'Write word positions: <stem>.words.json beside the Markdown lists every text-layer word of each selected page with its bbox (PDF points, top-left origin, display orientation; image inputs in source pixels) and the words inline OCR recognized, tagged source "text" or "ocr"; under --ocr-mode all the OCR words go to ocr/<stem>-pNNN.words.json beside each sidecar. Never triggers OCR. PDF and image inputs only.' },
1041
- { key: "ocrMode", flag: "--ocr-mode", type: "enum", default: "textless", settable: false, enumValues: ["textless", "all"], help: "OCR policy: textless (default) OCRs only pages with an empty text layer, inline; all OCRs every selected page and writes the recognized text to ocr/<stem>-pNNN.md sidecars, leaving the Markdown untouched. all requires --ocr and an explicit --pages selection (PDF, PPTX, DOC)." },
1050
+ { key: "words", toolHelp: "Write word positions to <stem>.words.json, or ocr/<stem>-pNNN.words.json for ocrMode all. Never triggers OCR. PDF and image inputs only.", flag: "--words", type: "bool", default: false, settable: false, help: 'Write word positions: <stem>.words.json beside the Markdown lists every text-layer word of each selected page with its bbox (PDF points, top-left origin, display orientation; image inputs in source pixels) and the words inline OCR recognized, tagged source "text" or "ocr"; under --ocr-mode all the OCR words go to ocr/<stem>-pNNN.words.json beside each sidecar. Never triggers OCR. PDF and image inputs only.' },
1051
+ { key: "ocrMode", toolHelp: "textless (default): OCR empty text layers inline. all: OCR selected pages to ocr/ sidecars without changing Markdown; requires ocr and explicit pages (PDF, PPTX, DOC).", flag: "--ocr-mode", type: "enum", default: "textless", settable: false, enumValues: ["textless", "all"], help: "OCR policy: textless (default) OCRs only pages with an empty text layer, inline; all OCRs every selected page and writes the recognized text to ocr/<stem>-pNNN.md sidecars, leaving the Markdown untouched. all requires --ocr and an explicit --pages selection (PDF, PPTX, DOC)." },
1042
1052
  { key: "primaryTimeoutMs", flag: "--primary-timeout", type: "int", default: 6e4, settable: true, env: "PI_DOC_TO_MD_CONVERT_TIMEOUT_MS", help: "pymupdf4llm tier and DOCX child (docx mode); also the unpdf tier" },
1043
1053
  { key: "fallbackTimeoutMs", flag: "--fallback-timeout", type: "int", default: 3e4, settable: true, help: "PyMuPDF get_text tier (including DOCX LibreOffice fallback); also PDF and DOCX info and Excel rendered views" },
1044
1054
  { key: "sofficeTimeoutMs", flag: "--soffice-timeout", type: "int", default: 12e4, settable: true, env: "PI_DOC_TO_MD_SOFFICE_TIMEOUT_MS", help: "DOCX/PPTX -> PDF via LibreOffice; also Excel rendered views" },
@@ -1052,7 +1062,7 @@ var DOC_TO_MD_OPTIONS = [
1052
1062
  { key: "ocr", flag: "--ocr", type: "bool", default: false, settable: true, help: "Run OCR on pages without a text layer and on image inputs when Tesseract language data is installed; off by default (--no-ocr turns a settings-level true off)" },
1053
1063
  { key: "ocrLanguage", flag: "--ocr-language", type: "lang", default: "eng", settable: true, help: "Tesseract language code(s), +-joined, e.g. deu+eng" },
1054
1064
  { key: "ocrMaxPages", flag: null, type: "int", default: 10, settable: true, settingsOnly: true, help: "Most pages one invocation OCRs; ocrMode all rejects a larger distinct-page selection before any work, textless mode OCRs the first ocrMaxPages textless pages and names the rest in the OCR: line" },
1055
- { key: "hideAnnotations", flag: "--hide-annotations", type: "bool", default: false, settable: true, help: "Render PDF pages without annotations (sticky notes, highlights, stamps - and form-field widgets, so filled form values disappear); default paints them, as PyMuPDF does. Applies to pages/ renders and textless-page renders, not to OCR text or embedded images; also lets an annotated scan be delivered as its embedded image." }
1065
+ { key: "hideAnnotations", toolHelp: "Render PDF pages without annotations or form widgets (filled values disappear); default paints them. Applies to pages/ and textless-page renders, not OCR text or embedded images.", flag: "--hide-annotations", type: "bool", default: false, settable: true, help: "Render PDF pages without annotations (sticky notes, highlights, stamps - and form-field widgets, so filled form values disappear); default paints them, as PyMuPDF does. Applies to pages/ renders and textless-page renders, not to OCR text or embedded images; also lets an annotated scan be delivered as its embedded image." }
1056
1066
  ];
1057
1067
  var TUNABLE_DEFAULTS = Object.fromEntries(
1058
1068
  DOC_TO_MD_OPTIONS.filter((d) => d.settable).map((d) => [d.key, d.default])
@@ -2353,7 +2363,6 @@ var MAX_RETRY_AFTER_MS = 3e4;
2353
2363
  var RETRY_AFTER_DEFAULT_S = 2;
2354
2364
  var JSON_METHODS = /* @__PURE__ */ new Set(["chat.postMessage", "chat.update", "canvases.edit"]);
2355
2365
  var ERROR_HINTS = {
2356
- channel_not_found: "check the name or run slack_cache_refresh",
2357
2366
  not_in_channel: "invite the bot to the channel",
2358
2367
  msg_too_long: "message exceeds Slack's length ceiling",
2359
2368
  is_archived: "the channel is archived",
@@ -3043,7 +3052,7 @@ ${USAGE}
3043
3052
  const code = slackFailureCode(err, mutationStarted, method);
3044
3053
  if (err instanceof SlackError) {
3045
3054
  let message = err.message.includes(err.code) ? err.message : `${err.code}: ${err.message}`;
3046
- const hint = ERROR_HINTS[err.code];
3055
+ const hint = err.code === "channel_not_found" ? "check the channel ID and that the token's user is a member of it" : ERROR_HINTS[err.code];
3047
3056
  if (hint && !message.includes(hint)) message += `; ${hint}`;
3048
3057
  if (typeof err.data?.channel === "string") message += ` channel=${err.data.channel}`;
3049
3058
  stderr(`${message}
@@ -3129,7 +3138,7 @@ ${USAGE}
3129
3138
  try {
3130
3139
  const r = o.info ? await inspectDocument(o) : await convertDocument(o);
3131
3140
  if (parsed.json) {
3132
- const payload = o.info ? r.details : (({ path, backend, pymupdfVersion, inputType, file, outputDir, ...handle }) => handle)(r.details);
3141
+ const payload = o.info ? r.details : publicHandle(r.details);
3133
3142
  process.stdout.write(`${JSON.stringify(payload)}
3134
3143
  `);
3135
3144
  } else process.stdout.write(`${r.output}
@@ -7,15 +7,60 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
7
7
  import { keyHint } from "@earendil-works/pi-coding-agent";
8
8
  import { Text } from "@earendil-works/pi-tui";
9
9
  import { Type, type TObject, type TSchema } from "@sinclair/typebox";
10
+ import type { JsonObject } from "@earendil-works/pi-ai";
10
11
  import { resolveConfig } from "../lib/extension-config.ts";
11
12
  import {
12
13
  DOC_TO_MD_OPTIONS, type DocToMdDetails, type OptionDescriptor, type PerCallInput, type Tunables,
13
14
  coerceDocToMdSettings, convertDocument, inspectDocument, resolveOptions,
14
15
  } from "../lib/doc-to-md-core.ts";
15
16
  import { resolve } from "node:path";
17
+ import { publicHandle } from "../lib/doc-to-md-handle.ts";
18
+
19
+ const nullable = <T extends TSchema>(schema: T) => Type.Union([schema, Type.Null()]);
20
+ const strings = <T extends string>(values: T[]) => Type.Union(values.map((value) => Type.Literal(value)));
21
+ const pages = Type.Array(Type.Integer());
22
+ const pageStrings = Type.Record(Type.String(), Type.String());
23
+ const inputType = strings(["pdf", "docx", "doc", "pptx", "xlsx", "xlsm", "xls", "html", "image", "email"]);
24
+ const tocEntry = { level: Type.Integer(), title: Type.String(), page: nullable(Type.Integer()) };
25
+ const ocrSchema = Type.Object({
26
+ status: strings(["off", "unavailable", "skipped", "ran"]), lang: Type.String(),
27
+ textless: pages, pages, noText: pages, ocrFailed: pages, budgetStopped: pages, ceilingStopped: pages,
28
+ ocrMaxPages: Type.Integer(), reason: nullable(Type.String()), tesseract: nullable(Type.Boolean()),
29
+ mode: strings(["textless", "all"]), sidecars: pageStrings, wordSidecars: pageStrings, ocrErrors: pageStrings,
30
+ killed: nullable(Type.Integer()), notAttempted: pages, childError: nullable(Type.String()),
31
+ });
32
+ const sheetSchema = Type.Object({
33
+ index: Type.Integer(), name: Type.String(), kind: strings(["worksheet", "chartsheet"]), hidden: Type.Boolean(),
34
+ rows: nullable(Type.Integer()), cols: nullable(Type.Integer()), hiddenRows: Type.Integer(), hiddenCols: Type.Integer(),
35
+ charts: Type.Integer(), images: Type.Integer(), rendered: Type.Boolean(), csv: nullable(Type.String()),
36
+ });
37
+ const outputSchema = Type.Union([
38
+ Type.Object({
39
+ savedTo: Type.String(), imagesDir: nullable(Type.String()), sheetsDir: nullable(Type.String()), pagesDir: nullable(Type.String()),
40
+ type: inputType,
41
+ engine: strings(["pymupdf4llm", "pymupdf-text", "unpdf", "openpyxl", "xlrd", "mammoth", "python-docx", "markdownify", "turndown", "copy", "extract-msg", "email"]),
42
+ tier: strings(["primary", "fallback", "unpdf", "excel", "docx", "html", "image", "email"]),
43
+ pageCount: nullable(Type.Integer()), pages: nullable(pages), explicitBreaks: nullable(Type.Integer()),
44
+ imageCount: Type.Integer(), pageImageCount: Type.Integer(), pageImagesReason: nullable(Type.String()), bytes: Type.Integer(), lines: Type.Integer(),
45
+ degraded: nullable(Type.String()), fallbackReason: nullable(Type.String()), failedPages: pages, emptyPages: pages,
46
+ notes: Type.Array(Type.String()), outline: Type.Array(Type.Object({ line: Type.Integer(), ...tocEntry })), outlineTotal: Type.Integer(), ocr: nullable(ocrSchema),
47
+ pageStats: nullable(Type.Array(Type.Union([
48
+ Type.Object({ page: Type.Integer(), chars: Type.Integer(), images: Type.Integer(), imageCoverage: Type.Number() }),
49
+ Type.Object({ page: Type.Integer(), error: Type.String() }),
50
+ ]))),
51
+ pageStatsPath: nullable(Type.String()), ocrDir: nullable(Type.String()),
52
+ nativeImages: Type.Array(Type.Object({ page: Type.Integer(), file: Type.String(), width: Type.Integer(), height: Type.Integer() })),
53
+ wordsPath: nullable(Type.String()), wordsReason: nullable(Type.String()), wordsErrors: pageStrings,
54
+ }),
55
+ Type.Object({
56
+ type: inputType, backend: strings(["uv", "python", "venv", "none"]), pageCount: nullable(Type.Integer()),
57
+ metadata: Type.Record(Type.String(), Type.String()), toc: Type.Array(Type.Object(tocEntry)), tocTotal: Type.Integer(),
58
+ sheets: nullable(Type.Array(sheetSchema)), sheetsTotal: Type.Integer(),
59
+ }),
60
+ ]);
16
61
 
17
62
  function schemaFor(d: OptionDescriptor): TSchema {
18
- const desc = { description: d.help };
63
+ const desc = { description: d.toolHelp ?? d.help };
19
64
  switch (d.type) {
20
65
  case "bool": return Type.Boolean(desc);
21
66
  case "int": return Type.Integer({ ...desc, minimum: 1 });
@@ -38,9 +83,10 @@ export default function docToMdExtension(pi: ExtensionAPI) {
38
83
  name: "doc_to_md",
39
84
  label: "Convert doc to Markdown bundle",
40
85
  description:
41
- "Convert a local PDF/DOCX/DOC/PPTX/XLSX/XLSM/XLS, email (.msg/.eml), HTML (.html/.htm) or image (.png .jpg .jpeg .tif .tiff .bmp .gif) to a Markdown bundle on disk and return a handle (Saved-To, Images-Dir, Page-Count, Outline, diagnostics) - the Markdown itself is never inlined; read the Saved-To file (offset/limit) for content. `info: true` returns page count, metadata and TOC (or the sheet inventory) without converting - use it to pick `pages`. `pages` selects inclusive 1-based pages (PDF/PPTX) or explicit-page-break segments (DOCX; rejected when the file has none); every selected PDF/PPTX page or DOCX segment when `pageCount > 1` ends with `--- end of page.page_number=N ---`. Images are always extracted into images/ with relative links. Primary engine pymupdf4llm, fallback PyMuPDF text (degraded, marked), pure-JS unpdf only when no Python backend exists. Excel yields a sheet inventory (worksheets + chartsheets), a full CSV per non-empty worksheet under sheets/, a bounded preview with formulas and cached values, merged/hidden disclosure, and rendered chart views when LibreOffice is available. DOCX converts directly (mammoth; python-docx text fallback) and keeps heading styles, so the handle Outline lists `L<line>` and `p<segment>` per heading; LibreOffice (soffice) is optional for DOCX (fallback route, degraded) and Excel rendered views, and required for PPTX. Use `outputDir` for a durable bundle; without it the bundle lands in a per-call temp dir. Input must be a local file path (use fetch first for URLs). HTML converts without Readability (markdownify; Turndown fallback): local and data: images are copied into images/, remote images stay links. Pages without a text layer keep their picture in images/, or pages/ with `pageImages: true`; image inputs keep their picture in images/. `pageImages: true` writes page renders to pages/<stem>-pNNN, and email attachments are saved under attachments/. OCR is off by default: `ocr: true` adds recognized text (labeled as OCR) when Tesseract language data is installed; the handle's OCR: line says what ran. Two-pass OCR: read Page-Stats first, then re-run with ocr: true, ocrMode: \"all\" and an explicit pages selection to get ocr/ sidecars for the pages you name. OCR is capped at quiver.docToMd.ocrMaxPages pages per call (default 10; settings-only, no tool parameter): ocrMode \"all\" rejects a larger distinct-page selection before any work, and textless mode OCRs the first ocrMaxPages textless pages and names the rest in the OCR: line with the pages to rerun.",
86
+ "Convert a local PDF/DOCX/DOC/PPTX/XLSX/XLSM/XLS, email (.msg/.eml), HTML (.html/.htm) or image (.png .jpg .jpeg .tif .tiff .bmp .gif) to a Markdown bundle on disk and return a handle (Saved-To, Images-Dir, Page-Count, Outline, diagnostics) - the Markdown itself is never inlined; read the Saved-To file (offset/limit) for content. `info: true` returns page count, metadata and TOC (or the sheet inventory) without converting - use it to pick `pages`. Images are extracted into images/ with relative links; Excel CSVs land in sheets/. LibreOffice is required for PPTX. Use `outputDir` for a durable bundle; without it the bundle lands in a per-call temp dir. Input must be a local file path (use fetch first for URLs). Pages without a text layer keep their picture in images/, or pages/ with `pageImages: true`; image inputs keep their picture in images/. `pageImages: true` writes page renders to pages/<stem>-pNNN, and email attachments are saved under attachments/. OCR is off by default: `ocr: true` adds recognized text (labeled as OCR) when Tesseract language data is installed; the handle's OCR: line says what ran. Two-pass OCR: read Page-Stats first, then re-run with ocr: true, ocrMode: \"all\" and an explicit pages selection to get ocr/ sidecars for the pages you name. OCR is capped at quiver.docToMd.ocrMaxPages pages per call (default 10; settings-only, no tool parameter): ocrMode \"all\" rejects a larger distinct-page selection before any work, and textless mode OCRs the first ocrMaxPages textless pages and names the rest in the OCR: line with the pages to rerun.",
42
87
  promptSnippet: "Convert a local PDF/DOCX/DOC/PPTX/XLSX/XLSM/XLS/MSG/EML/HTML/image to a Markdown bundle (handle returned; read Saved-To)",
43
88
  parameters: buildSchema(),
89
+ outputSchema,
44
90
 
45
91
  async execute(_toolCallId, params, signal, _onUpdate, ctx) {
46
92
  const settings = resolveConfig<Partial<Tunables>>(ctx.cwd, "docToMd", {}, (raw) => coerceDocToMdSettings(raw, (m) => console.warn(m)), (m) => console.warn(m));
@@ -48,7 +94,10 @@ export default function docToMdExtension(pi: ExtensionAPI) {
48
94
  const perCall: PerCallInput = { ...p, path: resolve(ctx.cwd, p.path), ...(p.outputDir ? { outputDir: resolve(ctx.cwd, p.outputDir) } : {}) };
49
95
  const o = resolveOptions(perCall, settings, process.env);
50
96
  const r = o.info ? await inspectDocument(o, signal) : await convertDocument(o, signal);
51
- return { content: [{ type: "text" as const, text: r.output }], details: r.details };
97
+ return {
98
+ content: [{ type: "text" as const, text: r.output }], details: r.details,
99
+ structuredContent: (o.info ? r.details : publicHandle(r.details as DocToMdDetails)) as unknown as JsonObject,
100
+ };
52
101
  },
53
102
 
54
103
  renderCall(args, theme) {
@@ -16,6 +16,13 @@ import { Text } from "@earendil-works/pi-tui";
16
16
  import { Type } from "@sinclair/typebox";
17
17
  import { fetchUrl, DEFAULT_TIMEOUT_MS, type FetchToolDetails } from "../lib/fetch-core.ts";
18
18
 
19
+ const resultFields = {
20
+ url: Type.String(),
21
+ status: Type.Optional(Type.Number()),
22
+ contentType: Type.Optional(Type.String()),
23
+ truncated: Type.Optional(Type.Literal(true)),
24
+ };
25
+
19
26
  export default function fetchExtension(pi: ExtensionAPI) {
20
27
  pi.registerTool({
21
28
  name: "fetch",
@@ -23,6 +30,10 @@ export default function fetchExtension(pi: ExtensionAPI) {
23
30
  description:
24
31
  "Fetch a URL over HTTP(S). HTML is extracted to Markdown (readability + turndown). Binary content (images, PDFs, archives) is saved untouched to a temp file and only a path is returned. Text/Markdown/JSON over 32KB or 1000 lines is written to a temp file with a 60-line preview; smaller content is returned inline. Parsable downloads are capped at 1MB, binary at 50MB. When the body is written to a file, grep it or read with offset/limit; converted Markdown is grep-able by heading (^#). GitHub issue/PR/repo/actions-run/actions-job URLs are served via the gh CLI when available (falls back to HTTP otherwise; raw=true forces the rendered HTML page); failed runs/jobs append failed-step logs (best-effort, summary-only when nothing failed).",
25
32
  promptSnippet: "Fetch the contents of a URL",
33
+ outputSchema: Type.Union([
34
+ Type.Object({ spilled: Type.Literal(false), ...resultFields, content: Type.String() }),
35
+ Type.Object({ spilled: Type.Literal(true), ...resultFields, file: Type.String() }),
36
+ ]),
26
37
  parameters: Type.Object({
27
38
  url: Type.String({ description: "Absolute http(s) URL" }),
28
39
  method: Type.Optional(
@@ -44,9 +55,17 @@ export default function fetchExtension(pi: ExtensionAPI) {
44
55
  }),
45
56
  async execute(_toolCallId, params, signal) {
46
57
  const result = await fetchUrl({ ...params, signal: signal ?? undefined });
58
+ const d = result.details;
47
59
  return {
48
60
  content: [{ type: "text" as const, text: result.output }],
49
- details: result.details,
61
+ details: d,
62
+ structuredContent: {
63
+ url: d.url!,
64
+ ...(d.status !== undefined ? { status: d.status } : {}),
65
+ ...(d.contentType !== undefined ? { contentType: d.contentType } : {}),
66
+ ...(d.truncated ? { truncated: true as const } : {}),
67
+ ...(d.spilled ? { spilled: true as const, file: d.file! } : { spilled: false as const, content: result.body }),
68
+ },
50
69
  };
51
70
  },
52
71
 
@@ -11,11 +11,16 @@
11
11
  import { 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
- import { readFileSync } from "node:fs";
14
+ import type { JsonValue } from "@earendil-works/pi-ai";
15
+ import { createHash } from "node:crypto";
16
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
17
+ import { tmpdir } from "node:os";
15
18
  import { basename, isAbsolute, join } from "node:path";
16
19
  import {
17
20
  defaultApiCall,
18
21
  defaultUploadBytes,
22
+ INLINE_MAX_BYTES,
23
+ INLINE_MAX_LINES,
19
24
  buildPolicyBlock,
20
25
  discoverRepoRoot,
21
26
  resolveSlackConfig,
@@ -53,6 +58,45 @@ const SLACK_FORMATTING_GUIDANCE: { rules: string[]; example: string } = {
53
58
  example: 'Native list example: {"text":"- First\\n- Second","blocks":[{"type":"rich_text","elements":[{"type":"rich_text_list","style":"bullet","elements":[{"type":"rich_text_section","elements":[{"type":"text","text":"First"}]},{"type":"rich_text_section","elements":[{"type":"text","text":"Second"}]}]}]}]}',
54
59
  };
55
60
 
61
+ const SlackMessage = Type.Object({
62
+ ts: Type.String(),
63
+ text: Type.String(),
64
+ user: Type.Optional(Type.String()),
65
+ thread_ts: Type.Optional(Type.String()),
66
+ channel: Type.Optional(Type.Union([
67
+ Type.String(),
68
+ Type.Object({ id: Type.Optional(Type.String()), name: Type.Optional(Type.String()) }, { additionalProperties: true }),
69
+ ])),
70
+ permalink: Type.Optional(Type.String()),
71
+ }, { additionalProperties: true });
72
+
73
+ const searchFields = {
74
+ total: Type.Number(),
75
+ page: Type.Number(),
76
+ page_count: Type.Number(),
77
+ };
78
+
79
+ const threadFields = {
80
+ complete: Type.Boolean(),
81
+ next_cursor: Type.Optional(Type.String()),
82
+ message_count: Type.Number(),
83
+ caveat: Type.Optional(Type.String()),
84
+ };
85
+
86
+ function structuredMessages(messages: Record<string, unknown>[], slug: string): { messages: JsonValue[] } | { file: string } {
87
+ const json = JSON.stringify(messages);
88
+ if (Buffer.byteLength(json, "utf8") <= INLINE_MAX_BYTES && json.split("\n").length <= INLINE_MAX_LINES) {
89
+ // These are raw JSON objects from Slack's transport, not a projected message subset.
90
+ return { messages: messages as JsonValue[] };
91
+ }
92
+ const hash = createHash("sha256").update(json).digest("hex").slice(0, 8);
93
+ const dir = join(tmpdir(), "pi-slack");
94
+ mkdirSync(dir, { recursive: true });
95
+ const file = join(dir, `${Date.now()}-${hash}-${slug}.json`);
96
+ writeFileSync(file, json, "utf8");
97
+ return { file };
98
+ }
99
+
56
100
  const IDENTITY = Type.Union([Type.Literal("user"), Type.Literal("bot")], {
57
101
  description: 'Which token to act as: "user" (a real person, needed for slack_search/slack_thread) or "bot" (an app identity). Determines which credential source is used and whose name shows as the author.',
58
102
  });
@@ -69,7 +113,10 @@ export function formatToolError(err: unknown, identity?: "user" | "bot"): Error
69
113
  ? Object.fromEntries(Object.entries(err.data).filter(([key]) => ALLOWED_ERROR_DATA_KEYS.has(key)))
70
114
  : undefined;
71
115
  const data = filtered && Object.keys(filtered).length > 0 ? `\n${JSON.stringify(filtered)}` : "";
72
- return new Error(`${err.code}: ${err.message}${identitySuffix}${data}`);
116
+ const hint = err.code === "channel_not_found"
117
+ ? "; check the name, or run `tools.slack_cache_refresh({})` from a codemode script to refresh the name cache"
118
+ : "";
119
+ return new Error(`${err.code}: ${err.message}${hint}${identitySuffix}${data}`);
73
120
  }
74
121
  if (err instanceof Error) return err;
75
122
  return new Error(String(err));
@@ -170,11 +217,11 @@ function mentionAwareResult(
170
217
  };
171
218
  }
172
219
 
173
- export function searchResultText(result: SearchResult): string {
220
+ export function searchResultText(result: Omit<SearchResult, "matches">): string {
174
221
  return `${result.output}\n\ntotal: ${result.total} | page: ${result.page} of ${result.pageCount}`;
175
222
  }
176
223
 
177
- export function threadResultText(result: ThreadResult, raw = false): string {
224
+ export function threadResultText(result: Omit<ThreadResult, "messages">, raw = false): string {
178
225
  if (raw) return result.output;
179
226
  const lines = [result.output, "", `complete: ${result.complete}`];
180
227
  if (!result.complete && result.nextCursor) lines.push(`next_cursor: ${result.nextCursor}`);
@@ -257,6 +304,10 @@ export default function slackExtension(pi: ExtensionAPI) {
257
304
  name: "slack_search",
258
305
  label: "Slack Search",
259
306
  promptSnippet: "Search Slack messages with Slack's search operator grammar",
307
+ outputSchema: Type.Union([
308
+ Type.Object({ matches: Type.Array(SlackMessage), ...searchFields }),
309
+ Type.Object({ file: Type.String(), ...searchFields }),
310
+ ]),
260
311
  description:
261
312
  'Search Slack messages via search.messages. Always uses the "user" identity (search.messages accepts only user tokens - no `as` param). `query` uses Slack\'s documented operator grammar (e.g. `in:#channel-name`, `from:@display-name`); channel/user names in the query are passed through as-is, never rewritten to IDs. `count` (default 20, max 100) and optional `page` control a single page of Slack\'s offset-paginated results. Output is compact (author, channel, ts, permalink, text) and size-gated: over 32KB/1000 lines it is written to a temp file with a 60-line preview.',
262
313
  parameters: Type.Object({
@@ -268,8 +319,15 @@ export default function slackExtension(pi: ExtensionAPI) {
268
319
  return guarded(async () => {
269
320
  const { deps } = await resolveCall("user", cfg, ctx, signal, repoRoot);
270
321
  const result = await searchMessages(params, deps);
322
+ const structured = structuredMessages(result.matches, "search");
271
323
  return {
272
324
  content: [{ type: "text" as const, text: searchResultText(result) }],
325
+ structuredContent: {
326
+ ...("messages" in structured ? { matches: structured.messages } : structured),
327
+ total: result.total,
328
+ page: result.page,
329
+ page_count: result.pageCount,
330
+ },
273
331
  details: result,
274
332
  };
275
333
  }, "user");
@@ -282,8 +340,12 @@ export default function slackExtension(pi: ExtensionAPI) {
282
340
  name: "slack_thread",
283
341
  label: "Slack Thread",
284
342
  promptSnippet: "Read all replies in a Slack thread",
343
+ outputSchema: Type.Union([
344
+ Type.Object({ messages: Type.Array(SlackMessage), ...threadFields }),
345
+ Type.Object({ file: Type.String(), ...threadFields }),
346
+ ]),
285
347
  description:
286
- '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. `raw: true` is for block extraction and slack_update round-trips: it returns the thread messages as a pure JSON array (no status trailer - `complete`/`next_cursor` stay in the result details and are not visible in the content, so an incomplete raw thread is a partial array with no in-content signal: try JSON.parse, on failure read the file named in the truncation line, and use default mode when completeness matters). Both modes are size-gated like slack_search: over the cap the full output is written to a temp file.',
348
+ '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. `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.',
287
349
  parameters: Type.Object({
288
350
  channel: Type.Optional(Type.String({ description: "#name, channel ID, @name, or user ID (DM)" })),
289
351
  ts: Type.Optional(Type.String({ description: "Thread parent timestamp" })),
@@ -302,6 +364,13 @@ export default function slackExtension(pi: ExtensionAPI) {
302
364
  );
303
365
  return {
304
366
  content: [{ type: "text" as const, text: threadResultText(result, params.raw === true) }],
367
+ structuredContent: {
368
+ ...structuredMessages(result.messages, "thread"),
369
+ complete: result.complete,
370
+ message_count: result.messageCount,
371
+ ...(result.nextCursor !== undefined ? { next_cursor: result.nextCursor } : {}),
372
+ ...(result.caveat !== undefined ? { caveat: result.caveat } : {}),
373
+ },
305
374
  details: result,
306
375
  };
307
376
  }, "user");
@@ -315,8 +384,8 @@ export default function slackExtension(pi: ExtensionAPI) {
315
384
  label: "Slack Post",
316
385
  promptSnippet: "Post a Slack message, reply, or headline+detail announcement",
317
386
  description:
318
- "Post a Slack message via chat.postMessage, as `as: \"user\"` or `as: \"bot\"`. `channel` accepts #name, channel ID, @name, or user ID (DM). Plain post: `text` and/or `blocks` (Block Kit JSON, passed through unvalidated). Threaded reply: also set `thread_ts` - no headline is ever emitted, `thread_body` (or `text`) becomes the reply body. Announce mode: set `thread_body` WITHOUT `thread_ts` - posts a short single-line `text` headline, then posts the detail `blocks` with `thread_body` fallback (or text-only `thread_body`) as the first threaded reply in the same call; for text-only detail, if `thread_body`'s rendered length exceeds the configured uploadThresholdChars (default 4000), it is delivered as a threaded file upload instead. Recovery: re-invoke with `thread_ts` set (never re-omit it) to post only into the existing thread - a second headline is never sent. On detail-delivery failure the headline is marked \"detail pending\" and the detail is saved to a temp file; the returned error supplies recovery-artifact details. `unfurl_links`/`unfurl_media` apply to this post only, are omitted when unset (Slack's default stands), and slack_update cannot change unfurling after the fact." + "\n\n" + SLACK_FORMATTING_GUIDANCE.rules.join("\n") + "\n\n" + SLACK_FORMATTING_GUIDANCE.example,
319
- promptGuidelines: SLACK_FORMATTING_GUIDANCE.rules,
387
+ "Post a Slack message via chat.postMessage, as `as: \"user\"` or `as: \"bot\"`. `channel` accepts #name, channel ID, @name, or user ID (DM). Plain post: `text` and/or `blocks` (Block Kit JSON, passed through unvalidated). Threaded reply: also set `thread_ts` - no headline is ever emitted, `thread_body` (or `text`) becomes the reply body. Announce mode: set `thread_body` WITHOUT `thread_ts` - posts a short single-line `text` headline, then posts the detail `blocks` with `thread_body` fallback (or text-only `thread_body`) as the first threaded reply in the same call; for text-only detail, if `thread_body`'s rendered length exceeds the configured uploadThresholdChars (default 4000), it is delivered as a threaded file upload instead. Recovery: re-invoke with `thread_ts` set (never re-omit it) to post only into the existing thread - a second headline is never sent. On detail-delivery failure the headline is marked \"detail pending\" and the detail is saved to a temp file; the returned error supplies recovery-artifact details. `unfurl_links`/`unfurl_media` apply to this post only, are omitted when unset (Slack's default stands), and slack_update cannot change unfurling after the fact.",
388
+ promptGuidelines: [...SLACK_FORMATTING_GUIDANCE.rules, SLACK_FORMATTING_GUIDANCE.example],
320
389
  parameters: Type.Object({
321
390
  as: IDENTITY,
322
391
  channel: Type.String({ description: "#name, channel ID, @name, or user ID (DM)" }),
@@ -398,8 +467,8 @@ export default function slackExtension(pi: ExtensionAPI) {
398
467
  label: "Slack Update",
399
468
  promptSnippet: "Edit an existing Slack message",
400
469
  description:
401
- 'Edit a message via chat.update, as `as: "user"` or `as: "bot"`. `channel` accepts #name, channel ID, @name, or user ID (DM). Only the identity that originally posted the message can edit it (Slack constraint; surfaced as an error otherwise). Accepts `text` and/or `blocks` (Block Kit JSON, unvalidated).' + "\n\n" + SLACK_FORMATTING_GUIDANCE.rules.join("\n") + "\n\n" + SLACK_FORMATTING_GUIDANCE.example,
402
- promptGuidelines: SLACK_FORMATTING_GUIDANCE.rules,
470
+ 'Edit a message via chat.update, as `as: "user"` or `as: "bot"`. `channel` accepts #name, channel ID, @name, or user ID (DM). Only the identity that originally posted the message can edit it (Slack constraint; surfaced as an error otherwise). Accepts `text` and/or `blocks` (Block Kit JSON, unvalidated).',
471
+ promptGuidelines: [...SLACK_FORMATTING_GUIDANCE.rules, SLACK_FORMATTING_GUIDANCE.example],
403
472
  parameters: Type.Object({
404
473
  as: IDENTITY,
405
474
  channel: Type.String({ description: "#name, channel ID, @name, or user ID (DM)" }),
@@ -526,10 +595,11 @@ export default function slackExtension(pi: ExtensionAPI) {
526
595
 
527
596
  pi.registerTool({
528
597
  name: "slack_cache_refresh",
598
+ exposure: "codemode",
529
599
  label: "Slack Cache Refresh",
530
600
  promptSnippet: "Rebuild the Slack channel/user name->ID cache",
531
601
  description:
532
- 'Rebuild the Slack channel and user name->ID cache from scratch (full conversations.list + users.list scan, atomic replace). Uses the "user" identity when a user token is configured, else falls back to "bot" (no `as` param). Run this after channels/users change or when a #name/@name lookup unexpectedly fails with name_not_found. Reports the resulting channel, user, and email counts - a low email/user ratio hints the users:read.email scope may be missing.',
602
+ 'Refresh the channel/user name cache after channel_not_found or a rename; reachable only from codemode scripts as tools.slack_cache_refresh({}).',
533
603
  parameters: Type.Object({}),
534
604
  async execute(_toolCallId, _params, signal) {
535
605
  const identity = pickCacheRefreshIdentity(cfg, process.env, repoRoot);
@@ -1,4 +1,5 @@
1
1
  import type { InputType, OcrMode } from "./doc-to-md-options.ts";
2
+ import type { DocToMdDetails } from "./doc-to-md-core.ts";
2
3
 
3
4
  export type Tier = "primary" | "fallback" | "unpdf" | "excel" | "docx" | "html" | "image" | "email";
4
5
  export type Engine = "pymupdf4llm" | "pymupdf-text" | "unpdf" | "openpyxl" | "xlrd" | "mammoth" | "python-docx" | "markdownify" | "turndown" | "copy" | "extract-msg" | "email";
@@ -58,6 +59,13 @@ export interface InfoData {
58
59
  toc: TocEntry[]; tocTotal: number; sheets: SheetInfo[] | null; sheetsTotal: number;
59
60
  }
60
61
 
62
+ export type PublicHandleData = HandleData;
63
+
64
+ export function publicHandle(details: DocToMdDetails): PublicHandleData {
65
+ const { path, backend, pymupdfVersion, inputType, file, outputDir, ...handle } = details;
66
+ return handle;
67
+ }
68
+
61
69
  const TITLE_MAX = 80;
62
70
  const NOTE_MAX_LINES = 5;
63
71
  const NOTE_MAX_CHARS = 200;
@@ -60,6 +60,7 @@ export interface OptionDescriptor {
60
60
  settingsOnly?: boolean;
61
61
  enumValues?: readonly string[];
62
62
  help: string;
63
+ toolHelp?: string;
63
64
  }
64
65
 
65
66
  export class UsageError extends Error {}
@@ -72,12 +73,12 @@ export const IMAGE_EXTS: readonly string[] = [".png", ".jpg", ".jpeg", ".tif", "
72
73
  export const DOC_TO_MD_OPTIONS: readonly OptionDescriptor[] = [
73
74
  { key: "path", flag: null, type: "string", default: null, settable: false, help: "Local .pdf .docx .doc .pptx .xlsx .xlsm .xls .msg .eml .html .htm .png .jpg .jpeg .tif .tiff .bmp .gif file" },
74
75
  { key: "info", flag: "--info", type: "bool", default: false, settable: false, help: "Inspect only (page count, metadata, TOC or sheet inventory); no bundle" },
75
- { key: "pages", flag: "--pages", type: "pages", default: null, settable: false, help: "Inclusive 1-based pages, e.g. \"12-15\" or \"3,7,10-12\" (PDF/DOCX/DOC/PPTX only); default all; \"\" means all pages. DOCX: selects explicit-page-break segments; rejected when the file has none" },
76
- { key: "outputDir", flag: "--output-dir", type: "string", default: null, settable: false, help: "Bundle root for <stem>.md + images/; default a per-call temp dir. <stem> = basename without extension with [^A-Za-z0-9._-]+ -> _ (empty -> document); a second call on the same stem writes <stem>-2.md" },
76
+ { key: "pages", toolHelp: "Inclusive 1-based pages, e.g. \"12-15\" or \"3,7,10-12\" (PDF/DOCX/DOC/PPTX); default all; \"\" means all pages; DOCX selects explicit-page-break segments, rejected when the file has none.", flag: "--pages", type: "pages", default: null, settable: false, help: "Inclusive 1-based pages, e.g. \"12-15\" or \"3,7,10-12\" (PDF/DOCX/DOC/PPTX only); default all; \"\" means all pages. DOCX: selects explicit-page-break segments; rejected when the file has none" },
77
+ { key: "outputDir", toolHelp: "Bundle root for <stem>.md + images/; default a per-call temp dir.", flag: "--output-dir", type: "string", default: null, settable: false, help: "Bundle root for <stem>.md + images/; default a per-call temp dir. <stem> = basename without extension with [^A-Za-z0-9._-]+ -> _ (empty -> document); a second call on the same stem writes <stem>-2.md" },
77
78
  { key: "overwrite", flag: "--overwrite", type: "bool", default: false, settable: false, help: "Replace an existing completed <stem>.md bundle" },
78
79
  { key: "pageImages", flag: "--page-images", type: "bool", default: false, settable: false, help: "Also render every selected page to pages/<stem>-pNNN.<imageFormat> at imageDpi (PDF, PPTX, .doc, DOCX via LibreOffice); off by default" },
79
- { key: "words", flag: "--words", type: "bool", default: false, settable: false, help: "Write word positions: <stem>.words.json beside the Markdown lists every text-layer word of each selected page with its bbox (PDF points, top-left origin, display orientation; image inputs in source pixels) and the words inline OCR recognized, tagged source \"text\" or \"ocr\"; under --ocr-mode all the OCR words go to ocr/<stem>-pNNN.words.json beside each sidecar. Never triggers OCR. PDF and image inputs only." },
80
- { key: "ocrMode", flag: "--ocr-mode", type: "enum", default: "textless", settable: false, enumValues: ["textless", "all"], help: "OCR policy: textless (default) OCRs only pages with an empty text layer, inline; all OCRs every selected page and writes the recognized text to ocr/<stem>-pNNN.md sidecars, leaving the Markdown untouched. all requires --ocr and an explicit --pages selection (PDF, PPTX, DOC)." },
80
+ { key: "words", toolHelp: "Write word positions to <stem>.words.json, or ocr/<stem>-pNNN.words.json for ocrMode all. Never triggers OCR. PDF and image inputs only.", flag: "--words", type: "bool", default: false, settable: false, help: "Write word positions: <stem>.words.json beside the Markdown lists every text-layer word of each selected page with its bbox (PDF points, top-left origin, display orientation; image inputs in source pixels) and the words inline OCR recognized, tagged source \"text\" or \"ocr\"; under --ocr-mode all the OCR words go to ocr/<stem>-pNNN.words.json beside each sidecar. Never triggers OCR. PDF and image inputs only." },
81
+ { key: "ocrMode", toolHelp: "textless (default): OCR empty text layers inline. all: OCR selected pages to ocr/ sidecars without changing Markdown; requires ocr and explicit pages (PDF, PPTX, DOC).", flag: "--ocr-mode", type: "enum", default: "textless", settable: false, enumValues: ["textless", "all"], help: "OCR policy: textless (default) OCRs only pages with an empty text layer, inline; all OCRs every selected page and writes the recognized text to ocr/<stem>-pNNN.md sidecars, leaving the Markdown untouched. all requires --ocr and an explicit --pages selection (PDF, PPTX, DOC)." },
81
82
  { key: "primaryTimeoutMs", flag: "--primary-timeout", type: "int", default: 60000, settable: true, env: "PI_DOC_TO_MD_CONVERT_TIMEOUT_MS", help: "pymupdf4llm tier and DOCX child (docx mode); also the unpdf tier" },
82
83
  { key: "fallbackTimeoutMs", flag: "--fallback-timeout", type: "int", default: 30000, settable: true, help: "PyMuPDF get_text tier (including DOCX LibreOffice fallback); also PDF and DOCX info and Excel rendered views" },
83
84
  { key: "sofficeTimeoutMs", flag: "--soffice-timeout", type: "int", default: 120000, settable: true, env: "PI_DOC_TO_MD_SOFFICE_TIMEOUT_MS", help: "DOCX/PPTX -> PDF via LibreOffice; also Excel rendered views" },
@@ -91,7 +92,7 @@ export const DOC_TO_MD_OPTIONS: readonly OptionDescriptor[] = [
91
92
  { key: "ocr", flag: "--ocr", type: "bool", default: false, settable: true, help: "Run OCR on pages without a text layer and on image inputs when Tesseract language data is installed; off by default (--no-ocr turns a settings-level true off)" },
92
93
  { key: "ocrLanguage", flag: "--ocr-language", type: "lang", default: "eng", settable: true, help: "Tesseract language code(s), +-joined, e.g. deu+eng" },
93
94
  { key: "ocrMaxPages", flag: null, type: "int", default: 10, settable: true, settingsOnly: true, help: "Most pages one invocation OCRs; ocrMode all rejects a larger distinct-page selection before any work, textless mode OCRs the first ocrMaxPages textless pages and names the rest in the OCR: line" },
94
- { key: "hideAnnotations", flag: "--hide-annotations", type: "bool", default: false, settable: true, help: "Render PDF pages without annotations (sticky notes, highlights, stamps - and form-field widgets, so filled form values disappear); default paints them, as PyMuPDF does. Applies to pages/ renders and textless-page renders, not to OCR text or embedded images; also lets an annotated scan be delivered as its embedded image." },
95
+ { key: "hideAnnotations", toolHelp: "Render PDF pages without annotations or form widgets (filled values disappear); default paints them. Applies to pages/ and textless-page renders, not OCR text or embedded images.", flag: "--hide-annotations", type: "bool", default: false, settable: true, help: "Render PDF pages without annotations (sticky notes, highlights, stamps - and form-field widgets, so filled form values disappear); default paints them, as PyMuPDF does. Applies to pages/ renders and textless-page renders, not to OCR text or embedded images; also lets an annotated scan be delivered as its embedded image." },
95
96
  ];
96
97
 
97
98
  export const TUNABLE_DEFAULTS: Tunables = Object.fromEntries(
package/lib/fetch-core.ts CHANGED
@@ -53,6 +53,7 @@ export interface FetchOptions {
53
53
  }
54
54
 
55
55
  export interface FetchResult {
56
+ body: string;
56
57
  output: string;
57
58
  details: FetchToolDetails;
58
59
  }
@@ -177,6 +178,7 @@ function renderGhResult(target: GhTarget, stdout: string, failedLogs?: string):
177
178
  : `Source: ${ghSourceLine(target, ref)}`;
178
179
  if (!spill) {
179
180
  return {
181
+ body,
180
182
  output: [source, "", body].join("\n"),
181
183
  details: { ...baseDetails, spilled: false },
182
184
  };
@@ -184,6 +186,7 @@ function renderGhResult(target: GhTarget, stdout: string, failedLogs?: string):
184
186
  const spillUrl = target.kind === "repo" ? `https://github.com/${target.slug}` : target.url;
185
187
  const file = spillToFile(spillUrl, body, "md");
186
188
  return {
189
+ body: "",
187
190
  output: [
188
191
  source,
189
192
  `Body: ${formatSize(bytes)} across ${lines} lines — written to file (too large to inline)`,
@@ -534,8 +537,9 @@ export async function fetchUrl(opts: FetchOptions): Promise<FetchResult> {
534
537
  // HEAD or bodyless response: headers only.
535
538
  if (!res.body || (opts.method ?? "GET") === "HEAD") {
536
539
  return {
540
+ body: "",
537
541
  output: [...header, "Length: 0 (no body)"].join("\n"),
538
- details: { url: res.url, status: res.status, contentType: ct, charset, bytes: 0 } as FetchToolDetails,
542
+ details: { url: res.url, status: res.status, ...(res.headers.has("content-type") ? { contentType: ct } : {}), charset, bytes: 0 },
539
543
  };
540
544
  }
541
545
 
@@ -543,7 +547,7 @@ export async function fetchUrl(opts: FetchOptions): Promise<FetchResult> {
543
547
  const baseDetails: FetchToolDetails = {
544
548
  url: res.url,
545
549
  status: res.status,
546
- contentType: ct,
550
+ ...(res.headers.has("content-type") ? { contentType: ct } : {}),
547
551
  charset,
548
552
  bytes: collected.bytes,
549
553
  truncated: collected.truncated,
@@ -553,6 +557,7 @@ export async function fetchUrl(opts: FetchOptions): Promise<FetchResult> {
553
557
  if (collected.category === "binary") {
554
558
  const note = collected.truncated ? " (truncated to 50MB)" : "";
555
559
  return {
560
+ body: "",
556
561
  output: [
557
562
  ...header,
558
563
  `Body: ${formatSize(collected.bytes)}${note} binary (${mimeType(ct) || "unknown"}) — saved untouched for processing`,
@@ -589,6 +594,7 @@ export async function fetchUrl(opts: FetchOptions): Promise<FetchResult> {
589
594
 
590
595
  if (!spill) {
591
596
  return {
597
+ body,
592
598
  output: [...header, lengthLine, "", body + truncNote].join("\n"),
593
599
  details: { ...baseDetails, spilled: false },
594
600
  };
@@ -600,6 +606,7 @@ export async function fetchUrl(opts: FetchOptions): Promise<FetchResult> {
600
606
  ? "Read slices of this file with the read tool (offset/limit) or grep it; do not read the whole file unless you must. Markdown is grep-able by heading (^#)."
601
607
  : "Read slices of this file with the read tool (offset/limit) or grep it; do not read the whole file unless you must.";
602
608
  return {
609
+ body: "",
603
610
  output: [
604
611
  ...header,
605
612
  lengthLine,
package/lib/slack-core.ts CHANGED
@@ -309,7 +309,6 @@ export type UploadBytes = (url: string, bytes: Uint8Array, opts?: { signal?: Abo
309
309
  const JSON_METHODS = new Set(["chat.postMessage", "chat.update", "canvases.edit"]);
310
310
 
311
311
  export const ERROR_HINTS: Record<string, string> = {
312
- channel_not_found: "check the name or run slack_cache_refresh",
313
312
  not_in_channel: "invite the bot to the channel",
314
313
  msg_too_long: "message exceeds Slack's length ceiling",
315
314
  is_archived: "the channel is archived",
@@ -507,6 +506,7 @@ export const THREAD_PAGE_CAP = 50;
507
506
  export const THREAD_MESSAGE_CAP = 5_000;
508
507
 
509
508
  export interface SearchResult {
509
+ matches: Record<string, unknown>[];
510
510
  output: string;
511
511
  spilled: boolean;
512
512
  path?: string;
@@ -516,6 +516,7 @@ export interface SearchResult {
516
516
  }
517
517
 
518
518
  export interface ThreadResult {
519
+ messages: Record<string, unknown>[];
519
520
  output: string;
520
521
  spilled: boolean;
521
522
  path?: string;
@@ -564,7 +565,7 @@ export async function searchMessages(
564
565
 
565
566
  const rendered = matches.map(renderSearchLine).join("\n");
566
567
  const gated = gateOutput(rendered, "search");
567
- return { ...gated, total, page, pageCount };
568
+ return { ...gated, matches, total, page, pageCount };
568
569
  }
569
570
 
570
571
  function inlineElementText(element: unknown): string {
@@ -735,7 +736,7 @@ export async function readThread(
735
736
 
736
737
  const rendered = args.raw === true ? JSON.stringify(messages, null, 2) : messages.map(renderThreadLine).join("\n");
737
738
  const gated = gateOutput(rendered, "thread");
738
- return { ...gated, complete, nextCursor, caveat, messageCount: messages.length };
739
+ return { ...gated, messages, complete, nextCursor, caveat, messageCount: messages.length };
739
740
  }
740
741
 
741
742
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-quiver",
3
- "version": "6.15.2",
3
+ "version": "6.16.0",
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, Opus 4.8 fast mode, and a provider-stall watchdog.",
5
5
  "author": "Jacek Juraszek",
6
6
  "license": "MIT",
@@ -27,7 +27,7 @@
27
27
  "cli"
28
28
  ],
29
29
  "engines": {
30
- "node": ">=20"
30
+ "node": "^24.15.0 || >=26.0.0"
31
31
  },
32
32
  "bin": {
33
33
  "pi-quiver": "dist/bin/pi-quiver.js"
@@ -87,20 +87,21 @@
87
87
  },
88
88
  "dependencies": {
89
89
  "@mozilla/readability": "^0.6.0",
90
- "jsdom": "^26.0.0",
91
- "turndown": "^7.2.0",
90
+ "jsdom": "^31.0.0",
91
+ "turndown": "^7.2.5",
92
92
  "turndown-plugin-gfm": "^1.0.2",
93
- "unpdf": "^1.8.1"
93
+ "unpdf": "^2.1.0"
94
94
  },
95
95
  "devDependencies": {
96
- "@earendil-works/pi-ai": "^0.87.1",
97
- "@earendil-works/pi-coding-agent": "^0.87.1",
98
- "@earendil-works/pi-tui": "^0.87.1",
99
- "@sinclair/typebox": "^0.34.49",
100
- "@types/jsdom": "^28.0.3",
101
- "@types/node": "^26.1.0",
96
+ "@earendil-works/pi-ai": "^1.5.0",
97
+ "@earendil-works/pi-codemode": "^1.5.0",
98
+ "@earendil-works/pi-coding-agent": "^1.5.0",
99
+ "@earendil-works/pi-tui": "^1.5.0",
100
+ "@sinclair/typebox": "^0.34.52",
101
+ "@types/jsdom": "^30.0.0",
102
+ "@types/node": "^26.6.6",
102
103
  "@types/turndown": "^5.0.6",
103
104
  "esbuild": "^0.28.2",
104
- "typescript": "^6.0.3"
105
+ "typescript": "^7.0.2"
105
106
  }
106
107
  }