@herbertgao/pi-extensions 2026.11.18 → 2026.11.20

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 (177) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +5 -5
  3. package/THIRD_PARTY_NOTICES.md +3 -24
  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 +6 -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/package.json +1 -1
  64. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +317 -105
  65. package/node_modules/@herbertgao/pi-subagents/SECURITY.md +2 -2
  66. package/node_modules/@herbertgao/pi-subagents/docs/rpc.md +240 -36
  67. package/node_modules/@herbertgao/pi-subagents/docs/translations.md +63 -0
  68. package/node_modules/@herbertgao/pi-subagents/docs/workflows.md +1 -1
  69. package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
  70. package/node_modules/@herbertgao/pi-subagents/src/agent-file-toggle.ts +2 -0
  71. package/node_modules/@herbertgao/pi-subagents/src/agent-manager.ts +89 -6
  72. package/node_modules/@herbertgao/pi-subagents/src/agent-runner.ts +6 -2
  73. package/node_modules/@herbertgao/pi-subagents/src/agent-types.ts +20 -11
  74. package/node_modules/@herbertgao/pi-subagents/src/cache-retention.ts +39 -0
  75. package/node_modules/@herbertgao/pi-subagents/src/completion-outbox.ts +5 -0
  76. package/node_modules/@herbertgao/pi-subagents/src/cross-extension-rpc.ts +185 -44
  77. package/node_modules/@herbertgao/pi-subagents/src/custom-agents.ts +7 -0
  78. package/node_modules/@herbertgao/pi-subagents/src/group-join.ts +9 -0
  79. package/node_modules/@herbertgao/pi-subagents/src/index.ts +126 -116
  80. package/node_modules/@herbertgao/pi-subagents/src/mention-clone.ts +3 -2
  81. package/node_modules/@herbertgao/pi-subagents/src/settings.ts +21 -0
  82. package/node_modules/@herbertgao/pi-subagents/src/subagent-info.ts +115 -0
  83. package/node_modules/@herbertgao/pi-subagents/src/types.ts +11 -7
  84. package/node_modules/@herbertgao/pi-subagents/src/ui/agent-widget.ts +2 -3
  85. package/node_modules/@herbertgao/pi-subagents/src/ui/conversation-viewer.ts +1 -1
  86. package/node_modules/@herbertgao/pi-subagents/src/workflow/meta.ts +2 -2
  87. package/node_modules/@herbertgao/pi-subagents/src/workflow-info.ts +184 -0
  88. package/node_modules/pi-commandcode-provider/CHANGELOG.md +10 -0
  89. package/node_modules/pi-commandcode-provider/README.md +3 -2
  90. package/node_modules/pi-commandcode-provider/index.ts +120 -13
  91. package/node_modules/pi-commandcode-provider/package.json +4 -3
  92. package/node_modules/pi-commandcode-provider/src/commandcode-catalog.ts +11 -2
  93. package/node_modules/pi-commandcode-provider/src/pricing.ts +17 -1
  94. package/node_modules/pi-commandcode-provider/src/quota-command.ts +3 -2
  95. package/node_modules/pi-commandcode-provider/src/zdr.ts +163 -0
  96. package/node_modules/pi-typesafe/README.md +1 -1
  97. package/node_modules/pi-typesafe/dist/ask.js +6 -3
  98. package/node_modules/pi-typesafe/dist/auth.d.ts +31 -7
  99. package/node_modules/pi-typesafe/dist/auth.js +159 -55
  100. package/node_modules/pi-typesafe/dist/batch.d.ts +16 -2
  101. package/node_modules/pi-typesafe/dist/batch.js +62 -22
  102. package/node_modules/pi-typesafe/dist/calibrate.d.ts +38 -11
  103. package/node_modules/pi-typesafe/dist/calibrate.js +56 -24
  104. package/node_modules/pi-typesafe/dist/client.d.ts +13 -0
  105. package/node_modules/pi-typesafe/dist/client.js +67 -27
  106. package/node_modules/pi-typesafe/dist/errors.d.ts +20 -0
  107. package/node_modules/pi-typesafe/dist/errors.js +105 -2
  108. package/node_modules/pi-typesafe/dist/extension.d.ts +106 -0
  109. package/node_modules/pi-typesafe/dist/extension.js +206 -106
  110. package/node_modules/pi-typesafe/dist/index.d.ts +8 -8
  111. package/node_modules/pi-typesafe/dist/index.js +3 -3
  112. package/node_modules/pi-typesafe/dist/key-prompt.d.ts +20 -0
  113. package/node_modules/pi-typesafe/dist/key-prompt.js +23 -3
  114. package/node_modules/pi-typesafe/dist/login.d.ts +58 -1
  115. package/node_modules/pi-typesafe/dist/login.js +167 -13
  116. package/node_modules/pi-typesafe/dist/schema.d.ts +3 -0
  117. package/node_modules/pi-typesafe/dist/schema.js +47 -13
  118. package/node_modules/pi-typesafe/dist/ui.d.ts +2 -1
  119. package/node_modules/pi-typesafe/dist/usage.d.ts +53 -0
  120. package/node_modules/pi-typesafe/dist/usage.js +79 -40
  121. package/node_modules/pi-typesafe/package.json +3 -3
  122. package/package.json +12 -15
  123. package/node_modules/pi-antigravity/README.md +0 -298
  124. package/node_modules/pi-antigravity/docs/reader-guarantees.md +0 -35
  125. package/node_modules/pi-antigravity/package.json +0 -87
  126. package/node_modules/pi-antigravity/src/auth/accounts.ts +0 -327
  127. package/node_modules/pi-antigravity/src/auth/index.ts +0 -23
  128. package/node_modules/pi-antigravity/src/auth/oauth.ts +0 -445
  129. package/node_modules/pi-antigravity/src/client/client.ts +0 -602
  130. package/node_modules/pi-antigravity/src/client/enterprise.ts +0 -150
  131. package/node_modules/pi-antigravity/src/client/index.ts +0 -2
  132. package/node_modules/pi-antigravity/src/diagnostics/diagnostics.ts +0 -104
  133. package/node_modules/pi-antigravity/src/diagnostics/index.ts +0 -1
  134. package/node_modules/pi-antigravity/src/features/generate-image.ts +0 -132
  135. package/node_modules/pi-antigravity/src/features/google-search.ts +0 -72
  136. package/node_modules/pi-antigravity/src/features/read-url-content.ts +0 -124
  137. package/node_modules/pi-antigravity/src/image/image.ts +0 -427
  138. package/node_modules/pi-antigravity/src/image/index.ts +0 -1
  139. package/node_modules/pi-antigravity/src/image/native.ts +0 -69
  140. package/node_modules/pi-antigravity/src/index.ts +0 -547
  141. package/node_modules/pi-antigravity/src/models/discovery.ts +0 -176
  142. package/node_modules/pi-antigravity/src/models/grouping.ts +0 -487
  143. package/node_modules/pi-antigravity/src/models/index.ts +0 -3
  144. package/node_modules/pi-antigravity/src/models/models.ts +0 -647
  145. package/node_modules/pi-antigravity/src/search/index.ts +0 -1
  146. package/node_modules/pi-antigravity/src/search/search.ts +0 -967
  147. package/node_modules/pi-antigravity/src/stream/index.ts +0 -1
  148. package/node_modules/pi-antigravity/src/stream/stream.ts +0 -1961
  149. package/node_modules/pi-antigravity/src/types/enums.ts +0 -52
  150. package/node_modules/pi-antigravity/src/types/index.ts +0 -2
  151. package/node_modules/pi-antigravity/src/types/types.ts +0 -329
  152. package/node_modules/pi-antigravity/src/usage/index.ts +0 -1
  153. package/node_modules/pi-antigravity/src/usage/usage.ts +0 -437
  154. package/node_modules/pi-antigravity/src/utils/address.ts +0 -180
  155. package/node_modules/pi-antigravity/src/utils/credits.ts +0 -149
  156. package/node_modules/pi-antigravity/src/utils/html.ts +0 -31
  157. package/node_modules/pi-antigravity/src/utils/http.ts +0 -96
  158. package/node_modules/pi-antigravity/src/utils/index.ts +0 -5
  159. package/node_modules/pi-antigravity/src/utils/security.ts +0 -278
  160. package/node_modules/pi-antigravity/src/utils/text.ts +0 -66
  161. package/node_modules/pi-antigravity/src/utils/util.ts +0 -217
  162. package/node_modules/pi-antigravity/src/web-fetch/document.ts +0 -83
  163. package/node_modules/pi-antigravity/src/web-fetch/fences.ts +0 -24
  164. package/node_modules/pi-antigravity/src/web-fetch/header.ts +0 -97
  165. package/node_modules/pi-antigravity/src/web-fetch/index.ts +0 -3
  166. package/node_modules/pi-antigravity/src/web-fetch/inspect.ts +0 -328
  167. package/node_modules/pi-antigravity/src/web-fetch/limits.ts +0 -4
  168. package/node_modules/pi-antigravity/src/web-fetch/markdown.ts +0 -744
  169. package/node_modules/pi-antigravity/src/web-fetch/mdn.ts +0 -164
  170. package/node_modules/pi-antigravity/src/web-fetch/media.ts +0 -11
  171. package/node_modules/pi-antigravity/src/web-fetch/metadata.ts +0 -9
  172. package/node_modules/pi-antigravity/src/web-fetch/representation.ts +0 -93
  173. package/node_modules/pi-antigravity/src/web-fetch/save.ts +0 -71
  174. package/node_modules/pi-antigravity/src/web-fetch/sites.ts +0 -138
  175. package/node_modules/pi-antigravity/src/web-fetch/vendor.d.ts +0 -9
  176. package/node_modules/pi-antigravity/src/web-fetch/web-fetch.ts +0 -957
  177. package/node_modules/pi-antigravity/tsconfig.json +0 -21
