@herbertgao/pi-extensions 2026.10.9 → 2026.10.11

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.
Files changed (127) hide show
  1. package/README.md +13 -9
  2. package/THIRD_PARTY_NOTICES.md +2 -2
  3. package/node_modules/@dietrichgebert/ponytail/.qoder-plugin/plugin.json +1 -1
  4. package/node_modules/@dietrichgebert/ponytail/README.md +16 -0
  5. package/node_modules/@dietrichgebert/ponytail/hooks/band/board.ts +560 -0
  6. package/node_modules/@dietrichgebert/ponytail/hooks/band/logo.ts +3 -0
  7. package/node_modules/@dietrichgebert/ponytail/hooks/band/metrics.ts +317 -0
  8. package/node_modules/@dietrichgebert/ponytail/hooks/band/register.tsx +472 -0
  9. package/node_modules/@dietrichgebert/ponytail/hooks/band/types.d.ts +35 -0
  10. package/node_modules/@dietrichgebert/ponytail/hooks/claude-band.json +6 -0
  11. package/node_modules/@dietrichgebert/ponytail/hooks/ponytail-band-import.js +274 -0
  12. package/node_modules/@dietrichgebert/ponytail/hooks/ponytail-mode-tracker.js +43 -5
  13. package/node_modules/@dietrichgebert/ponytail/package.json +1 -1
  14. package/node_modules/@dietrichgebert/ponytail/skills/ponytail/SKILL.md +1 -1
  15. package/node_modules/@dietrichgebert/ponytail/skills/ponytail-debt/SKILL.md +1 -2
  16. package/node_modules/@dietrichgebert/ponytail/skills/ponytail-gain/SKILL.md +0 -1
  17. package/node_modules/@dietrichgebert/ponytail/skills/ponytail-help/SKILL.md +6 -0
  18. package/node_modules/@herbertgao/pi-cc-extensions/README.en.md +10 -5
  19. package/node_modules/@herbertgao/pi-cc-extensions/README.md +6 -1
  20. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/config.ts +6 -1
  21. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/panel.ts +14 -3
  22. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/token-rate.ts +21 -5
  23. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/working-message.ts +23 -4
  24. package/node_modules/@herbertgao/pi-cc-extensions/extensions/index.ts +1 -1
  25. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/compact-mode.ts +126 -42
  26. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/markdown-enhance.ts +4 -128
  27. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/mouse/interaction.ts +24 -6
  28. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/mouse/scroll.ts +69 -16
  29. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/mouse/sticky-prompt.ts +1 -1
  30. package/node_modules/@herbertgao/pi-cc-extensions/package.json +4 -4
  31. package/node_modules/@herbertgao/sol-pi/README.md +7 -1
  32. package/node_modules/@herbertgao/sol-pi/docs/compatibility.md +28 -4
  33. package/node_modules/@herbertgao/sol-pi/docs/configuration.md +17 -4
  34. package/node_modules/@herbertgao/sol-pi/package.json +1 -1
  35. package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/action-fusion/index.ts +35 -25
  36. package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/action-fusion/then-run.ts +95 -26
  37. package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/evidence-preserving-reducer/candidate.ts +39 -2
  38. package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/evidence-preserving-reducer/index.ts +24 -0
  39. package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/observation-pack/index.ts +12 -7
  40. package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/online-context-compact/extension.ts +138 -130
  41. package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/online-context-compact/projection.ts +88 -14
  42. package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/online-context-compact/tools.ts +9 -0
  43. package/node_modules/@herbertgao/sol-pi/src/sol-pi/index.ts +14 -5
  44. package/node_modules/@herbertgao/sol-pi/src/sol-pi/shell-options.ts +22 -0
  45. package/node_modules/@herbertgao/sol-pi/src/sol-pi/tui.ts +11 -0
  46. package/node_modules/@juicesharp/rpiv-ask-user-question/answer-channel.ts +109 -0
  47. package/node_modules/@juicesharp/rpiv-ask-user-question/ask-user-question.ts +117 -71
  48. package/node_modules/@juicesharp/rpiv-ask-user-question/docs/hosts.md +2 -0
  49. package/node_modules/@juicesharp/rpiv-ask-user-question/docs/keyboard.md +3 -1
  50. package/node_modules/@juicesharp/rpiv-ask-user-question/docs/startup-performance.md +83 -0
  51. package/node_modules/@juicesharp/rpiv-ask-user-question/docs/tool-schema.md +74 -5
  52. package/node_modules/@juicesharp/rpiv-ask-user-question/events.ts +84 -0
  53. package/node_modules/@juicesharp/rpiv-ask-user-question/index.ts +10 -4
  54. package/node_modules/@juicesharp/rpiv-ask-user-question/package.json +4 -2
  55. package/node_modules/@juicesharp/rpiv-ask-user-question/presentation.ts +1 -1
  56. package/node_modules/@juicesharp/rpiv-ask-user-question/reconcile.ts +1 -1
  57. package/node_modules/@juicesharp/rpiv-ask-user-question/rpc-fallback.ts +5 -4
  58. package/node_modules/@juicesharp/rpiv-ask-user-question/state/build-questionnaire.ts +19 -19
  59. package/node_modules/@juicesharp/rpiv-ask-user-question/state/i18n-bridge.ts +1 -1
  60. package/node_modules/@juicesharp/rpiv-ask-user-question/state/key-router.ts +7 -4
  61. package/node_modules/@juicesharp/rpiv-ask-user-question/state/questionnaire-session.ts +10 -10
  62. package/node_modules/@juicesharp/rpiv-ask-user-question/state/row-intent.ts +2 -2
  63. package/node_modules/@juicesharp/rpiv-ask-user-question/state/selectors/contract.ts +6 -6
  64. package/node_modules/@juicesharp/rpiv-ask-user-question/state/selectors/derivations.ts +2 -2
  65. package/node_modules/@juicesharp/rpiv-ask-user-question/state/selectors/focus.ts +1 -1
  66. package/node_modules/@juicesharp/rpiv-ask-user-question/state/selectors/projections.ts +9 -9
  67. package/node_modules/@juicesharp/rpiv-ask-user-question/state/state-reducer.ts +5 -5
  68. package/node_modules/@juicesharp/rpiv-ask-user-question/state/state.ts +2 -2
  69. package/node_modules/@juicesharp/rpiv-ask-user-question/tool/external-answer.ts +125 -0
  70. package/node_modules/@juicesharp/rpiv-ask-user-question/tool/format-answer.ts +1 -1
  71. package/node_modules/@juicesharp/rpiv-ask-user-question/tool/normalize-params.ts +1 -1
  72. package/node_modules/@juicesharp/rpiv-ask-user-question/tool/response-envelope.ts +2 -2
  73. package/node_modules/@juicesharp/rpiv-ask-user-question/tool/types.ts +1 -1
  74. package/node_modules/@juicesharp/rpiv-ask-user-question/tool/validate-questionnaire.ts +1 -1
  75. package/node_modules/@juicesharp/rpiv-ask-user-question/view/component-binding.ts +4 -4
  76. package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/multi-select-view.ts +4 -4
  77. package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/option-list-view.ts +2 -2
  78. package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/preview/markdown-content-cache.ts +3 -3
  79. package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/preview/preview-block-renderer.ts +5 -5
  80. package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/preview/preview-layout-decider.ts +3 -3
  81. package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/preview/preview-pane.ts +10 -10
  82. package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/submit-picker.ts +2 -2
  83. package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/tab-bar.ts +1 -1
  84. package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/wrapping-select.ts +1 -1
  85. package/node_modules/@juicesharp/rpiv-ask-user-question/view/dialog-builder.ts +9 -9
  86. package/node_modules/@juicesharp/rpiv-ask-user-question/view/dialog-copy.ts +1 -1
  87. package/node_modules/@juicesharp/rpiv-ask-user-question/view/props-adapter.ts +8 -8
  88. package/node_modules/@juicesharp/rpiv-ask-user-question/view/tab-components.ts +4 -4
  89. package/node_modules/@juicesharp/rpiv-ask-user-question/view/tab-content-strategy.ts +10 -10
  90. package/node_modules/@narumitw/pi-btw/dist/index.ts +3 -0
  91. package/node_modules/@narumitw/pi-btw/dist/index.ts.map +2 -2
  92. package/node_modules/@narumitw/pi-btw/package.json +4 -4
  93. package/node_modules/@narumitw/pi-btw/src/fullscreen-ui.ts +6 -0
  94. package/node_modules/@narumitw/pi-btw/src/keybindings.ts +1 -1
  95. package/node_modules/@narumitw/pi-caffeinate/dist/index.ts +1 -0
  96. package/node_modules/@narumitw/pi-caffeinate/dist/index.ts.map +2 -2
  97. package/node_modules/@narumitw/pi-caffeinate/package.json +3 -3
  98. package/node_modules/@narumitw/pi-caffeinate/src/inhibitor-process.ts +1 -0
  99. package/node_modules/pi-antigravity/README.md +6 -2
  100. package/node_modules/pi-antigravity/package.json +2 -2
  101. package/node_modules/pi-antigravity/src/client/client.ts +44 -52
  102. package/node_modules/pi-antigravity/src/index.ts +13 -0
  103. package/node_modules/pi-antigravity/src/models/discovery.ts +25 -2
  104. package/node_modules/pi-antigravity/src/models/grouping.ts +107 -68
  105. package/node_modules/pi-antigravity/src/models/models.ts +10 -0
  106. package/node_modules/pi-antigravity/src/search/search.ts +581 -43
  107. package/node_modules/pi-antigravity/src/stream/stream.ts +53 -13
  108. package/node_modules/pi-antigravity/src/types/types.ts +13 -0
  109. package/node_modules/pi-antigravity/src/usage/usage.ts +11 -3
  110. package/node_modules/pi-web-access/CHANGELOG.md +21 -0
  111. package/node_modules/pi-web-access/README.md +22 -7
  112. package/node_modules/pi-web-access/credential-source.ts +54 -4
  113. package/node_modules/pi-web-access/curator-page.ts +3 -1
  114. package/node_modules/pi-web-access/curator-server.ts +1 -0
  115. package/node_modules/pi-web-access/deepseek.ts +204 -0
  116. package/node_modules/pi-web-access/dist/index.js +927 -642
  117. package/node_modules/pi-web-access/dist/mcp-cli.js +877 -615
  118. package/node_modules/pi-web-access/gemini-adc.ts +48 -1
  119. package/node_modules/pi-web-access/gemini-search.ts +8 -4
  120. package/node_modules/pi-web-access/index.ts +16 -1
  121. package/node_modules/pi-web-access/package.json +1 -1
  122. package/node_modules/pi-web-access/page-query.ts +12 -6
  123. package/node_modules/pi-web-access/query-rewrite.ts +16 -13
  124. package/node_modules/pi-web-access/summary-review.ts +16 -6
  125. package/node_modules/pi-web-access/utils.ts +3 -0
  126. package/node_modules/pi-web-access/web-tool-core.ts +2 -0
  127. package/package.json +10 -10
