pi-quiver 6.16.3 → 6.17.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
@@ -3,6 +3,14 @@
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.17.0 - 2026-11-20
7
+
8
+ - `message-timestamps` shows the newest saved message's local date and time in pi's shared terminal footer by default. Set `quiver.messageTimestamps.transcript` to `true` for dim time lines after prompts and settled runs, or use `/timestamps` to change either display for the current session. (#44)
9
+
10
+ ## v6.16.4 - 2026-11-19
11
+
12
+ - `slack_search` and `slack_thread` compact text renders `<@U...>` as `@Display Name` when the user is in the name cache, and a labeled `<!subteam^S...|@handle>` as `@handle`. A `rich_text` `usergroup` element renders as `<!subteam^S...>` instead of `[usergroup]`. Uncached user tokens keep their original spelling and optional label; uncached `rich_text` users render as `<@ID>`. Literal text, code, raw output, and structured results keep Slack's tokens. (#42)
13
+
6
14
  ## v6.16.3 - 2026-11-17
7
15
 
8
16
  - `fast-mode` applies to a custom provider entry whose `baseUrl` host is `api.anthropic.com`, not only to pi's built-in `anthropic` provider. Proxy providers stay excluded. (#41)
package/README.md CHANGED
@@ -18,7 +18,7 @@ But the moment an agent does that, one `fetch` or PDF read can dump hundreds of
18
18
 
19
19
  `fetch` brings real web pages and GitHub issues/PRs into context and is size-gated by construction: over 32 KB or 1000 lines spills to a temp file with a preview and a grep/read hint. `doc_to_md` converts local PDF/DOCX/DOC/PPTX/XLSX/XLSM/XLS, MSG/EML, HTML, and image files into a Markdown bundle on disk and returns only a concise handle; OCR is opt-in and uses optional Tesseract language data. Ingestion is what makes data-driven work possible; bounded tool results keep it safe.
20
20
 
21
- `session-name`, `sword-header`, `fast-mode`, `provider-stall-watchdog`, and `slack` are opt-in ergonomics, recovery, and integration controls: session labeling, a themed startup header, Anthropic fast mode, semantic-stall recovery, and context-safe Slack search/threads/posting with repo-policy injection, `@name` mention resolution, cached emails, and per-call unfurl control.
21
+ `message-timestamps` shows the newest saved message's date and time in the terminal footer without setup. Its transcript lines are opt-in. `session-name`, `sword-header`, `fast-mode`, `provider-stall-watchdog`, and `slack` are opt-in ergonomics, recovery, and integration controls: session labeling, a themed startup header, Anthropic fast mode, semantic-stall recovery, and context-safe Slack search/threads/posting with repo-policy injection, `@name` mention resolution, cached emails, and per-call unfurl control.
22
22
 
23
23
  ## Part of the pi agent toolkit
24
24
 
@@ -33,7 +33,7 @@ No code dependency between them. pi-quiver is call-level: `fetch` gates the size
33
33
 
34
34
  ## Mental model
35
35
 
36
- Every ingestion extension here is context-safe by construction, not by convention: `fetch` size-gates every call, while `doc_to_md` always writes a bundle and returns a handle instead of inline Markdown. `fetch` and `doc_to_md` bring real sources in; `session-name`, `sword-header`, `fast-mode`, `provider-stall-watchdog`, and `slack` are opt-in.
36
+ Every ingestion extension here is context-safe by construction, not by convention: `fetch` size-gates every call, while `doc_to_md` always writes a bundle and returns a handle instead of inline Markdown. `fetch` and `doc_to_md` bring real sources in, and `message-timestamps` shows the last-message time in the footer by default. Its transcript lines stay off until enabled. `session-name`, `sword-header`, `fast-mode`, `provider-stall-watchdog`, and `slack` are opt-in.
37
37
 
38
38
  ```mermaid
39
39
  flowchart LR
@@ -66,6 +66,7 @@ A 300 KB changelog page never touches your context window - you get a preview an
66
66
  | --- | --- | --- |
67
67
  | `extensions/fetch.ts` | `fetch` | Retrieve URLs over HTTP(S). HTML -> Markdown (Readability extraction, Turndown conversion). Binary saved untouched to a temp file. GitHub issue/PR/repo/actions-run/actions-job URLs auto-route through `gh` (falls back to HTTP); failed runs/jobs include failed-step logs (best-effort, summary-only otherwise). Same size gate as `fetch`. Behavior lives in `lib/fetch-core.ts`; also exposed as the `pi-quiver fetch` CLI (see [Claude Code support](#claude-code-support)). |
68
68
  | `extensions/doc_to_md.ts` | `doc_to_md` | Convert a local PDF/DOCX/DOC/PPTX/XLSX/XLSM/XLS, MSG/EML, HTML, or image file to a Markdown bundle on disk (`<stem>.md` + `images/`, spreadsheet `sheets/`, optional `pageImages` in `pages/`, and email `attachments/`) and return a handle (paths, page count, outline, diagnostics) - never inline Markdown. `info` inspects PDF/Office inputs; `pages` selects 1-based PDF/Office pages (DOCX: explicit-page-break segments); HTML, image, and email inputs reject both; every selected PDF/PPTX page or DOCX segment when `pageCount > 1` ends with `--- end of page.page_number=N ---`. Tiers: pymupdf4llm -> PyMuPDF text (degraded) -> unpdf worker (no Python only). Excel -> sheet inventory, full CSVs, bounded previews, and optional rendered views. HTML keeps local and `data:` images in the bundle and remote images as links; image inputs keep the original image. Scanned PDF pages keep a page picture on both Python tiers; eligible single full-page images are delivered as their embedded stream, without re-encoding or render DPI; opt-in OCR needs Tesseract language data. DOCX converts directly (mammoth, python-docx fallback); LibreOffice pagination marks the degraded route. The Outline lists `L<line>` and `p<page>` per heading. Settings under `quiver.docToMd`. Every conversion that goes through the Python PDF tiers (PDF, PPTX, `.doc`, DOCX via LibreOffice) writes `<stem>.pages.json` (per-page chars, image count, image coverage; handle line `Page-Stats:`); unpdf writes no stats. `ocrMode: "all"` with `ocr: true` and an explicit `pages` forces OCR on those pages into `ocr/<stem>-pNNN.md` sidecars, leaving the Markdown byte-identical to the same selected-page call without OCR. `words: true` (CLI `--words`, per-call only - no settings key) writes `<stem>.words.json` with every word's bbox per selected PDF/image page (`source` `text` or `ocr`), plus `ocr/<stem>-pNNN.words.json` beside each forced-OCR sidecar; it never triggers OCR. |
69
+ | `extensions/message-timestamps.ts` | `/timestamps` | Show the newest saved message time in the shared footer (on by default). Add dim time lines after prompts and settled runs (off by default). |
69
70
  | `extensions/session-name.ts` | `/session-name` | Manual + opt-in automatic session naming, naming rules and deny list, long-session revisits, and Ghostty/Herdr tab rename. OFF by default. |
70
71
  | `extensions/sword-header.ts` | `/builtin-header` | Themed ASCII startup header replacing pi's default logo. OFF by default. |
71
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. |
@@ -83,7 +84,7 @@ Full routing rules, size-gate mechanics, and config: [doc/fetch.md](doc/fetch.md
83
84
  | Size gate | Text/Markdown/JSON output over 32 KB or 1000 lines spills to a temp file with a 60-line preview instead of inlining. |
84
85
  | Content routing | HTML -> Markdown, binary -> untouched file, GitHub URLs -> `gh` CLI (failed runs/jobs get failed-step logs appended), everything else -> the size gate. |
85
86
  | Graceful degradation | Optional binaries (`gh`, `uv`, LibreOffice) are never hard install-time deps; each has a defined, documented fallback or failure mode. |
86
- | Opt-in extensions | `session-name`, `sword-header`, `fast-mode`, `provider-stall-watchdog`, and `slack` do nothing until explicitly enabled in `settings.json`. |
87
+ | Opt-in extensions | `session-name`, `sword-header`, `fast-mode`, `provider-stall-watchdog`, and `slack` do nothing until explicitly enabled in `settings.json`. The timestamp footer is on without setup; transcript lines are opt-in. |
87
88
  | Provider stall recovery | The watchdog detects a missing first stream event and missing parsed semantic progress, not network liveness. The pre-first-event tier covers every mode and origin; the mid-stream tier is TUI-only. |
88
89
 
89
90
  ## When to use
@@ -143,9 +144,26 @@ The npm package's bundled JS deps install automatically on `pi install`. A few *
143
144
 
144
145
  None is a hard install-time dependency of the package; they are tools you provide in the environment where pi runs.
145
146
 
147
+ ### Message timestamps
148
+
149
+ The two displays work only in the terminal UI. Set them independently under `quiver.messageTimestamps` in `settings.json`. A project's `.pi/settings.json` applies only when pi trusts the project.
150
+
151
+ | Switch | What it shows |
152
+ |---|---|
153
+ | `footer` (default `true`) | The newest saved message's local date and time on the shared footer row. Tool and shell results and saved custom messages count; timestamp records do not. |
154
+ | `transcript` (default `false`) | A dim local date and time after each prompt delivered to the model and after each settled run. The records stay in the session file and never reach the model. |
155
+
156
+ If you run a `!` shell command during a model run, its output can appear below the final time line in live chat. On resume, the output appears above that line; the time stays the same.
157
+
158
+ A shell result or custom message saved while pi is idle updates the footer time on the next prompt, `/tree`, `/timestamps footer on`, or session start. During a run, another extension can queue several custom messages for the end of the turn. Pi saves them in one batch. At the next refresh, the footer shows only the newest message's time. The extension adds no timer or polling.
159
+
160
+ Use `/timestamps` to see both settings. `/timestamps footer on` and `/timestamps footer off` change the footer immediately. `/timestamps transcript on` and `/timestamps transcript off` control new lines from the next message. These commands apply only to the current session; reloading or switching sessions restores the settings from disk.
161
+
162
+ Changing the transcript switch does not redraw the chat. After switching it off, Ctrl+O hides lines that pi redraws. After switching it on, a stored line that was not drawn needs a transcript rebuild (such as `/tree`) to appear.
163
+
146
164
  ### Opt-in extension config
147
165
 
148
- These extensions are opt-in via `settings.json` (project `.pi/settings.json` overrides the global agent-dir layer), nested under an optional `"quiver"` root:
166
+ The following extensions are opt-in via `settings.json` (project `.pi/settings.json` overrides the global agent-dir layer), nested under an optional `"quiver"` root:
149
167
 
150
168
  ```jsonc
151
169
  {
@@ -294,7 +312,7 @@ Operational notes:
294
312
  | `botTokenEnv` | `SLACK_BOT_TOKEN` | Env var name holding the bot token. |
295
313
  | `uploadThresholdChars` | `4000` | Link-collapsed length above which an announce/thread detail body is delivered as a file upload instead of inline text. |
296
314
 
297
- Each setting can also be overridden per-process via `PI_QUIVER_SLACK_ENABLED`, `PI_QUIVER_SLACK_CACHE_PATH`, `PI_QUIVER_SLACK_USER_TOKEN_ENV`, `PI_QUIVER_SLACK_BOT_TOKEN_ENV`, and `PI_QUIVER_SLACK_UPLOAD_THRESHOLD_CHARS` - applied on top of the resolved `settings.json` layers, same override rung the extension's config resolver defines. `userTokenCommand` and `userTokenCommandTimeoutSeconds` are settings-only: pi executes the argv directly, without a shell, on every user-identity Slack tool call. For example, macOS Keychain can supply the token with `"userTokenCommand": ["security", "find-generic-password", "-s", "slack-user-token", "-w"]`. Its stdout is the token; empty output, nonzero exit, or timeout is a sanitized hard error and never falls back to `userTokenEnv`. Without the command, tokens resolve per call from process env, then the repo `.env`, then the primary checkout's `.env` (linked worktrees), then a per-user `~/.config/pi-quiver/.env` (`$XDG_CONFIG_HOME` / `%APPDATA%` aware); a file lacking the key falls through to the next rung - see [doc/slack.md](doc/slack.md). Bot resolution is unchanged. Restart pi after changing Slack settings because the extension captures them at session start. `slack_thread` flattens Block Kit blocks by default and accepts `raw: true` for JSON output suitable for `slack_update` round-trips. Full reference incl. cache layering, the announce protocol, thread output modes, and the `search.messages`/`conversations.replies` throttle caveats: [doc/slack.md](doc/slack.md).
315
+ Each setting can also be overridden per-process via `PI_QUIVER_SLACK_ENABLED`, `PI_QUIVER_SLACK_CACHE_PATH`, `PI_QUIVER_SLACK_USER_TOKEN_ENV`, `PI_QUIVER_SLACK_BOT_TOKEN_ENV`, and `PI_QUIVER_SLACK_UPLOAD_THRESHOLD_CHARS` - applied on top of the resolved `settings.json` layers, same override rung the extension's config resolver defines. `userTokenCommand` and `userTokenCommandTimeoutSeconds` are settings-only: pi executes the argv directly, without a shell, on every user-identity Slack tool call. For example, macOS Keychain can supply the token with `"userTokenCommand": ["security", "find-generic-password", "-s", "slack-user-token", "-w"]`. Its stdout is the token; empty output, nonzero exit, or timeout is a sanitized hard error and never falls back to `userTokenEnv`. Without the command, tokens resolve per call from process env, then the repo `.env`, then the primary checkout's `.env` (linked worktrees), then a per-user `~/.config/pi-quiver/.env` (`$XDG_CONFIG_HOME` / `%APPDATA%` aware); a file lacking the key falls through to the next rung - see [doc/slack.md](doc/slack.md). Bot resolution is unchanged. Restart pi after changing Slack settings because the extension captures them at session start. `slack_thread` flattens Block Kit blocks by default and accepts `raw: true` for JSON output suitable for `slack_update` round-trips. Compact `slack_search` and `slack_thread` text renders cached user mentions as `@Display Name` and keeps uncached tokens as Slack sent them, including any label. Full reference incl. cache layering, the announce protocol, thread output modes, and the `search.messages`/`conversations.replies` throttle caveats: [doc/slack.md](doc/slack.md).
298
316
 
299
317
  ### doc_to_md settings
300
318
 
@@ -354,7 +372,7 @@ to, and a flat `slack` block is ignored without a warning.
354
372
 
355
373
  **Exposed:** the `quiver` plugin, served from this repo's `.claude-plugin/marketplace.json`, with three skills: `fetch` (invoked as `quiver:fetch` / `/quiver:fetch`), `doc-to-md` (invoked as `quiver:doc-to-md` / `/quiver:doc-to-md`), and `elevator` (invoked as `/quiver:elevator`, user-invoked only). The `fetch` skill runs `npx -y pi-quiver@latest fetch <url> [flags]` via Bash - full parameter parity with the pi tool (`--method`, `--header`, `--body`, `--raw`, `--timeout-ms`), same GitHub `gh` routing (including failed-step logs on failed runs/jobs), same size gate, same binary-to-temp-file handling. See [doc/fetch.md](doc/fetch.md#claude-code-cli-pi-quiver-fetch) for exit codes and flags. The `doc-to-md` skill is generated at release from its hand-written intro and option schema; it runs `npx -y pi-quiver@<release version> doc-to-md [flags] <path>` with full flag parity and the same handle output. See [doc/doc-to-md.md](doc/doc-to-md.md#cli-pi-quiver-doc-to-md) for exit codes and flags, and [install channels](doc/doc-to-md.md#install-channels) for npm versus marketplace updates.
356
374
 
357
- **Not exposed as plugin skills:** the other pi extensions in this package (`session-name`, `sword-header`, `fast-mode`, `provider-stall-watchdog`, `slack`); Slack is available through the CLI instead. The marketplace allowlists only `./skills/fetch`, `./skills/doc-to-md`, and `./skills/elevator`, and the npm tarball never ships `skills/` or `.claude-plugin/` (pi's own `files` allowlist excludes them, and pi's explicit `pi.extensions` manifest makes them invisible to pi's convention-directory auto-discovery either way).
375
+ **Not exposed as plugin skills:** the other pi extensions in this package (`message-timestamps`, `session-name`, `sword-header`, `fast-mode`, `provider-stall-watchdog`, `slack`); Slack is available through the CLI instead. The marketplace allowlists only `./skills/fetch`, `./skills/doc-to-md`, and `./skills/elevator`, and the npm tarball never ships `skills/` or `.claude-plugin/` (pi's own `files` allowlist excludes them, and pi's explicit `pi.extensions` manifest makes them invisible to pi's convention-directory auto-discovery either way).
358
376
 
359
377
  Add the marketplace and enable the plugin in `.claude/settings.json`:
360
378
 
@@ -2110,7 +2110,8 @@ var QUIVER_CONFIG_KEYS = {
2110
2110
  swordHeader: ["enabled"],
2111
2111
  providerStallWatchdog: ["enabled", "firstEventMs", "warningMs", "recoveryMs", "maxStallRetries", "models"],
2112
2112
  slack: ["enabled", "cachePath", "policyPath", "userTokenEnv", "userTokenCommand", "userTokenCommandTimeoutSeconds", "botTokenEnv", "uploadThresholdChars"],
2113
- docToMd: DOC_TO_MD_OPTIONS.filter((o) => o.settable).map((o) => o.key)
2113
+ docToMd: DOC_TO_MD_OPTIONS.filter((o) => o.settable).map((o) => o.key),
2114
+ messageTimestamps: ["footer", "transcript"]
2114
2115
  };
2115
2116
  var isPlainObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
2116
2117
  var emittedWarnings = /* @__PURE__ */ new Set();
@@ -0,0 +1,121 @@
1
+ import { join } from "node:path";
2
+ import { getAgentDir, type ExtensionAPI, type ExtensionContext, type SessionEntry } from "@earendil-works/pi-coding-agent";
3
+
4
+ import { Text } from "@earendil-works/pi-tui";
5
+
6
+ import { resolveConfigFrom } from "../lib/settings-core.ts";
7
+
8
+ export const DEFAULT_CONFIG = { footer: true, transcript: false };
9
+
10
+ type Config = typeof DEFAULT_CONFIG;
11
+
12
+ function coerce(raw: unknown): Partial<Config> | undefined {
13
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
14
+ const patch: Partial<Config> = {};
15
+ if ("footer" in raw && typeof raw.footer === "boolean") patch.footer = raw.footer;
16
+ if ("transcript" in raw && typeof raw.transcript === "boolean") patch.transcript = raw.transcript;
17
+ return patch;
18
+ }
19
+
20
+ export function resolveTimestampConfig(settings: ReturnType<ExtensionAPI["getSettings"]>, warn?: (message: string) => void): Config {
21
+ const global = resolveConfigFrom([join(getAgentDir(), "settings.json")], "messageTimestamps", DEFAULT_CONFIG, coerce, warn);
22
+ const { quiver } = settings as { quiver?: { messageTimestamps?: unknown } };
23
+ return { ...global, ...coerce(quiver?.messageTimestamps) };
24
+ }
25
+
26
+ export function formatTime(date: Date, locale?: string, timeZone?: string): string {
27
+ return new Intl.DateTimeFormat(locale, {
28
+ month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", timeZone,
29
+ }).format(date);
30
+ }
31
+
32
+ export function newestMessageTime(branch: readonly SessionEntry[]): string | undefined {
33
+ for (let i = branch.length - 1; i >= 0; i--) {
34
+ const entry = branch[i];
35
+ if (entry.type === "message" || entry.type === "custom_message") return entry.timestamp;
36
+ }
37
+ return undefined;
38
+ }
39
+
40
+ export function parseArgs(args: string) {
41
+ const trimmed = args.trim();
42
+ if (!trimmed) return { kind: "status" } as const;
43
+ const [target, state, extra] = trimmed.split(/\s+/);
44
+ if (!extra && (target === "footer" || target === "transcript") && (state === "on" || state === "off")) {
45
+ return { kind: "set", target, on: state === "on" } as const;
46
+ }
47
+ return { kind: "usage" } as const;
48
+ }
49
+
50
+ export default function (pi: ExtensionAPI) {
51
+ let config: { footer: boolean; transcript?: boolean } = { footer: DEFAULT_CONFIG.footer };
52
+ let promptPending = false;
53
+
54
+ const recordType = "message-timestamp";
55
+ pi.registerEntryRenderer(recordType, (entry, _options, theme) => {
56
+ if (config.transcript === undefined) {
57
+ // Reload and session replacement bind the destination's core settings before replay, but emit session_start after it.
58
+ config = resolveTimestampConfig(pi.getSettings());
59
+ }
60
+ return config.transcript ? new Text(theme.fg("dim", formatTime(new Date(entry.timestamp))), 1, 0) : undefined;
61
+ });
62
+
63
+ function refreshFooter(ctx: ExtensionContext) {
64
+ const timestamp = config.footer ? newestMessageTime(ctx.sessionManager.getBranch()) : undefined;
65
+ ctx.ui.setStatus("message-timestamps", timestamp === undefined ? undefined :
66
+ ctx.ui.theme.fg("dim", `last message ${formatTime(new Date(timestamp))}`));
67
+ }
68
+
69
+ pi.on("session_start", (_event, ctx) => {
70
+ if (ctx.mode !== "tui") return;
71
+ promptPending = false;
72
+ config = resolveTimestampConfig(pi.getSettings(), (m) => ctx.ui.notify(m, "warning"));
73
+ refreshFooter(ctx);
74
+ });
75
+
76
+ function refresh(_event: unknown, ctx: ExtensionContext) {
77
+ if (ctx.mode === "tui") refreshFooter(ctx);
78
+ }
79
+ pi.on("session_tree", refresh);
80
+
81
+ pi.on("message_end", (event, ctx) => {
82
+ if (ctx.mode !== "tui") return;
83
+ if (event.message.role === "user") promptPending = config.transcript === true;
84
+ });
85
+
86
+ // message_end precedes persistence. Flush after the prompt's save, before the next sibling or model request.
87
+ function flushPromptRecord(_event: unknown, ctx: ExtensionContext) {
88
+ if (ctx.mode !== "tui") return;
89
+ if (promptPending && config.transcript) pi.appendEntry(recordType);
90
+ promptPending = false;
91
+ }
92
+ pi.on("message_start", flushPromptRecord);
93
+ pi.on("context", flushPromptRecord);
94
+ pi.on("agent_settled", (_event, ctx) => {
95
+ if (ctx.mode !== "tui") return;
96
+ if (config.transcript) pi.appendEntry(recordType);
97
+ });
98
+
99
+ pi.on("message_start", refresh);
100
+ pi.on("context", refresh);
101
+ pi.on("tool_execution_start", refresh);
102
+ pi.on("turn_end", refresh);
103
+ pi.on("agent_settled", refresh);
104
+
105
+ pi.registerCommand("timestamps", {
106
+ description: "Show or toggle footer and transcript timestamps",
107
+ handler: async (args, ctx) => {
108
+ if (ctx.mode !== "tui") return;
109
+ const parsed = parseArgs(args);
110
+ if (parsed.kind === "usage") {
111
+ ctx.ui.notify("Usage: /timestamps [footer|transcript] [on|off]", "warning");
112
+ return;
113
+ }
114
+ if (parsed.kind === "set") {
115
+ config[parsed.target] = parsed.on;
116
+ if (parsed.target === "footer") refreshFooter(ctx);
117
+ }
118
+ ctx.ui.notify(`Message timestamps: footer ${config.footer ? "on" : "off"}, transcript ${config.transcript ? "on" : "off"}`, "info");
119
+ },
120
+ });
121
+ }
@@ -43,7 +43,7 @@ import {
43
43
  type ThreadResult,
44
44
  type UnresolvedMention,
45
45
  } from "../lib/slack-core.ts";
46
- import { cacheFilePath, teamIdFor, resolveChannel, refreshCache, resolveMentions, assertSameTeam, type CacheCtx } from "../lib/slack-cache.ts";
46
+ import { cacheFilePath, cachedUserNames, teamIdFor, resolveChannel, refreshCache, resolveMentions, assertSameTeam, type CacheCtx } from "../lib/slack-cache.ts";
47
47
 
48
48
  const SLACK_FORMATTING_GUIDANCE: { rules: string[]; example: string } = {
49
49
  rules: [
@@ -124,6 +124,7 @@ export function formatToolError(err: unknown, identity?: "user" | "bot"): Error
124
124
 
125
125
  interface ResolvedCall {
126
126
  token: string;
127
+ teamId: string;
127
128
  filePath: string;
128
129
  cacheCtx: CacheCtx;
129
130
  deps: CoreDeps;
@@ -156,7 +157,7 @@ async function resolveCall(
156
157
  const filePath = cacheFilePath(cfg, repoRoot, teamId);
157
158
  const cacheCtx: CacheCtx = { apiCall: defaultApiCall, token, filePath, signal };
158
159
  const deps: CoreDeps = { apiCall: defaultApiCall, token, signal };
159
- return { token, filePath, cacheCtx, deps };
160
+ return { token, teamId, filePath, cacheCtx, deps };
160
161
  }
161
162
 
162
163
  /**
@@ -309,7 +310,7 @@ export default function slackExtension(pi: ExtensionAPI) {
309
310
  Type.Object({ file: Type.String(), ...searchFields }),
310
311
  ]),
311
312
  description:
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.',
313
+ '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. In compact text, cached user mentions render as `@Display Name` and labeled groups as `@handle`. Uncached user tokens keep their original text, including any label.',
313
314
  parameters: Type.Object({
314
315
  query: Type.String({ description: "Slack search query, e.g. 'deploy in:#eng from:@alice'" }),
315
316
  count: Type.Optional(Type.Integer({ minimum: 1, maximum: 100, default: 20 })),
@@ -317,8 +318,8 @@ export default function slackExtension(pi: ExtensionAPI) {
317
318
  }),
318
319
  async execute(_toolCallId, params, signal) {
319
320
  return guarded(async () => {
320
- const { deps } = await resolveCall("user", cfg, ctx, signal, repoRoot);
321
- const result = await searchMessages(params, deps);
321
+ const { deps, filePath, teamId } = await resolveCall("user", cfg, ctx, signal, repoRoot);
322
+ const result = await searchMessages(params, { ...deps, userNames: cachedUserNames(filePath, teamId) });
322
323
  const structured = structuredMessages(result.matches, "search");
323
324
  return {
324
325
  content: [{ type: "text" as const, text: searchResultText(result) }],
@@ -345,7 +346,7 @@ export default function slackExtension(pi: ExtensionAPI) {
345
346
  Type.Object({ file: Type.String(), ...threadFields }),
346
347
  ]),
347
348
  description:
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.',
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.',
349
350
  parameters: Type.Object({
350
351
  channel: Type.Optional(Type.String({ description: "#name, channel ID, @name, or user ID (DM)" })),
351
352
  ts: Type.Optional(Type.String({ description: "Thread parent timestamp" })),
@@ -355,12 +356,12 @@ export default function slackExtension(pi: ExtensionAPI) {
355
356
  }),
356
357
  async execute(_toolCallId, params, signal) {
357
358
  return guarded(async () => {
358
- const { deps, cacheCtx } = await resolveCall("user", cfg, ctx, signal, repoRoot);
359
+ const { deps, cacheCtx, filePath, teamId } = await resolveCall("user", cfg, ctx, signal, repoRoot);
359
360
  const channel =
360
361
  params.permalink === undefined && params.channel !== undefined ? await resolveChannel(params.channel, cacheCtx) : undefined;
361
362
  const result = await readThread(
362
363
  { channel, ts: params.ts, permalink: params.permalink, cursor: params.cursor, raw: params.raw },
363
- deps,
364
+ params.raw === true ? deps : { ...deps, userNames: cachedUserNames(filePath, teamId) },
364
365
  );
365
366
  return {
366
367
  content: [{ type: "text" as const, text: threadResultText(result, params.raw === true) }],
@@ -42,6 +42,7 @@ export const QUIVER_CONFIG_KEYS: Record<string, readonly string[]> = {
42
42
  providerStallWatchdog: ["enabled", "firstEventMs", "warningMs", "recoveryMs", "maxStallRetries", "models"],
43
43
  slack: ["enabled", "cachePath", "policyPath", "userTokenEnv", "userTokenCommand", "userTokenCommandTimeoutSeconds", "botTokenEnv", "uploadThresholdChars"],
44
44
  docToMd: DOC_TO_MD_OPTIONS.filter((o) => o.settable).map((o) => o.key),
45
+ messageTimestamps: ["footer", "transcript"],
45
46
  };
46
47
 
47
48
  const isPlainObject = (v: unknown): v is Record<string, unknown> => v !== null && typeof v === "object" && !Array.isArray(v);
@@ -289,6 +289,22 @@ export async function resolveUser(input: string, ctx: CacheCtx): Promise<string>
289
289
  throw new SlackError("name_not_found", `No user named "${name}" was found in the workspace.`);
290
290
  }
291
291
 
292
+ /**
293
+ * User ID -> name for rendering `<@U...>` in read output: display name, else real name, else the
294
+ * username key. Read-only and offline - an ID the cache has never seen is simply absent.
295
+ */
296
+ export function cachedUserNames(filePath: string, teamId: string): Map<string, string> {
297
+ const cache = readCacheFile(filePath);
298
+ const names = new Map<string, string>();
299
+ if (!cache?.team_id || cache.team_id !== teamId) return names;
300
+ for (const [username, user] of Object.entries(cache.users ?? {})) {
301
+ if (typeof user?.id !== "string" || !user.id) continue;
302
+ const name = [user.display_name, user.real_name, username].find((s) => typeof s === "string" && s.length > 0);
303
+ if (name) names.set(user.id, name);
304
+ }
305
+ return names;
306
+ }
307
+
292
308
  const MENTION_DENY = new Set(["here", "channel", "everyone"]);
293
309
  const MENTION_BOUNDARY = new Set([" ", "\t", "\n", "\r", "(", "[", "*", "_", '"', "'"]);
294
310
  // `_` is trimmed here even though it is also a boundary character: it is a legal username
package/lib/slack-core.ts CHANGED
@@ -496,10 +496,28 @@ export function gateOutput(text: string, slug: string): { output: string; spille
496
496
  * search/thread reads surface the throttle instead of spinning.
497
497
  */
498
498
 
499
+ type UserNames = ReadonlyMap<string, string>;
500
+
499
501
  export interface CoreDeps {
500
502
  apiCall: ApiCall;
501
503
  token: string;
502
504
  signal?: AbortSignal;
505
+ /** User ID -> display name for compact read output. */
506
+ userNames?: UserNames;
507
+ }
508
+
509
+ const CODE_OR_MENTION = /```[\s\S]*?(?:```|$)|`[^`\r\n]*`|<@([UW][A-Z0-9]+)(?:\|[^>]*)?>|<!subteam\^[A-Z0-9]+(?:\|@?([^>]+))?>/g;
510
+
511
+ function compactUserMention(id: string, names: UserNames | undefined, token = `<@${id}>`): string {
512
+ const name = names?.get(id);
513
+ return name === undefined ? token : `@${name}`;
514
+ }
515
+
516
+ export function renderMentionTokens(text: string, userNames?: UserNames): string {
517
+ return text.replace(CODE_OR_MENTION, (token, userId: string | undefined, handle: string | undefined) => {
518
+ if (userId !== undefined) return compactUserMention(userId, userNames, token);
519
+ return handle === undefined ? token : `@${handle}`;
520
+ });
503
521
  }
504
522
 
505
523
  export const THREAD_PAGE_CAP = 50;
@@ -537,14 +555,18 @@ export function parsePermalink(url: string): { channel: string; ts: string } | u
537
555
  return { channel, ts: `${digits.slice(0, -6)}.${digits.slice(-6)}` };
538
556
  }
539
557
 
540
- function renderSearchLine(match: Record<string, unknown>): string {
558
+ function compactMessageText({ text, mrkdwn }: Record<string, unknown>, userNames?: UserNames): string {
559
+ if (typeof text !== "string") return "";
560
+ return (mrkdwn === false ? text : renderMentionTokens(text, userNames)).replace(/\r?\n/g, " ");
561
+ }
562
+
563
+ function renderSearchLine(match: Record<string, unknown>, userNames?: UserNames): string {
541
564
  const author = typeof match.username === "string" ? match.username : String(match.user ?? "unknown");
542
565
  const channelObj = match.channel as Record<string, unknown> | undefined;
543
566
  const channelName = typeof channelObj?.name === "string" ? channelObj.name : String(channelObj?.id ?? "unknown");
544
567
  const ts = String(match.ts ?? "");
545
568
  const permalink = String(match.permalink ?? "");
546
- const text = typeof match.text === "string" ? match.text.replace(/\r?\n/g, " ") : "";
547
- return `${author} | #${channelName} | ${ts} | ${permalink} | ${text}`;
569
+ return `${author} | #${channelName} | ${ts} | ${permalink} | ${compactMessageText(match, userNames)}`;
548
570
  }
549
571
 
550
572
  export async function searchMessages(
@@ -563,22 +585,27 @@ export async function searchMessages(
563
585
  const page = typeof paging.page === "number" ? paging.page : (args.page ?? 1);
564
586
  const pageCount = typeof paging.pages === "number" ? paging.pages : 1;
565
587
 
566
- const rendered = matches.map(renderSearchLine).join("\n");
588
+ const rendered = matches.map((match) => renderSearchLine(match, deps.userNames)).join("\n");
567
589
  const gated = gateOutput(rendered, "search");
568
590
  return { ...gated, matches, total, page, pageCount };
569
591
  }
570
592
 
571
- function inlineElementText(element: unknown): string {
593
+ function inlineElementText(element: unknown, userNames: UserNames | undefined, preformatted: boolean): string {
572
594
  if (typeof element !== "object" || element === null) return "[unknown]";
573
595
  const el = element as Record<string, unknown>;
574
596
  const type = typeof el.type === "string" ? el.type : "unknown";
575
597
  switch (type) {
576
598
  case "text":
577
599
  return typeof el.text === "string" ? el.text : "[text]";
578
- case "user":
579
- return typeof el.user_id === "string" ? `<@${el.user_id}>` : "[user]";
600
+ case "user": {
601
+ if (typeof el.user_id !== "string") return "[user]";
602
+ const code = (el.style as { code?: boolean } | undefined)?.code;
603
+ return preformatted || code ? `<@${el.user_id}>` : compactUserMention(el.user_id, userNames);
604
+ }
580
605
  case "channel":
581
606
  return typeof el.channel_id === "string" ? `<#${el.channel_id}>` : "[channel]";
607
+ case "usergroup":
608
+ return typeof el.usergroup_id === "string" ? `<!subteam^${el.usergroup_id}>` : "[usergroup]";
582
609
  case "link":
583
610
  if (typeof el.text === "string" && el.text.length > 0) return el.text;
584
611
  return typeof el.url === "string" ? el.url : "[link]";
@@ -589,35 +616,43 @@ function inlineElementText(element: unknown): string {
589
616
  }
590
617
  }
591
618
 
592
- function richTextContainerText(element: unknown): string {
619
+ function richTextContainerText(element: unknown, userNames?: UserNames): string {
593
620
  if (typeof element !== "object" || element === null) return "[unknown]";
594
621
  const el = element as Record<string, unknown>;
595
622
  const type = typeof el.type === "string" ? el.type : "unknown";
596
623
  switch (type) {
597
624
  case "rich_text_section":
598
625
  case "rich_text_quote":
599
- case "rich_text_preformatted":
600
- return Array.isArray(el.elements) ? el.elements.map(inlineElementText).join("") : "";
626
+ case "rich_text_preformatted": {
627
+ const preformatted = type === "rich_text_preformatted";
628
+ return Array.isArray(el.elements) ? el.elements.map((item) => inlineElementText(item, userNames, preformatted)).join("") : "";
629
+ }
601
630
  case "rich_text_list":
602
631
  return Array.isArray(el.elements)
603
- ? el.elements.map(richTextContainerText).filter((s) => s.length > 0).join(" ")
632
+ ? el.elements.map((item) => richTextContainerText(item, userNames)).filter((s) => s.length > 0).join(" ")
604
633
  : "";
605
634
  default:
606
635
  return `[${type}]`;
607
636
  }
608
637
  }
609
638
 
610
- function contextElementText(element: unknown): string {
639
+ function textObjectText(element: unknown, userNames?: UserNames): string | undefined {
640
+ const el = element as { type?: unknown; text?: unknown } | undefined;
641
+ if (typeof el?.text !== "string") return undefined;
642
+ return el.type === "mrkdwn" ? renderMentionTokens(el.text, userNames) : el.text;
643
+ }
644
+
645
+ function contextElementText(element: unknown, userNames?: UserNames): string {
611
646
  if (typeof element !== "object" || element === null) return "[unknown]";
612
647
  const el = element as Record<string, unknown>;
613
648
  const type = typeof el.type === "string" ? el.type : "unknown";
614
649
  if (type === "plain_text" || type === "mrkdwn") {
615
- return typeof el.text === "string" ? el.text : `[${type}]`;
650
+ return textObjectText(el, userNames) ?? `[${type}]`;
616
651
  }
617
652
  return `[${type}]`;
618
653
  }
619
654
 
620
- function blockText(block: unknown): string {
655
+ function blockText(block: unknown, userNames?: UserNames): string {
621
656
  if (typeof block !== "object" || block === null) return "[unknown]";
622
657
  const b = block as Record<string, unknown>;
623
658
  const type = typeof b.type === "string" ? b.type : "unknown";
@@ -626,44 +661,37 @@ function blockText(block: unknown): string {
626
661
  const text = (b.text as Record<string, unknown> | undefined)?.text;
627
662
  return typeof text === "string" ? text : "";
628
663
  }
629
- case "section": {
630
- const parts: string[] = [];
631
- const text = (b.text as Record<string, unknown> | undefined)?.text;
632
- if (typeof text === "string" && text.length > 0) parts.push(text);
633
- if (Array.isArray(b.fields)) {
634
- for (const field of b.fields) {
635
- const fieldText = (field as Record<string, unknown> | undefined)?.text;
636
- if (typeof fieldText === "string" && fieldText.length > 0) parts.push(fieldText);
637
- }
638
- }
639
- return parts.join(" ");
640
- }
664
+ case "section":
665
+ return [b.text, ...(Array.isArray(b.fields) ? b.fields : [])]
666
+ .map((field) => textObjectText(field, userNames))
667
+ .filter(Boolean)
668
+ .join(" ");
641
669
  case "context":
642
670
  return Array.isArray(b.elements)
643
- ? b.elements.map(contextElementText).filter((s) => s.length > 0).join(" ")
671
+ ? b.elements.map((el) => contextElementText(el, userNames)).filter((s) => s.length > 0).join(" ")
644
672
  : "";
645
673
  case "rich_text":
646
674
  return Array.isArray(b.elements)
647
- ? b.elements.map(richTextContainerText).filter((s) => s.length > 0).join(" ")
675
+ ? b.elements.map((el) => richTextContainerText(el, userNames)).filter((s) => s.length > 0).join(" ")
648
676
  : "";
649
677
  default:
650
678
  return `[${type}]`;
651
679
  }
652
680
  }
653
681
 
654
- export function renderBlocks(blocks: unknown[]): string {
682
+ export function renderBlocks(blocks: unknown[], userNames?: UserNames): string {
655
683
  return blocks
656
- .map(blockText)
684
+ .map((block) => blockText(block, userNames))
657
685
  .filter((s) => s.length > 0)
658
686
  .join(" / ")
659
687
  .replace(/\r?\n/g, " ");
660
688
  }
661
689
 
662
- function renderThreadLine(message: Record<string, unknown>): string {
690
+ function renderThreadLine(message: Record<string, unknown>, userNames?: UserNames): string {
663
691
  const author = typeof message.user === "string" ? message.user : String(message.username ?? "unknown");
664
692
  const ts = String(message.ts ?? "");
665
- const flattened = Array.isArray(message.blocks) && message.blocks.length > 0 ? renderBlocks(message.blocks) : "";
666
- const body = (flattened.length > 0 ? flattened : typeof message.text === "string" ? message.text : "").replace(/\r?\n/g, " ");
693
+ const flattened = Array.isArray(message.blocks) ? renderBlocks(message.blocks, userNames) : "";
694
+ const body = flattened || compactMessageText(message, userNames);
667
695
  return `${author} | ${ts} | ${body}`;
668
696
  }
669
697
 
@@ -734,7 +762,10 @@ export async function readThread(
734
762
  cursor = fetchedCursor;
735
763
  }
736
764
 
737
- const rendered = args.raw === true ? JSON.stringify(messages, null, 2) : messages.map(renderThreadLine).join("\n");
765
+ const rendered =
766
+ args.raw === true
767
+ ? JSON.stringify(messages, null, 2)
768
+ : messages.map((message) => renderThreadLine(message, deps.userNames)).join("\n");
738
769
  const gated = gateOutput(rendered, "thread");
739
770
  return { ...gated, messages, complete, nextCursor, caveat, messageCount: messages.length };
740
771
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-quiver",
3
- "version": "6.16.3",
3
+ "version": "6.17.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, Anthropic fast mode, and a provider-stall watchdog.",
5
5
  "author": "Jacek Juraszek",
6
6
  "license": "MIT",
@@ -741,7 +741,7 @@ def mode_pdf_fallback(o):
741
741
  try:
742
742
  for n in pages:
743
743
  stats.append(page_stats(doc, n))
744
- links = [f"![](images/{f})" for f in keep.get(n, [])]
744
+ links = []
745
745
  text = ""
746
746
  page_pic = None
747
747
  meta = {}
@@ -754,7 +754,10 @@ def mode_pdf_fallback(o):
754
754
  ocr_info["textless"].append(n)
755
755
  if status is None:
756
756
  status = ocr_status(False, lang)
757
- if n not in keep:
757
+ if n in keep:
758
+ alt = "" if text else f"page {n}"
759
+ links = [f"![{alt}](images/{f})" for f in keep[n]]
760
+ else:
758
761
  d = page_dir(staging, n)
759
762
  if not text:
760
763
  pic, meta = textless_picture(worker, page, n, d, o, notes, render=not o.get("pageImages"))