@herbertgao/pi-extensions 2026.11.17 → 2026.11.19

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 (159) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +3 -3
  3. package/THIRD_PARTY_NOTICES.md +2 -23
  4. package/node_modules/@estebanforge/pi-antigravity-bridge/CHANGELOG.md +956 -0
  5. package/node_modules/{pi-antigravity → @estebanforge/pi-antigravity-bridge}/LICENSE +1 -1
  6. package/node_modules/@estebanforge/pi-antigravity-bridge/README.md +240 -0
  7. package/node_modules/@estebanforge/pi-antigravity-bridge/extensions/index.ts +2117 -0
  8. package/node_modules/@estebanforge/pi-antigravity-bridge/package.json +61 -0
  9. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/connection.ts +644 -0
  10. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/driver.ts +1043 -0
  11. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/events.ts +323 -0
  12. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/home.ts +145 -0
  13. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/jsonrpc.ts +243 -0
  14. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/setup.ts +107 -0
  15. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/usage-estimate.ts +61 -0
  16. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agents.ts +64 -0
  17. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-install.ts +93 -0
  18. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-paths.ts +30 -0
  19. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-setup.ts +81 -0
  20. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-version.ts +289 -0
  21. package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-detect.ts +161 -0
  22. package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-gate.ts +233 -0
  23. package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-hook.ts +325 -0
  24. package/node_modules/@estebanforge/pi-antigravity-bridge/src/artifacts-ui.ts +88 -0
  25. package/node_modules/@estebanforge/pi-antigravity-bridge/src/artifacts.ts +144 -0
  26. package/node_modules/@estebanforge/pi-antigravity-bridge/src/ask-tool.ts +1221 -0
  27. package/node_modules/@estebanforge/pi-antigravity-bridge/src/background-watch.ts +225 -0
  28. package/node_modules/@estebanforge/pi-antigravity-bridge/src/bridge-catalog.ts +197 -0
  29. package/node_modules/@estebanforge/pi-antigravity-bridge/src/config.ts +523 -0
  30. package/node_modules/@estebanforge/pi-antigravity-bridge/src/daily-log.ts +196 -0
  31. package/node_modules/@estebanforge/pi-antigravity-bridge/src/dialog-lock.ts +48 -0
  32. package/node_modules/@estebanforge/pi-antigravity-bridge/src/diff-render.ts +207 -0
  33. package/node_modules/@estebanforge/pi-antigravity-bridge/src/driver-types.ts +168 -0
  34. package/node_modules/@estebanforge/pi-antigravity-bridge/src/driver.ts +907 -0
  35. package/node_modules/@estebanforge/pi-antigravity-bridge/src/engine-picker.ts +160 -0
  36. package/node_modules/@estebanforge/pi-antigravity-bridge/src/frame-guard.ts +38 -0
  37. package/node_modules/@estebanforge/pi-antigravity-bridge/src/handoff-toast.ts +21 -0
  38. package/node_modules/@estebanforge/pi-antigravity-bridge/src/mcp-registration.ts +376 -0
  39. package/node_modules/@estebanforge/pi-antigravity-bridge/src/mcp-server.ts +618 -0
  40. package/node_modules/@estebanforge/pi-antigravity-bridge/src/models.ts +404 -0
  41. package/node_modules/@estebanforge/pi-antigravity-bridge/src/native-tools.ts +104 -0
  42. package/node_modules/@estebanforge/pi-antigravity-bridge/src/parked-turn.ts +125 -0
  43. package/node_modules/@estebanforge/pi-antigravity-bridge/src/patch-cleanup.ts +523 -0
  44. package/node_modules/@estebanforge/pi-antigravity-bridge/src/poll-fold.ts +55 -0
  45. package/node_modules/@estebanforge/pi-antigravity-bridge/src/prompt-images.ts +92 -0
  46. package/node_modules/@estebanforge/pi-antigravity-bridge/src/provider.ts +2214 -0
  47. package/node_modules/@estebanforge/pi-antigravity-bridge/src/queued-messages.ts +152 -0
  48. package/node_modules/@estebanforge/pi-antigravity-bridge/src/quota-notice.ts +40 -0
  49. package/node_modules/@estebanforge/pi-antigravity-bridge/src/redact.ts +27 -0
  50. package/node_modules/@estebanforge/pi-antigravity-bridge/src/sessions.ts +197 -0
  51. package/node_modules/@estebanforge/pi-antigravity-bridge/src/skills.ts +207 -0
  52. package/node_modules/@estebanforge/pi-antigravity-bridge/src/stream-events.ts +161 -0
  53. package/node_modules/@estebanforge/pi-antigravity-bridge/src/stream-sanitizer.ts +180 -0
  54. package/node_modules/@estebanforge/pi-antigravity-bridge/src/subagent-roster.ts +245 -0
  55. package/node_modules/@estebanforge/pi-antigravity-bridge/src/sysprompt-agent.ts +130 -0
  56. package/node_modules/@estebanforge/pi-antigravity-bridge/src/tasks-ui.ts +90 -0
  57. package/node_modules/@estebanforge/pi-antigravity-bridge/src/tasks.ts +174 -0
  58. package/node_modules/@estebanforge/pi-antigravity-bridge/src/usage.ts +174 -0
  59. package/node_modules/@estebanforge/pi-antigravity-bridge/src/web-tools.ts +320 -0
  60. package/node_modules/@herbertgao/pi-cc-extensions/CHANGELOG.md +12 -0
  61. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/panel.ts +1 -1
  62. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/prompt-editor.ts +3 -1
  63. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/index.ts +7 -0
  64. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/agent-badge.ts +244 -0
  65. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/ccstyle-tool.ts +1 -1
  66. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/grouping.ts +10 -3
  67. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/names.ts +18 -0
  68. package/node_modules/@herbertgao/pi-cc-extensions/package.json +1 -1
  69. package/node_modules/@herbertgao/pi-inline-skill-commands/README.md +18 -0
  70. package/node_modules/@herbertgao/pi-inline-skill-commands/package.json +1 -1
  71. package/node_modules/@herbertgao/pi-inline-skill-commands/src/index.ts +80 -0
  72. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +320 -102
  73. package/node_modules/@herbertgao/pi-subagents/SECURITY.md +2 -2
  74. package/node_modules/@herbertgao/pi-subagents/docs/rpc.md +240 -30
  75. package/node_modules/@herbertgao/pi-subagents/docs/translations.md +63 -0
  76. package/node_modules/@herbertgao/pi-subagents/docs/workflows.md +1 -1
  77. package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
  78. package/node_modules/@herbertgao/pi-subagents/src/agent-file-toggle.ts +2 -0
  79. package/node_modules/@herbertgao/pi-subagents/src/agent-manager.ts +89 -6
  80. package/node_modules/@herbertgao/pi-subagents/src/agent-runner.ts +6 -2
  81. package/node_modules/@herbertgao/pi-subagents/src/agent-types.ts +27 -13
  82. package/node_modules/@herbertgao/pi-subagents/src/cache-retention.ts +39 -0
  83. package/node_modules/@herbertgao/pi-subagents/src/completion-outbox.ts +5 -0
  84. package/node_modules/@herbertgao/pi-subagents/src/cross-extension-rpc.ts +217 -41
  85. package/node_modules/@herbertgao/pi-subagents/src/custom-agents.ts +7 -0
  86. package/node_modules/@herbertgao/pi-subagents/src/group-join.ts +9 -0
  87. package/node_modules/@herbertgao/pi-subagents/src/index.ts +126 -93
  88. package/node_modules/@herbertgao/pi-subagents/src/mention-clone.ts +3 -2
  89. package/node_modules/@herbertgao/pi-subagents/src/settings.ts +21 -0
  90. package/node_modules/@herbertgao/pi-subagents/src/subagent-info.ts +115 -0
  91. package/node_modules/@herbertgao/pi-subagents/src/types.ts +11 -7
  92. package/node_modules/@herbertgao/pi-subagents/src/ui/agent-widget.ts +2 -3
  93. package/node_modules/@herbertgao/pi-subagents/src/ui/conversation-viewer.ts +1 -1
  94. package/node_modules/@herbertgao/pi-subagents/src/workflow/meta.ts +2 -2
  95. package/node_modules/@herbertgao/pi-subagents/src/workflow-info.ts +184 -0
  96. package/node_modules/pi-commandcode-provider/CHANGELOG.md +10 -0
  97. package/node_modules/pi-commandcode-provider/README.md +3 -2
  98. package/node_modules/pi-commandcode-provider/index.ts +120 -13
  99. package/node_modules/pi-commandcode-provider/package.json +4 -3
  100. package/node_modules/pi-commandcode-provider/src/commandcode-catalog.ts +11 -2
  101. package/node_modules/pi-commandcode-provider/src/pricing.ts +17 -1
  102. package/node_modules/pi-commandcode-provider/src/quota-command.ts +3 -2
  103. package/node_modules/pi-commandcode-provider/src/zdr.ts +163 -0
  104. package/package.json +12 -15
  105. package/node_modules/pi-antigravity/README.md +0 -298
  106. package/node_modules/pi-antigravity/docs/reader-guarantees.md +0 -35
  107. package/node_modules/pi-antigravity/package.json +0 -87
  108. package/node_modules/pi-antigravity/src/auth/accounts.ts +0 -327
  109. package/node_modules/pi-antigravity/src/auth/index.ts +0 -23
  110. package/node_modules/pi-antigravity/src/auth/oauth.ts +0 -445
  111. package/node_modules/pi-antigravity/src/client/client.ts +0 -602
  112. package/node_modules/pi-antigravity/src/client/enterprise.ts +0 -150
  113. package/node_modules/pi-antigravity/src/client/index.ts +0 -2
  114. package/node_modules/pi-antigravity/src/diagnostics/diagnostics.ts +0 -104
  115. package/node_modules/pi-antigravity/src/diagnostics/index.ts +0 -1
  116. package/node_modules/pi-antigravity/src/features/generate-image.ts +0 -132
  117. package/node_modules/pi-antigravity/src/features/google-search.ts +0 -72
  118. package/node_modules/pi-antigravity/src/features/read-url-content.ts +0 -124
  119. package/node_modules/pi-antigravity/src/image/image.ts +0 -427
  120. package/node_modules/pi-antigravity/src/image/index.ts +0 -1
  121. package/node_modules/pi-antigravity/src/image/native.ts +0 -69
  122. package/node_modules/pi-antigravity/src/index.ts +0 -547
  123. package/node_modules/pi-antigravity/src/models/discovery.ts +0 -176
  124. package/node_modules/pi-antigravity/src/models/grouping.ts +0 -487
  125. package/node_modules/pi-antigravity/src/models/index.ts +0 -3
  126. package/node_modules/pi-antigravity/src/models/models.ts +0 -647
  127. package/node_modules/pi-antigravity/src/search/index.ts +0 -1
  128. package/node_modules/pi-antigravity/src/search/search.ts +0 -967
  129. package/node_modules/pi-antigravity/src/stream/index.ts +0 -1
  130. package/node_modules/pi-antigravity/src/stream/stream.ts +0 -1961
  131. package/node_modules/pi-antigravity/src/types/enums.ts +0 -52
  132. package/node_modules/pi-antigravity/src/types/index.ts +0 -2
  133. package/node_modules/pi-antigravity/src/types/types.ts +0 -329
  134. package/node_modules/pi-antigravity/src/usage/index.ts +0 -1
  135. package/node_modules/pi-antigravity/src/usage/usage.ts +0 -437
  136. package/node_modules/pi-antigravity/src/utils/address.ts +0 -180
  137. package/node_modules/pi-antigravity/src/utils/credits.ts +0 -149
  138. package/node_modules/pi-antigravity/src/utils/html.ts +0 -31
  139. package/node_modules/pi-antigravity/src/utils/http.ts +0 -96
  140. package/node_modules/pi-antigravity/src/utils/index.ts +0 -5
  141. package/node_modules/pi-antigravity/src/utils/security.ts +0 -278
  142. package/node_modules/pi-antigravity/src/utils/text.ts +0 -66
  143. package/node_modules/pi-antigravity/src/utils/util.ts +0 -217
  144. package/node_modules/pi-antigravity/src/web-fetch/document.ts +0 -83
  145. package/node_modules/pi-antigravity/src/web-fetch/fences.ts +0 -24
  146. package/node_modules/pi-antigravity/src/web-fetch/header.ts +0 -97
  147. package/node_modules/pi-antigravity/src/web-fetch/index.ts +0 -3
  148. package/node_modules/pi-antigravity/src/web-fetch/inspect.ts +0 -328
  149. package/node_modules/pi-antigravity/src/web-fetch/limits.ts +0 -4
  150. package/node_modules/pi-antigravity/src/web-fetch/markdown.ts +0 -744
  151. package/node_modules/pi-antigravity/src/web-fetch/mdn.ts +0 -164
  152. package/node_modules/pi-antigravity/src/web-fetch/media.ts +0 -11
  153. package/node_modules/pi-antigravity/src/web-fetch/metadata.ts +0 -9
  154. package/node_modules/pi-antigravity/src/web-fetch/representation.ts +0 -93
  155. package/node_modules/pi-antigravity/src/web-fetch/save.ts +0 -71
  156. package/node_modules/pi-antigravity/src/web-fetch/sites.ts +0 -138
  157. package/node_modules/pi-antigravity/src/web-fetch/vendor.d.ts +0 -9
  158. package/node_modules/pi-antigravity/src/web-fetch/web-fetch.ts +0 -957
  159. package/node_modules/pi-antigravity/tsconfig.json +0 -21