@@ -1,3 +1,6 @@
1
+ import { lookup } from "node:dns/promises";
2
+ import { isIP } from "node:net";
3
+
1
4
  import {
2
5
  antigravityHeaders,
3
6
  endpointCandidates,
@@ -7,7 +10,7 @@ import {
7
10
  import { AntigravityRequestType, AntigravityUserAgent, GeminiRole } from "../types/enums.js";
8
11
  import { antigravityFetch } from "../utils/http.js";
9
12
  import { safeError } from "../utils/security.js";
10
- import { antigravityRequestEnvelope, isRecord } from "../utils/util.js";
13
+ import { antigravityEnv, antigravityRequestEnvelope, isRecord } from "../utils/util.js";
11
14
 
12
15
  /** Default search model: fast grounding model for interactive tool calls. */
13
16
  export const DEFAULT_SEARCH_MODEL = "gemini-3.5-flash-lite";
@@ -36,6 +39,16 @@ export type SearchSource = {
36
39
  index?: number;
37
40
  title: string;
38
41
  url: string;
42
+ /**
43
+ * Destination recovered by following the grounding redirect. Google wraps every
44
+ * source in an opaque `.../grounding-api-redirect/<token>` URL whose path carries
45
+ * no information, so this is what citations should link to when available.
46
+ */
47
+ resolvedUrl?: string;
48
+ /** The page's `<title>` (or `og:title`), when it could be fetched. */
49
+ pageTitle?: string;
50
+ /** Rendered label: page title, else host plus readable path, else host. */
51
+ label?: string;
39
52
  };
40
53
 
41
54
  export type SearchSupport = {
@@ -143,8 +156,15 @@ export function buildSearchRequest(
143
156
  tools.push({ urlContext: {} });
144
157
  }
145
158
 
146
- // Default budget stays at 0 so interactive lookups stay fast. --thinking opts into planning.
147
- const thinkingBudget = options.thinking ? 4096 : 0;
159
+ // Lite models and Gemini 4 reject an explicit zero budget (#84). Leave that config unset
160
+ // unless the caller opted into planning, or this is a non-Lite fallback.
161
+ const generationConfig: Record<string, unknown> = {};
162
+ if (options.thinking || (options.thinking === undefined && !model.includes("lite"))) {
163
+ generationConfig.thinkingConfig = {
164
+ thinkingBudget: options.thinking ? 4096 : 2048,
165
+ includeThoughts: false,
166
+ };
167
+ }
148
168
  const envelope = antigravityRequestEnvelope(model, false);
149
169
 
150
170
  return {
@@ -162,12 +182,7 @@ export function buildSearchRequest(
162
182
  },
163
183
  ],
164
184
  tools,
165
- generationConfig: {
166
- thinkingConfig: {
167
- thinkingBudget,
168
- includeThoughts: false,
169
- },
170
- },
185
+ generationConfig,
171
186
  },
172
187
  requestType: AntigravityRequestType.Agent,
173
188
  userAgent: AntigravityUserAgent.Antigravity,
@@ -283,9 +298,474 @@ export function parseSearchResponse(data: unknown): SearchResult {
283
298
  return result;
284
299
  }
285
300
 
301
+ /** Google wraps each source in this host; its path is an opaque token, not a readable path. */
302
+ const GROUNDING_REDIRECT_HOST = "vertexaisearch.cloud.google.com";
303
+
304
+ /** Budget for one redirect resolution or page title fetch. */
305
+ const SOURCE_ENRICH_TIMEOUT_MS = 6_000;
306
+
307
+ /** Parallel enrichment requests per search. */
308
+ const SOURCE_ENRICH_CONCURRENCY = 6;
309
+
310
+ /** Upper bound on bytes read while looking for the page title. */
311
+ const PAGE_TITLE_BYTE_CAP = 64 * 1024;
312
+
313
+ /** Redirect hops chased while looking for a page title. */
314
+ const PAGE_TITLE_MAX_HOPS = 3;
315
+
316
+ const SOURCE_CACHE_LIMIT = 500;
317
+ const resolvedUrlCache = new Map<string, string>();
318
+ const pageTitleCache = new Map<string, string>();
319
+
320
+ /** Insert into a bounded cache, evicting the oldest entry once it is full. */
321
+ function remember(map: Map<string, string>, key: string, value: string): void {
322
+ if (map.size >= SOURCE_CACHE_LIMIT) {
323
+ const oldest = map.keys().next().value;
324
+ if (oldest !== undefined) map.delete(oldest);
325
+ }
326
+ map.set(key, value);
327
+ }
328
+
329
+ /** Combined signal that still has a deadline when the caller supplied its own. */
330
+ function withDeadline(signal: AbortSignal | undefined, ms: number): AbortSignal {
331
+ const timeout = AbortSignal.timeout(ms);
332
+ if (!signal) return timeout;
333
+ const anyFn = (AbortSignal as unknown as { any?: (signals: AbortSignal[]) => AbortSignal }).any;
334
+ return anyFn ? anyFn([signal, timeout]) : signal;
335
+ }
336
+
337
+ /** True when a grounding title is nothing but a host, which names no page by itself. */
338
+ function isBareDomainTitle(title: string): boolean {
339
+ return /^[a-z0-9.-]+\.[a-z]{2,}$/i.test(title);
340
+ }
341
+
342
+ /** Host of a URL, or the input unchanged when it does not parse. */
343
+ function hostnameOf(url: string): string {
344
+ try {
345
+ return new URL(url).hostname;
346
+ } catch {
347
+ return url;
348
+ }
349
+ }
350
+
351
+ /**
352
+ * True for an address this process must never be pointed at by a search result.
353
+ *
354
+ * `URL.hostname` keeps the brackets around an IPv6 literal, so they come off before the
355
+ * check: `[::1]` would otherwise look like a hostname instead of an address.
356
+ */
357
+ export function isPrivateAddress(address: string): boolean {
358
+ const bare = address.startsWith("[") && address.endsWith("]") ? address.slice(1, -1) : address;
359
+ const version = isIP(bare);
360
+ if (version === 4) {
361
+ const [a = 0, b = 0] = bare.split(".").map(Number);
362
+ if (a === 0 || a === 10 || a === 127) return true;
363
+ if (a === 100 && b >= 64 && b <= 127) return true; // carrier-grade NAT
364
+ if (a === 169 && b === 254) return true; // link-local, and the metadata endpoint
365
+ if (a === 172 && b >= 16 && b <= 31) return true;
366
+ if (a === 192 && b === 168) return true;
367
+ if (a === 198 && (b === 18 || b === 19)) return true; // benchmarking range
368
+ return a >= 224; // multicast, then reserved
369
+ }
370
+ if (version === 6) {
371
+ const lowered = bare.toLowerCase();
372
+ if (lowered === "::" || lowered === "::1") return true;
373
+ if (/^f[cd]/.test(lowered)) return true; // unique local
374
+ if (/^fe[89ab]/.test(lowered)) return true; // link-local
375
+ const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(lowered)?.[1];
376
+ return mapped ? isPrivateAddress(mapped) : false;
377
+ }
378
+ return false;
379
+ }
380
+
381
+ /**
382
+ * Whether a page URL is safe to request: http(s), a public literal, and not a name that
383
+ * resolves somewhere internal.
384
+ *
385
+ * Resolving first narrows the window but does not close it, because `fetch` resolves
386
+ * again when it connects. Closing it outright takes a private dispatcher, and this
387
+ * provider deliberately leaves the host's proxy-aware dispatcher in place, so treat this
388
+ * as a filter rather than as a guarantee.
389
+ */
390
+ async function isFetchablePageUrl(rawUrl: string): Promise<boolean> {
391
+ let parsed: URL;
392
+ try {
393
+ parsed = new URL(rawUrl);
394
+ } catch {
395
+ return false;
396
+ }
397
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;
398
+ const host = parsed.hostname.toLowerCase().replace(/\.$/, "");
399
+ if (!host || isPrivateAddress(host)) return false;
400
+ if (/^(.*\.)?(localhost|local|internal|home\.arpa)$/.test(host)) return false;
401
+ if (isIP(host)) return true; // a public literal, already checked above
402
+ try {
403
+ const records = await lookup(host, { all: true });
404
+ return records.length > 0 && records.every((record) => !isPrivateAddress(record.address));
405
+ } catch {
406
+ return false;
407
+ }
408
+ }
409
+
410
+ /**
411
+ * Readable path segment for a label, but never the grounding redirect path: that is an
412
+ * opaque token, and using it produces labels that are all distinct yet say nothing.
413
+ */
414
+ function readablePath(url: string | undefined): string {
415
+ if (!url) return "";
416
+ try {
417
+ const parsed = new URL(url);
418
+ if (
419
+ parsed.hostname === GROUNDING_REDIRECT_HOST ||
420
+ parsed.hostname.endsWith(`.${GROUNDING_REDIRECT_HOST}`)
421
+ ) {
422
+ return "";
423
+ }
424
+ const pathname = parsed.pathname.replace(/\/+$/, "");
425
+ if (!pathname || pathname === "/" || pathname.includes("grounding-api-redirect")) return "";
426
+ return pathname;
427
+ } catch {
428
+ return "";
429
+ }
430
+ }
431
+
432
+ /** Turn the handful of entities that appear in title text back into characters. */
433
+ function decodeHtmlEntities(text: string): string {
434
+ return text
435
+ .replace(/&#(\d+);/g, (_, code: string) => String.fromCodePoint(Number(code)))
436
+ .replace(/&#x([0-9a-f]+);/gi, (_, code: string) => String.fromCodePoint(parseInt(code, 16)))
437
+ .replace(/&quot;/g, '"')
438
+ .replace(/&apos;|&#39;/g, "'")
439
+ .replace(/&lt;/g, "<")
440
+ .replace(/&gt;/g, ">")
441
+ .replace(/&nbsp;/g, " ")
442
+ .replace(/&amp;/g, "&")
443
+ .replace(/\s+/g, " ")
444
+ .trim();
445
+ }
446
+
447
+ /**
448
+ * Label shown inline at the claim and in the source list.
449
+ *
450
+ * A bare domain cannot distinguish several pages from one host (three `github.com`
451
+ * entries), and a page title is not always usable either: some sites return only their
452
+ * brand, so Reddit reports "Reddit" for every thread. Both cases fall back to
453
+ * `host + readable path`.
454
+ */
455
+ export function sourceLabel(source: SearchSource): string {
456
+ // The chunk title is the real host; the raw url can be the opaque redirect host, which
457
+ // must never surface as a label.
458
+ const host = isBareDomainTitle(source.title)
459
+ ? source.title.trim()
460
+ : hostnameOf(source.resolvedUrl ?? source.url);
461
+ const path = readablePath(source.resolvedUrl) || readablePath(source.url);
462
+ const hostAndPath = path ? `${host}${path}` : host;
463
+
464
+ const pageTitle = source.pageTitle?.trim();
465
+ if (pageTitle) {
466
+ const condensed = pageTitle.toLowerCase().replace(/[^a-z0-9]/g, "");
467
+ const brand = host.replace(/^www\./, "").split(".")[0] ?? "";
468
+ if (pageTitle.length >= 15 && condensed !== brand) return pageTitle;
469
+ }
470
+
471
+ if (source.title && !isBareDomainTitle(source.title)) return source.title;
472
+ return hostAndPath;
473
+ }
474
+ /** True only for the Google grounding redirect host, never a URL that merely mentions it. */
475
+ function isGroundingRedirectUrl(raw: string): boolean {
476
+ try {
477
+ const parsed = new URL(raw);
478
+ const host = parsed.hostname.toLowerCase().replace(/\.$/, "");
479
+ return (
480
+ parsed.protocol === "https:" &&
481
+ (host === GROUNDING_REDIRECT_HOST || host.endsWith(`.${GROUNDING_REDIRECT_HOST}`))
482
+ );
483
+ } catch {
484
+ return false;
485
+ }
486
+ }
487
+
488
+ /** Follow one grounding redirect without downloading the target page. */
489
+ async function resolveGroundingRedirect(url: string, signal?: AbortSignal): Promise<string> {
490
+ if (!isGroundingRedirectUrl(url)) return "";
491
+ try {
492
+ const response = await antigravityFetch(url, {
493
+ redirect: "manual",
494
+ signal: withDeadline(signal, SOURCE_ENRICH_TIMEOUT_MS),
495
+ });
496
+ const location = response.headers.get("location");
497
+ if (response.status < 300 || response.status >= 400 || !location) return "";
498
+ const next = new URL(location, url).toString();
499
+ // Do not return, cache, or later fetch a redirect into loopback or metadata.
500
+ if (!(await isFetchablePageUrl(next))) return "";
501
+ return next;
502
+ } catch {
503
+ // Caller keeps the original redirect URL.
504
+ }
505
+ return "";
506
+ }
507
+
508
+ /**
509
+ * Read the title out of a response body, stopping at the byte cap.
510
+ *
511
+ * The cap counts bytes, not characters: `String.length` counts UTF-16 code units, so a
512
+ * page in a multi-byte encoding would read well past the intended limit. The slice keeps
513
+ * one oversized chunk from being appended whole before the limit can be checked.
514
+ */
515
+ async function readPageTitle(response: Response): Promise<string> {
516
+ const body = response.body as ReadableStream<Uint8Array> | null;
517
+ if (!body) return "";
518
+ const reader = body.getReader();
519
+ const decoder = new TextDecoder();
520
+ let buffer = "";
521
+ let bytesRead = 0;
522
+ try {
523
+ while (bytesRead < PAGE_TITLE_BYTE_CAP) {
524
+ const chunk = await reader.read();
525
+ if (chunk.done) break;
526
+ const value = chunk.value;
527
+ if (!value) continue;
528
+ const remaining = PAGE_TITLE_BYTE_CAP - bytesRead;
529
+ const slice = value.byteLength > remaining ? value.subarray(0, remaining) : value;
530
+ bytesRead += slice.byteLength;
531
+ buffer += decoder.decode(slice, { stream: true });
532
+ if (/<\/head>/i.test(buffer)) break;
533
+ }
534
+ } finally {
535
+ void reader.cancel().catch(() => {});
536
+ }
537
+ const openGraph = buffer.match(
538
+ /<meta[^>]+property=["']og:title["'][^>]+content=["']([^"']+)/i,
539
+ )?.[1];
540
+ const titleTag = buffer.match(/<title[^>]*>([\s\S]*?)<\/title>/i)?.[1];
541
+ return decodeHtmlEntities(openGraph || titleTag || "");
542
+ }
543
+
544
+ /**
545
+ * Read just enough of a page to recover its title; blocked or slow sites return empty.
546
+ *
547
+ * Search results are attacker-influenced input, so this follows no redirect on its own:
548
+ * every hop is checked before it is requested, and the number of hops is capped. A
549
+ * redirect is the ordinary way an innocent-looking URL reaches loopback or a cloud
550
+ * metadata address, and whatever comes back is shown to the model.
551
+ */
552
+ async function fetchPageTitle(url: string, signal?: AbortSignal): Promise<string> {
553
+ if (!url || url.includes(GROUNDING_REDIRECT_HOST)) return "";
554
+ // One deadline for the whole chain, so extra hops cannot multiply the wait.
555
+ const deadline = withDeadline(signal, SOURCE_ENRICH_TIMEOUT_MS);
556
+ let current = url;
557
+ for (let hop = 0; hop <= PAGE_TITLE_MAX_HOPS; hop += 1) {
558
+ if (!(await isFetchablePageUrl(current))) return "";
559
+ let response: Response;
560
+ try {
561
+ response = await antigravityFetch(current, {
562
+ redirect: "manual",
563
+ signal: deadline,
564
+ headers: { "User-Agent": "Mozilla/5.0 (compatible; pi-antigravity/1.0)" },
565
+ });
566
+ } catch {
567
+ return "";
568
+ }
569
+ if (response.status >= 300 && response.status < 400) {
570
+ const location = response.headers.get("location");
571
+ if (!location) return "";
572
+ try {
573
+ current = new URL(location, current).toString();
574
+ } catch {
575
+ return "";
576
+ }
577
+ continue;
578
+ }
579
+ if (!response.ok) return "";
580
+ const contentType = response.headers.get("content-type") ?? "";
581
+ if (contentType && !/text\/html|application\/xhtml/i.test(contentType)) return "";
582
+ return await readPageTitle(response);
583
+ }
584
+ return "";
585
+ }
586
+
587
+ /**
588
+ * Add a real link and a readable label to every source.
589
+ *
590
+ * This exists because `groundingChunks[].web` carries only `uri` and `title`: no snippet,
591
+ * no page title, and a title that is a bare domain almost every time. Without this step
592
+ * a model reading the result cannot tell what any source is. Failures degrade to the
593
+ * bare domain rather than to the opaque redirect URL.
594
+ *
595
+ * `ANTIGRAVITY_NO_SOURCE_ENRICH=1` skips it for callers that would rather not emit one
596
+ * extra request per source.
597
+ */
598
+ async function enrichSources(sources: SearchSource[], signal?: AbortSignal): Promise<void> {
599
+ if (antigravityEnv("NO_SOURCE_ENRICH") === "1") {
600
+ for (const source of sources) source.label = sourceLabel(source);
601
+ return;
602
+ }
603
+
604
+ let cursor = 0;
605
+ const worker = async (): Promise<void> => {
606
+ for (;;) {
607
+ const position = cursor++;
608
+ if (position >= sources.length) return;
609
+ const source = sources[position];
610
+ if (!source) continue;
611
+
612
+ const redirect = source.url;
613
+ if (!isGroundingRedirectUrl(redirect)) {
614
+ source.resolvedUrl = redirect;
615
+ } else {
616
+ const cached = resolvedUrlCache.get(redirect);
617
+ if (cached !== undefined) {
618
+ source.resolvedUrl = cached;
619
+ } else {
620
+ const resolved = await resolveGroundingRedirect(redirect, signal);
621
+ if (resolved) {
622
+ remember(resolvedUrlCache, redirect, resolved);
623
+ source.resolvedUrl = resolved;
624
+ }
625
+ }
626
+ }
627
+
628
+ const target = source.resolvedUrl ?? source.url;
629
+ const cachedTitle = pageTitleCache.get(target);
630
+ if (cachedTitle !== undefined) {
631
+ source.pageTitle = cachedTitle;
632
+ } else {
633
+ const title = await fetchPageTitle(target, signal);
634
+ if (title) {
635
+ remember(pageTitleCache, target, title);
636
+ source.pageTitle = title;
637
+ }
638
+ }
639
+
640
+ source.label = sourceLabel(source);
641
+ }
642
+ };
643
+
644
+ await Promise.all(
645
+ Array.from({ length: Math.min(SOURCE_ENRICH_CONCURRENCY, sources.length) }, () => worker()),
646
+ );
647
+ }
648
+
649
+ /** Keep a label from breaking out of its link slot or its list line. */
650
+ function escapeLinkText(text: string): string {
651
+ return text.replace(/[[\]]/g, "\\$&").replace(/\s+/g, " ");
652
+ }
653
+
654
+ /** Encode characters that would close a Markdown link destination. */
655
+ function escapeLinkDestination(url: string): string {
656
+ return url.replace(/\)/g, "%29").replace(/ /g, "%20");
657
+ }
658
+
659
+ /** One contiguous claim, carrying every source index that supports it. */
660
+ type CitationSpan = { start: number; end: number; indices: number[] };
661
+
662
+ type LineKind = "text" | "skip" | "table-row";
663
+ type LineInfo = { start: number; end: number; kind: LineKind; pipeAt?: number };
664
+
665
+ /**
666
+ * Classify every line so citations never land in prose-hostile places.
667
+ *
668
+ * Google attaches supports to Markdown headings too, which would produce
669
+ * `### Single-Writer Rule[1,2]` noise, and a marker appended after a table row's final
670
+ * `|` adds a phantom column. Fenced code needs protecting for the same reason.
671
+ */
672
+ function analyzeLines(text: string): LineInfo[] {
673
+ const raw = text.split("\n");
674
+ const lines: LineInfo[] = [];
675
+ let offset = 0;
676
+ let inFence = false;
677
+ for (let index = 0; index < raw.length; index++) {
678
+ const line = raw[index] ?? "";
679
+ const start = offset;
680
+ const end = start + line.length;
681
+ offset = end + 1;
682
+
683
+ let kind: LineKind = "text";
684
+ let pipeAt: number | undefined;
685
+ const isTableLine = (value: string): boolean => /^\s*\|?[\s:|-]*-[\s:|-]*\|/.test(value);
686
+
687
+ if (/^\s*```/.test(line)) {
688
+ inFence = !inFence;
689
+ kind = "skip";
690
+ } else if (inFence) {
691
+ kind = "skip";
692
+ } else if (/^\s*#{1,6}\s/.test(line)) {
693
+ kind = "skip";
694
+ } else if (line.trim().startsWith("|")) {
695
+ const next = raw[index + 1] ?? "";
696
+ if (isTableLine(line) || isTableLine(next)) {
697
+ kind = "skip"; // separator or header row: a marker here breaks the table
698
+ } else {
699
+ const lastPipe = line.lastIndexOf("|");
700
+ kind = "table-row";
701
+ pipeAt = lastPipe > 0 ? start + lastPipe : end;
702
+ }
703
+ }
704
+ lines.push({ start, end, kind, pipeAt });
705
+ }
706
+ return lines;
707
+ }
708
+
709
+ /** The classified line containing a character offset. */
710
+ function lineAt(lines: LineInfo[], position: number): LineInfo | undefined {
711
+ return lines.find((line) => position >= line.start && position <= line.end);
712
+ }
713
+
714
+ /** Drop spans contained in a larger span, then merge overlapping ones, so one claim gets one marker. */
715
+ function mergeCitationSpans(spans: CitationSpan[]): CitationSpan[] {
716
+ const sorted = [...spans].sort((a, b) => a.start - b.start || b.end - a.end);
717
+ const kept: CitationSpan[] = [];
718
+ for (const span of sorted) {
719
+ const container = kept.find((other) => other.start <= span.start && other.end >= span.end);
720
+ if (container) {
721
+ container.indices = [...new Set([...container.indices, ...span.indices])].sort(
722
+ (a, b) => a - b,
723
+ );
724
+ continue;
725
+ }
726
+ kept.push({ start: span.start, end: span.end, indices: [...span.indices] });
727
+ }
728
+ const merged: CitationSpan[] = [];
729
+ for (const span of kept) {
730
+ const previous = merged[merged.length - 1];
731
+ if (previous && span.start <= previous.end) {
732
+ previous.end = Math.max(previous.end, span.end);
733
+ previous.indices = [...new Set([...previous.indices, ...span.indices])].sort((a, b) => a - b);
734
+ continue;
735
+ }
736
+ merged.push({ ...span });
737
+ }
738
+ return merged;
739
+ }
740
+
741
+ /**
742
+ * Map each UTF-8 byte offset in `text` to the JS character index it starts at.
743
+ * Keep in sync with the byte-based verification below.
744
+ */
745
+ function buildByteToCharMap(text: string): number[] {
746
+ const map: number[] = [];
747
+ for (let index = 0; index < text.length;) {
748
+ const codePoint = text.codePointAt(index) as number;
749
+ const width = codePoint > 0xffff ? 2 : 1;
750
+ const byteLength = Buffer.byteLength(text.slice(index, index + width), "utf8");
751
+ for (let byte = 0; byte < byteLength; byte++) map.push(index);
752
+ index += width;
753
+ }
754
+ map.push(text.length);
755
+ return map;
756
+ }
757
+
286
758
  /**
287
759
  * Google's offsets are UTF-8 bytes within a content Part, not JS character indices.
288
- * Verify each segment before inserting citations; skip unsafe mappings.
760
+ *
761
+ * Each segment is verified byte-for-byte before use. A segment whose bytes do not match
762
+ * its reported text is relocated by searching the part instead of being discarded: the
763
+ * offsets drift on some answers (table-heavy ones in particular), and dropping those
764
+ * citations silently removes exactly the provenance this function exists to provide.
765
+ *
766
+ * Markers are grouped per insertion point. The first mention of a source carries both its
767
+ * number and a full link, so the number always matches its entry in the source list below and
768
+ * the reader never has to resolve an unexplained `[n]`.
289
769
  */
290
770
  function citeSearchText(res: SearchResult): string {
291
771
  if (!res.supports?.length) return res.text;
@@ -294,38 +774,88 @@ function citeSearchText(res: SearchResult): string {
294
774
  if (textParts.map((part) => part.text).join("\n\n") !== res.text) {
295
775
  return res.text;
296
776
  }
297
- const sourceIndices = new Set(res.sources.map((source, index) => source.index ?? index));
298
- const parts = textParts.map((part) => {
777
+
778
+ const bySourceIndex = new Map<number, { number: number; label: string; url: string }>();
779
+ res.sources.forEach((source, position) => {
780
+ const sourceIndex = source.index ?? position;
781
+ bySourceIndex.set(sourceIndex, {
782
+ number: sourceIndex + 1,
783
+ label: sourceLabel(source),
784
+ url: source.resolvedUrl ?? source.url,
785
+ });
786
+ });
787
+
788
+ const seen = new Set<number>();
789
+ const insertionsByPart = new Map<number, Array<{ at: number; text: string }>>();
790
+
791
+ for (const part of textParts) {
299
792
  const bytes = Buffer.from(part.text, "utf8");
300
- const insertions = new Map<number, Set<number>>();
793
+ const byteToChar = buildByteToCharMap(part.text);
794
+ const lines = analyzeLines(part.text);
795
+ const spans: CitationSpan[] = [];
796
+
301
797
  for (const support of res.supports ?? []) {
302
- const start = support.startIndex ?? 0;
303
- const end = support.endIndex;
304
- if (
305
- (support.partIndex ?? 0) !== part.index ||
306
- !Number.isInteger(start) ||
307
- start < 0 ||
308
- end === undefined ||
309
- !Number.isInteger(end) ||
310
- end <= start ||
311
- end > bytes.length ||
312
- bytes.subarray(start, end).toString("utf8") !== support.text
313
- )
314
- continue;
315
- const indices = insertions.get(end) ?? new Set<number>();
316
- for (const index of support.sourceIndices) {
317
- if (Number.isInteger(index) && index >= 0 && sourceIndices.has(index)) indices.add(index);
798
+ if ((support.partIndex ?? 0) !== part.index) continue;
799
+ const indices = support.sourceIndices.filter((index) => bySourceIndex.has(index));
800
+ if (indices.length === 0) continue;
801
+
802
+ let start = support.startIndex;
803
+ let end = support.endIndex;
804
+ const offsetsTrustworthy =
805
+ typeof start === "number" &&
806
+ typeof end === "number" &&
807
+ Number.isInteger(start) &&
808
+ Number.isInteger(end) &&
809
+ start >= 0 &&
810
+ end > start &&
811
+ end <= bytes.length &&
812
+ bytes.subarray(start, end).toString("utf8") === support.text;
813
+
814
+ if (!offsetsTrustworthy) {
815
+ const located = part.text.indexOf(support.text);
816
+ if (located < 0) continue;
817
+ start = Buffer.byteLength(part.text.slice(0, located), "utf8");
818
+ end = start + Buffer.byteLength(support.text, "utf8");
318
819
  }
319
- insertions.set(end, indices);
820
+
821
+ const startChar = byteToChar[start as number] ?? part.text.length;
822
+ const endChar = byteToChar[end as number] ?? part.text.length;
823
+ if (endChar <= startChar) continue;
824
+ spans.push({
825
+ start: startChar,
826
+ end: endChar,
827
+ indices: [...new Set(indices)].sort((a, b) => a - b),
828
+ });
829
+ }
830
+
831
+ for (const span of mergeCitationSpans(spans)) {
832
+ const line = lineAt(lines, span.end);
833
+ if (!line || line.kind === "skip") continue;
834
+ const at = line.kind === "table-row" ? (line.pipeAt ?? span.end) : span.end;
835
+ const pieces = span.indices.map((index) => {
836
+ const source = bySourceIndex.get(index);
837
+ if (!source) return "";
838
+ if (seen.has(index)) return `[${source.number}]`;
839
+ seen.add(index);
840
+ // The first mention carries the number too, so it matches the sources list below.
841
+ return `[${source.number}] [${escapeLinkText(source.label)}](${escapeLinkDestination(source.url)})`;
842
+ });
843
+ const text = ` ${pieces.filter(Boolean).join(" ")}`;
844
+ const list = insertionsByPart.get(part.index) ?? [];
845
+ list.push({ at, text });
846
+ insertionsByPart.set(part.index, list);
320
847
  }
321
- let cited = bytes;
322
- for (const [end, indices] of [...insertions].sort(([a], [b]) => b - a)) {
323
- const references = [...indices].map((index) => `[${index + 1}]`).join("");
324
- cited = Buffer.concat([cited.subarray(0, end), Buffer.from(references), cited.subarray(end)]);
848
+ }
849
+
850
+ const rendered = textParts.map((part) => {
851
+ let text = part.text;
852
+ for (const insertion of (insertionsByPart.get(part.index) ?? []).sort((a, b) => b.at - a.at)) {
853
+ text = text.slice(0, insertion.at) + insertion.text + text.slice(insertion.at);
325
854
  }
326
- return cited.toString("utf8");
855
+ return text;
327
856
  });
328
- return parts.join("\n\n") || res.text;
857
+
858
+ return rendered.join("\n\n") || res.text;
329
859
  }
330
860
 
331
861
  /**
@@ -342,10 +872,11 @@ export function formatSearchResult(res: SearchResult): string {
342
872
 
343
873
  if (res.sources.length > 0) {
344
874
  const list = res.sources
345
- .map(
346
- (s, index) =>
347
- `- ${res.supports?.length ? `[${(s.index ?? index) + 1}] ` : ""}[${s.title}](${s.url})`,
348
- )
875
+ .map((s, index) => {
876
+ const number = res.supports?.length ? `[${(s.index ?? index) + 1}] ` : "";
877
+ const url = s.resolvedUrl ?? s.url;
878
+ return `- ${number}[${escapeLinkText(sourceLabel(s))}](${escapeLinkDestination(url)})`;
879
+ })
349
880
  .join("\n");
350
881
  sections.push(`### Sources\n${list}`);
351
882
  }
@@ -389,10 +920,16 @@ export async function executeAntigravitySearch(options: ExecuteSearchOptions): P
389
920
 
390
921
  if (!response.ok) {
391
922
  lastError = jsonOrTextError(await response.text()).slice(0, 400);
392
- if (response.status === 404 || [429, 500, 502, 503, 504].includes(response.status)) {
393
- continue; // Retry next endpoint for transient failures or missing model endpoints
923
+ const modelRejected =
924
+ response.status === 400 && /invalid argument|thinking/i.test(lastError);
925
+ if (
926
+ response.status === 404 ||
927
+ modelRejected ||
928
+ [429, 500, 502, 503, 504].includes(response.status)
929
+ ) {
930
+ continue; // Retry next endpoint, or the next fallback model, for model-specific 400s
394
931
  }
395
- // Fail fast on non-retryable client errors (e.g. 400 Bad Request, 401 Unauthorized, 403 Forbidden)
932
+ // Fail fast on non-retryable client errors (e.g. 401 Unauthorized, 403 Forbidden)
396
933
  throw Object.assign(new Error(lastError), { fatal: true });
397
934
  }
398
935
 
@@ -411,6 +948,7 @@ export async function executeAntigravitySearch(options: ExecuteSearchOptions): P
411
948
  }
412
949
 
413
950
  const parsed = parseSearchResponse(data);
951
+ await enrichSources(parsed.sources, options.signal);
414
952
  return formatSearchResult(parsed);
415
953
  } catch (error) {
416
954
  if (options.signal?.aborted) throw error;