@@ -1,1961 +0,0 @@
1
- import {
2
- calculateCost,
3
- createAssistantMessageEventStream,
4
- type Api,
5
- type AssistantMessage,
6
- type AssistantMessageEventStream,
7
- type Context,
8
- type Model,
9
- type TextContent,
10
- type Tool,
11
- type ToolCall,
12
- } from "@earendil-works/pi-ai";
13
- // Namespace import: transcript helpers exist on pi-ai >= 0.86; resolved at runtime.
14
- import * as piAi from "@earendil-works/pi-ai";
15
- import { failoverToNextAccount } from "../auth/accounts.js";
16
- import {
17
- antigravityHeaders,
18
- endpointCandidates,
19
- fetchAvailableRuntimeModel,
20
- formatRequestDiagnostics,
21
- isUsableRuntimeModelId,
22
- jsonOrTextError,
23
- loadCodeAssist,
24
- parseApiKey,
25
- resolveProjectId,
26
- } from "../client/client.js";
27
- import {
28
- enterpriseStreamUrl,
29
- resolveEnterpriseTarget,
30
- toEnterpriseGenerateBody,
31
- } from "../client/enterprise.js";
32
- import {
33
- getCurrentAvailableModels,
34
- getCurrentEndpoint,
35
- getCurrentMatchedModelDebug,
36
- runWithDiagnostics,
37
- setLastAvailableModels,
38
- setLastEndpoint,
39
- setLastError,
40
- setLastLatencyMs,
41
- setLastMatchedModelDebug,
42
- setLastProjectId,
43
- setLastResolvedRuntimeModel,
44
- setLastStatus,
45
- setLastToolSchemaWarnings,
46
- } from "../diagnostics/diagnostics.js";
47
- import {
48
- AntigravityRequestType,
49
- AntigravityUserAgent,
50
- GeminiRole,
51
- GeminiToolCallingMode,
52
- StopReason,
53
- ToolChoice,
54
- } from "../types/enums.js";
55
- import {
56
- getCurrentAntigravityRouting,
57
- getMaxOutputTokens,
58
- advertisedSiblingRuntimes,
59
- getAntigravityRequestModelId,
60
- getFallbackRuntimeModel,
61
- getThinkingConfig,
62
- PROVIDER_ID,
63
- } from "../models/models.js";
64
- import { extractValidationUrl, redactSecrets, safeError } from "../utils/security.js";
65
- import {
66
- ANTIGRAVITY_API,
67
- type ActiveBlock,
68
- type AntigravityGenerateRequest,
69
- type AntigravityStreamOptions,
70
- type ContentBlock,
71
- type GeminiContent,
72
- type GeminiFunctionDeclaration,
73
- type GeminiFunctionResponsePart,
74
- type GeminiGenerationConfig,
75
- type GeminiInlineDataPart,
76
- type GeminiPart,
77
- type GeminiRequestBody,
78
- type GeminiTextPart,
79
- type StreamChunk,
80
- } from "../types/types.js";
81
- import {
82
- antigravityEnv,
83
- antigravityRequestEnvelope,
84
- isRecord,
85
- resolveSessionTrajectory,
86
- sanitizeText,
87
- } from "../utils/util.js";
88
- import { isCreditsEnabled } from "../utils/credits.js";
89
- import { antigravityFetch, prewarmConnection } from "../utils/http.js";
90
-
91
- export { ANTIGRAVITY_API };
92
-
93
- const ANTIGRAVITY_SYSTEM_INSTRUCTION =
94
- "You are Antigravity, a powerful agentic AI coding assistant designed by Google DeepMind. " +
95
- "You are pair programming with a user to solve coding tasks. Be concise, practical, and tool-aware.";
96
-
97
- const ANTIGRAVITY_NO_PREAMBLE_INSTRUCTION =
98
- 'CRITICAL: NEVER output rule checks, formatting guidelines, constraint checklists (e.g. "No emdashes"), internal thinking/reasoning preambles, or fake "[Observation from ...]" tool logs in the final response. When calling a tool, emit a real functionCall; never simulate tool calls or tool observations in plain text. Output only the final response.';
99
-
100
- const CONTINUATION_TEXT = "Continue the active task using the available instructions and context.";
101
- let toolCallCounter = 0;
102
-
103
- function sanitizeToolCallId(id: string, fallbackName?: string): string {
104
- const cleaned = id.replace(/[^a-zA-Z0-9_-]/g, "_");
105
- const capped = cleaned.slice(0, 64);
106
- return capped || `${fallbackName || "tool"}_${++toolCallCounter}`;
107
- }
108
-
109
- function toolCallIdNeeded(modelId: string, runtimeModel: string): boolean {
110
- return (
111
- modelId.startsWith("claude-") ||
112
- modelId.startsWith("gpt-oss-") ||
113
- runtimeModel.startsWith("claude-") ||
114
- runtimeModel.startsWith("gpt-oss-")
115
- );
116
- }
117
-
118
- interface SystemMessageLike {
119
- role?: string;
120
- content?: string | Array<{ type?: string; text?: string }>;
121
- sections?: Record<string, unknown>;
122
- toolsAdded?: Tool[];
123
- toolsRemoved?: Array<{ name: string }>;
124
- tools?: Tool[];
125
- }
126
-
127
- interface PiAiTranscriptModule {
128
- getCurrentTools?: (messages: Context["messages"]) => Tool[];
129
- getCurrentSystemPrompt?: (messages: Context["messages"]) => string;
130
- }
131
-
132
- function transcriptModule(): PiAiTranscriptModule {
133
- return piAi;
134
- }
135
-
136
- function asSystemMessages(messages: Context["messages"] | undefined): SystemMessageLike[] {
137
- return [...(messages ?? [])] as SystemMessageLike[];
138
- }
139
-
140
- function extractTranscriptSystemPrompt(messages: readonly SystemMessageLike[]): string {
141
- const parts: string[] = [];
142
- for (const message of messages) {
143
- if (message?.role !== "system") continue;
144
- if (message.sections && typeof message.sections === "object") {
145
- const sectionParts = Object.values(message.sections).filter(
146
- (value): value is string => typeof value === "string" && value.trim().length > 0,
147
- );
148
- if (sectionParts.length > 0) {
149
- parts.push(sectionParts.join("\n\n"));
150
- continue;
151
- }
152
- }
153
- if (typeof message.content === "string" && message.content.trim()) {
154
- parts.push(message.content);
155
- } else if (Array.isArray(message.content)) {
156
- const texts = message.content
157
- .map((block) => (typeof block === "string" ? block : block?.text || ""))
158
- .filter((text) => text.trim().length > 0);
159
- if (texts.length > 0) parts.push(texts.join("\n\n"));
160
- }
161
- }
162
- return parts.join("\n\n");
163
- }
164
-
165
- function extractTranscriptTools(messages: readonly SystemMessageLike[]): Tool[] {
166
- const tools = new Map<string, Tool>();
167
- for (const message of messages) {
168
- if (message?.role !== "system") continue;
169
- for (const tool of message.toolsRemoved ?? []) {
170
- tools.delete(tool.name);
171
- }
172
- for (const tool of [...(message.toolsAdded ?? []), ...(message.tools ?? [])]) {
173
- if (tool && typeof tool.name === "string") tools.set(tool.name, tool);
174
- }
175
- }
176
- return [...tools.values()];
177
- }
178
-
179
- /**
180
- * pi >= 0.86 hands providers a normalized TranscriptContext: the system prompt and
181
- * tool declarations live in system messages and must be read with
182
- * `getCurrentSystemPrompt()` / `getCurrentTools()`. Older releases still pass the
183
- * flat Context fields. Resolve both so requests are not sent without tools.
184
- */
185
- export function resolveCurrentSystemPrompt(context: Context): string | undefined {
186
- const helper = transcriptModule().getCurrentSystemPrompt;
187
- if (typeof helper === "function") {
188
- try {
189
- const fromHelper = helper(context.messages ?? []);
190
- if (fromHelper?.trim()) return fromHelper;
191
- } catch {
192
- // Fall through to local replay / legacy fields.
193
- }
194
- }
195
- const fromTranscript = extractTranscriptSystemPrompt(asSystemMessages(context.messages));
196
- if (fromTranscript.trim()) return fromTranscript;
197
- return context.systemPrompt;
198
- }
199
-
200
- export function resolveCurrentTools(context: Context): Tool[] | undefined {
201
- const helper = transcriptModule().getCurrentTools;
202
- if (typeof helper === "function") {
203
- try {
204
- const fromHelper = helper(context.messages ?? []);
205
- if (fromHelper.length > 0) return fromHelper;
206
- } catch {
207
- // Fall through to local replay / legacy fields.
208
- }
209
- }
210
- const fromTranscript = extractTranscriptTools(asSystemMessages(context.messages));
211
- if (fromTranscript.length > 0) return fromTranscript;
212
- return context.tools;
213
- }
214
-
215
- const base64SignaturePattern = /^[A-Za-z0-9+/]+={0,2}$/;
216
- function isValidThoughtSignature(signature?: string): boolean {
217
- if (!signature || typeof signature !== "string" || signature.length === 0) return false;
218
- if (signature.length % 4 !== 0) return false;
219
- return base64SignaturePattern.test(signature);
220
- }
221
-
222
- function geminiRequiresThoughtSignature(runtimeModel: string): boolean {
223
- if (!runtimeModel.startsWith("gemini-")) return false;
224
- const match = runtimeModel.match(/^gemini-(\d+)/);
225
- if (match) {
226
- const major = Number.parseInt(match[1], 10);
227
- return major >= 3;
228
- }
229
- return true;
230
- }
231
-
232
- function parseImageData(raw: string, explicitMime?: string): { data: string; mimeType: string } {
233
- const match = raw.match(/^data:([^;]+);base64,(.+)$/s);
234
- if (match) {
235
- return {
236
- mimeType: explicitMime || match[1] || "image/png",
237
- data: match[2].trim(),
238
- };
239
- }
240
- return {
241
- mimeType: explicitMime || "image/png",
242
- data: raw.trim(),
243
- };
244
- }
245
-
246
- const SKILL_BLOCK_PATTERN = /<skill\b[^>]*>[\s\S]*?<\/skill\s*>/gi;
247
-
248
- function skillBlocks(content: unknown): string[] {
249
- const texts =
250
- typeof content === "string"
251
- ? [content]
252
- : Array.isArray(content)
253
- ? content.flatMap((item) =>
254
- isRecord(item) && item.type === "text" && typeof item.text === "string"
255
- ? [item.text]
256
- : [],
257
- )
258
- : [];
259
- return texts.flatMap((text) => text.match(SKILL_BLOCK_PATTERN) || []);
260
- }
261
-
262
- function withoutSkillBlocks(text: string): string {
263
- return text.replace(SKILL_BLOCK_PATTERN, "");
264
- }
265
-
266
- function asTextParts(content: unknown): Array<GeminiTextPart | GeminiInlineDataPart> {
267
- const textPart = (text: string): GeminiTextPart[] => {
268
- const userText = withoutSkillBlocks(text);
269
- return userText.trim() ? [{ text: sanitizeText(userText) }] : [];
270
- };
271
- if (typeof content === "string") return textPart(content);
272
- if (!Array.isArray(content)) return [];
273
- return content.flatMap((item): Array<GeminiTextPart | GeminiInlineDataPart> => {
274
- if (!isRecord(item)) return [];
275
- const block = item as ContentBlock;
276
- if (block.type === "text") return textPart(block.text);
277
- if (block.type === "image") {
278
- const rawData = block.data || block.source?.data;
279
- if (!rawData) return [];
280
- const explicitMime = block.mimeType || block.mediaType || block.source?.mediaType;
281
- const { data, mimeType } = parseImageData(rawData, explicitMime);
282
- return data ? [{ inlineData: { mimeType, data } }] : [];
283
- }
284
- return [];
285
- });
286
- }
287
-
288
- function asImageParts(content: unknown): GeminiInlineDataPart[] {
289
- if (!Array.isArray(content)) return [];
290
- return content.flatMap((item): GeminiInlineDataPart[] => {
291
- if (!isRecord(item)) return [];
292
- const block = item as ContentBlock;
293
- if (block.type === "image") {
294
- const rawData = block.data || block.source?.data;
295
- if (!rawData) return [];
296
- const explicitMime = block.mimeType || block.mediaType || block.source?.mediaType;
297
- const { data, mimeType } = parseImageData(rawData, explicitMime);
298
- return data ? [{ inlineData: { mimeType, data } }] : [];
299
- }
300
- return [];
301
- });
302
- }
303
-
304
- function appendTurn(contents: GeminiContent[], role: GeminiRole, parts: GeminiPart[]): void {
305
- if (!parts.length) return;
306
- const last = contents[contents.length - 1];
307
- if (last && last.role === role) {
308
- last.parts.push(...parts);
309
- } else {
310
- contents.push({ role, parts });
311
- }
312
- }
313
-
314
- /** Exported for unit tests. */
315
- export function convertMessages(
316
- model: Model<Api>,
317
- context: Context,
318
- runtimeModel: string,
319
- ): GeminiContent[] {
320
- return convertMessagesWithMetadata(model, context, runtimeModel).contents;
321
- }
322
-
323
- function convertMessagesWithMetadata(
324
- model: Model<Api>,
325
- context: Context,
326
- runtimeModel: string,
327
- ): { contents: GeminiContent[]; hasDegradedToolObservations: boolean } {
328
- const contents: GeminiContent[] = [];
329
- let hasDegradedToolObservations = false;
330
- const requiresSig = geminiRequiresThoughtSignature(runtimeModel);
331
- const droppedToolCallIds = new Map<string, string>();
332
- const droppedEmptyToolCalls = new Map<string, string[]>();
333
- for (const msg of context.messages) {
334
- if ((msg.role as string) === "system") continue;
335
- if (msg.role === "user") {
336
- const parts = asTextParts(msg.content);
337
- appendTurn(contents, GeminiRole.User, parts);
338
- } else if (msg.role === "assistant") {
339
- if (msg.stopReason === "error" || msg.stopReason === "aborted") {
340
- continue;
341
- }
342
- const parts: GeminiPart[] = [];
343
- const isSameModel = msg.provider === PROVIDER_ID && msg.model === model.id;
344
- const toolCalls = msg.content.filter((b): b is ToolCall => b.type === "toolCall");
345
- const firstCallHasSig =
346
- toolCalls.length > 0 && isValidThoughtSignature(toolCalls[0]?.thoughtSignature);
347
- const allSigsValid = toolCalls.every(
348
- (tc) => !tc.thoughtSignature || isValidThoughtSignature(tc.thoughtSignature),
349
- );
350
- const groupIsSigned = isSameModel && firstCallHasSig && allSigsValid;
351
-
352
- for (const block of msg.content) {
353
- if (block.type === "text") {
354
- const textSig =
355
- isSameModel && isValidThoughtSignature(block.textSignature)
356
- ? block.textSignature
357
- : undefined;
358
- if ((!block.text || block.text.trim() === "") && !textSig) {
359
- continue;
360
- }
361
- parts.push({
362
- text: sanitizeText(block.text),
363
- ...(textSig ? { thoughtSignature: textSig } : {}),
364
- });
365
- } else if (block.type === "thinking" && String(block.thinking || "").trim()) {
366
- if (!isSameModel) continue;
367
- if (requiresSig && !isValidThoughtSignature(block.thinkingSignature) && !groupIsSigned) {
368
- continue;
369
- }
370
- parts.push({
371
- thought: true,
372
- text: sanitizeText(block.thinking),
373
- ...(block.thinkingSignature ? { thoughtSignature: block.thinkingSignature } : {}),
374
- });
375
- } else if (block.type === "toolCall") {
376
- if (requiresSig && !groupIsSigned) {
377
- const rawId = block.id || "";
378
- const argsText = (() => {
379
- try {
380
- return JSON.stringify(block.arguments ?? {});
381
- } catch {
382
- return "{}";
383
- }
384
- })();
385
- if (rawId) {
386
- droppedToolCallIds.set(rawId, argsText);
387
- } else {
388
- const queue = droppedEmptyToolCalls.get(block.name) ?? [];
389
- queue.push(argsText);
390
- droppedEmptyToolCalls.set(block.name, queue);
391
- }
392
- } else {
393
- // Tool call IDs can be reused later in a session; a replayable call
394
- // must not inherit the dropped status of an earlier call.
395
- const rawId = block.id || "";
396
- if (rawId) droppedToolCallIds.delete(rawId);
397
- else droppedEmptyToolCalls.delete(block.name);
398
- parts.push({
399
- functionCall: {
400
- name: block.name,
401
- args: block.arguments ?? {},
402
- ...(toolCallIdNeeded(model.id, runtimeModel)
403
- ? { id: sanitizeToolCallId(block.id || "", block.name) }
404
- : {}),
405
- },
406
- ...(block.thoughtSignature ? { thoughtSignature: block.thoughtSignature } : {}),
407
- });
408
- }
409
- }
410
- }
411
- // Keep a boundary between the human's message and flattened tool results.
412
- // A real functionCall cannot be replayed without the required signature.
413
- if (!parts.length && requiresSig && !groupIsSigned && toolCalls.length > 0) {
414
- parts.push({ text: "[Earlier tool call omitted because its signature is unavailable.]" });
415
- }
416
- appendTurn(contents, GeminiRole.Model, parts);
417
- } else if (msg.role === "toolResult") {
418
- const text = msg.content
419
- .filter((c): c is TextContent => c.type === "text")
420
- .map((c) => sanitizeText(c.text))
421
- .join("\n");
422
- const responseText = text || (msg.isError ? "Tool failed" : "");
423
- const imageParts = asImageParts(msg.content);
424
- const rawId = msg.toolCallId || "";
425
- const sanitizedId = toolCallIdNeeded(model.id, runtimeModel)
426
- ? sanitizeToolCallId(rawId, msg.toolName)
427
- : rawId;
428
- let droppedId = rawId;
429
- let droppedArgs = requiresSig
430
- ? rawId
431
- ? droppedToolCallIds.get(rawId)
432
- : droppedEmptyToolCalls.get(msg.toolName)?.[0]
433
- : undefined;
434
- if (
435
- requiresSig &&
436
- rawId &&
437
- droppedArgs === undefined &&
438
- toolCallIdNeeded(model.id, runtimeModel)
439
- ) {
440
- const matches = [...droppedToolCallIds.entries()].filter(
441
- ([id]) => sanitizeToolCallId(id, msg.toolName) === sanitizedId,
442
- );
443
- if (matches.length > 1) {
444
- throw new Error("Ambiguous sanitized tool call ID in historical tool results.");
445
- }
446
- if (matches[0]) [droppedId, droppedArgs] = matches[0];
447
- }
448
- if (droppedArgs !== undefined) {
449
- if (rawId) {
450
- droppedToolCallIds.delete(droppedId);
451
- } else {
452
- const queue = droppedEmptyToolCalls.get(msg.toolName);
453
- queue?.shift();
454
- if (queue && queue.length === 0) droppedEmptyToolCalls.delete(msg.toolName);
455
- }
456
- hasDegradedToolObservations = true;
457
- const label =
458
- droppedArgs === "{}" ? `\`${msg.toolName}\`` : `\`${msg.toolName}\` (${droppedArgs})`;
459
- appendTurn(contents, GeminiRole.User, [
460
- { text: sanitizeText(`[Observation from ${label}:\n${responseText}]`) },
461
- ...imageParts,
462
- ]);
463
- } else {
464
- const part: GeminiFunctionResponsePart = {
465
- functionResponse: {
466
- name: msg.toolName,
467
- response: msg.isError ? { error: responseText } : { output: responseText },
468
- ...(toolCallIdNeeded(model.id, runtimeModel)
469
- ? { id: sanitizeToolCallId(msg.toolCallId || "", msg.toolName) }
470
- : {}),
471
- },
472
- };
473
- appendTurn(contents, GeminiRole.User, [part, ...imageParts]);
474
- }
475
- }
476
- }
477
-
478
- // A function-call model turn is only valid immediately after a user turn
479
- // (including a function-response turn). Compacted history can drop that
480
- // boundary, so restore it before applying the natural-language bridge.
481
- for (let index = 0; index < contents.length; index += 1) {
482
- const turn = contents[index];
483
- if (
484
- turn?.role === GeminiRole.Model &&
485
- turn.parts.some((part) => "functionCall" in part) &&
486
- contents[index - 1]?.role !== GeminiRole.User
487
- ) {
488
- contents.splice(index, 0, {
489
- role: GeminiRole.User,
490
- parts: [{ text: CONTINUATION_TEXT }],
491
- });
492
- index += 1;
493
- }
494
- }
495
-
496
- // Google Antigravity requires a natural-language user part in the request,
497
- // including tool-only continuation turns. Keep injected Skills in the system
498
- // instruction, then add this protocol bridge only when existing context gives
499
- // the model something concrete to act on.
500
- const hasUserText = contents.some(
501
- (turn) =>
502
- turn.role === GeminiRole.User &&
503
- turn.parts.some((part) => "text" in part && Boolean(part.text.trim())),
504
- );
505
- if (!hasUserText && contents.length > 0) {
506
- const bridge = {
507
- text: CONTINUATION_TEXT,
508
- };
509
- const userTurn = contents.find((turn) => turn.role === GeminiRole.User);
510
- if (userTurn) userTurn.parts.push(bridge);
511
- else contents.unshift({ role: GeminiRole.User, parts: [bridge] });
512
- }
513
-
514
- const lastTurn = contents.at(-1);
515
- if (lastTurn?.role === GeminiRole.Model) {
516
- if (lastTurn.parts.some((part) => "functionCall" in part)) {
517
- throw new Error(
518
- "Antigravity request is missing tool result(s) for the final assistant tool call. Provide the corresponding tool result before continuing.",
519
- );
520
- }
521
- appendTurn(contents, GeminiRole.User, [{ text: CONTINUATION_TEXT }]);
522
- }
523
-
524
- return { contents, hasDegradedToolObservations };
525
- }
526
-
527
- type SchemaReferenceIssue = {
528
- path: string;
529
- ref: string;
530
- reason: string;
531
- };
532
-
533
- type DereferencedSchema = {
534
- schema: unknown;
535
- issues: SchemaReferenceIssue[];
536
- };
537
-
538
- type DereferenceState = {
539
- nodes: number;
540
- };
541
-
542
- const MAX_SCHEMA_DEREFERENCE_DEPTH = 64;
543
- const MAX_SCHEMA_DEREFERENCE_NODES = 10_000;
544
- const SCHEMA_MAP_KEYWORDS = new Set([
545
- "properties",
546
- "patternProperties",
547
- "dependentSchemas",
548
- "dependencies",
549
- ]);
550
- const SCHEMA_VALUE_KEYWORDS = new Set([
551
- "additionalItems",
552
- "additionalProperties",
553
- "contains",
554
- "contentSchema",
555
- "else",
556
- "if",
557
- "items",
558
- "not",
559
- "propertyNames",
560
- "then",
561
- "unevaluatedItems",
562
- "unevaluatedProperties",
563
- ]);
564
- const SCHEMA_ARRAY_KEYWORDS = new Set(["allOf", "anyOf", "oneOf", "prefixItems"]);
565
-
566
- /** Resolve a local RFC 6901 JSON Pointer against the original tool schema. */
567
- function resolveLocalJsonPointer(ref: string, rootSchema: unknown): unknown {
568
- if (ref === "#") return rootSchema;
569
- if (!ref.startsWith("#/")) return undefined;
570
-
571
- let current: unknown = rootSchema;
572
- for (const token of ref.slice(2).split("/")) {
573
- const key = token.replace(/~1/g, "/").replace(/~0/g, "~");
574
- if (Array.isArray(current)) {
575
- if (!/^(0|[1-9]\d*)$/.test(key)) return undefined;
576
- const index = Number(key);
577
- if (!Number.isSafeInteger(index) || index >= current.length) return undefined;
578
- current = current[index];
579
- continue;
580
- }
581
- if (!current || typeof current !== "object") return undefined;
582
- if (!Object.prototype.hasOwnProperty.call(current, key)) return undefined;
583
- current = (current as Record<string, unknown>)[key];
584
- }
585
- return current;
586
- }
587
-
588
- /** Dereference every schema in a keyword map without interpreting map keys as JSON Schema keywords. */
589
- function dereferenceSchemaMap(
590
- schemaMap: unknown,
591
- rootSchema: unknown,
592
- refStack: Set<string>,
593
- objectStack: Set<object>,
594
- state: DereferenceState,
595
- path: string,
596
- depth: number,
597
- ): DereferencedSchema {
598
- if (!isRecord(schemaMap)) {
599
- return dereferenceSchema(schemaMap, rootSchema, refStack, objectStack, state, path, depth);
600
- }
601
-
602
- const out: Record<string, unknown> = {};
603
- const issues: SchemaReferenceIssue[] = [];
604
- for (const [key, value] of Object.entries(schemaMap)) {
605
- const result = dereferenceSchema(
606
- value,
607
- rootSchema,
608
- refStack,
609
- objectStack,
610
- state,
611
- `${path}.${key}`,
612
- depth,
613
- );
614
- out[key] = result.schema;
615
- issues.push(...result.issues);
616
- }
617
- return { schema: out, issues };
618
- }
619
-
620
- /**
621
- * Inline reachable local references while bounding expansion of untrusted MCP schemas.
622
- * A reported issue causes only the affected tool declaration to be omitted.
623
- */
624
- function dereferenceSchema(
625
- schema: unknown,
626
- rootSchema: unknown = schema,
627
- refStack = new Set<string>(),
628
- objectStack = new Set<object>(),
629
- state: DereferenceState = { nodes: 0 },
630
- path = "$",
631
- depth = 0,
632
- ): DereferencedSchema {
633
- if (depth > MAX_SCHEMA_DEREFERENCE_DEPTH) {
634
- return {
635
- schema: {},
636
- issues: [
637
- {
638
- path,
639
- ref: "(depth limit)",
640
- reason: `schema expansion exceeded ${MAX_SCHEMA_DEREFERENCE_DEPTH} levels`,
641
- },
642
- ],
643
- };
644
- }
645
- state.nodes += 1;
646
- if (state.nodes > MAX_SCHEMA_DEREFERENCE_NODES) {
647
- return {
648
- schema: {},
649
- issues: [
650
- {
651
- path,
652
- ref: "(node limit)",
653
- reason: `schema expansion exceeded ${MAX_SCHEMA_DEREFERENCE_NODES} nodes`,
654
- },
655
- ],
656
- };
657
- }
658
- if (!schema || typeof schema !== "object") return { schema, issues: [] };
659
-
660
- if (Array.isArray(schema)) {
661
- const results = schema.map((item, index) =>
662
- dereferenceSchema(
663
- item,
664
- rootSchema,
665
- refStack,
666
- objectStack,
667
- state,
668
- `${path}[${index}]`,
669
- depth + 1,
670
- ),
671
- );
672
- return {
673
- schema: results.map((result) => result.schema),
674
- issues: results.flatMap((result) => result.issues),
675
- };
676
- }
677
-
678
- const s = schema as Record<string, unknown>;
679
- if (objectStack.has(s)) {
680
- return {
681
- schema: {},
682
- issues: [{ path, ref: "(object cycle)", reason: "circular schema object" }],
683
- };
684
- }
685
-
686
- const nextObjectStack = new Set(objectStack);
687
- nextObjectStack.add(s);
688
-
689
- if (typeof s.$ref === "string") {
690
- const ref = s.$ref;
691
- if (refStack.has(ref)) {
692
- return {
693
- schema: {},
694
- issues: [{ path, ref, reason: "circular local reference" }],
695
- };
696
- }
697
-
698
- const target = resolveLocalJsonPointer(ref, rootSchema);
699
- if (target === undefined) {
700
- return {
701
- schema: {},
702
- issues: [{ path, ref, reason: "target is not present in the root schema" }],
703
- };
704
- }
705
-
706
- const nextRefStack = new Set(refStack);
707
- nextRefStack.add(ref);
708
- const resolved = dereferenceSchema(
709
- target,
710
- rootSchema,
711
- nextRefStack,
712
- nextObjectStack,
713
- state,
714
- path,
715
- depth + 1,
716
- );
717
- const { $ref: _, ...siblings } = s;
718
- const siblingResult = dereferenceSchema(
719
- siblings,
720
- rootSchema,
721
- refStack,
722
- nextObjectStack,
723
- state,
724
- path,
725
- depth + 1,
726
- );
727
-
728
- if (isRecord(resolved.schema) && isRecord(siblingResult.schema)) {
729
- return {
730
- schema: { ...resolved.schema, ...siblingResult.schema },
731
- issues: [...resolved.issues, ...siblingResult.issues],
732
- };
733
- }
734
- return {
735
- schema: resolved.schema,
736
- issues: [...resolved.issues, ...siblingResult.issues],
737
- };
738
- }
739
-
740
- const out: Record<string, unknown> = {};
741
- const issues: SchemaReferenceIssue[] = [];
742
- for (const [key, value] of Object.entries(s)) {
743
- // Definitions are available through rootSchema while resolving $ref, but must
744
- // not be emitted because the Antigravity backend requires self-contained schemas.
745
- if (key === "$defs" || key === "definitions") continue;
746
-
747
- let result: DereferencedSchema | undefined;
748
- if (SCHEMA_MAP_KEYWORDS.has(key)) {
749
- result = dereferenceSchemaMap(
750
- value,
751
- rootSchema,
752
- refStack,
753
- nextObjectStack,
754
- state,
755
- `${path}.${key}`,
756
- depth + 1,
757
- );
758
- } else if (SCHEMA_VALUE_KEYWORDS.has(key) || SCHEMA_ARRAY_KEYWORDS.has(key)) {
759
- result = dereferenceSchema(
760
- value,
761
- rootSchema,
762
- refStack,
763
- nextObjectStack,
764
- state,
765
- `${path}.${key}`,
766
- depth + 1,
767
- );
768
- }
769
-
770
- if (result) {
771
- out[key] = result.schema;
772
- issues.push(...result.issues);
773
- } else {
774
- out[key] = value;
775
- }
776
- }
777
- return { schema: out, issues };
778
- }
779
-
780
- function ensureRootObjectSchema(schema: unknown): Record<string, unknown> {
781
- if (!isRecord(schema)) {
782
- return { type: "object", properties: {} };
783
- }
784
- if (!schema.type) {
785
- return { ...schema, type: "object", properties: schema.properties || {} };
786
- }
787
- return schema;
788
- }
789
-
790
- const META_SCHEMA_KEYWORDS = new Set([
791
- "$schema",
792
- "$id",
793
- "$anchor",
794
- "$dynamicAnchor",
795
- "$vocabulary",
796
- "$comment",
797
- "$defs",
798
- "definitions",
799
- ]);
800
-
801
- /** Remove schema metadata without treating user-defined property names as keywords. */
802
- function stripMetaSchemaMap(schemaMap: unknown): unknown {
803
- if (!isRecord(schemaMap)) return stripMetaSchema(schemaMap);
804
- return Object.fromEntries(
805
- Object.entries(schemaMap).map(([key, value]) => [key, stripMetaSchema(value)]),
806
- );
807
- }
808
-
809
- /** Remove metadata that Cloud Code Assist rejects from JSON Schema keyword positions. */
810
- function stripMetaSchema(schema: unknown): unknown {
811
- if (!schema || typeof schema !== "object") return schema;
812
- if (Array.isArray(schema)) return schema.map(stripMetaSchema);
813
-
814
- const out: Record<string, unknown> = {};
815
- for (const [key, value] of Object.entries(schema)) {
816
- if (META_SCHEMA_KEYWORDS.has(key)) continue;
817
- if (SCHEMA_MAP_KEYWORDS.has(key)) {
818
- out[key] = stripMetaSchemaMap(value);
819
- } else if (SCHEMA_VALUE_KEYWORDS.has(key) || SCHEMA_ARRAY_KEYWORDS.has(key)) {
820
- out[key] = stripMetaSchema(value);
821
- } else {
822
- out[key] = value;
823
- }
824
- }
825
- return out;
826
- }
827
-
828
- /**
829
- * Protobuf `Schema` fields accepted by Cloud Code Assist's Claude/GPT custom-tool
830
- * bridge (`parameters` field). Anything else — `nullable`, `anyOf`, `format`,
831
- * `$ref`, etc. — returns `Unknown name "..."` / Invalid JSON payload (400).
832
- * Allowlist rather than denylist so new JSON Schema keywords cannot 400 the request.
833
- * Pi still validates tool args after the model calls them.
834
- */
835
- const CUSTOM_TOOL_SCHEMA_ALLOW = new Set([
836
- "type",
837
- "description",
838
- "properties",
839
- "required",
840
- "items",
841
- "enum",
842
- ]);
843
-
844
- function normalizeCustomToolType(value: unknown): unknown {
845
- if (typeof value === "string") return value;
846
- if (!Array.isArray(value)) return undefined;
847
- // JSON Schema union types like ["string","null"] → first non-null scalar type.
848
- const entries = value as unknown[];
849
- const scalar = entries.find(
850
- (entry): entry is string => typeof entry === "string" && entry !== "null",
851
- );
852
- return scalar;
853
- }
854
-
855
- function normalizeCustomToolSchema(schema: unknown): unknown {
856
- if (!schema || typeof schema !== "object") return schema;
857
- if (Array.isArray(schema)) return schema.map(normalizeCustomToolSchema);
858
-
859
- const out: Record<string, unknown> = {};
860
- for (const [key, value] of Object.entries(schema)) {
861
- if (!CUSTOM_TOOL_SCHEMA_ALLOW.has(key)) continue;
862
- if (key === "type") {
863
- const normalizedType = normalizeCustomToolType(value);
864
- if (normalizedType !== undefined) out.type = normalizedType;
865
- continue;
866
- }
867
- if (key === "properties" && value && typeof value === "object" && !Array.isArray(value)) {
868
- // Property names are user-defined, not Schema keywords — never allowlist-filter them.
869
- const props: Record<string, unknown> = {};
870
- for (const [propName, propSchema] of Object.entries(value as Record<string, unknown>)) {
871
- props[propName] = normalizeCustomToolSchema(propSchema);
872
- }
873
- out.properties = props;
874
- continue;
875
- }
876
- if (
877
- key === "enum" &&
878
- Array.isArray(value) &&
879
- !value.every((entry) => typeof entry === "string")
880
- ) {
881
- continue;
882
- }
883
- out[key] = normalizeCustomToolSchema(value);
884
- }
885
- return out;
886
- }
887
-
888
- /**
889
- * Gemini accepts JSON Schema through parametersJsonSchema. Claude and GPT-OSS
890
- * use Cloud Code Assist's custom-tool bridge, which requires a compatible
891
- * Draft 2020-12 subset in the legacy parameters field.
892
- */
893
- export function convertTools(
894
- tools: Tool[] | undefined,
895
- useLegacyParameters = false,
896
- ): { functionDeclarations: GeminiFunctionDeclaration[] }[] | undefined {
897
- if (!tools?.length) return undefined;
898
-
899
- const warnings: string[] = [];
900
- const functionDeclarations = tools.flatMap((tool) => {
901
- const dereferenced = dereferenceSchema(tool.parameters);
902
- if (dereferenced.issues.length > 0) {
903
- const detail = dereferenced.issues
904
- .map((issue) => `${issue.path} (${issue.ref}: ${issue.reason})`)
905
- .join(", ");
906
- warnings.push(`Skipped tool '${tool.name}' due to unresolved schema reference: ${detail}`);
907
- return [];
908
- }
909
-
910
- const rootObject = ensureRootObjectSchema(dereferenced.schema);
911
- const schema = stripMetaSchema(rootObject);
912
- return [
913
- {
914
- name: tool.name,
915
- description: tool.description,
916
- ...(useLegacyParameters
917
- ? { parameters: normalizeCustomToolSchema(schema) }
918
- : { parametersJsonSchema: schema }),
919
- },
920
- ];
921
- });
922
-
923
- setLastToolSchemaWarnings(warnings.length ? warnings : undefined);
924
- if (!functionDeclarations.length) return undefined;
925
- return [{ functionDeclarations }];
926
- }
927
-
928
- function mapToolChoiceMode(
929
- toolChoice: AntigravityStreamOptions["toolChoice"],
930
- ): GeminiToolCallingMode {
931
- if (toolChoice === ToolChoice.None) return GeminiToolCallingMode.None;
932
- if (toolChoice === ToolChoice.Any || toolChoice === ToolChoice.Required)
933
- return GeminiToolCallingMode.Any;
934
- return GeminiToolCallingMode.Auto;
935
- }
936
-
937
- /**
938
- * Neutralize system prompt phrases that trigger false 429 RESOURCE_EXHAUSTED
939
- * responses from the Antigravity proxy when paired with `requestType: "agent"`.
940
- */
941
- export function sanitizeSystemPrompt(text: string): string {
942
- return text
943
- .replace(
944
- /running inside pi,\s*a coding agent harness/gi,
945
- "running inside your development environment",
946
- )
947
- .replace(/inside pi,\s*a coding agent harness/gi, "inside your development environment")
948
- .replace(
949
- /(coding assistant )running inside pi(?=[.,!?;:\s]|$)(?!\.\w)/gi,
950
- "$1running inside your development environment",
951
- )
952
- .replace(
953
- /(coding agent )inside pi(?=[.,!?;:\s]|$)(?!\.\w)/gi,
954
- "$1inside your development environment",
955
- )
956
- .replace(/\bpractical,\s*and tool-aware\./gi, "practical, and tool aware.");
957
- }
958
-
959
- /** Exported for unit tests. */
960
- export function buildRequest(
961
- model: Model<Api>,
962
- context: Context,
963
- projectId: string,
964
- options: AntigravityStreamOptions,
965
- runtimeModel: string,
966
- ): AntigravityGenerateRequest {
967
- const injectedSkills = context.messages.flatMap((msg) =>
968
- msg.role === "user" ? skillBlocks(msg.content) : [],
969
- );
970
- const rawSystemPromptText = resolveCurrentSystemPrompt(context);
971
- const systemPromptText = rawSystemPromptText
972
- ? sanitizeSystemPrompt(rawSystemPromptText)
973
- : undefined;
974
- const declaredTools = resolveCurrentTools(context);
975
- const systemParts = systemPromptText
976
- ? [{ text: sanitizeText(systemPromptText) }]
977
- : [
978
- { text: sanitizeSystemPrompt(ANTIGRAVITY_SYSTEM_INSTRUCTION) },
979
- { text: ANTIGRAVITY_NO_PREAMBLE_INSTRUCTION },
980
- ];
981
- systemParts.push(...injectedSkills.map((skill) => ({ text: sanitizeText(skill) })));
982
-
983
- const { contents, hasDegradedToolObservations } = convertMessagesWithMetadata(
984
- model,
985
- context,
986
- runtimeModel,
987
- );
988
- if (systemPromptText && hasDegradedToolObservations) {
989
- systemParts.push({ text: ANTIGRAVITY_NO_PREAMBLE_INSTRUCTION });
990
- }
991
- if (hasDegradedToolObservations) {
992
- appendTurn(contents, GeminiRole.User, [
993
- {
994
- text: '[History note: Earlier "[Observation from ...]" blocks are historical tool results, not a format to imitate. To use a tool now, emit a real functionCall.]',
995
- },
996
- ]);
997
- }
998
- const hasUserText = contents.some(
999
- (turn) =>
1000
- turn.role === GeminiRole.User &&
1001
- turn.parts.some((part) => "text" in part && Boolean(part.text.trim())),
1002
- );
1003
- if (!hasUserText && (injectedSkills.length > 0 || Boolean(systemPromptText))) {
1004
- contents.unshift({
1005
- role: GeminiRole.User,
1006
- parts: [{ text: "Apply the active system instructions." }],
1007
- });
1008
- }
1009
-
1010
- const request: GeminiRequestBody = {
1011
- contents,
1012
- systemInstruction: {
1013
- role: GeminiRole.User,
1014
- parts: systemParts,
1015
- },
1016
- };
1017
-
1018
- const generationConfig: GeminiGenerationConfig = {};
1019
- if (options.temperature !== undefined) generationConfig.temperature = options.temperature;
1020
- const thinking = getThinkingConfig(runtimeModel, options.reasoning ?? "off");
1021
- if (thinking) generationConfig.thinkingConfig = thinking;
1022
- const maxAllowed = getMaxOutputTokens(model.id, runtimeModel);
1023
- if (options.maxTokens !== undefined) {
1024
- generationConfig.maxOutputTokens = Math.min(options.maxTokens, maxAllowed);
1025
- } else {
1026
- generationConfig.maxOutputTokens = Math.min(maxAllowed, model.maxTokens || maxAllowed);
1027
- }
1028
- if (Object.keys(generationConfig).length) request.generationConfig = generationConfig;
1029
-
1030
- const isClaude = model.id.startsWith("claude-") || runtimeModel.startsWith("claude-");
1031
- const tools = convertTools(declaredTools, isClaude || model.id.startsWith("gpt-oss-"));
1032
- if (tools) {
1033
- request.tools = tools;
1034
- }
1035
- if (options.toolChoice && options.toolChoice !== ToolChoice.Auto) {
1036
- request.toolConfig = {
1037
- functionCallingConfig: {
1038
- mode: mapToolChoiceMode(options.toolChoice),
1039
- },
1040
- };
1041
- }
1042
-
1043
- const isNonGemini =
1044
- isClaude ||
1045
- model.id.startsWith("gpt-oss-") ||
1046
- runtimeModel.startsWith("gpt-oss-") ||
1047
- (!model.id.startsWith("gemini-") && !runtimeModel.startsWith("gemini-"));
1048
-
1049
- // Pure agy CLI wire alignment:
1050
- // - step in requestId (.../<step>) equals contents.length (total content blocks)
1051
- // - last_step_index is 0-based index of the last content block (contents.length - 1)
1052
- // - request_id is ${trajectoryId}-${requestIndex} (0-based HTTP request sequence counter)
1053
- // In multi-turn agent loops (with tools), every completed assistant response increments the request counter.
1054
- const step = Math.max(1, request.contents.length);
1055
- const lastStepIndex = String(Math.max(0, request.contents.length - 1));
1056
- const requestIndex =
1057
- context.messages?.filter(
1058
- (m) => m.role === "assistant" && m.stopReason !== "error" && m.stopReason !== "aborted",
1059
- ).length ?? 0;
1060
-
1061
- const { conversationId, trajectoryId, sessionId } = resolveSessionTrajectory(
1062
- context,
1063
- options.sessionId,
1064
- );
1065
-
1066
- const envelope = antigravityRequestEnvelope(runtimeModel, {
1067
- isClaude,
1068
- isNonGemini,
1069
- step,
1070
- lastStepIndex,
1071
- requestIndex,
1072
- conversationId,
1073
- trajectoryId,
1074
- sessionId,
1075
- });
1076
- request.sessionId = envelope.sessionId;
1077
- request.labels = envelope.labels;
1078
-
1079
- const generateRequest: AntigravityGenerateRequest = {
1080
- project: projectId,
1081
- model: runtimeModel,
1082
- request,
1083
- requestType: AntigravityRequestType.Agent,
1084
- userAgent: AntigravityUserAgent.Antigravity,
1085
- requestId: envelope.requestId,
1086
- };
1087
- if (isCreditsEnabled()) {
1088
- generateRequest.enabledCreditTypes = ["GOOGLE_ONE_AI"];
1089
- }
1090
-
1091
- return generateRequest;
1092
- }
1093
-
1094
- /** Exported for unit tests. */
1095
- export function mapStopReason(reason: string | undefined): StopReason {
1096
- if (reason === "STOP") return StopReason.Stop;
1097
- if (reason === "MAX_TOKENS") return StopReason.Length;
1098
- return reason ? StopReason.Error : StopReason.Stop;
1099
- }
1100
-
1101
- /** Account quota walls. These must stay non-retryable and may fail over to another login. */
1102
- function isAccountQuota429(text: string): boolean {
1103
- return (
1104
- /Individual quota reached/i.test(text) ||
1105
- /Resets? in /i.test(text) ||
1106
- /AI credits balance is too low|INSUFFICIENT_G1_CREDITS/i.test(text) ||
1107
- (!/rate.?limit/i.test(text) && /quota exceeded|exceeded your|daily limit/i.test(text))
1108
- );
1109
- }
1110
-
1111
- /** Short throttles. Pi retries these; persistent model unavailability must not match. */
1112
- function isRetryableRateLimit(text: string): boolean {
1113
- return /rate.?limit|too many requests/i.test(text);
1114
- }
1115
-
1116
- /**
1117
- * Generic capacity 429 with no reset hint. Dead tiers and live-but-throttled
1118
- * tiers share this body (#89, #122, #125). Callers decide whether to walk
1119
- * endpoints and sibling tiers; the public error stays non-retryable for Pi
1120
- * once those attempts are exhausted.
1121
- */
1122
- export function isGenericResourceExhausted(text: string): boolean {
1123
- if (isAccountQuota429(text) || isRetryableRateLimit(text)) return false;
1124
- return /resource has been exhausted|RESOURCE_EXHAUSTED/i.test(text);
1125
- }
1126
-
1127
- /**
1128
- * Keep the numeric status out of non-retryable errors. Pi treats the digits 429 as a
1129
- * retryable provider error even when the friendly text says the model is unavailable.
1130
- */
1131
- function publicErrorStatus(status: number | undefined, friendly: string): string {
1132
- if (status === undefined) return "no response";
1133
- return /retrying automatically/i.test(friendly) ? String(status) : "request-failed";
1134
- }
1135
-
1136
- /** Record a static route so doctor output is not matched=none on models that skip discovery. */
1137
- function recordStaticRouteDiagnostics(runtimeModel: string): void {
1138
- if (!getCurrentMatchedModelDebug()) {
1139
- setLastMatchedModelDebug(`static:${runtimeModel}`);
1140
- }
1141
- if (!getCurrentAvailableModels()) {
1142
- const ids = Object.keys(getCurrentAntigravityRouting());
1143
- setLastAvailableModels(ids.length > 0 ? ids.join(",") : "static-catalog");
1144
- }
1145
- }
1146
-
1147
- /** Exported for unit tests. */
1148
- export function friendlyAntigravityError(status: number | undefined, text: string): string {
1149
- const msg = redactSecrets(jsonOrTextError(text)).slice(0, 500);
1150
- if (status === 400) {
1151
- if (/Requests ending with a model turn are not supported/i.test(msg)) {
1152
- return "Antigravity rejected an invalid conversation message boundary. Next: update the extension or add a user message / start a new session, then retry.";
1153
- }
1154
- if (
1155
- /function call turn comes immediately after a user turn or after a function response turn/i.test(
1156
- msg,
1157
- )
1158
- ) {
1159
- return "Antigravity rejected an invalid function-call message boundary. Next: update the extension or start a new session, then retry; re-login is not required.";
1160
- }
1161
- if (/API key not valid|API_KEY_INVALID/i.test(msg)) {
1162
- return "Antigravity login expired or credentials are invalid. Next: run /login antigravity, then retry.";
1163
- }
1164
- if (/Invalid JSON payload|Unknown name/i.test(msg)) {
1165
- return `Antigravity request format was rejected by the backend (${msg}). Next: switch to a simpler model or retry after updating the extension.`;
1166
- }
1167
- if (/Request contains an invalid argument/i.test(msg)) {
1168
- return `Antigravity rejected this request (${msg}). Next: retry once; if it keeps failing, switch models or re-login.`;
1169
- }
1170
- return `Bad request from Antigravity. Next: retry once, then run /login antigravity if it keeps failing. Backend said: ${msg}`;
1171
- }
1172
- if (status === 401) {
1173
- return "Antigravity authentication failed. Next: run /login antigravity, then retry.";
1174
- }
1175
- if (status === 403) {
1176
- const verifyUrl = extractValidationUrl(text);
1177
- const verifyHint = verifyUrl
1178
- ? ` Open this link in a browser signed in to the same Google account to verify: ${verifyUrl}`
1179
- : "";
1180
- if (/#3501|do not have a valid license of this product/i.test(msg)) {
1181
- return "This account's Gemini Enterprise license was not accepted on the consumer endpoint. Next: set ANTIGRAVITY_LOCATION to eu, us, or global, plus ANTIGRAVITY_ENTERPRISE_PROJECT and ANTIGRAVITY_USER_TIER from the license selector, then retry. A regional location is not sent to cloudcode-pa.";
1182
- }
1183
- if (/permission|forbidden|access/i.test(msg) && !verifyUrl) {
1184
- return "Antigravity access was denied for this account or project. Next: try another model, re-login, or use an account with access.";
1185
- }
1186
- return `Antigravity denied this request. Next: re-login or try another model. Backend said: ${msg}${verifyHint}`;
1187
- }
1188
- if (status === 404) {
1189
- if (/Requested entity was not found/i.test(msg)) {
1190
- return "This model is not available right now. Next: switch to gemini-3.8-flash, gemini-3.7-flash, gemini-3.6-flash, gemini-3.5-flash, gemini-3.1-pro, or another working model.";
1191
- }
1192
- return `Antigravity could not find the requested resource. Next: retry or switch models. Backend said: ${msg}`;
1193
- }
1194
- if (status === 408) return "Antigravity timed out. Next: retry the same request.";
1195
- if (status === 409) {
1196
- return "Antigravity reported a conflict for this request. Next: retry once or start a new chat session.";
1197
- }
1198
- if (status === 429) {
1199
- if (/AI credits balance is too low|INSUFFICIENT_G1_CREDITS/i.test(msg)) {
1200
- return "Your AI credits balance is exhausted. Please refill credits in Google One or wait for your regular quota to reset. Next: switch models or retry later.";
1201
- }
1202
- const wait = msg.match(/Resets? in ([^.\n]+)/i)?.[1]?.trim();
1203
- if (/Individual quota reached/i.test(msg)) {
1204
- const hint = isCreditsEnabled()
1205
- ? " (AI credits overage active; credit balance may be depleted)"
1206
- : " (Enable AI credits fallback with /antigravity.credits on)";
1207
- return `Quota reached. Please wait ${wait || "for reset"}.${hint} Next: switch models or try again after reset.`;
1208
- }
1209
- // Google answers a real quota wall with a "Resets in …" hint, but uses generic
1210
- // RESOURCE_EXHAUSTED ("Resource has been exhausted (e.g. check quota).") for
1211
- // transient throttling and capacity pressure. Classifying on the word "quota"
1212
- // alone wrongly marked transient throttling as a hard quota wall, disabling
1213
- // Pi's automatic retry backoff. Keep real quota walls non-retryable, and
1214
- // format transient throttling so Pi's retry mechanism engages.
1215
- const hardLimit =
1216
- Boolean(wait) ||
1217
- (!/rate.?limit/i.test(msg) &&
1218
- /quota exceeded|exceeded your|limit reached|reached your|daily limit/i.test(msg));
1219
- if (hardLimit) {
1220
- const hint = isCreditsEnabled()
1221
- ? " (AI credits overage active; credit balance may be depleted)"
1222
- : " (Enable AI credits fallback with /antigravity.credits on)";
1223
- return `Quota reached.${wait ? ` Please wait ${wait}.` : ""}${hint} Next: switch models or retry later.`;
1224
- }
1225
- if (/rate.?limit|too many requests/i.test(msg)) {
1226
- return "Rate limited by Antigravity (429 ResourceExhausted). Next: retrying automatically; if it persists, switch models.";
1227
- }
1228
- // A generic RESOURCE_EXHAUSTED body, with no reset hint, is how unavailable models
1229
- // such as gemini-3.1-pro fail (#89). Do not include 429/ResourceExhausted: those
1230
- // tokens make Pi burn its automatic retry budget and look like an account quota wall.
1231
- return `This model is unavailable right now (${msg || "resource exhausted"}). Next: switch to gemini-3.8-flash or another Flash model. This is not necessarily an account quota wall.`;
1232
- }
1233
- if (status === 500) {
1234
- return "Antigravity had an internal server error. Next: retry in a moment or switch models.";
1235
- }
1236
- if (status === 502) return "Antigravity returned a bad gateway error. Next: retry in a moment.";
1237
- if (status === 503) {
1238
- if (/No capacity available/i.test(msg)) {
1239
- return "This model has no capacity right now. Next: retry later or switch to another model.";
1240
- }
1241
- return "Antigravity is temporarily unavailable. Next: retry in a moment or switch models.";
1242
- }
1243
- if (status === 504) return "Antigravity timed out upstream. Next: retry in a moment.";
1244
- return msg;
1245
- }
1246
-
1247
- function createOutput(model: Model<Api>): AssistantMessage {
1248
- return {
1249
- role: "assistant",
1250
- content: [],
1251
- api: ANTIGRAVITY_API,
1252
- provider: PROVIDER_ID,
1253
- model: model.id,
1254
- usage: {
1255
- input: 0,
1256
- output: 0,
1257
- cacheRead: 0,
1258
- cacheWrite: 0,
1259
- totalTokens: 0,
1260
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
1261
- },
1262
- stopReason: "stop",
1263
- timestamp: Date.now(),
1264
- };
1265
- }
1266
-
1267
- function asToolCallArguments(args: Record<string, unknown> | undefined): ToolCall["arguments"] {
1268
- return (args ?? {}) as ToolCall["arguments"];
1269
- }
1270
-
1271
- /** Default response-header deadline for streaming requests (see fetchWithHeaderDeadline). */
1272
- const STREAM_HEADER_TIMEOUT_DEFAULT_MS = 180_000;
1273
- /** Default mid-body stall deadline: abort when no SSE bytes arrive for this long. */
1274
- const STREAM_STALL_TIMEOUT_DEFAULT_MS = 300_000;
1275
-
1276
- function envTimeoutMs(name: string, fallback: number): number {
1277
- const raw = antigravityEnv(name);
1278
- if (!raw || !/^\d+$/.test(raw)) return fallback;
1279
- const value = Number(raw);
1280
- return Number.isSafeInteger(value) ? value : fallback;
1281
- }
1282
-
1283
- /**
1284
- * Streaming header deadline in milliseconds, from ANTIGRAVITY_STREAM_HEADER_TIMEOUT_MS
1285
- * (or the legacy NOAGY_ prefix). 0 disables the deadline; invalid values fall back
1286
- * to the default.
1287
- */
1288
- export function streamHeaderTimeoutMs(): number {
1289
- return envTimeoutMs("STREAM_HEADER_TIMEOUT_MS", STREAM_HEADER_TIMEOUT_DEFAULT_MS);
1290
- }
1291
-
1292
- /**
1293
- * Mid-body stall deadline in milliseconds, from ANTIGRAVITY_STREAM_STALL_TIMEOUT_MS
1294
- * (legacy NOAGY_ prefix honored). 0 disables. A healthy SSE stream emits bytes
1295
- * continuously while generating, so a silent gap this long means the connection
1296
- * is dead even though headers arrived — abort with a named error rather than
1297
- * hanging until an external process timeout.
1298
- */
1299
- export function streamStallTimeoutMs(): number {
1300
- return envTimeoutMs("STREAM_STALL_TIMEOUT_MS", STREAM_STALL_TIMEOUT_DEFAULT_MS);
1301
- }
1302
-
1303
- function stallError(stallMs: number): Error {
1304
- // "timed out" is deliberate: pi's retryable provider-error pattern matches
1305
- // it, so a mid-body stall auto-retries instead of dying as a terminal error.
1306
- return new Error(`stream stalled: no data for ${stallMs}ms (timed out)`);
1307
- }
1308
-
1309
- /**
1310
- * Guard a response body against mid-stream stalls while retaining caller
1311
- * cancellation until the body finishes or is cancelled. The wrapper reads only
1312
- * when its consumer pulls, preserving backpressure; its timer is unref'd so an
1313
- * armed deadline cannot keep the process alive.
1314
- */
1315
- function guardResponseBody(
1316
- response: Response,
1317
- controller: AbortController,
1318
- stallMs: number,
1319
- cleanup: () => void,
1320
- ): Response {
1321
- if (!response.body) {
1322
- cleanup();
1323
- return response;
1324
- }
1325
- const reader = response.body.getReader();
1326
- let timer: ReturnType<typeof setTimeout> | undefined;
1327
- let finished = false;
1328
- const finish = () => {
1329
- if (finished) return;
1330
- finished = true;
1331
- if (timer) clearTimeout(timer);
1332
- cleanup();
1333
- };
1334
- const reset = () => {
1335
- if (stallMs <= 0) return;
1336
- if (timer) clearTimeout(timer);
1337
- timer = setTimeout(() => controller.abort(stallError(stallMs)), stallMs);
1338
- };
1339
- let streamController: ReadableStreamDefaultController<Uint8Array> | undefined;
1340
- const abortBody = () => {
1341
- streamController?.error(controller.signal.reason);
1342
- void reader.cancel(controller.signal.reason).catch(() => undefined);
1343
- finish();
1344
- };
1345
- controller.signal.addEventListener("abort", abortBody, { once: true });
1346
- reset();
1347
- const guarded = new ReadableStream<Uint8Array>({
1348
- start(controller) {
1349
- streamController = controller;
1350
- },
1351
- async pull(streamController) {
1352
- try {
1353
- const chunk = await reader.read();
1354
- if (chunk.done) {
1355
- finish();
1356
- streamController.close();
1357
- return;
1358
- }
1359
- if (!(chunk.value instanceof Uint8Array)) {
1360
- throw new Error("Response body yielded an invalid chunk");
1361
- }
1362
- reset();
1363
- streamController.enqueue(chunk.value);
1364
- } catch (error) {
1365
- finish();
1366
- streamController.error(error);
1367
- }
1368
- },
1369
- async cancel(reason) {
1370
- finish();
1371
- await reader.cancel(reason);
1372
- },
1373
- });
1374
- return new Response(guarded, response);
1375
- }
1376
-
1377
- /**
1378
- * Fetch with a response-header deadline and a mid-body stall watchdog. A server
1379
- * can accept a request on a warm keep-alive socket and then never send response
1380
- * headers (header phase), or send headers and then go silent mid-body (stall
1381
- * phase); either way the request is aborted with a named error instead of
1382
- * hanging until an external process timeout. Long healthy responses are never
1383
- * cut: the header timer disarms once headers arrive, and the stall timer resets
1384
- * on every chunk, so only genuine silence aborts.
1385
- *
1386
- * Exported with an injectable fetch for unit tests.
1387
- */
1388
- export async function fetchWithHeaderDeadline(
1389
- url: string,
1390
- init: RequestInit,
1391
- callerSignal: AbortSignal | undefined,
1392
- timeoutMs: number,
1393
- stallMs: number = 0,
1394
- fetchFn: (input: string, init: RequestInit) => Promise<Response> = antigravityFetch,
1395
- ): Promise<Response> {
1396
- if (timeoutMs <= 0 && stallMs <= 0) {
1397
- return fetchFn(url, { ...init, signal: callerSignal ?? init.signal });
1398
- }
1399
- const controller = new AbortController();
1400
- const forward = () => controller.abort(callerSignal?.reason);
1401
- const cleanup = () => callerSignal?.removeEventListener("abort", forward);
1402
- callerSignal?.addEventListener("abort", forward, { once: true });
1403
- if (callerSignal?.aborted) forward();
1404
- const timer =
1405
- timeoutMs > 0
1406
- ? setTimeout(
1407
- () =>
1408
- controller.abort(
1409
- // "timed out" keeps the message on pi's retryable-error list (see stallError).
1410
- new Error(`no response headers within ${timeoutMs}ms (timed out)`),
1411
- ),
1412
- timeoutMs,
1413
- )
1414
- : undefined;
1415
- let responseBodyGuarded = false;
1416
- try {
1417
- const response = await fetchFn(url, { ...init, signal: controller.signal });
1418
- responseBodyGuarded = Boolean(response.body);
1419
- return guardResponseBody(response, controller, stallMs, cleanup);
1420
- } finally {
1421
- if (timer) clearTimeout(timer);
1422
- if (!responseBodyGuarded) cleanup();
1423
- }
1424
- }
1425
-
1426
- /** Exported for unit tests. */
1427
-
1428
- export async function streamResponse(
1429
- response: Response,
1430
- stream: AssistantMessageEventStream,
1431
- output: AssistantMessage,
1432
- model?: Model<Api>,
1433
- ): Promise<boolean> {
1434
- if (!response.body) throw new Error("No response body");
1435
- const reader = response.body.getReader();
1436
- const decoder = new TextDecoder();
1437
- let buffer = "";
1438
- // Consumed-prefix offset: the buffer is compacted once per network chunk instead of
1439
- // re-copying the whole remainder for every SSE line.
1440
- let scanStart = 0;
1441
- let started = false;
1442
- let currentBlock: ActiveBlock | null = null;
1443
- let hasContent = false;
1444
- let sawFinishReason = false;
1445
- let stray = "";
1446
- const blocks = output.content;
1447
- const blockIndex = () => blocks.length - 1;
1448
-
1449
- const consumeStray = (line: string) => {
1450
- const trimmed = line.trim();
1451
- if (!trimmed || trimmed.startsWith(":")) return;
1452
- stray = stray ? `${stray}\n${trimmed}` : trimmed;
1453
- const start = stray.indexOf("{");
1454
- if (start < 0) return;
1455
- let parsed: unknown;
1456
- try {
1457
- parsed = JSON.parse(stray.slice(start));
1458
- } catch {
1459
- return;
1460
- }
1461
- if (!parsed || typeof parsed !== "object" || !("error" in parsed)) return;
1462
- const record = parsed as { error?: { code?: unknown; message?: unknown } };
1463
- const status = typeof record.error?.code === "number" ? record.error.code : undefined;
1464
- if (status !== undefined) setLastStatus(status);
1465
- const friendly = friendlyAntigravityError(status, stray.slice(start));
1466
- throw new Error(status ? `${friendly} (${status})` : friendly);
1467
- };
1468
-
1469
- const handleLine = (line: string) => {
1470
- if (!line.startsWith("data:")) {
1471
- consumeStray(line);
1472
- return;
1473
- }
1474
- const json = line.slice(5).trim();
1475
- if (!json || json === "[DONE]") return;
1476
-
1477
- let chunk: StreamChunk;
1478
- try {
1479
- chunk = JSON.parse(json) as StreamChunk;
1480
- } catch {
1481
- return;
1482
- }
1483
-
1484
- if (chunk.error) {
1485
- const status = typeof chunk.error.code === "number" ? chunk.error.code : undefined;
1486
- if (status !== undefined) setLastStatus(status);
1487
- const friendly = friendlyAntigravityError(status, JSON.stringify({ error: chunk.error }));
1488
- throw new Error(status ? `${friendly} (${status})` : chunk.error.message || friendly);
1489
- }
1490
-
1491
- const responseData = chunk.response || chunk;
1492
- // Record the model the gateway actually served (may differ from the requested runtime model).
1493
- if (responseData.modelVersion) output.responseModel = responseData.modelVersion;
1494
- if (responseData.responseId) output.responseId = responseData.responseId;
1495
- const candidate = responseData.candidates?.[0];
1496
-
1497
- for (const part of candidate?.content?.parts || []) {
1498
- if (part.text !== undefined) {
1499
- hasContent = true;
1500
- const isThinking = part.thought === true;
1501
- const type = isThinking ? "thinking" : "text";
1502
- if (!currentBlock || currentBlock.type !== type) {
1503
- finishCurrent();
1504
- currentBlock = isThinking
1505
- ? { type: "thinking", thinking: "", thinkingSignature: undefined }
1506
- : { type: "text", text: "" };
1507
- blocks.push(currentBlock);
1508
- ensureStarted();
1509
- stream.push({
1510
- type: isThinking ? "thinking_start" : "text_start",
1511
- contentIndex: blockIndex(),
1512
- partial: output,
1513
- });
1514
- }
1515
- if (isThinking && currentBlock.type === "thinking") {
1516
- currentBlock.thinking += part.text;
1517
- if (part.thoughtSignature) currentBlock.thinkingSignature = part.thoughtSignature;
1518
- stream.push({
1519
- type: "thinking_delta",
1520
- contentIndex: blockIndex(),
1521
- delta: part.text,
1522
- partial: output,
1523
- });
1524
- } else if (!isThinking && currentBlock.type === "text") {
1525
- currentBlock.text += part.text;
1526
- if (part.thoughtSignature) currentBlock.textSignature = part.thoughtSignature;
1527
- stream.push({
1528
- type: "text_delta",
1529
- contentIndex: blockIndex(),
1530
- delta: part.text,
1531
- partial: output,
1532
- });
1533
- }
1534
- }
1535
-
1536
- if (part.functionCall) {
1537
- hasContent = true;
1538
- finishCurrent();
1539
- const rawId = part.functionCall.id || "";
1540
- const toolCall: ToolCall = {
1541
- type: "toolCall",
1542
- id: sanitizeToolCallId(rawId, part.functionCall.name),
1543
- name: part.functionCall.name || "",
1544
- arguments: asToolCallArguments(part.functionCall.args),
1545
- ...(part.thoughtSignature ? { thoughtSignature: part.thoughtSignature } : {}),
1546
- };
1547
- blocks.push(toolCall);
1548
- ensureStarted();
1549
- stream.push({ type: "toolcall_start", contentIndex: blockIndex(), partial: output });
1550
- stream.push({
1551
- type: "toolcall_delta",
1552
- contentIndex: blockIndex(),
1553
- delta: JSON.stringify(toolCall.arguments),
1554
- partial: output,
1555
- });
1556
- stream.push({
1557
- type: "toolcall_end",
1558
- contentIndex: blockIndex(),
1559
- toolCall,
1560
- partial: output,
1561
- });
1562
- }
1563
- }
1564
-
1565
- if (candidate?.finishReason) {
1566
- sawFinishReason = true;
1567
- output.rawStopReason = candidate.finishReason;
1568
- output.stopReason = blocks.some((b) => b.type === "toolCall")
1569
- ? StopReason.ToolUse
1570
- : mapStopReason(candidate.finishReason);
1571
- }
1572
-
1573
- if (responseData.usageMetadata) {
1574
- const prompt = responseData.usageMetadata.promptTokenCount || 0;
1575
- const cacheRead = responseData.usageMetadata.cachedContentTokenCount || 0;
1576
- const thoughts = responseData.usageMetadata.thoughtsTokenCount || 0;
1577
- output.usage.input = prompt - cacheRead;
1578
- output.usage.output = (responseData.usageMetadata.candidatesTokenCount || 0) + thoughts;
1579
- output.usage.reasoning = thoughts;
1580
- output.usage.cacheRead = cacheRead;
1581
- output.usage.totalTokens = responseData.usageMetadata.totalTokenCount || 0;
1582
- if (model?.cost) {
1583
- calculateCost(model, output.usage);
1584
- } else {
1585
- output.usage.cost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 };
1586
- }
1587
- }
1588
- };
1589
-
1590
- const ensureStarted = () => {
1591
- if (!started) {
1592
- stream.push({ type: "start", partial: output });
1593
- started = true;
1594
- }
1595
- };
1596
-
1597
- const finishCurrent = () => {
1598
- if (!currentBlock) return;
1599
- if (currentBlock.type === "text") {
1600
- stream.push({
1601
- type: "text_end",
1602
- contentIndex: blockIndex(),
1603
- content: currentBlock.text,
1604
- partial: output,
1605
- });
1606
- } else {
1607
- stream.push({
1608
- type: "thinking_end",
1609
- contentIndex: blockIndex(),
1610
- content: currentBlock.thinking,
1611
- partial: output,
1612
- });
1613
- }
1614
- currentBlock = null;
1615
- };
1616
-
1617
- while (true) {
1618
- const result = await reader.read();
1619
- if (result.done) break;
1620
- if (!(result.value instanceof Uint8Array)) continue;
1621
- buffer += decoder.decode(result.value, { stream: true });
1622
-
1623
- let newlineIdx: number;
1624
- while ((newlineIdx = buffer.indexOf("\n", scanStart)) !== -1) {
1625
- const line = buffer.slice(scanStart, newlineIdx);
1626
- scanStart = newlineIdx + 1;
1627
- handleLine(line.replace(/\r$/, ""));
1628
- }
1629
-
1630
- if (scanStart > 0) {
1631
- buffer = buffer.slice(scanStart);
1632
- scanStart = 0;
1633
- }
1634
- }
1635
-
1636
- buffer += decoder.decode();
1637
- if (buffer.length > 0) handleLine(buffer.replace(/\r$/, ""));
1638
- if (!sawFinishReason) {
1639
- throw new Error(
1640
- "Antigravity stream ended without a finish reason; the response was terminated before completion.",
1641
- );
1642
- }
1643
-
1644
- finishCurrent();
1645
- return hasContent;
1646
- }
1647
-
1648
- /**
1649
- * Per-turn POST counter keyed on (pi session, requestIndex): nonce 0 is the
1650
- * first-ever request for that turn, anything above is a retry — pi's
1651
- * auto-retry, a manual /retry, or our own empty-response loop.
1652
- */
1653
- const turnRequestNonces = new Map<string, number>();
1654
-
1655
- function nextRequestNonce(turnKey: string): number {
1656
- const nonce = turnRequestNonces.get(turnKey) ?? 0;
1657
- turnRequestNonces.set(turnKey, nonce + 1);
1658
- if (turnRequestNonces.size > 64) {
1659
- const oldest = turnRequestNonces.keys().next().value;
1660
- if (oldest !== undefined) turnRequestNonces.delete(oldest);
1661
- }
1662
- return nonce;
1663
- }
1664
-
1665
- /**
1666
- * Upstream identity for a retry POST. The backend keys its per-session state on
1667
- * this int64, and a crashed stream can keep generating server-side while the
1668
- * backend serializes later same-session requests behind it — the literal retry
1669
- * then hangs almost deterministically even though a fresh request succeeds.
1670
- * Every POST after the first for a turn therefore mints a fresh identity.
1671
- */
1672
- function retrySessionSeed(sessionId: string | undefined, nonce: number): string {
1673
- return sessionId?.trim() ? `${sessionId}:r${nonce}` : `retry:${crypto.randomUUID()}`;
1674
- }
1675
-
1676
- export function streamAntigravity(
1677
- model: Model<Api>,
1678
- context: Context,
1679
- options?: AntigravityStreamOptions,
1680
- ): AssistantMessageEventStream {
1681
- const stream = createAssistantMessageEventStream();
1682
- const opts = options ?? {};
1683
-
1684
- void runWithDiagnostics(async () => {
1685
- const startTime = Date.now();
1686
- const output = createOutput(model);
1687
- try {
1688
- let creds = parseApiKey(opts.apiKey);
1689
- const triedAccessTokens = new Set<string>([creds.token]);
1690
- const enterpriseTarget = resolveEnterpriseTarget();
1691
- const primaryEndpoint = enterpriseTarget?.host ?? endpointCandidates()[0];
1692
- if (primaryEndpoint) prewarmConnection(primaryEndpoint);
1693
- // Skip loadCodeAssist roundtrip when credentials already carry a projectId.
1694
- const warmedProject = creds.projectId ? null : await loadCodeAssist(creds.token);
1695
- let projectId = resolveProjectId({
1696
- token: creds.token,
1697
- warmedProject,
1698
- credentialProjectId: creds.projectId,
1699
- });
1700
- setLastProjectId(projectId);
1701
-
1702
- const effort = opts.reasoning ?? "off";
1703
- const isKnownModel = model.id in getCurrentAntigravityRouting();
1704
- const baseRuntimeModel =
1705
- antigravityEnv("RUNTIME_MODEL")?.trim() || getAntigravityRequestModelId(model.id, effort);
1706
-
1707
- let initialRuntimeModel = baseRuntimeModel;
1708
- // Skip pre-flight model discovery for known static models to optimize TTFT latency.
1709
- // Dynamic lookup is only needed for unmapped custom models.
1710
- if (!isKnownModel && !antigravityEnv("RUNTIME_MODEL")) {
1711
- const dynamic = await fetchAvailableRuntimeModel(creds.token, projectId, baseRuntimeModel);
1712
- if (dynamic?.id && isUsableRuntimeModelId(dynamic.id)) {
1713
- initialRuntimeModel = dynamic.id;
1714
- }
1715
- }
1716
-
1717
- const runtimeCandidates = [initialRuntimeModel];
1718
- const fallback = getFallbackRuntimeModel(initialRuntimeModel, effort);
1719
- if (fallback && fallback !== initialRuntimeModel) {
1720
- runtimeCandidates.push(fallback);
1721
- }
1722
-
1723
- const headersFor = (token: string): Record<string, string> => {
1724
- const headers = antigravityHeaders(token);
1725
- if (!enterpriseTarget) return headers;
1726
- const userAgent = headers["User-Agent"] || "";
1727
- return {
1728
- ...headers,
1729
- "User-Agent": userAgent.replace("auth_method=consumer", "auth_method=gcp"),
1730
- };
1731
- };
1732
- let requestHeaders = headersFor(creds.token);
1733
-
1734
- // Turn identity mirrors buildRequest's requestIndex (count of successful
1735
- // assistant messages): it stays constant across retries of one turn and
1736
- // changes the moment any turn succeeds.
1737
- const turnKey = `${opts.sessionId ?? "anonymous"}:${
1738
- context.messages?.filter(
1739
- (m) => m.role === "assistant" && m.stopReason !== "error" && m.stopReason !== "aborted",
1740
- ).length ?? 0
1741
- }`;
1742
-
1743
- let response: Response | undefined;
1744
- let lastText = "";
1745
- let received = false;
1746
- let runtimeModel = initialRuntimeModel;
1747
-
1748
- for (let emptyAttempt = 0; emptyAttempt <= 2; emptyAttempt++) {
1749
- if (opts.signal?.aborted) throw new Error("Request was aborted");
1750
- if (emptyAttempt > 0) {
1751
- const delay = 500 * 2 ** (emptyAttempt - 1);
1752
- await new Promise((res) => setTimeout(res, delay));
1753
- }
1754
-
1755
- for (let candIdx = 0; candIdx < runtimeCandidates.length; candIdx++) {
1756
- runtimeModel = runtimeCandidates[candIdx]!;
1757
- setLastResolvedRuntimeModel(runtimeModel);
1758
- recordStaticRouteDiagnostics(runtimeModel);
1759
- response = undefined;
1760
- let lastEndpointError: Error | undefined;
1761
- const endpoints = enterpriseTarget ? [enterpriseTarget.host] : endpointCandidates();
1762
- for (const endpoint of endpoints) {
1763
- setLastEndpoint(endpoint);
1764
- // Every POST after the first for this turn replays under a fresh
1765
- // upstream session/trajectory so it cannot queue behind the crashed
1766
- // attempt's server-side generation (see retrySessionSeed).
1767
- const nonce = nextRequestNonce(turnKey);
1768
- const attemptOptions =
1769
- nonce === 0 ? opts : { ...opts, sessionId: retrySessionSeed(opts.sessionId, nonce) };
1770
- let payload: unknown = buildRequest(
1771
- model,
1772
- context,
1773
- enterpriseTarget?.projectId || projectId,
1774
- attemptOptions,
1775
- runtimeModel,
1776
- );
1777
- if (enterpriseTarget) {
1778
- payload = toEnterpriseGenerateBody(
1779
- payload as AntigravityGenerateRequest,
1780
- enterpriseTarget,
1781
- );
1782
- }
1783
- const rewritten = await opts.onPayload?.(payload, model);
1784
- if (rewritten !== undefined) payload = rewritten;
1785
- const body = JSON.stringify(payload);
1786
- const url = enterpriseTarget
1787
- ? enterpriseStreamUrl(enterpriseTarget)
1788
- : `${endpoint}/v1internal:streamGenerateContent?alt=sse`;
1789
- try {
1790
- response = await fetchWithHeaderDeadline(
1791
- url,
1792
- {
1793
- method: "POST",
1794
- headers: requestHeaders,
1795
- body,
1796
- },
1797
- opts.signal,
1798
- streamHeaderTimeoutMs(),
1799
- streamStallTimeoutMs(),
1800
- );
1801
- } catch (error) {
1802
- // Caller cancellation is not an endpoint failure — propagate it. A
1803
- // transport failure or our own header deadline abort means this
1804
- // endpoint may be wedged; ENDPOINT_FALLBACKS exist for that, so
1805
- // fall through instead of dying without trying them.
1806
- if (opts.signal?.aborted) throw error;
1807
- lastEndpointError = error instanceof Error ? error : new Error(String(error));
1808
- continue;
1809
- }
1810
- setLastStatus(response.status);
1811
- if (response.ok) break;
1812
- lastText = await response.text();
1813
- if (response.status === 429 && isAccountQuota429(lastText)) break;
1814
- // Generic RESOURCE_EXHAUSTED is capacity pressure when another endpoint
1815
- // or same-generation tier might still be live (#122, #125). A model
1816
- // that fails every one of those still uses the non-retryable #89 message.
1817
- if (response.status === 429 && isGenericResourceExhausted(lastText)) continue;
1818
- if (response.status === 429 && !isRetryableRateLimit(lastText)) break;
1819
- if (![403, 404, 429, 500, 502, 503, 504].includes(response.status)) break;
1820
- }
1821
-
1822
- // Every endpoint threw before sending headers: rethrow the original
1823
- // transport error so its message (which pi classifies for auto-retry)
1824
- // survives instead of being masked by the generic failure path below.
1825
- if (!response && lastEndpointError !== undefined) throw lastEndpointError;
1826
-
1827
- if (response?.ok) break;
1828
- if (response?.status === 404) {
1829
- if (candIdx + 1 < runtimeCandidates.length) {
1830
- continue;
1831
- }
1832
- if (isKnownModel && candIdx === runtimeCandidates.length - 1) {
1833
- const dynamic = await fetchAvailableRuntimeModel(
1834
- creds.token,
1835
- projectId,
1836
- baseRuntimeModel,
1837
- );
1838
- if (
1839
- dynamic?.id &&
1840
- !runtimeCandidates.includes(dynamic.id) &&
1841
- isUsableRuntimeModelId(dynamic.id)
1842
- ) {
1843
- runtimeCandidates.push(dynamic.id);
1844
- continue;
1845
- }
1846
- }
1847
- }
1848
- if (response?.status === 429 && isGenericResourceExhausted(lastText)) {
1849
- const nextSibling = advertisedSiblingRuntimes(runtimeModel).find(
1850
- (id) => !runtimeCandidates.includes(id),
1851
- );
1852
- if (nextSibling && runtimeCandidates.length < 4) {
1853
- // Same-generation tiers before a cross-generation compatibility fallback.
1854
- runtimeCandidates.splice(candIdx + 1, 0, nextSibling);
1855
- continue;
1856
- }
1857
- }
1858
- break;
1859
- }
1860
-
1861
- if (!response || !response.ok) {
1862
- if (antigravityEnv("DEBUG_DUMP") === "1") {
1863
- try {
1864
- const body = JSON.stringify(
1865
- buildRequest(model, context, projectId, opts, runtimeModel),
1866
- );
1867
- let parsedBody: unknown = body;
1868
- try {
1869
- parsedBody = JSON.parse(body) as unknown;
1870
- } catch {
1871
- parsedBody = body;
1872
- }
1873
- await (
1874
- await import("node:fs/promises")
1875
- ).writeFile(
1876
- "/tmp/antigravity-last-request.json",
1877
- JSON.stringify(
1878
- {
1879
- status: response?.status,
1880
- runtimeModel,
1881
- lastText: lastText.slice(0, 4000),
1882
- body: parsedBody,
1883
- },
1884
- null,
1885
- 2,
1886
- ),
1887
- );
1888
- } catch {
1889
- // ignore dump failures
1890
- }
1891
- }
1892
- const friendly = friendlyAntigravityError(response?.status, lastText);
1893
- if (response?.status === 429 && /Quota reached\./i.test(friendly)) {
1894
- const next = await failoverToNextAccount(triedAccessTokens);
1895
- if (next) {
1896
- triedAccessTokens.add(next.token);
1897
- creds = next;
1898
- requestHeaders = headersFor(creds.token);
1899
- const switchedProject = creds.projectId ? null : await loadCodeAssist(creds.token);
1900
- projectId = resolveProjectId({
1901
- token: creds.token,
1902
- warmedProject: switchedProject,
1903
- credentialProjectId: creds.projectId,
1904
- });
1905
- setLastProjectId(projectId);
1906
- emptyAttempt = -1;
1907
- continue;
1908
- }
1909
- throw new Error(friendly);
1910
- }
1911
- throw new Error(
1912
- `Antigravity API error (${publicErrorStatus(response?.status, friendly)}, ${formatRequestDiagnostics({ projectId, runtimeModel })}): ${friendly}`,
1913
- );
1914
- }
1915
-
1916
- output.content = [];
1917
- output.usage = {
1918
- input: 0,
1919
- output: 0,
1920
- cacheRead: 0,
1921
- cacheWrite: 0,
1922
- totalTokens: 0,
1923
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
1924
- };
1925
- output.stopReason = "stop";
1926
-
1927
- received = await streamResponse(response, stream, output, model);
1928
- if (received) break;
1929
- }
1930
-
1931
- if (!received) throw new Error("Antigravity API returned an empty response");
1932
- setLastLatencyMs(Date.now() - startTime);
1933
- if (output.stopReason === "error" || output.stopReason === "aborted") {
1934
- const errorDetail = output.rawStopReason
1935
- ? `Provider stopped with: ${output.rawStopReason}`
1936
- : "An unknown error occurred";
1937
- output.errorMessage = output.errorMessage || errorDetail;
1938
- setLastError(output.errorMessage);
1939
- stream.push({ type: "error", reason: output.stopReason, error: output });
1940
- } else if (output.stopReason === "pending") {
1941
- throw new Error("Antigravity API returned no stop reason");
1942
- } else {
1943
- stream.push({ type: "done", reason: output.stopReason, message: output });
1944
- }
1945
- stream.end();
1946
- } catch (error) {
1947
- setLastLatencyMs(Date.now() - startTime);
1948
- output.stopReason = opts.signal?.aborted ? "aborted" : "error";
1949
- output.errorMessage = safeError(error);
1950
- setLastError(output.errorMessage);
1951
- // Ensure endpoint is recorded even if failure happened before setLastEndpoint.
1952
- if (!getCurrentEndpoint() && endpointCandidates()[0]) {
1953
- setLastEndpoint(endpointCandidates()[0]);
1954
- }
1955
- stream.push({ type: "error", reason: output.stopReason, error: output });
1956
- stream.end();
1957
- }
1958
- });
1959
-
1960
- return stream;
1961
- }