pi-quiver 6.16.2 → 6.16.4

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.16.4 - 2026-11-19
7
+
8
+ - `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)
9
+
10
+ ## v6.16.3 - 2026-11-17
11
+
12
+ - `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)
13
+
6
14
  ## v6.16.2 - 2026-11-15
7
15
 
8
16
  - `fast-mode` covers every model in Anthropic's fast-mode availability table: Claude Fable 5.2 and Mythos 5.2 join Opus 5.5, Opus 5, and Opus 4.8. The `fast-mode-2026-02-01` beta header goes only to Opus 5 (research preview) and Opus 4.8 (deprecated), the two models Anthropic still requires it on; Fable 5.2, Mythos 5.2, and Opus 5.5 get `speed: "fast"` alone and keep the `anthropic-beta` header pi built. Opus 5.5 previously got the header through the `claude-opus-5` prefix, which dropped pi's `message-threads-2026-08-12` beta and cost a rejected first attempt on every request. Cost correction stays 2x, checked against the rate card for all five models. (#40)
package/README.md CHANGED
@@ -210,7 +210,7 @@ survive untouched.
210
210
 
211
211
  `swordHeader` swaps the header at `session_start`, which runs after pi has already drawn its built-in pixel logo, so the logo shows for a moment before the sword replaces it. To skip that flash set pi's own `"quietStartup": true` in `~/.pi/agent/settings.json`: pi then draws an empty header slot at startup and the sword fills it. Quiet startup also drops pi's key-hint lines, which the sword header does not reproduce.
212
212
 
213
- `fastMode` only affects `claude-fable-5-2`, `claude-mythos-5-2`, `claude-opus-5-5`, `claude-opus-5`, and `claude-opus-4-8` requests on Anthropic's `anthropic-messages` API - the models in Anthropic's [fast-mode availability table](https://platform.claude.com/docs/en/build-with-claude/fast-mode#feature-availability); enabling it opts into premium fast-mode pricing. `--fast` forces it on for one launch; `/fast on|off` toggles live. Proxy providers (opencode, cloudflare-ai-gateway) are excluded. Fable 5.2, Mythos 5.2, and Opus 5.5 get `speed: "fast"` alone, and pi's `anthropic-beta` header goes out as pi built it. Opus 5 (research preview) and Opus 4.8 (deprecated by Anthropic, removal date 2026-11-30) also get the `fast-mode-2026-02-01` beta header. That header injection needs the `before_provider_headers` hook (pi bundling `@earendil-works/pi-coding-agent` >= 0.80.5); on older pi the beta header is silently not sent. The `anthropic-beta` header is discovered at request time by probing pi's own request assembly (no network), so conditional betas pi adds - e.g. `server-side-fallback-2026-07-01` for models with server-side fallback - are preserved alongside `fast-mode-2026-02-01`. If the probe fails, the header falls back to the static OAuth-identity + fast-mode list. See [doc/fetch.md](doc/fetch.md) and [doc/doc-to-md.md](doc/doc-to-md.md) for the ingestion tools' full reference; session-name/sword-header behavior above is complete.
213
+ `fastMode` only affects `claude-fable-5-2`, `claude-mythos-5-2`, `claude-opus-5-5`, `claude-opus-5`, and `claude-opus-4-8` requests on Anthropic's `anthropic-messages` API - the models in Anthropic's [fast-mode availability table](https://platform.claude.com/docs/en/build-with-claude/fast-mode#feature-availability); enabling it opts into premium fast-mode pricing. `--fast` forces it on for one launch; `/fast on|off` toggles live. The provider must be pi's built-in `anthropic` or a custom provider whose `baseUrl` host is `api.anthropic.com`; proxy providers (opencode, cloudflare-ai-gateway) are excluded. Fable 5.2, Mythos 5.2, and Opus 5.5 get `speed: "fast"` alone, and pi's `anthropic-beta` header goes out as pi built it. Opus 5 (research preview) and Opus 4.8 (deprecated by Anthropic, removal date 2026-11-30) also get the `fast-mode-2026-02-01` beta header. That header injection needs the `before_provider_headers` hook (pi bundling `@earendil-works/pi-coding-agent` >= 0.80.5); on older pi the beta header is silently not sent. The `anthropic-beta` header is discovered at request time by probing pi's own request assembly (no network), so conditional betas pi adds - e.g. `server-side-fallback-2026-07-01` for models with server-side fallback - are preserved alongside `fast-mode-2026-02-01`. If the probe fails, the header falls back to the static OAuth-identity + fast-mode list. See [doc/fetch.md](doc/fetch.md) and [doc/doc-to-md.md](doc/doc-to-md.md) for the ingestion tools' full reference; session-name/sword-header behavior above is complete.
214
214
 
215
215
  `pi-ai` prices every fast request at standard rates - it has no `usage.speed` support and no request-level pricing modifier - so `fastMode` corrects the reported cost itself: a `message_end` handler scales all four `usage.cost` components by `FAST_MODE_COST_MULTIPLIER` (2x) and returns the corrected message. Persisted session JSONL and pi's own native cost display are always exact, since they're written from this corrected message. pi-cohort's live `Σ$` reflects the correction only when pi-quiver's `message_end` handler runs before pi-cohort's - best-effort, depending on extension load order - and is reconciled on pi-cohort's next `session_start` regardless. The upstream fix (teaching `pi-ai`'s `Usage`/`calculateCost` about `usage.speed`) is the better long-term path and is tracked separately.
216
216
 
@@ -294,7 +294,7 @@ Operational notes:
294
294
  | `botTokenEnv` | `SLACK_BOT_TOKEN` | Env var name holding the bot token. |
295
295
  | `uploadThresholdChars` | `4000` | Link-collapsed length above which an announce/thread detail body is delivered as a file upload instead of inline text. |
296
296
 
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).
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. 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
298
 
299
299
  ### doc_to_md settings
300
300
 
@@ -95,7 +95,15 @@ export function coerce(raw: unknown): Partial<Config> | undefined {
95
95
  return undefined;
96
96
  }
97
97
 
98
- type ModelLike = { id?: string; api?: string; provider?: string } | undefined;
98
+ type ModelLike = { id?: string; api?: string; provider?: string; baseUrl?: string } | undefined;
99
+
100
+ // Proxies and cloud platforms reuse Anthropic's model ids on anthropic-messages
101
+ // and must never see fast-mode signals, so the endpoint has to be Anthropic's
102
+ // own: pi's built-in provider, or a custom provider entry aimed at the same host.
103
+ function isAnthropicEndpoint(model: NonNullable<ModelLike>): boolean {
104
+ if (model.provider === "anthropic") return true;
105
+ return URL.parse(model.baseUrl ?? "")?.hostname === "api.anthropic.com";
106
+ }
99
107
 
100
108
  function fastModeModel(model: ModelLike) {
101
109
  const id = model?.id;
@@ -105,7 +113,7 @@ function fastModeModel(model: ModelLike) {
105
113
 
106
114
  export function shouldInject(enabled: boolean, model: ModelLike): boolean {
107
115
  if (!enabled || !model) return false;
108
- if (model.provider !== "anthropic") return false;
116
+ if (!isAnthropicEndpoint(model)) return false;
109
117
  if (model.api !== "anthropic-messages") return false;
110
118
  return fastModeModel(model) !== undefined;
111
119
  }
@@ -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) }],
@@ -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.2",
3
+ "version": "6.16.4",
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"))