@@ -1,967 +0,0 @@
1
- import { lookup } from "node:dns/promises";
2
- import { isIP } from "node:net";
3
-
4
- import {
5
- antigravityHeaders,
6
- endpointCandidates,
7
- jsonOrTextError,
8
- parseApiKey,
9
- } from "../client/client.js";
10
- import { AntigravityRequestType, AntigravityUserAgent, GeminiRole } from "../types/enums.js";
11
- import { antigravityFetch } from "../utils/http.js";
12
- import { safeError } from "../utils/security.js";
13
- import { antigravityEnv, antigravityRequestEnvelope, isRecord } from "../utils/util.js";
14
-
15
- /** Default search model: fast grounding model for interactive tool calls. */
16
- export const DEFAULT_SEARCH_MODEL = "gemini-3.5-flash-lite";
17
-
18
- /** Fallback runtime candidates if the primary model is missing or out of capacity. */
19
- export const SEARCH_MODEL_FALLBACKS = [
20
- DEFAULT_SEARCH_MODEL,
21
- "gemini-3.1-flash-lite",
22
- "gemini-3-flash",
23
- ] as const;
24
-
25
- export const SEARCH_SYSTEM_INSTRUCTION = `You are a careful research assistant using Google Search grounding.
26
- Return a compact evidence brief with exactly these sections:
27
- ## Findings
28
- ## Gaps
29
- ## Next checks
30
-
31
- Rules:
32
- - Verify each claim inside the specific item, function, or section it refers to. Do not copy an attribute from a neighboring entry on the same page.
33
- - Prefer primary documentation and exact names, versions, and constraints over marketing summaries.
34
- - If a fact is not supported by a retrieved source, put it under Gaps instead of stating it as a finding.
35
- - Keep the brief short enough for an interactive agent tool call.`;
36
-
37
- export type SearchSource = {
38
- /** Original groundingChunks index, including gaps from skipped non-web chunks. */
39
- index?: number;
40
- title: string;
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;
52
- };
53
-
54
- export type SearchSupport = {
55
- text: string;
56
- startIndex?: number;
57
- endIndex?: number;
58
- partIndex?: number;
59
- sourceIndices: number[];
60
- };
61
-
62
- export type SearchResult = {
63
- text: string;
64
- sources: SearchSource[];
65
- queries: string[];
66
- /** Optional so existing callers can still construct results with the original shape. */
67
- parts?: Array<{ index: number; text: string }>;
68
- supports?: SearchSupport[];
69
- };
70
-
71
- export type ExecuteSearchOptions = {
72
- apiKey?: string;
73
- query: string;
74
- instruction?: string;
75
- urls?: string[];
76
- thinking?: boolean;
77
- signal?: AbortSignal;
78
- };
79
-
80
- export type SearchCommandArgs = {
81
- query: string;
82
- urls?: string[];
83
- thinking?: boolean;
84
- };
85
-
86
- /**
87
- * Parse arguments for the interactive `/antigravity.search` command.
88
- * Supports flags:
89
- * --thinking: enable deep reasoning for search planning
90
- * --url <url>: pass target URL for context analysis (can be repeated)
91
- *
92
- * @param args - Raw string of CLI arguments.
93
- * @returns Parsed command arguments containing query, optional URLs, and thinking flag.
94
- */
95
- export function parseSearchCommandArgs(args: string): SearchCommandArgs {
96
- const tokens = args.trim().split(/\s+/).filter(Boolean);
97
- const out: SearchCommandArgs = { query: "" };
98
- const rest: string[] = [];
99
-
100
- for (let i = 0; i < tokens.length; i++) {
101
- const token = tokens[i];
102
- if (token === undefined) continue;
103
- const next = tokens[i + 1];
104
-
105
- if (token === "--thinking") {
106
- out.thinking = true;
107
- continue;
108
- }
109
- if (token === "--url" && next) {
110
- out.urls = out.urls ?? [];
111
- out.urls.push(next);
112
- i += 1;
113
- continue;
114
- }
115
- rest.push(token);
116
- }
117
-
118
- out.query = rest.join(" ");
119
- return out;
120
- }
121
-
122
- /**
123
- * Builds the Antigravity wire request payload for Gemini Google Search Grounding.
124
- * Includes the required `requestType` and `requestId` envelope fields.
125
- *
126
- * @param options - Options including search query, lead agent directives, target URLs, and thinking preference.
127
- * @param model - Target model identifier (e.g., `gemini-3-flash`).
128
- * @param projectId - Google Cloud Project ID.
129
- * @returns Serialized request object matching the Antigravity wire contract.
130
- */
131
- export function buildSearchRequest(
132
- options: {
133
- query: string;
134
- instruction?: string;
135
- urls?: string[];
136
- thinking?: boolean;
137
- },
138
- model: string,
139
- projectId: string,
140
- ): Record<string, unknown> {
141
- let systemInstructionText = SEARCH_SYSTEM_INSTRUCTION;
142
- if (options.instruction?.trim()) {
143
- systemInstructionText += `\n\n[SPECIFIC DIRECTIVE FROM LEAD AGENT]:\n${options.instruction.trim()}\nYou MUST strictly follow this directive during search query formulation and synthesis.`;
144
- }
145
-
146
- let prompt = options.query.trim();
147
- if (options.instruction?.trim()) {
148
- prompt = `[Lead Agent Directive]: ${options.instruction.trim()}\n\nSearch Query: ${prompt}`;
149
- }
150
- if (options.urls && options.urls.length > 0) {
151
- prompt += `\n\nURLs to analyze in detail:\n${options.urls.join("\n")}`;
152
- }
153
-
154
- const tools: Array<Record<string, unknown>> = [{ googleSearch: {} }];
155
- if (options.urls && options.urls.length > 0) {
156
- tools.push({ urlContext: {} });
157
- }
158
-
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
- }
168
- const envelope = antigravityRequestEnvelope(model, false);
169
-
170
- return {
171
- project: projectId,
172
- model,
173
- request: {
174
- systemInstruction: {
175
- role: GeminiRole.User,
176
- parts: [{ text: systemInstructionText }],
177
- },
178
- contents: [
179
- {
180
- role: GeminiRole.User,
181
- parts: [{ text: prompt }],
182
- },
183
- ],
184
- tools,
185
- generationConfig,
186
- },
187
- requestType: AntigravityRequestType.Agent,
188
- userAgent: AntigravityUserAgent.Antigravity,
189
- requestId: envelope.requestId,
190
- };
191
- }
192
-
193
- /** Read candidates from either the wrapped Antigravity or direct Gemini response. */
194
- function candidateList(data: unknown): unknown {
195
- if (!isRecord(data)) return undefined;
196
- if (isRecord(data.response)) return data.response.candidates;
197
- return data.candidates;
198
- }
199
-
200
- /** Return the first array entry without assuming its response shape. */
201
- function firstUnknownItem(value: unknown): unknown {
202
- if (!Array.isArray(value)) return undefined;
203
- return (value as unknown[])[0];
204
- }
205
-
206
- /**
207
- * Parse visible candidate text and grounding metadata from an Antigravity response.
208
- * Preserve original part and source indices so UTF-8 citation offsets remain usable.
209
- *
210
- * @param data - Raw JSON response from Antigravity generateContent API.
211
- * @returns Synthesized text, web queries, sources, and grounding supports.
212
- */
213
- export function parseSearchResponse(data: unknown): SearchResult {
214
- const result: SearchResult = { text: "", sources: [], queries: [], parts: [], supports: [] };
215
- if (!isRecord(data)) return result;
216
-
217
- const responseObj = isRecord(data.response) ? data.response : data;
218
- const candidates = Array.isArray(responseObj.candidates)
219
- ? (responseObj.candidates as unknown[])
220
- : [];
221
- const candidate = candidates[0];
222
-
223
- if (!isRecord(candidate)) {
224
- const errorObj = isRecord(data.error)
225
- ? data.error
226
- : isRecord(responseObj.error)
227
- ? responseObj.error
228
- : undefined;
229
- const msg =
230
- typeof errorObj?.message === "string"
231
- ? errorObj.message
232
- : "No candidate returned from Antigravity Search";
233
- result.text = `Error: ${msg}`;
234
- return result;
235
- }
236
-
237
- // Extract synthesized text (ignoring thinking parts)
238
- const content = isRecord(candidate.content) ? candidate.content : undefined;
239
- if (Array.isArray(content?.parts)) {
240
- result.parts = content.parts.flatMap((part, index) =>
241
- isRecord(part) && !part.thought && typeof part.text === "string" && part.text
242
- ? [{ index, text: part.text }]
243
- : [],
244
- );
245
- result.text = result.parts.map((part) => part.text).join("\n\n");
246
- }
247
-
248
- // Extract grounding citations & executed queries
249
- const grounding = isRecord(candidate.groundingMetadata) ? candidate.groundingMetadata : undefined;
250
- if (grounding) {
251
- if (Array.isArray(grounding.webSearchQueries)) {
252
- result.queries = grounding.webSearchQueries.filter((q): q is string => typeof q === "string");
253
- }
254
- if (Array.isArray(grounding.groundingChunks)) {
255
- for (const [index, chunk] of grounding.groundingChunks.entries()) {
256
- if (!isRecord(chunk)) continue;
257
- const web = isRecord(chunk.web) ? chunk.web : undefined;
258
- if (typeof web?.uri === "string") {
259
- result.sources.push({
260
- index,
261
- title: typeof web.title === "string" && web.title.trim() ? web.title.trim() : web.uri,
262
- url: web.uri,
263
- });
264
- }
265
- }
266
- }
267
- if (Array.isArray(grounding.groundingSupports)) {
268
- const sourceIndices = new Set(result.sources.map((source) => source.index));
269
- const textPartIndices = new Set(result.parts?.map((part) => part.index));
270
- for (const support of grounding.groundingSupports) {
271
- if (!isRecord(support) || !isRecord(support.segment)) continue;
272
- if (
273
- typeof support.segment.text !== "string" ||
274
- !Array.isArray(support.groundingChunkIndices)
275
- )
276
- continue;
277
- const partIndex = support.segment.partIndex ?? 0;
278
- if (typeof partIndex !== "number" || !textPartIndices.has(partIndex)) continue;
279
- const indices = support.groundingChunkIndices.filter(
280
- (index): index is number =>
281
- typeof index === "number" && Number.isInteger(index) && sourceIndices.has(index),
282
- );
283
- if (indices.length === 0) continue;
284
- result.supports?.push({
285
- text: support.segment.text,
286
- startIndex:
287
- typeof support.segment.startIndex === "number" ? support.segment.startIndex : undefined,
288
- endIndex:
289
- typeof support.segment.endIndex === "number" ? support.segment.endIndex : undefined,
290
- partIndex:
291
- typeof support.segment.partIndex === "number" ? support.segment.partIndex : undefined,
292
- sourceIndices: indices,
293
- });
294
- }
295
- }
296
- }
297
-
298
- return result;
299
- }
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) return "";
554
- try {
555
- if (new URL(url).hostname === GROUNDING_REDIRECT_HOST) return "";
556
- } catch {
557
- return "";
558
- }
559
- // One deadline for the whole chain, so extra hops cannot multiply the wait.
560
- const deadline = withDeadline(signal, SOURCE_ENRICH_TIMEOUT_MS);
561
- let current = url;
562
- for (let hop = 0; hop <= PAGE_TITLE_MAX_HOPS; hop += 1) {
563
- if (!(await isFetchablePageUrl(current))) return "";
564
- let response: Response;
565
- try {
566
- response = await antigravityFetch(current, {
567
- redirect: "manual",
568
- signal: deadline,
569
- headers: { "User-Agent": "Mozilla/5.0 (compatible; pi-antigravity/1.0)" },
570
- });
571
- } catch {
572
- return "";
573
- }
574
- if (response.status >= 300 && response.status < 400) {
575
- const location = response.headers.get("location");
576
- if (!location) return "";
577
- try {
578
- current = new URL(location, current).toString();
579
- } catch {
580
- return "";
581
- }
582
- continue;
583
- }
584
- if (!response.ok) return "";
585
- const contentType = response.headers.get("content-type") ?? "";
586
- if (contentType && !/text\/html|application\/xhtml/i.test(contentType)) return "";
587
- return await readPageTitle(response);
588
- }
589
- return "";
590
- }
591
-
592
- /**
593
- * Add a real link and a readable label to every source.
594
- *
595
- * This exists because `groundingChunks[].web` carries only `uri` and `title`: no snippet,
596
- * no page title, and a title that is a bare domain almost every time. Without this step
597
- * a model reading the result cannot tell what any source is. Failures degrade to the
598
- * bare domain rather than to the opaque redirect URL.
599
- *
600
- * `ANTIGRAVITY_NO_SOURCE_ENRICH=1` skips it for callers that would rather not emit one
601
- * extra request per source.
602
- */
603
- async function enrichSources(sources: SearchSource[], signal?: AbortSignal): Promise<void> {
604
- if (antigravityEnv("NO_SOURCE_ENRICH") === "1") {
605
- for (const source of sources) source.label = sourceLabel(source);
606
- return;
607
- }
608
-
609
- let cursor = 0;
610
- const worker = async (): Promise<void> => {
611
- for (;;) {
612
- const position = cursor++;
613
- if (position >= sources.length) return;
614
- const source = sources[position];
615
- if (!source) continue;
616
-
617
- const redirect = source.url;
618
- if (!isGroundingRedirectUrl(redirect)) {
619
- source.resolvedUrl = redirect;
620
- } else {
621
- const cached = resolvedUrlCache.get(redirect);
622
- if (cached !== undefined) {
623
- source.resolvedUrl = cached;
624
- } else {
625
- const resolved = await resolveGroundingRedirect(redirect, signal);
626
- if (resolved) {
627
- remember(resolvedUrlCache, redirect, resolved);
628
- source.resolvedUrl = resolved;
629
- }
630
- }
631
- }
632
-
633
- const target = source.resolvedUrl ?? source.url;
634
- const cachedTitle = pageTitleCache.get(target);
635
- if (cachedTitle !== undefined) {
636
- source.pageTitle = cachedTitle;
637
- } else {
638
- const title = await fetchPageTitle(target, signal);
639
- if (title) {
640
- remember(pageTitleCache, target, title);
641
- source.pageTitle = title;
642
- }
643
- }
644
-
645
- source.label = sourceLabel(source);
646
- }
647
- };
648
-
649
- await Promise.all(
650
- Array.from({ length: Math.min(SOURCE_ENRICH_CONCURRENCY, sources.length) }, () => worker()),
651
- );
652
- }
653
-
654
- /** Keep a label from breaking out of its link slot or its list line. */
655
- function escapeLinkText(text: string): string {
656
- return text.replace(/[\\[\]]/g, "\\$&").replace(/\s+/g, " ");
657
- }
658
-
659
- /** Encode characters that would close a Markdown link destination. */
660
- function escapeLinkDestination(url: string): string {
661
- return url.replace(/\)/g, "%29").replace(/ /g, "%20");
662
- }
663
-
664
- /** One contiguous claim, carrying every source index that supports it. */
665
- type CitationSpan = { start: number; end: number; indices: number[] };
666
-
667
- type LineKind = "text" | "skip" | "table-row";
668
- type LineInfo = { start: number; end: number; kind: LineKind; pipeAt?: number };
669
-
670
- /**
671
- * Classify every line so citations never land in prose-hostile places.
672
- *
673
- * Google attaches supports to Markdown headings too, which would produce
674
- * `### Single-Writer Rule[1,2]` noise, and a marker appended after a table row's final
675
- * `|` adds a phantom column. Fenced code needs protecting for the same reason.
676
- */
677
- function analyzeLines(text: string): LineInfo[] {
678
- const raw = text.split("\n");
679
- const lines: LineInfo[] = [];
680
- let offset = 0;
681
- let inFence = false;
682
- for (let index = 0; index < raw.length; index++) {
683
- const line = raw[index] ?? "";
684
- const start = offset;
685
- const end = start + line.length;
686
- offset = end + 1;
687
-
688
- let kind: LineKind = "text";
689
- let pipeAt: number | undefined;
690
- const isTableLine = (value: string): boolean => /^\s*\|?[\s:|-]*-[\s:|-]*\|/.test(value);
691
-
692
- if (/^\s*```/.test(line)) {
693
- inFence = !inFence;
694
- kind = "skip";
695
- } else if (inFence) {
696
- kind = "skip";
697
- } else if (/^\s*#{1,6}\s/.test(line)) {
698
- kind = "skip";
699
- } else if (line.trim().startsWith("|")) {
700
- const next = raw[index + 1] ?? "";
701
- if (isTableLine(line) || isTableLine(next)) {
702
- kind = "skip"; // separator or header row: a marker here breaks the table
703
- } else {
704
- const lastPipe = line.lastIndexOf("|");
705
- kind = "table-row";
706
- pipeAt = lastPipe > 0 ? start + lastPipe : end;
707
- }
708
- }
709
- lines.push({ start, end, kind, pipeAt });
710
- }
711
- return lines;
712
- }
713
-
714
- /** The classified line containing a character offset. */
715
- function lineAt(lines: LineInfo[], position: number): LineInfo | undefined {
716
- return lines.find((line) => position >= line.start && position <= line.end);
717
- }
718
-
719
- /** Drop spans contained in a larger span, then merge overlapping ones, so one claim gets one marker. */
720
- function mergeCitationSpans(spans: CitationSpan[]): CitationSpan[] {
721
- const sorted = [...spans].sort((a, b) => a.start - b.start || b.end - a.end);
722
- const kept: CitationSpan[] = [];
723
- for (const span of sorted) {
724
- const container = kept.find((other) => other.start <= span.start && other.end >= span.end);
725
- if (container) {
726
- container.indices = [...new Set([...container.indices, ...span.indices])].sort(
727
- (a, b) => a - b,
728
- );
729
- continue;
730
- }
731
- kept.push({ start: span.start, end: span.end, indices: [...span.indices] });
732
- }
733
- const merged: CitationSpan[] = [];
734
- for (const span of kept) {
735
- const previous = merged[merged.length - 1];
736
- if (previous && span.start <= previous.end) {
737
- previous.end = Math.max(previous.end, span.end);
738
- previous.indices = [...new Set([...previous.indices, ...span.indices])].sort((a, b) => a - b);
739
- continue;
740
- }
741
- merged.push({ ...span });
742
- }
743
- return merged;
744
- }
745
-
746
- /**
747
- * Map each UTF-8 byte offset in `text` to the JS character index it starts at.
748
- * Keep in sync with the byte-based verification below.
749
- */
750
- function buildByteToCharMap(text: string): number[] {
751
- const map: number[] = [];
752
- for (let index = 0; index < text.length;) {
753
- const codePoint = text.codePointAt(index) as number;
754
- const width = codePoint > 0xffff ? 2 : 1;
755
- const byteLength = Buffer.byteLength(text.slice(index, index + width), "utf8");
756
- for (let byte = 0; byte < byteLength; byte++) map.push(index);
757
- index += width;
758
- }
759
- map.push(text.length);
760
- return map;
761
- }
762
-
763
- /**
764
- * Google's offsets are UTF-8 bytes within a content Part, not JS character indices.
765
- *
766
- * Each segment is verified byte-for-byte before use. A segment whose bytes do not match
767
- * its reported text is relocated by searching the part instead of being discarded: the
768
- * offsets drift on some answers (table-heavy ones in particular), and dropping those
769
- * citations silently removes exactly the provenance this function exists to provide.
770
- *
771
- * Markers are grouped per insertion point. The first mention of a source carries both its
772
- * number and a full link, so the number always matches its entry in the source list below and
773
- * the reader never has to resolve an unexplained `[n]`.
774
- */
775
- function citeSearchText(res: SearchResult): string {
776
- if (!res.supports?.length) return res.text;
777
- const textParts = res.parts ?? [{ index: 0, text: res.text }];
778
- // Respect callers editing result.text; original offsets no longer apply.
779
- if (textParts.map((part) => part.text).join("\n\n") !== res.text) {
780
- return res.text;
781
- }
782
-
783
- const bySourceIndex = new Map<number, { number: number; label: string; url: string }>();
784
- res.sources.forEach((source, position) => {
785
- const sourceIndex = source.index ?? position;
786
- bySourceIndex.set(sourceIndex, {
787
- number: sourceIndex + 1,
788
- label: sourceLabel(source),
789
- url: source.resolvedUrl ?? source.url,
790
- });
791
- });
792
-
793
- const seen = new Set<number>();
794
- const insertionsByPart = new Map<number, Array<{ at: number; text: string }>>();
795
-
796
- for (const part of textParts) {
797
- const bytes = Buffer.from(part.text, "utf8");
798
- const byteToChar = buildByteToCharMap(part.text);
799
- const lines = analyzeLines(part.text);
800
- const spans: CitationSpan[] = [];
801
-
802
- for (const support of res.supports ?? []) {
803
- if ((support.partIndex ?? 0) !== part.index) continue;
804
- const indices = support.sourceIndices.filter((index) => bySourceIndex.has(index));
805
- if (indices.length === 0) continue;
806
-
807
- let start = support.startIndex;
808
- let end = support.endIndex;
809
- const offsetsTrustworthy =
810
- typeof start === "number" &&
811
- typeof end === "number" &&
812
- Number.isInteger(start) &&
813
- Number.isInteger(end) &&
814
- start >= 0 &&
815
- end > start &&
816
- end <= bytes.length &&
817
- bytes.subarray(start, end).toString("utf8") === support.text;
818
-
819
- if (!offsetsTrustworthy) {
820
- const located = part.text.indexOf(support.text);
821
- if (located < 0) continue;
822
- start = Buffer.byteLength(part.text.slice(0, located), "utf8");
823
- end = start + Buffer.byteLength(support.text, "utf8");
824
- }
825
-
826
- const startChar = byteToChar[start as number] ?? part.text.length;
827
- const endChar = byteToChar[end as number] ?? part.text.length;
828
- if (endChar <= startChar) continue;
829
- spans.push({
830
- start: startChar,
831
- end: endChar,
832
- indices: [...new Set(indices)].sort((a, b) => a - b),
833
- });
834
- }
835
-
836
- for (const span of mergeCitationSpans(spans)) {
837
- const line = lineAt(lines, span.end);
838
- if (!line || line.kind === "skip") continue;
839
- const at = line.kind === "table-row" ? (line.pipeAt ?? span.end) : span.end;
840
- const pieces = span.indices.map((index) => {
841
- const source = bySourceIndex.get(index);
842
- if (!source) return "";
843
- if (seen.has(index)) return `[${source.number}]`;
844
- seen.add(index);
845
- // The first mention carries the number too, so it matches the sources list below.
846
- return `[${source.number}] [${escapeLinkText(source.label)}](${escapeLinkDestination(source.url)})`;
847
- });
848
- const text = ` ${pieces.filter(Boolean).join(" ")}`;
849
- const list = insertionsByPart.get(part.index) ?? [];
850
- list.push({ at, text });
851
- insertionsByPart.set(part.index, list);
852
- }
853
- }
854
-
855
- const rendered = textParts.map((part) => {
856
- let text = part.text;
857
- for (const insertion of (insertionsByPart.get(part.index) ?? []).sort((a, b) => b.at - a.at)) {
858
- text = text.slice(0, insertion.at) + insertion.text + text.slice(insertion.at);
859
- }
860
- return text;
861
- });
862
-
863
- return rendered.join("\n\n") || res.text;
864
- }
865
-
866
- /**
867
- * Formats structured SearchResult into clean Markdown for agent consumption.
868
- *
869
- * @param res - Structured search result containing text, sources, and executed queries.
870
- * @returns Formatted markdown string.
871
- */
872
- export function formatSearchResult(res: SearchResult): string {
873
- const sections: string[] = [];
874
-
875
- const cited = citeSearchText(res);
876
- if (cited) sections.push(cited);
877
-
878
- if (res.sources.length > 0) {
879
- const list = res.sources
880
- .map((s, index) => {
881
- const number = res.supports?.length ? `[${(s.index ?? index) + 1}] ` : "";
882
- const url = s.resolvedUrl ?? s.url;
883
- return `- ${number}[${escapeLinkText(sourceLabel(s))}](${escapeLinkDestination(url)})`;
884
- })
885
- .join("\n");
886
- sections.push(`### Sources\n${list}`);
887
- }
888
-
889
- if (res.queries.length > 0) {
890
- const queries = res.queries.map((q) => `\`${q}\``).join(", ");
891
- sections.push(`*Search queries: ${queries}*`);
892
- }
893
-
894
- return sections.join("\n\n");
895
- }
896
-
897
- /**
898
- * Execute real-time Google Search grounding via Antigravity backend with automatic fallback.
899
- *
900
- * @param options - Execution options containing query, API credentials, and optional directives.
901
- * @returns Markdown formatted search result with synthesis, citations, and search queries.
902
- */
903
- export async function executeAntigravitySearch(options: ExecuteSearchOptions): Promise<string> {
904
- const query = options.query.trim();
905
- if (!query) throw new Error("Search query is required.");
906
-
907
- const creds = parseApiKey(options.apiKey);
908
- const headers = antigravityHeaders(creds.token);
909
-
910
- let lastError = "no endpoint available";
911
-
912
- for (const model of SEARCH_MODEL_FALLBACKS) {
913
- const body = JSON.stringify(buildSearchRequest(options, model, creds.projectId));
914
-
915
- for (const endpoint of endpointCandidates()) {
916
- if (options.signal?.aborted) throw new Error("Search request was aborted");
917
-
918
- try {
919
- const response = await antigravityFetch(`${endpoint}/v1internal:generateContent`, {
920
- method: "POST",
921
- headers,
922
- body,
923
- signal: options.signal,
924
- });
925
-
926
- if (!response.ok) {
927
- lastError = jsonOrTextError(await response.text()).slice(0, 400);
928
- const modelRejected =
929
- response.status === 400 && /invalid argument|thinking/i.test(lastError);
930
- if (
931
- response.status === 404 ||
932
- modelRejected ||
933
- [429, 500, 502, 503, 504].includes(response.status)
934
- ) {
935
- continue; // Retry next endpoint, or the next fallback model, for model-specific 400s
936
- }
937
- // Fail fast on non-retryable client errors (e.g. 401 Unauthorized, 403 Forbidden)
938
- throw Object.assign(new Error(lastError), { fatal: true });
939
- }
940
-
941
- const data: unknown = await response.json();
942
- const cand = firstUnknownItem(candidateList(data));
943
-
944
- const candidateText =
945
- isRecord(cand) && isRecord(cand.content) && Array.isArray(cand.content.parts)
946
- ? (cand.content.parts[0] as { text?: string })?.text
947
- : undefined;
948
-
949
- // Skip responses indicating deprecated model and move to next fallback model
950
- if (candidateText && candidateText.includes("is no longer available. Please switch")) {
951
- lastError = `Model ${model} deprecated: ${candidateText.slice(0, 100)}`;
952
- break;
953
- }
954
-
955
- const parsed = parseSearchResponse(data);
956
- await enrichSources(parsed.sources, options.signal);
957
- return formatSearchResult(parsed);
958
- } catch (error) {
959
- if (options.signal?.aborted) throw error;
960
- if (error instanceof Error && (error as { fatal?: boolean }).fatal) throw error;
961
- lastError = safeError(error).slice(0, 400);
962
- }
963
- }
964
- }
965
-
966
- throw new Error(`Antigravity Google Search failed: ${lastError}`);
967
- }