opencode-antigravity-auth-remix 1.0.7

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 (187) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +723 -0
  3. package/dist/index.d.ts +4 -0
  4. package/dist/index.d.ts.map +1 -0
  5. package/dist/index.js +3 -0
  6. package/dist/index.js.map +1 -0
  7. package/dist/src/antigravity/oauth.d.ts +31 -0
  8. package/dist/src/antigravity/oauth.d.ts.map +1 -0
  9. package/dist/src/antigravity/oauth.js +168 -0
  10. package/dist/src/antigravity/oauth.js.map +1 -0
  11. package/dist/src/constants.d.ts +107 -0
  12. package/dist/src/constants.d.ts.map +1 -0
  13. package/dist/src/constants.js +138 -0
  14. package/dist/src/constants.js.map +1 -0
  15. package/dist/src/hooks/auto-update-checker/cache.d.ts +3 -0
  16. package/dist/src/hooks/auto-update-checker/cache.d.ts.map +1 -0
  17. package/dist/src/hooks/auto-update-checker/cache.js +71 -0
  18. package/dist/src/hooks/auto-update-checker/cache.js.map +1 -0
  19. package/dist/src/hooks/auto-update-checker/checker.d.ts +16 -0
  20. package/dist/src/hooks/auto-update-checker/checker.d.ts.map +1 -0
  21. package/dist/src/hooks/auto-update-checker/checker.js +237 -0
  22. package/dist/src/hooks/auto-update-checker/checker.js.map +1 -0
  23. package/dist/src/hooks/auto-update-checker/constants.d.ts +9 -0
  24. package/dist/src/hooks/auto-update-checker/constants.d.ts.map +1 -0
  25. package/dist/src/hooks/auto-update-checker/constants.js +23 -0
  26. package/dist/src/hooks/auto-update-checker/constants.js.map +1 -0
  27. package/dist/src/hooks/auto-update-checker/index.d.ts +34 -0
  28. package/dist/src/hooks/auto-update-checker/index.d.ts.map +1 -0
  29. package/dist/src/hooks/auto-update-checker/index.js +125 -0
  30. package/dist/src/hooks/auto-update-checker/index.js.map +1 -0
  31. package/dist/src/hooks/auto-update-checker/types.d.ts +25 -0
  32. package/dist/src/hooks/auto-update-checker/types.d.ts.map +1 -0
  33. package/dist/src/hooks/auto-update-checker/types.js +1 -0
  34. package/dist/src/hooks/auto-update-checker/types.js.map +1 -0
  35. package/dist/src/plugin/accounts.d.ts +58 -0
  36. package/dist/src/plugin/accounts.d.ts.map +1 -0
  37. package/dist/src/plugin/accounts.js +350 -0
  38. package/dist/src/plugin/accounts.js.map +1 -0
  39. package/dist/src/plugin/auth.d.ts +21 -0
  40. package/dist/src/plugin/auth.d.ts.map +1 -0
  41. package/dist/src/plugin/auth.js +46 -0
  42. package/dist/src/plugin/auth.js.map +1 -0
  43. package/dist/src/plugin/cache/index.d.ts +5 -0
  44. package/dist/src/plugin/cache/index.d.ts.map +1 -0
  45. package/dist/src/plugin/cache/index.js +5 -0
  46. package/dist/src/plugin/cache/index.js.map +1 -0
  47. package/dist/src/plugin/cache/signature-cache.d.ts +111 -0
  48. package/dist/src/plugin/cache/signature-cache.d.ts.map +1 -0
  49. package/dist/src/plugin/cache/signature-cache.js +373 -0
  50. package/dist/src/plugin/cache/signature-cache.js.map +1 -0
  51. package/dist/src/plugin/cache.d.ts +44 -0
  52. package/dist/src/plugin/cache.d.ts.map +1 -0
  53. package/dist/src/plugin/cache.js +200 -0
  54. package/dist/src/plugin/cache.js.map +1 -0
  55. package/dist/src/plugin/cli.d.ts +19 -0
  56. package/dist/src/plugin/cli.d.ts.map +1 -0
  57. package/dist/src/plugin/cli.js +59 -0
  58. package/dist/src/plugin/cli.js.map +1 -0
  59. package/dist/src/plugin/config/index.d.ts +16 -0
  60. package/dist/src/plugin/config/index.d.ts.map +1 -0
  61. package/dist/src/plugin/config/index.js +16 -0
  62. package/dist/src/plugin/config/index.js.map +1 -0
  63. package/dist/src/plugin/config/loader.d.ts +35 -0
  64. package/dist/src/plugin/config/loader.d.ts.map +1 -0
  65. package/dist/src/plugin/config/loader.js +178 -0
  66. package/dist/src/plugin/config/loader.js.map +1 -0
  67. package/dist/src/plugin/config/schema.d.ts +257 -0
  68. package/dist/src/plugin/config/schema.d.ts.map +1 -0
  69. package/dist/src/plugin/config/schema.js +229 -0
  70. package/dist/src/plugin/config/schema.js.map +1 -0
  71. package/dist/src/plugin/core/streaming/index.d.ts +3 -0
  72. package/dist/src/plugin/core/streaming/index.d.ts.map +1 -0
  73. package/dist/src/plugin/core/streaming/index.js +3 -0
  74. package/dist/src/plugin/core/streaming/index.js.map +1 -0
  75. package/dist/src/plugin/core/streaming/transformer.d.ts +9 -0
  76. package/dist/src/plugin/core/streaming/transformer.d.ts.map +1 -0
  77. package/dist/src/plugin/core/streaming/transformer.js +134 -0
  78. package/dist/src/plugin/core/streaming/transformer.js.map +1 -0
  79. package/dist/src/plugin/core/streaming/types.d.ts +26 -0
  80. package/dist/src/plugin/core/streaming/types.d.ts.map +1 -0
  81. package/dist/src/plugin/core/streaming/types.js +1 -0
  82. package/dist/src/plugin/core/streaming/types.js.map +1 -0
  83. package/dist/src/plugin/debug.d.ts +68 -0
  84. package/dist/src/plugin/debug.d.ts.map +1 -0
  85. package/dist/src/plugin/debug.js +321 -0
  86. package/dist/src/plugin/debug.js.map +1 -0
  87. package/dist/src/plugin/errors.d.ts +28 -0
  88. package/dist/src/plugin/errors.d.ts.map +1 -0
  89. package/dist/src/plugin/errors.js +42 -0
  90. package/dist/src/plugin/errors.js.map +1 -0
  91. package/dist/src/plugin/logger.d.ts +54 -0
  92. package/dist/src/plugin/logger.d.ts.map +1 -0
  93. package/dist/src/plugin/logger.js +120 -0
  94. package/dist/src/plugin/logger.js.map +1 -0
  95. package/dist/src/plugin/project.d.ts +33 -0
  96. package/dist/src/plugin/project.d.ts.map +1 -0
  97. package/dist/src/plugin/project.js +239 -0
  98. package/dist/src/plugin/project.js.map +1 -0
  99. package/dist/src/plugin/recovery/constants.d.ts +22 -0
  100. package/dist/src/plugin/recovery/constants.d.ts.map +1 -0
  101. package/dist/src/plugin/recovery/constants.js +43 -0
  102. package/dist/src/plugin/recovery/constants.js.map +1 -0
  103. package/dist/src/plugin/recovery/index.d.ts +12 -0
  104. package/dist/src/plugin/recovery/index.d.ts.map +1 -0
  105. package/dist/src/plugin/recovery/index.js +12 -0
  106. package/dist/src/plugin/recovery/index.js.map +1 -0
  107. package/dist/src/plugin/recovery/storage.d.ts +24 -0
  108. package/dist/src/plugin/recovery/storage.d.ts.map +1 -0
  109. package/dist/src/plugin/recovery/storage.js +354 -0
  110. package/dist/src/plugin/recovery/storage.js.map +1 -0
  111. package/dist/src/plugin/recovery/types.d.ts +116 -0
  112. package/dist/src/plugin/recovery/types.d.ts.map +1 -0
  113. package/dist/src/plugin/recovery/types.js +6 -0
  114. package/dist/src/plugin/recovery/types.js.map +1 -0
  115. package/dist/src/plugin/recovery.d.ts +61 -0
  116. package/dist/src/plugin/recovery.d.ts.map +1 -0
  117. package/dist/src/plugin/recovery.js +376 -0
  118. package/dist/src/plugin/recovery.js.map +1 -0
  119. package/dist/src/plugin/refresh-queue.d.ts +101 -0
  120. package/dist/src/plugin/refresh-queue.d.ts.map +1 -0
  121. package/dist/src/plugin/refresh-queue.js +244 -0
  122. package/dist/src/plugin/refresh-queue.js.map +1 -0
  123. package/dist/src/plugin/request-helpers.d.ts +270 -0
  124. package/dist/src/plugin/request-helpers.d.ts.map +1 -0
  125. package/dist/src/plugin/request-helpers.js +2158 -0
  126. package/dist/src/plugin/request-helpers.js.map +1 -0
  127. package/dist/src/plugin/request.d.ts +87 -0
  128. package/dist/src/plugin/request.d.ts.map +1 -0
  129. package/dist/src/plugin/request.js +1233 -0
  130. package/dist/src/plugin/request.js.map +1 -0
  131. package/dist/src/plugin/search.d.ts +19 -0
  132. package/dist/src/plugin/search.d.ts.map +1 -0
  133. package/dist/src/plugin/search.js +191 -0
  134. package/dist/src/plugin/search.js.map +1 -0
  135. package/dist/src/plugin/server.d.ts +23 -0
  136. package/dist/src/plugin/server.d.ts.map +1 -0
  137. package/dist/src/plugin/server.js +222 -0
  138. package/dist/src/plugin/server.js.map +1 -0
  139. package/dist/src/plugin/storage.d.ts +77 -0
  140. package/dist/src/plugin/storage.d.ts.map +1 -0
  141. package/dist/src/plugin/storage.js +207 -0
  142. package/dist/src/plugin/storage.js.map +1 -0
  143. package/dist/src/plugin/stores/signature-store.d.ts +5 -0
  144. package/dist/src/plugin/stores/signature-store.d.ts.map +1 -0
  145. package/dist/src/plugin/stores/signature-store.js +25 -0
  146. package/dist/src/plugin/stores/signature-store.js.map +1 -0
  147. package/dist/src/plugin/thinking-recovery.d.ts +90 -0
  148. package/dist/src/plugin/thinking-recovery.d.ts.map +1 -0
  149. package/dist/src/plugin/thinking-recovery.js +316 -0
  150. package/dist/src/plugin/thinking-recovery.js.map +1 -0
  151. package/dist/src/plugin/token.d.ts +19 -0
  152. package/dist/src/plugin/token.d.ts.map +1 -0
  153. package/dist/src/plugin/token.js +128 -0
  154. package/dist/src/plugin/token.js.map +1 -0
  155. package/dist/src/plugin/transform/claude.d.ts +80 -0
  156. package/dist/src/plugin/transform/claude.d.ts.map +1 -0
  157. package/dist/src/plugin/transform/claude.js +265 -0
  158. package/dist/src/plugin/transform/claude.js.map +1 -0
  159. package/dist/src/plugin/transform/cross-model-sanitizer.d.ts +35 -0
  160. package/dist/src/plugin/transform/cross-model-sanitizer.d.ts.map +1 -0
  161. package/dist/src/plugin/transform/cross-model-sanitizer.js +225 -0
  162. package/dist/src/plugin/transform/cross-model-sanitizer.js.map +1 -0
  163. package/dist/src/plugin/transform/gemini.d.ts +63 -0
  164. package/dist/src/plugin/transform/gemini.d.ts.map +1 -0
  165. package/dist/src/plugin/transform/gemini.js +142 -0
  166. package/dist/src/plugin/transform/gemini.js.map +1 -0
  167. package/dist/src/plugin/transform/index.d.ts +14 -0
  168. package/dist/src/plugin/transform/index.d.ts.map +1 -0
  169. package/dist/src/plugin/transform/index.js +14 -0
  170. package/dist/src/plugin/transform/index.js.map +1 -0
  171. package/dist/src/plugin/transform/model-resolver.d.ts +78 -0
  172. package/dist/src/plugin/transform/model-resolver.d.ts.map +1 -0
  173. package/dist/src/plugin/transform/model-resolver.js +221 -0
  174. package/dist/src/plugin/transform/model-resolver.js.map +1 -0
  175. package/dist/src/plugin/transform/types.d.ts +93 -0
  176. package/dist/src/plugin/transform/types.d.ts.map +1 -0
  177. package/dist/src/plugin/transform/types.js +1 -0
  178. package/dist/src/plugin/transform/types.js.map +1 -0
  179. package/dist/src/plugin/types.d.ts +97 -0
  180. package/dist/src/plugin/types.d.ts.map +1 -0
  181. package/dist/src/plugin/types.js +1 -0
  182. package/dist/src/plugin/types.js.map +1 -0
  183. package/dist/src/plugin.d.ts +8 -0
  184. package/dist/src/plugin.d.ts.map +1 -0
  185. package/dist/src/plugin.js +1845 -0
  186. package/dist/src/plugin.js.map +1 -0
  187. package/package.json +65 -0
@@ -0,0 +1,1233 @@
1
+ import crypto from "node:crypto";
2
+ import { ANTIGRAVITY_HEADERS, GEMINI_CLI_HEADERS, ANTIGRAVITY_ENDPOINT, GEMINI_CLI_ENDPOINT, EMPTY_SCHEMA_PLACEHOLDER_NAME, EMPTY_SCHEMA_PLACEHOLDER_DESCRIPTION, } from "../constants";
3
+ import { cacheSignature, getCachedSignature } from "./cache";
4
+ import { createStreamingTransformer, transformSseLine, transformStreamingPayload, } from "./core/streaming";
5
+ import { defaultSignatureStore } from "./stores/signature-store";
6
+ import { DEBUG_MESSAGE_PREFIX, isDebugEnabled, logAntigravityDebugResponse, } from "./debug";
7
+ import { createLogger } from "./logger";
8
+ import { cleanJSONSchemaForAntigravity, DEFAULT_THINKING_BUDGET, deepFilterThinkingBlocks, extractThinkingConfig, extractUsageFromSsePayload, extractUsageMetadata, fixToolResponseGrouping, validateAndFixClaudeToolPairing, applyToolPairingFixes, injectParameterSignatures, injectToolHardeningInstruction, isThinkingCapableModel, normalizeThinkingConfig, parseAntigravityApiBody, resolveThinkingConfig, rewriteAntigravityPreviewAccessError, transformThinkingParts, } from "./request-helpers";
9
+ import { CLAUDE_TOOL_SYSTEM_INSTRUCTION, CLAUDE_DESCRIPTION_PROMPT, } from "../constants";
10
+ import { analyzeConversationState, closeToolLoopForThinking, needsThinkingRecovery, } from "./thinking-recovery";
11
+ import { sanitizeCrossModelPayloadInPlace } from "./transform/cross-model-sanitizer";
12
+ import { resolveModelWithTier, isClaudeModel, isClaudeThinkingModel, CLAUDE_THINKING_MAX_OUTPUT_TOKENS, } from "./transform";
13
+ import { detectErrorType } from "./recovery";
14
+ const log = createLogger("request");
15
+ const PLUGIN_SESSION_ID = `-${crypto.randomUUID()}`;
16
+ const MIN_SIGNATURE_LENGTH = 50;
17
+ function buildSignatureSessionKey(sessionId, model, conversationKey, projectKey) {
18
+ const modelKey = typeof model === "string" && model.trim() ? model.toLowerCase() : "unknown";
19
+ const projectPart = typeof projectKey === "string" && projectKey.trim()
20
+ ? projectKey.trim()
21
+ : "default";
22
+ const conversationPart = typeof conversationKey === "string" && conversationKey.trim()
23
+ ? conversationKey.trim()
24
+ : "default";
25
+ return `${sessionId}:${modelKey}:${projectPart}:${conversationPart}`;
26
+ }
27
+ function shouldCacheThinkingSignatures(model) {
28
+ if (typeof model !== "string")
29
+ return false;
30
+ const lower = model.toLowerCase();
31
+ // Both Claude and Gemini 3 models require thought signature caching
32
+ // for multi-turn conversations with function calling
33
+ return lower.includes("claude") || lower.includes("gemini-3");
34
+ }
35
+ function hashConversationSeed(seed) {
36
+ return crypto.createHash("sha256").update(seed, "utf8").digest("hex").slice(0, 16);
37
+ }
38
+ function extractTextFromContent(content) {
39
+ if (typeof content === "string") {
40
+ return content;
41
+ }
42
+ if (!Array.isArray(content)) {
43
+ return "";
44
+ }
45
+ for (const block of content) {
46
+ if (!block || typeof block !== "object") {
47
+ continue;
48
+ }
49
+ const anyBlock = block;
50
+ if (typeof anyBlock.text === "string") {
51
+ return anyBlock.text;
52
+ }
53
+ if (anyBlock.text && typeof anyBlock.text === "object" && typeof anyBlock.text.text === "string") {
54
+ return anyBlock.text.text;
55
+ }
56
+ }
57
+ return "";
58
+ }
59
+ function extractConversationSeedFromMessages(messages) {
60
+ const system = messages.find((message) => message?.role === "system");
61
+ const users = messages.filter((message) => message?.role === "user");
62
+ const firstUser = users[0];
63
+ const lastUser = users.length > 0 ? users[users.length - 1] : undefined;
64
+ const systemText = system ? extractTextFromContent(system.content) : "";
65
+ const userText = firstUser ? extractTextFromContent(firstUser.content) : "";
66
+ const fallbackUserText = !userText && lastUser ? extractTextFromContent(lastUser.content) : "";
67
+ return [systemText, userText || fallbackUserText].filter(Boolean).join("|");
68
+ }
69
+ function extractConversationSeedFromContents(contents) {
70
+ const users = contents.filter((content) => content?.role === "user");
71
+ const firstUser = users[0];
72
+ const lastUser = users.length > 0 ? users[users.length - 1] : undefined;
73
+ const primaryUser = firstUser && Array.isArray(firstUser.parts) ? extractTextFromContent(firstUser.parts) : "";
74
+ if (primaryUser) {
75
+ return primaryUser;
76
+ }
77
+ if (lastUser && Array.isArray(lastUser.parts)) {
78
+ return extractTextFromContent(lastUser.parts);
79
+ }
80
+ return "";
81
+ }
82
+ function resolveConversationKey(requestPayload) {
83
+ const anyPayload = requestPayload;
84
+ const candidates = [
85
+ anyPayload.conversationId,
86
+ anyPayload.conversation_id,
87
+ anyPayload.thread_id,
88
+ anyPayload.threadId,
89
+ anyPayload.chat_id,
90
+ anyPayload.chatId,
91
+ anyPayload.sessionId,
92
+ anyPayload.session_id,
93
+ anyPayload.metadata?.conversation_id,
94
+ anyPayload.metadata?.conversationId,
95
+ anyPayload.metadata?.thread_id,
96
+ anyPayload.metadata?.threadId,
97
+ ];
98
+ for (const candidate of candidates) {
99
+ if (typeof candidate === "string" && candidate.trim()) {
100
+ return candidate.trim();
101
+ }
102
+ }
103
+ const systemSeed = extractTextFromContent(anyPayload.systemInstruction?.parts
104
+ ?? anyPayload.systemInstruction
105
+ ?? anyPayload.system
106
+ ?? anyPayload.system_instruction);
107
+ const messageSeed = Array.isArray(anyPayload.messages)
108
+ ? extractConversationSeedFromMessages(anyPayload.messages)
109
+ : Array.isArray(anyPayload.contents)
110
+ ? extractConversationSeedFromContents(anyPayload.contents)
111
+ : "";
112
+ const seed = [systemSeed, messageSeed].filter(Boolean).join("|");
113
+ if (!seed) {
114
+ return undefined;
115
+ }
116
+ return `seed-${hashConversationSeed(seed)}`;
117
+ }
118
+ function resolveConversationKeyFromRequests(requestObjects) {
119
+ for (const req of requestObjects) {
120
+ const key = resolveConversationKey(req);
121
+ if (key) {
122
+ return key;
123
+ }
124
+ }
125
+ return undefined;
126
+ }
127
+ function resolveProjectKey(candidate, fallback) {
128
+ if (typeof candidate === "string" && candidate.trim()) {
129
+ return candidate.trim();
130
+ }
131
+ if (typeof fallback === "string" && fallback.trim()) {
132
+ return fallback.trim();
133
+ }
134
+ return undefined;
135
+ }
136
+ function formatDebugLinesForThinking(lines) {
137
+ const cleaned = lines
138
+ .map((line) => line.trim())
139
+ .filter((line) => line.length > 0)
140
+ .slice(-50);
141
+ return `${DEBUG_MESSAGE_PREFIX}\n${cleaned.map((line) => `- ${line}`).join("\n")}`;
142
+ }
143
+ function injectDebugThinking(response, debugText) {
144
+ if (!response || typeof response !== "object") {
145
+ return response;
146
+ }
147
+ const resp = response;
148
+ if (Array.isArray(resp.candidates) && resp.candidates.length > 0) {
149
+ const candidates = resp.candidates.slice();
150
+ const first = candidates[0];
151
+ if (first &&
152
+ typeof first === "object" &&
153
+ first.content &&
154
+ typeof first.content === "object" &&
155
+ Array.isArray(first.content.parts)) {
156
+ const parts = [{ thought: true, text: debugText }, ...first.content.parts];
157
+ candidates[0] = { ...first, content: { ...first.content, parts } };
158
+ return { ...resp, candidates };
159
+ }
160
+ return resp;
161
+ }
162
+ if (Array.isArray(resp.content)) {
163
+ const content = [{ type: "thinking", thinking: debugText }, ...resp.content];
164
+ return { ...resp, content };
165
+ }
166
+ if (!resp.reasoning_content) {
167
+ return { ...resp, reasoning_content: debugText };
168
+ }
169
+ return resp;
170
+ }
171
+ function stripInjectedDebugFromParts(parts) {
172
+ if (!Array.isArray(parts)) {
173
+ return parts;
174
+ }
175
+ return parts.filter((part) => {
176
+ if (!part || typeof part !== "object") {
177
+ return true;
178
+ }
179
+ const record = part;
180
+ const text = typeof record.text === "string"
181
+ ? record.text
182
+ : typeof record.thinking === "string"
183
+ ? record.thinking
184
+ : undefined;
185
+ if (text && text.startsWith(DEBUG_MESSAGE_PREFIX)) {
186
+ return false;
187
+ }
188
+ return true;
189
+ });
190
+ }
191
+ function stripInjectedDebugFromRequestPayload(payload) {
192
+ const anyPayload = payload;
193
+ if (Array.isArray(anyPayload.contents)) {
194
+ anyPayload.contents = anyPayload.contents.map((content) => {
195
+ if (!content || typeof content !== "object") {
196
+ return content;
197
+ }
198
+ if (Array.isArray(content.parts)) {
199
+ return { ...content, parts: stripInjectedDebugFromParts(content.parts) };
200
+ }
201
+ if (Array.isArray(content.content)) {
202
+ return { ...content, content: stripInjectedDebugFromParts(content.content) };
203
+ }
204
+ return content;
205
+ });
206
+ }
207
+ if (Array.isArray(anyPayload.messages)) {
208
+ anyPayload.messages = anyPayload.messages.map((message) => {
209
+ if (!message || typeof message !== "object") {
210
+ return message;
211
+ }
212
+ if (Array.isArray(message.content)) {
213
+ return { ...message, content: stripInjectedDebugFromParts(message.content) };
214
+ }
215
+ return message;
216
+ });
217
+ }
218
+ }
219
+ function isGeminiToolUsePart(part) {
220
+ return !!(part && typeof part === "object" && (part.functionCall || part.tool_use || part.toolUse));
221
+ }
222
+ function isGeminiThinkingPart(part) {
223
+ return !!(part &&
224
+ typeof part === "object" &&
225
+ (part.thought === true || part.type === "thinking" || part.type === "reasoning"));
226
+ }
227
+ function ensureThoughtSignature(part, sessionId) {
228
+ if (!part || typeof part !== "object") {
229
+ return part;
230
+ }
231
+ const text = typeof part.text === "string" ? part.text : typeof part.thinking === "string" ? part.thinking : "";
232
+ if (!text) {
233
+ return part;
234
+ }
235
+ if (part.thought === true) {
236
+ if (!part.thoughtSignature) {
237
+ const cached = getCachedSignature(sessionId, text);
238
+ if (cached) {
239
+ return { ...part, thoughtSignature: cached };
240
+ }
241
+ }
242
+ return part;
243
+ }
244
+ if ((part.type === "thinking" || part.type === "reasoning") && !part.signature) {
245
+ const cached = getCachedSignature(sessionId, text);
246
+ if (cached) {
247
+ return { ...part, signature: cached };
248
+ }
249
+ }
250
+ return part;
251
+ }
252
+ function hasSignedThinkingPart(part) {
253
+ if (!part || typeof part !== "object") {
254
+ return false;
255
+ }
256
+ if (part.thought === true) {
257
+ return typeof part.thoughtSignature === "string" && part.thoughtSignature.length >= MIN_SIGNATURE_LENGTH;
258
+ }
259
+ if (part.type === "thinking" || part.type === "reasoning") {
260
+ return typeof part.signature === "string" && part.signature.length >= MIN_SIGNATURE_LENGTH;
261
+ }
262
+ return false;
263
+ }
264
+ function ensureThinkingBeforeToolUseInContents(contents, signatureSessionKey) {
265
+ return contents.map((content) => {
266
+ if (!content || typeof content !== "object" || !Array.isArray(content.parts)) {
267
+ return content;
268
+ }
269
+ const role = content.role;
270
+ if (role !== "model" && role !== "assistant") {
271
+ return content;
272
+ }
273
+ const parts = content.parts;
274
+ const hasToolUse = parts.some(isGeminiToolUsePart);
275
+ if (!hasToolUse) {
276
+ return content;
277
+ }
278
+ const thinkingParts = parts.filter(isGeminiThinkingPart).map((p) => ensureThoughtSignature(p, signatureSessionKey));
279
+ const otherParts = parts.filter((p) => !isGeminiThinkingPart(p));
280
+ const hasSignedThinking = thinkingParts.some(hasSignedThinkingPart);
281
+ if (hasSignedThinking) {
282
+ return { ...content, parts: [...thinkingParts, ...otherParts] };
283
+ }
284
+ const lastThinking = defaultSignatureStore.get(signatureSessionKey);
285
+ if (!lastThinking) {
286
+ return content;
287
+ }
288
+ const injected = {
289
+ thought: true,
290
+ text: lastThinking.text,
291
+ thoughtSignature: lastThinking.signature,
292
+ };
293
+ return { ...content, parts: [injected, ...otherParts] };
294
+ });
295
+ }
296
+ function ensureMessageThinkingSignature(block, sessionId) {
297
+ if (!block || typeof block !== "object") {
298
+ return block;
299
+ }
300
+ if (block.type !== "thinking" && block.type !== "redacted_thinking") {
301
+ return block;
302
+ }
303
+ if (typeof block.signature === "string" && block.signature.length >= MIN_SIGNATURE_LENGTH) {
304
+ return block;
305
+ }
306
+ const text = typeof block.thinking === "string" ? block.thinking : typeof block.text === "string" ? block.text : "";
307
+ if (!text) {
308
+ return block;
309
+ }
310
+ const cached = getCachedSignature(sessionId, text);
311
+ if (cached) {
312
+ return { ...block, signature: cached };
313
+ }
314
+ return block;
315
+ }
316
+ function hasToolUseInContents(contents) {
317
+ return contents.some((content) => {
318
+ if (!content || typeof content !== "object" || !Array.isArray(content.parts)) {
319
+ return false;
320
+ }
321
+ return content.parts.some(isGeminiToolUsePart);
322
+ });
323
+ }
324
+ function hasSignedThinkingInContents(contents) {
325
+ return contents.some((content) => {
326
+ if (!content || typeof content !== "object" || !Array.isArray(content.parts)) {
327
+ return false;
328
+ }
329
+ return content.parts.some(hasSignedThinkingPart);
330
+ });
331
+ }
332
+ function hasToolUseInMessages(messages) {
333
+ return messages.some((message) => {
334
+ if (!message || typeof message !== "object" || !Array.isArray(message.content)) {
335
+ return false;
336
+ }
337
+ return message.content.some((block) => block && typeof block === "object" && (block.type === "tool_use" || block.type === "tool_result"));
338
+ });
339
+ }
340
+ function hasSignedThinkingInMessages(messages) {
341
+ return messages.some((message) => {
342
+ if (!message || typeof message !== "object" || !Array.isArray(message.content)) {
343
+ return false;
344
+ }
345
+ return message.content.some((block) => block &&
346
+ typeof block === "object" &&
347
+ (block.type === "thinking" || block.type === "redacted_thinking") &&
348
+ typeof block.signature === "string" &&
349
+ block.signature.length >= MIN_SIGNATURE_LENGTH);
350
+ });
351
+ }
352
+ function ensureThinkingBeforeToolUseInMessages(messages, signatureSessionKey) {
353
+ return messages.map((message) => {
354
+ if (!message || typeof message !== "object" || !Array.isArray(message.content)) {
355
+ return message;
356
+ }
357
+ if (message.role !== "assistant") {
358
+ return message;
359
+ }
360
+ const blocks = message.content;
361
+ const hasToolUse = blocks.some((b) => b && typeof b === "object" && (b.type === "tool_use" || b.type === "tool_result"));
362
+ if (!hasToolUse) {
363
+ return message;
364
+ }
365
+ const thinkingBlocks = blocks
366
+ .filter((b) => b && typeof b === "object" && (b.type === "thinking" || b.type === "redacted_thinking"))
367
+ .map((b) => ensureMessageThinkingSignature(b, signatureSessionKey));
368
+ const otherBlocks = blocks.filter((b) => !(b && typeof b === "object" && (b.type === "thinking" || b.type === "redacted_thinking")));
369
+ const hasSignedThinking = thinkingBlocks.some((b) => typeof b.signature === "string" && b.signature.length >= MIN_SIGNATURE_LENGTH);
370
+ if (hasSignedThinking) {
371
+ return { ...message, content: [...thinkingBlocks, ...otherBlocks] };
372
+ }
373
+ const lastThinking = defaultSignatureStore.get(signatureSessionKey);
374
+ if (!lastThinking) {
375
+ return message;
376
+ }
377
+ const injected = {
378
+ type: "thinking",
379
+ thinking: lastThinking.text,
380
+ signature: lastThinking.signature,
381
+ };
382
+ return { ...message, content: [injected, ...otherBlocks] };
383
+ });
384
+ }
385
+ /**
386
+ * Gets the stable session ID for this plugin instance.
387
+ */
388
+ export function getPluginSessionId() {
389
+ return PLUGIN_SESSION_ID;
390
+ }
391
+ function generateSyntheticProjectId() {
392
+ const adjectives = ["useful", "bright", "swift", "calm", "bold"];
393
+ const nouns = ["fuze", "wave", "spark", "flow", "core"];
394
+ const adj = adjectives[Math.floor(Math.random() * adjectives.length)];
395
+ const noun = nouns[Math.floor(Math.random() * nouns.length)];
396
+ const randomPart = crypto.randomUUID().slice(0, 5).toLowerCase();
397
+ return `${adj}-${noun}-${randomPart}`;
398
+ }
399
+ const STREAM_ACTION = "streamGenerateContent";
400
+ /**
401
+ * Detects requests headed to the Google Generative Language API so we can intercept them.
402
+ */
403
+ export function isGenerativeLanguageRequest(input) {
404
+ return typeof input === "string" && input.includes("generativelanguage.googleapis.com");
405
+ }
406
+ export function prepareAntigravityRequest(input, init, accessToken, projectId, endpointOverride, headerStyle = "antigravity", forceThinkingRecovery = false, options) {
407
+ const baseInit = { ...init };
408
+ const headers = new Headers(init?.headers ?? {});
409
+ let resolvedProjectId = projectId?.trim() || "";
410
+ let toolDebugMissing = 0;
411
+ const toolDebugSummaries = [];
412
+ let toolDebugPayload;
413
+ let sessionId;
414
+ let needsSignedThinkingWarmup = false;
415
+ let thinkingRecoveryMessage;
416
+ if (!isGenerativeLanguageRequest(input)) {
417
+ return {
418
+ request: input,
419
+ init: { ...baseInit, headers },
420
+ streaming: false,
421
+ headerStyle,
422
+ };
423
+ }
424
+ headers.set("Authorization", `Bearer ${accessToken}`);
425
+ headers.delete("x-api-key");
426
+ const match = input.match(/\/models\/([^:]+):(\w+)/);
427
+ if (!match) {
428
+ return {
429
+ request: input,
430
+ init: { ...baseInit, headers },
431
+ streaming: false,
432
+ headerStyle,
433
+ };
434
+ }
435
+ const [, rawModel = "", rawAction = ""] = match;
436
+ const requestedModel = rawModel;
437
+ // Use model resolver for tier-based thinking configuration
438
+ const resolved = resolveModelWithTier(rawModel);
439
+ const effectiveModel = resolved.actualModel;
440
+ const streaming = rawAction === STREAM_ACTION;
441
+ const defaultEndpoint = headerStyle === "gemini-cli" ? GEMINI_CLI_ENDPOINT : ANTIGRAVITY_ENDPOINT;
442
+ const baseEndpoint = endpointOverride ?? defaultEndpoint;
443
+ const transformedUrl = `${baseEndpoint}/v1internal:${rawAction}${streaming ? "?alt=sse" : ""}`;
444
+ const isClaude = isClaudeModel(resolved.actualModel);
445
+ const isClaudeThinking = isClaudeThinkingModel(resolved.actualModel);
446
+ // Tier-based thinking configuration from model resolver
447
+ const tierThinkingBudget = resolved.thinkingBudget;
448
+ const tierThinkingLevel = resolved.thinkingLevel;
449
+ let signatureSessionKey = buildSignatureSessionKey(PLUGIN_SESSION_ID, effectiveModel, undefined, resolveProjectKey(projectId));
450
+ let body = baseInit.body;
451
+ if (typeof baseInit.body === "string" && baseInit.body) {
452
+ try {
453
+ const parsedBody = JSON.parse(baseInit.body);
454
+ const isWrapped = typeof parsedBody.project === "string" && "request" in parsedBody;
455
+ if (isWrapped) {
456
+ const wrappedBody = {
457
+ ...parsedBody,
458
+ model: effectiveModel,
459
+ };
460
+ // Some callers may already send an Antigravity-wrapped body.
461
+ // We still need to sanitize Claude thinking blocks (remove cache_control)
462
+ // and attach a stable sessionId so multi-turn signature caching works.
463
+ const requestRoot = wrappedBody.request;
464
+ const requestObjects = [];
465
+ if (requestRoot && typeof requestRoot === "object") {
466
+ requestObjects.push(requestRoot);
467
+ const nested = requestRoot.request;
468
+ if (nested && typeof nested === "object") {
469
+ requestObjects.push(nested);
470
+ }
471
+ }
472
+ const conversationKey = resolveConversationKeyFromRequests(requestObjects);
473
+ // Strip tier suffix from model for cache key to prevent cache misses on tier change
474
+ // e.g., "claude-opus-4-5-thinking-high" -> "claude-opus-4-5-thinking"
475
+ const modelForCacheKey = effectiveModel.replace(/-(minimal|low|medium|high)$/i, "");
476
+ signatureSessionKey = buildSignatureSessionKey(PLUGIN_SESSION_ID, modelForCacheKey, conversationKey, resolveProjectKey(parsedBody.project));
477
+ if (requestObjects.length > 0) {
478
+ sessionId = signatureSessionKey;
479
+ }
480
+ for (const req of requestObjects) {
481
+ // Use stable session ID for signature caching across multi-turn conversations
482
+ req.sessionId = signatureSessionKey;
483
+ stripInjectedDebugFromRequestPayload(req);
484
+ if (isClaude) {
485
+ // Step 0: Sanitize cross-model metadata (strips Gemini signatures when sending to Claude)
486
+ sanitizeCrossModelPayloadInPlace(req, { targetModel: effectiveModel });
487
+ // Step 1: Strip corrupted/unsigned thinking blocks FIRST
488
+ deepFilterThinkingBlocks(req, signatureSessionKey, getCachedSignature, true);
489
+ // Step 2: THEN inject signed thinking from cache (after stripping)
490
+ if (isClaudeThinking && Array.isArray(req.contents)) {
491
+ req.contents = ensureThinkingBeforeToolUseInContents(req.contents, signatureSessionKey);
492
+ }
493
+ if (isClaudeThinking && Array.isArray(req.messages)) {
494
+ req.messages = ensureThinkingBeforeToolUseInMessages(req.messages, signatureSessionKey);
495
+ }
496
+ // Step 3: Apply tool pairing fixes (ID assignment, response matching, orphan recovery)
497
+ applyToolPairingFixes(req, true);
498
+ }
499
+ }
500
+ if (isClaudeThinking && sessionId) {
501
+ const hasToolUse = requestObjects.some((req) => (Array.isArray(req.contents) && hasToolUseInContents(req.contents)) ||
502
+ (Array.isArray(req.messages) && hasToolUseInMessages(req.messages)));
503
+ const hasSignedThinking = requestObjects.some((req) => (Array.isArray(req.contents) && hasSignedThinkingInContents(req.contents)) ||
504
+ (Array.isArray(req.messages) && hasSignedThinkingInMessages(req.messages)));
505
+ const hasCachedThinking = defaultSignatureStore.has(signatureSessionKey);
506
+ needsSignedThinkingWarmup = hasToolUse && !hasSignedThinking && !hasCachedThinking;
507
+ }
508
+ body = JSON.stringify(wrappedBody);
509
+ }
510
+ else {
511
+ const requestPayload = { ...parsedBody };
512
+ const rawGenerationConfig = requestPayload.generationConfig;
513
+ const extraBody = requestPayload.extra_body;
514
+ if (isClaude) {
515
+ if (!requestPayload.toolConfig) {
516
+ requestPayload.toolConfig = {};
517
+ }
518
+ if (typeof requestPayload.toolConfig === "object" && requestPayload.toolConfig !== null) {
519
+ const toolConfig = requestPayload.toolConfig;
520
+ if (!toolConfig.functionCallingConfig) {
521
+ toolConfig.functionCallingConfig = {};
522
+ }
523
+ if (typeof toolConfig.functionCallingConfig === "object" && toolConfig.functionCallingConfig !== null) {
524
+ toolConfig.functionCallingConfig.mode = "VALIDATED";
525
+ }
526
+ }
527
+ }
528
+ // Resolve thinking configuration based on user settings and model capabilities
529
+ const userThinkingConfig = extractThinkingConfig(requestPayload, rawGenerationConfig, extraBody);
530
+ const hasAssistantHistory = Array.isArray(requestPayload.contents) &&
531
+ requestPayload.contents.some((c) => c?.role === "model" || c?.role === "assistant");
532
+ // For claude-sonnet-4-5 (without -thinking suffix), ignore client's thinkingConfig
533
+ // Only claude-sonnet-4-5-thinking-* variants should have thinking enabled
534
+ const isClaudeSonnetNonThinking = effectiveModel.toLowerCase() === "claude-sonnet-4-5";
535
+ const effectiveUserThinkingConfig = isClaudeSonnetNonThinking ? undefined : userThinkingConfig;
536
+ const finalThinkingConfig = resolveThinkingConfig(effectiveUserThinkingConfig, isClaudeSonnetNonThinking ? false : (resolved.isThinkingModel ?? isThinkingCapableModel(effectiveModel)), isClaude, hasAssistantHistory);
537
+ const normalizedThinking = normalizeThinkingConfig(finalThinkingConfig);
538
+ if (normalizedThinking) {
539
+ // Use tier-based thinking budget if specified via model suffix, otherwise fall back to user config
540
+ const thinkingBudget = tierThinkingBudget ?? normalizedThinking.thinkingBudget;
541
+ // Build thinking config based on model type
542
+ let thinkingConfig;
543
+ if (isClaudeThinking) {
544
+ // Claude uses snake_case keys
545
+ thinkingConfig = {
546
+ include_thoughts: normalizedThinking.includeThoughts ?? true,
547
+ ...(typeof thinkingBudget === "number" && thinkingBudget > 0
548
+ ? { thinking_budget: thinkingBudget }
549
+ : {}),
550
+ };
551
+ }
552
+ else if (tierThinkingLevel) {
553
+ // Gemini 3 uses thinkingLevel string (low/medium/high)
554
+ thinkingConfig = {
555
+ includeThoughts: normalizedThinking.includeThoughts,
556
+ thinkingLevel: tierThinkingLevel,
557
+ };
558
+ }
559
+ else {
560
+ // Gemini 2.5 and others use numeric budget
561
+ thinkingConfig = {
562
+ includeThoughts: normalizedThinking.includeThoughts,
563
+ ...(typeof thinkingBudget === "number" && thinkingBudget > 0 ? { thinkingBudget } : {}),
564
+ };
565
+ }
566
+ if (rawGenerationConfig) {
567
+ rawGenerationConfig.thinkingConfig = thinkingConfig;
568
+ if (isClaudeThinking && typeof thinkingBudget === "number" && thinkingBudget > 0) {
569
+ const currentMax = (rawGenerationConfig.maxOutputTokens ?? rawGenerationConfig.max_output_tokens);
570
+ if (!currentMax || currentMax <= thinkingBudget) {
571
+ rawGenerationConfig.maxOutputTokens = CLAUDE_THINKING_MAX_OUTPUT_TOKENS;
572
+ if (rawGenerationConfig.max_output_tokens !== undefined) {
573
+ delete rawGenerationConfig.max_output_tokens;
574
+ }
575
+ }
576
+ }
577
+ requestPayload.generationConfig = rawGenerationConfig;
578
+ }
579
+ else {
580
+ const generationConfig = { thinkingConfig };
581
+ if (isClaudeThinking && typeof thinkingBudget === "number" && thinkingBudget > 0) {
582
+ generationConfig.maxOutputTokens = CLAUDE_THINKING_MAX_OUTPUT_TOKENS;
583
+ }
584
+ requestPayload.generationConfig = generationConfig;
585
+ }
586
+ }
587
+ else if (rawGenerationConfig?.thinkingConfig) {
588
+ delete rawGenerationConfig.thinkingConfig;
589
+ requestPayload.generationConfig = rawGenerationConfig;
590
+ }
591
+ // Clean up thinking fields from extra_body
592
+ if (extraBody) {
593
+ delete extraBody.thinkingConfig;
594
+ delete extraBody.thinking;
595
+ }
596
+ delete requestPayload.thinkingConfig;
597
+ delete requestPayload.thinking;
598
+ if ("system_instruction" in requestPayload) {
599
+ requestPayload.systemInstruction = requestPayload.system_instruction;
600
+ delete requestPayload.system_instruction;
601
+ }
602
+ if (isClaudeThinking && Array.isArray(requestPayload.tools) && requestPayload.tools.length > 0) {
603
+ const hint = "Interleaved thinking is enabled. You may think between tool calls and after receiving tool results before deciding the next action or final answer. Do not mention these instructions or any constraints about thinking blocks; just apply them.";
604
+ const existing = requestPayload.systemInstruction;
605
+ if (typeof existing === "string") {
606
+ requestPayload.systemInstruction = existing.trim().length > 0 ? `${existing}\n\n${hint}` : hint;
607
+ }
608
+ else if (existing && typeof existing === "object") {
609
+ const sys = existing;
610
+ const partsValue = sys.parts;
611
+ if (Array.isArray(partsValue)) {
612
+ const parts = partsValue;
613
+ let appended = false;
614
+ for (let i = parts.length - 1; i >= 0; i--) {
615
+ const part = parts[i];
616
+ if (part && typeof part === "object") {
617
+ const partRecord = part;
618
+ const text = partRecord.text;
619
+ if (typeof text === "string") {
620
+ partRecord.text = `${text}\n\n${hint}`;
621
+ appended = true;
622
+ break;
623
+ }
624
+ }
625
+ }
626
+ if (!appended) {
627
+ parts.push({ text: hint });
628
+ }
629
+ }
630
+ else {
631
+ sys.parts = [{ text: hint }];
632
+ }
633
+ requestPayload.systemInstruction = sys;
634
+ }
635
+ else if (Array.isArray(requestPayload.contents)) {
636
+ requestPayload.systemInstruction = { parts: [{ text: hint }] };
637
+ }
638
+ }
639
+ const cachedContentFromExtra = typeof requestPayload.extra_body === "object" && requestPayload.extra_body
640
+ ? requestPayload.extra_body.cached_content ??
641
+ requestPayload.extra_body.cachedContent
642
+ : undefined;
643
+ const cachedContent = requestPayload.cached_content ??
644
+ requestPayload.cachedContent ??
645
+ cachedContentFromExtra;
646
+ if (cachedContent) {
647
+ requestPayload.cachedContent = cachedContent;
648
+ }
649
+ delete requestPayload.cached_content;
650
+ delete requestPayload.cachedContent;
651
+ if (requestPayload.extra_body && typeof requestPayload.extra_body === "object") {
652
+ delete requestPayload.extra_body.cached_content;
653
+ delete requestPayload.extra_body.cachedContent;
654
+ if (Object.keys(requestPayload.extra_body).length === 0) {
655
+ delete requestPayload.extra_body;
656
+ }
657
+ }
658
+ // Normalize tools. For Claude models, keep full function declarations (names + schemas).
659
+ if (Array.isArray(requestPayload.tools)) {
660
+ if (isClaude) {
661
+ const functionDeclarations = [];
662
+ const passthroughTools = [];
663
+ const normalizeSchema = (schema) => {
664
+ const createPlaceholderSchema = (base = {}) => ({
665
+ ...base,
666
+ type: "object",
667
+ properties: {
668
+ [EMPTY_SCHEMA_PLACEHOLDER_NAME]: {
669
+ type: "boolean",
670
+ description: EMPTY_SCHEMA_PLACEHOLDER_DESCRIPTION,
671
+ },
672
+ },
673
+ required: [EMPTY_SCHEMA_PLACEHOLDER_NAME],
674
+ });
675
+ if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
676
+ toolDebugMissing += 1;
677
+ return createPlaceholderSchema();
678
+ }
679
+ const cleaned = cleanJSONSchemaForAntigravity(schema);
680
+ if (!cleaned || typeof cleaned !== "object" || Array.isArray(cleaned)) {
681
+ toolDebugMissing += 1;
682
+ return createPlaceholderSchema();
683
+ }
684
+ // Claude VALIDATED mode requires tool parameters to be an object schema
685
+ // with at least one property.
686
+ const hasProperties = cleaned.properties &&
687
+ typeof cleaned.properties === "object" &&
688
+ Object.keys(cleaned.properties).length > 0;
689
+ cleaned.type = "object";
690
+ if (!hasProperties) {
691
+ cleaned.properties = {
692
+ [EMPTY_SCHEMA_PLACEHOLDER_NAME]: {
693
+ type: "boolean",
694
+ description: EMPTY_SCHEMA_PLACEHOLDER_DESCRIPTION,
695
+ },
696
+ };
697
+ cleaned.required = Array.isArray(cleaned.required)
698
+ ? Array.from(new Set([...cleaned.required, EMPTY_SCHEMA_PLACEHOLDER_NAME]))
699
+ : [EMPTY_SCHEMA_PLACEHOLDER_NAME];
700
+ }
701
+ return cleaned;
702
+ };
703
+ requestPayload.tools.forEach((tool) => {
704
+ const pushDeclaration = (decl, source) => {
705
+ const schema = decl?.parameters ||
706
+ decl?.parametersJsonSchema ||
707
+ decl?.input_schema ||
708
+ decl?.inputSchema ||
709
+ tool.parameters ||
710
+ tool.parametersJsonSchema ||
711
+ tool.input_schema ||
712
+ tool.inputSchema ||
713
+ tool.function?.parameters ||
714
+ tool.function?.parametersJsonSchema ||
715
+ tool.function?.input_schema ||
716
+ tool.function?.inputSchema ||
717
+ tool.custom?.parameters ||
718
+ tool.custom?.parametersJsonSchema ||
719
+ tool.custom?.input_schema;
720
+ let name = decl?.name ||
721
+ tool.name ||
722
+ tool.function?.name ||
723
+ tool.custom?.name ||
724
+ `tool-${functionDeclarations.length}`;
725
+ // Sanitize tool name: must be alphanumeric with underscores, no special chars
726
+ name = String(name).replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64);
727
+ const description = decl?.description ||
728
+ tool.description ||
729
+ tool.function?.description ||
730
+ tool.custom?.description ||
731
+ "";
732
+ functionDeclarations.push({
733
+ name,
734
+ description: String(description || ""),
735
+ parameters: normalizeSchema(schema),
736
+ });
737
+ toolDebugSummaries.push(`decl=${name},src=${source},hasSchema=${schema ? "y" : "n"}`);
738
+ };
739
+ if (Array.isArray(tool.functionDeclarations) && tool.functionDeclarations.length > 0) {
740
+ tool.functionDeclarations.forEach((decl) => pushDeclaration(decl, "functionDeclarations"));
741
+ return;
742
+ }
743
+ // Fall back to function/custom style definitions.
744
+ if (tool.function ||
745
+ tool.custom ||
746
+ tool.parameters ||
747
+ tool.input_schema ||
748
+ tool.inputSchema) {
749
+ pushDeclaration(tool.function ?? tool.custom ?? tool, "function/custom");
750
+ return;
751
+ }
752
+ // Preserve any non-function tool entries (e.g., codeExecution) untouched.
753
+ passthroughTools.push(tool);
754
+ });
755
+ const finalTools = [];
756
+ if (functionDeclarations.length > 0) {
757
+ finalTools.push({ functionDeclarations });
758
+ }
759
+ requestPayload.tools = finalTools.concat(passthroughTools);
760
+ }
761
+ else {
762
+ // Default normalization for non-Claude models
763
+ requestPayload.tools = requestPayload.tools.map((tool, toolIndex) => {
764
+ const newTool = { ...tool };
765
+ const schemaCandidates = [
766
+ newTool.function?.input_schema,
767
+ newTool.function?.parameters,
768
+ newTool.function?.inputSchema,
769
+ newTool.custom?.input_schema,
770
+ newTool.custom?.parameters,
771
+ newTool.parameters,
772
+ newTool.input_schema,
773
+ newTool.inputSchema,
774
+ ].filter(Boolean);
775
+ const schema = schemaCandidates[0];
776
+ const nameCandidate = newTool.name ||
777
+ newTool.function?.name ||
778
+ newTool.custom?.name ||
779
+ `tool-${toolIndex}`;
780
+ if (newTool.function && !newTool.function.input_schema && schema) {
781
+ newTool.function.input_schema = schema;
782
+ }
783
+ if (newTool.custom && !newTool.custom.input_schema && schema) {
784
+ newTool.custom.input_schema = schema;
785
+ }
786
+ if (!newTool.custom && newTool.function) {
787
+ newTool.custom = {
788
+ name: newTool.function.name || nameCandidate,
789
+ description: newTool.function.description,
790
+ input_schema: schema ?? { type: "object", properties: {}, additionalProperties: false },
791
+ };
792
+ }
793
+ if (!newTool.custom && !newTool.function) {
794
+ newTool.custom = {
795
+ name: nameCandidate,
796
+ description: newTool.description,
797
+ input_schema: schema ?? { type: "object", properties: {}, additionalProperties: false },
798
+ };
799
+ }
800
+ if (newTool.custom && !newTool.custom.input_schema) {
801
+ newTool.custom.input_schema = { type: "object", properties: {}, additionalProperties: false };
802
+ toolDebugMissing += 1;
803
+ }
804
+ toolDebugSummaries.push(`idx=${toolIndex}, hasCustom=${!!newTool.custom}, customSchema=${!!newTool.custom?.input_schema}, hasFunction=${!!newTool.function}, functionSchema=${!!newTool.function?.input_schema}`);
805
+ // Strip custom wrappers for Gemini; only function-style is accepted.
806
+ if (newTool.custom) {
807
+ delete newTool.custom;
808
+ }
809
+ return newTool;
810
+ });
811
+ }
812
+ try {
813
+ toolDebugPayload = JSON.stringify(requestPayload.tools);
814
+ }
815
+ catch {
816
+ toolDebugPayload = undefined;
817
+ }
818
+ // Apply Claude tool hardening (ported from LLM-API-Key-Proxy)
819
+ // Injects parameter signatures into descriptions and adds system instruction
820
+ // Can be disabled via config.claude_tool_hardening = false to reduce context size
821
+ const enableToolHardening = options?.claudeToolHardening ?? true;
822
+ if (enableToolHardening && isClaude && Array.isArray(requestPayload.tools) && requestPayload.tools.length > 0) {
823
+ // Inject parameter signatures into tool descriptions
824
+ requestPayload.tools = injectParameterSignatures(requestPayload.tools, CLAUDE_DESCRIPTION_PROMPT);
825
+ // Inject tool hardening system instruction
826
+ injectToolHardeningInstruction(requestPayload, CLAUDE_TOOL_SYSTEM_INSTRUCTION);
827
+ }
828
+ }
829
+ const conversationKey = resolveConversationKey(requestPayload);
830
+ signatureSessionKey = buildSignatureSessionKey(PLUGIN_SESSION_ID, effectiveModel, conversationKey, resolveProjectKey(projectId));
831
+ // For Claude models, filter out unsigned thinking blocks (required by Claude API)
832
+ // Attempts to restore signatures from cache for multi-turn conversations
833
+ // Handle both Gemini-style contents[] and Anthropic-style messages[] payloads.
834
+ if (isClaude) {
835
+ // Step 1: Strip corrupted/unsigned thinking blocks FIRST
836
+ deepFilterThinkingBlocks(requestPayload, signatureSessionKey, getCachedSignature, true);
837
+ // Step 2: THEN inject signed thinking from cache (after stripping)
838
+ if (isClaudeThinking && Array.isArray(requestPayload.contents)) {
839
+ requestPayload.contents = ensureThinkingBeforeToolUseInContents(requestPayload.contents, signatureSessionKey);
840
+ }
841
+ if (isClaudeThinking && Array.isArray(requestPayload.messages)) {
842
+ requestPayload.messages = ensureThinkingBeforeToolUseInMessages(requestPayload.messages, signatureSessionKey);
843
+ }
844
+ // Step 3: Check if warmup needed (AFTER injection attempt)
845
+ if (isClaudeThinking) {
846
+ const hasToolUse = (Array.isArray(requestPayload.contents) && hasToolUseInContents(requestPayload.contents)) ||
847
+ (Array.isArray(requestPayload.messages) && hasToolUseInMessages(requestPayload.messages));
848
+ const hasSignedThinking = (Array.isArray(requestPayload.contents) && hasSignedThinkingInContents(requestPayload.contents)) ||
849
+ (Array.isArray(requestPayload.messages) && hasSignedThinkingInMessages(requestPayload.messages));
850
+ const hasCachedThinking = defaultSignatureStore.has(signatureSessionKey);
851
+ needsSignedThinkingWarmup = hasToolUse && !hasSignedThinking && !hasCachedThinking;
852
+ }
853
+ }
854
+ // For Claude models, ensure functionCall/tool use parts carry IDs (required by Anthropic).
855
+ // We use a two-pass approach: first collect all functionCalls and assign IDs,
856
+ // then match functionResponses to their corresponding calls using a FIFO queue per function name.
857
+ if (isClaude && Array.isArray(requestPayload.contents)) {
858
+ let toolCallCounter = 0;
859
+ // Track pending call IDs per function name as a FIFO queue
860
+ const pendingCallIdsByName = new Map();
861
+ // First pass: assign IDs to all functionCalls and collect them
862
+ requestPayload.contents = requestPayload.contents.map((content) => {
863
+ if (!content || !Array.isArray(content.parts)) {
864
+ return content;
865
+ }
866
+ const newParts = content.parts.map((part) => {
867
+ if (part && typeof part === "object" && part.functionCall) {
868
+ const call = { ...part.functionCall };
869
+ if (!call.id) {
870
+ call.id = `tool-call-${++toolCallCounter}`;
871
+ }
872
+ const nameKey = typeof call.name === "string" ? call.name : `tool-${toolCallCounter}`;
873
+ // Push to the queue for this function name
874
+ const queue = pendingCallIdsByName.get(nameKey) || [];
875
+ queue.push(call.id);
876
+ pendingCallIdsByName.set(nameKey, queue);
877
+ return { ...part, functionCall: call };
878
+ }
879
+ return part;
880
+ });
881
+ return { ...content, parts: newParts };
882
+ });
883
+ // Second pass: match functionResponses to their corresponding calls (FIFO order)
884
+ requestPayload.contents = requestPayload.contents.map((content) => {
885
+ if (!content || !Array.isArray(content.parts)) {
886
+ return content;
887
+ }
888
+ const newParts = content.parts.map((part) => {
889
+ if (part && typeof part === "object" && part.functionResponse) {
890
+ const resp = { ...part.functionResponse };
891
+ if (!resp.id && typeof resp.name === "string") {
892
+ const queue = pendingCallIdsByName.get(resp.name);
893
+ if (queue && queue.length > 0) {
894
+ // Consume the first pending ID (FIFO order)
895
+ resp.id = queue.shift();
896
+ pendingCallIdsByName.set(resp.name, queue);
897
+ }
898
+ }
899
+ return { ...part, functionResponse: resp };
900
+ }
901
+ return part;
902
+ });
903
+ return { ...content, parts: newParts };
904
+ });
905
+ // Third pass: Apply orphan recovery for mismatched tool IDs
906
+ // This handles cases where context compaction or other processes
907
+ // create ID mismatches between calls and responses.
908
+ // Ported from LLM-API-Key-Proxy's _fix_tool_response_grouping()
909
+ requestPayload.contents = fixToolResponseGrouping(requestPayload.contents);
910
+ }
911
+ // Fourth pass: Fix Claude format tool pairing (defense in depth)
912
+ // Handles orphaned tool_use blocks in Claude's messages[] format
913
+ if (Array.isArray(requestPayload.messages)) {
914
+ requestPayload.messages = validateAndFixClaudeToolPairing(requestPayload.messages);
915
+ }
916
+ // =====================================================================
917
+ // LAST RESORT RECOVERY: "Let it crash and start again"
918
+ // =====================================================================
919
+ // If after all our processing we're STILL in a bad state (tool loop without
920
+ // thinking at turn start), don't try to fix it - just close the turn and
921
+ // start fresh. This prevents permanent session breakage.
922
+ //
923
+ // This handles cases where:
924
+ // - Context compaction stripped thinking blocks
925
+ // - Signature cache miss
926
+ // - Any other corruption we couldn't repair
927
+ // - API error indicated thinking_block_order issue (forceThinkingRecovery=true)
928
+ //
929
+ // The synthetic messages allow Claude to generate fresh thinking on the
930
+ // new turn instead of failing with "Expected thinking but found text".
931
+ if (isClaudeThinking && Array.isArray(requestPayload.contents)) {
932
+ const conversationState = analyzeConversationState(requestPayload.contents);
933
+ // Force recovery if API returned thinking_block_order error (retry case)
934
+ // or if proactive check detects we need recovery
935
+ if (forceThinkingRecovery || needsThinkingRecovery(conversationState)) {
936
+ // Set message for toast notification (shown in plugin.ts, respects quiet mode)
937
+ thinkingRecoveryMessage = forceThinkingRecovery
938
+ ? "Thinking recovery: retrying with fresh turn (API error)"
939
+ : "Thinking recovery: restarting turn (corrupted context)";
940
+ requestPayload.contents = closeToolLoopForThinking(requestPayload.contents);
941
+ defaultSignatureStore.delete(signatureSessionKey);
942
+ }
943
+ }
944
+ if ("model" in requestPayload) {
945
+ delete requestPayload.model;
946
+ }
947
+ stripInjectedDebugFromRequestPayload(requestPayload);
948
+ const effectiveProjectId = projectId?.trim() || generateSyntheticProjectId();
949
+ resolvedProjectId = effectiveProjectId;
950
+ const wrappedBody = {
951
+ project: effectiveProjectId,
952
+ model: effectiveModel,
953
+ request: requestPayload,
954
+ };
955
+ // Add additional Antigravity fields
956
+ Object.assign(wrappedBody, {
957
+ userAgent: "antigravity",
958
+ requestId: "agent-" + crypto.randomUUID(),
959
+ });
960
+ if (wrappedBody.request && typeof wrappedBody.request === 'object') {
961
+ // Use stable session ID for signature caching across multi-turn conversations
962
+ sessionId = signatureSessionKey;
963
+ wrappedBody.request.sessionId = signatureSessionKey;
964
+ }
965
+ body = JSON.stringify(wrappedBody);
966
+ }
967
+ }
968
+ catch (error) {
969
+ throw error;
970
+ }
971
+ }
972
+ if (streaming) {
973
+ headers.set("Accept", "text/event-stream");
974
+ }
975
+ // Add interleaved thinking header for Claude thinking models
976
+ // This enables real-time streaming of thinking tokens
977
+ if (isClaudeThinking) {
978
+ const existing = headers.get("anthropic-beta");
979
+ const interleavedHeader = "interleaved-thinking-2025-05-14";
980
+ if (existing) {
981
+ if (!existing.includes(interleavedHeader)) {
982
+ headers.set("anthropic-beta", `${existing},${interleavedHeader}`);
983
+ }
984
+ }
985
+ else {
986
+ headers.set("anthropic-beta", interleavedHeader);
987
+ }
988
+ }
989
+ const selectedHeaders = headerStyle === "gemini-cli" ? GEMINI_CLI_HEADERS : ANTIGRAVITY_HEADERS;
990
+ headers.set("User-Agent", selectedHeaders["User-Agent"]);
991
+ headers.set("X-Goog-Api-Client", selectedHeaders["X-Goog-Api-Client"]);
992
+ headers.set("Client-Metadata", selectedHeaders["Client-Metadata"]);
993
+ // Optional debug header to observe tool normalization on the backend if surfaced
994
+ if (toolDebugMissing > 0) {
995
+ headers.set("X-Opencode-Tools-Debug", String(toolDebugMissing));
996
+ }
997
+ return {
998
+ request: transformedUrl,
999
+ init: {
1000
+ ...baseInit,
1001
+ headers,
1002
+ body,
1003
+ },
1004
+ streaming,
1005
+ requestedModel,
1006
+ effectiveModel: effectiveModel,
1007
+ projectId: resolvedProjectId,
1008
+ endpoint: transformedUrl,
1009
+ sessionId,
1010
+ toolDebugMissing,
1011
+ toolDebugSummary: toolDebugSummaries.slice(0, 20).join(" | "),
1012
+ toolDebugPayload,
1013
+ needsSignedThinkingWarmup,
1014
+ headerStyle,
1015
+ thinkingRecoveryMessage,
1016
+ };
1017
+ }
1018
+ export function buildThinkingWarmupBody(bodyText, isClaudeThinking) {
1019
+ if (!bodyText || !isClaudeThinking) {
1020
+ return null;
1021
+ }
1022
+ let parsed;
1023
+ try {
1024
+ parsed = JSON.parse(bodyText);
1025
+ }
1026
+ catch {
1027
+ return null;
1028
+ }
1029
+ const warmupPrompt = "Warmup request for thinking signature.";
1030
+ const updateRequest = (req) => {
1031
+ req.contents = [{ role: "user", parts: [{ text: warmupPrompt }] }];
1032
+ delete req.tools;
1033
+ delete req.toolConfig;
1034
+ const generationConfig = (req.generationConfig ?? {});
1035
+ generationConfig.thinkingConfig = {
1036
+ include_thoughts: true,
1037
+ thinking_budget: DEFAULT_THINKING_BUDGET,
1038
+ };
1039
+ generationConfig.maxOutputTokens = CLAUDE_THINKING_MAX_OUTPUT_TOKENS;
1040
+ req.generationConfig = generationConfig;
1041
+ };
1042
+ if (parsed.request && typeof parsed.request === "object") {
1043
+ updateRequest(parsed.request);
1044
+ const nested = parsed.request.request;
1045
+ if (nested && typeof nested === "object") {
1046
+ updateRequest(nested);
1047
+ }
1048
+ }
1049
+ else {
1050
+ updateRequest(parsed);
1051
+ }
1052
+ return JSON.stringify(parsed);
1053
+ }
1054
+ /**
1055
+ * Normalizes Antigravity responses: applies retry headers, extracts cache usage into headers,
1056
+ * rewrites preview errors, flattens streaming payloads, and logs debug metadata.
1057
+ *
1058
+ * For streaming SSE responses, uses TransformStream for true real-time incremental streaming.
1059
+ * Thinking/reasoning tokens are transformed and forwarded immediately as they arrive.
1060
+ */
1061
+ export async function transformAntigravityResponse(response, streaming, debugContext, requestedModel, projectId, endpoint, effectiveModel, sessionId, toolDebugMissing, toolDebugSummary, toolDebugPayload, debugLines) {
1062
+ const contentType = response.headers.get("content-type") ?? "";
1063
+ const isJsonResponse = contentType.includes("application/json");
1064
+ const isEventStreamResponse = contentType.includes("text/event-stream");
1065
+ const debugText = isDebugEnabled() && Array.isArray(debugLines) && debugLines.length > 0
1066
+ ? formatDebugLinesForThinking(debugLines)
1067
+ : undefined;
1068
+ const cacheSignatures = shouldCacheThinkingSignatures(effectiveModel);
1069
+ if (!isJsonResponse && !isEventStreamResponse) {
1070
+ logAntigravityDebugResponse(debugContext, response, {
1071
+ note: "Non-JSON response (body omitted)",
1072
+ });
1073
+ return response;
1074
+ }
1075
+ // For successful streaming responses, use TransformStream to transform SSE events
1076
+ // while maintaining real-time streaming (no buffering of entire response).
1077
+ // This enables thinking tokens to be displayed as they arrive, like the Codex plugin.
1078
+ if (streaming && response.ok && isEventStreamResponse && response.body) {
1079
+ const headers = new Headers(response.headers);
1080
+ logAntigravityDebugResponse(debugContext, response, {
1081
+ note: "Streaming SSE response (real-time transform)",
1082
+ });
1083
+ const streamingTransformer = createStreamingTransformer(defaultSignatureStore, {
1084
+ onCacheSignature: cacheSignature,
1085
+ onInjectDebug: injectDebugThinking,
1086
+ transformThinkingParts,
1087
+ }, {
1088
+ signatureSessionKey: sessionId,
1089
+ debugText,
1090
+ cacheSignatures,
1091
+ });
1092
+ return new Response(response.body.pipeThrough(streamingTransformer), {
1093
+ status: response.status,
1094
+ statusText: response.statusText,
1095
+ headers,
1096
+ });
1097
+ }
1098
+ try {
1099
+ const headers = new Headers(response.headers);
1100
+ const text = await response.text();
1101
+ if (!response.ok) {
1102
+ let errorBody;
1103
+ try {
1104
+ errorBody = JSON.parse(text);
1105
+ }
1106
+ catch {
1107
+ errorBody = { error: { message: text } };
1108
+ }
1109
+ // Inject Debug Info
1110
+ if (errorBody?.error) {
1111
+ const debugInfo = `\n\n[Debug Info]\nRequested Model: ${requestedModel || "Unknown"}\nEffective Model: ${effectiveModel || "Unknown"}\nProject: ${projectId || "Unknown"}\nEndpoint: ${endpoint || "Unknown"}\nStatus: ${response.status}\nRequest ID: ${headers.get("x-request-id") || "N/A"}${toolDebugMissing !== undefined ? `\nTool Debug Missing: ${toolDebugMissing}` : ""}${toolDebugSummary ? `\nTool Debug Summary: ${toolDebugSummary}` : ""}${toolDebugPayload ? `\nTool Debug Payload: ${toolDebugPayload}` : ""}`;
1112
+ const injectedDebug = debugText ? `\n\n${debugText}` : "";
1113
+ errorBody.error.message = (errorBody.error.message || "Unknown error") + debugInfo + injectedDebug;
1114
+ // Check if this is a recoverable thinking error - throw to trigger retry
1115
+ const errorType = detectErrorType(errorBody.error.message || "");
1116
+ if (errorType === "thinking_block_order") {
1117
+ const recoveryError = new Error("THINKING_RECOVERY_NEEDED");
1118
+ recoveryError.recoveryType = errorType;
1119
+ recoveryError.originalError = errorBody;
1120
+ recoveryError.debugInfo = debugInfo;
1121
+ throw recoveryError;
1122
+ }
1123
+ // Detect context length / prompt too long errors - signal to caller for toast
1124
+ const errorMessage = errorBody.error.message?.toLowerCase() || "";
1125
+ if (errorMessage.includes("prompt is too long") ||
1126
+ errorMessage.includes("context length exceeded") ||
1127
+ errorMessage.includes("context_length_exceeded") ||
1128
+ errorMessage.includes("maximum context length")) {
1129
+ headers.set("x-antigravity-context-error", "prompt_too_long");
1130
+ }
1131
+ // Detect tool pairing errors - signal to caller for toast
1132
+ if (errorMessage.includes("tool_use") &&
1133
+ errorMessage.includes("tool_result") &&
1134
+ (errorMessage.includes("without") || errorMessage.includes("immediately after"))) {
1135
+ headers.set("x-antigravity-context-error", "tool_pairing");
1136
+ }
1137
+ return new Response(JSON.stringify(errorBody), {
1138
+ status: response.status,
1139
+ statusText: response.statusText,
1140
+ headers
1141
+ });
1142
+ }
1143
+ if (errorBody?.error?.details && Array.isArray(errorBody.error.details)) {
1144
+ const retryInfo = errorBody.error.details.find((detail) => detail['@type'] === 'type.googleapis.com/google.rpc.RetryInfo');
1145
+ if (retryInfo?.retryDelay) {
1146
+ const match = retryInfo.retryDelay.match(/^([\d.]+)s$/);
1147
+ if (match && match[1]) {
1148
+ const retrySeconds = parseFloat(match[1]);
1149
+ if (!isNaN(retrySeconds) && retrySeconds > 0) {
1150
+ const retryAfterSec = Math.ceil(retrySeconds).toString();
1151
+ const retryAfterMs = Math.ceil(retrySeconds * 1000).toString();
1152
+ headers.set('Retry-After', retryAfterSec);
1153
+ headers.set('retry-after-ms', retryAfterMs);
1154
+ }
1155
+ }
1156
+ }
1157
+ }
1158
+ }
1159
+ const init = {
1160
+ status: response.status,
1161
+ statusText: response.statusText,
1162
+ headers,
1163
+ };
1164
+ const usageFromSse = streaming && isEventStreamResponse ? extractUsageFromSsePayload(text) : null;
1165
+ const parsed = !streaming || !isEventStreamResponse ? parseAntigravityApiBody(text) : null;
1166
+ const patched = parsed ? rewriteAntigravityPreviewAccessError(parsed, response.status, requestedModel) : null;
1167
+ const effectiveBody = patched ?? parsed ?? undefined;
1168
+ const usage = usageFromSse ?? (effectiveBody ? extractUsageMetadata(effectiveBody) : null);
1169
+ if (usage?.cachedContentTokenCount !== undefined) {
1170
+ headers.set("x-antigravity-cached-content-token-count", String(usage.cachedContentTokenCount));
1171
+ if (usage.totalTokenCount !== undefined) {
1172
+ headers.set("x-antigravity-total-token-count", String(usage.totalTokenCount));
1173
+ }
1174
+ if (usage.promptTokenCount !== undefined) {
1175
+ headers.set("x-antigravity-prompt-token-count", String(usage.promptTokenCount));
1176
+ }
1177
+ if (usage.candidatesTokenCount !== undefined) {
1178
+ headers.set("x-antigravity-candidates-token-count", String(usage.candidatesTokenCount));
1179
+ }
1180
+ }
1181
+ logAntigravityDebugResponse(debugContext, response, {
1182
+ body: text,
1183
+ note: streaming ? "Streaming SSE payload (buffered fallback)" : undefined,
1184
+ headersOverride: headers,
1185
+ });
1186
+ // Note: successful streaming responses are handled above via TransformStream.
1187
+ // This path only handles non-streaming responses or failed streaming responses.
1188
+ if (!parsed) {
1189
+ return new Response(text, init);
1190
+ }
1191
+ if (effectiveBody?.response !== undefined) {
1192
+ const responseBody = debugText ? injectDebugThinking(effectiveBody.response, debugText) : effectiveBody.response;
1193
+ const transformed = transformThinkingParts(responseBody);
1194
+ return new Response(JSON.stringify(transformed), init);
1195
+ }
1196
+ if (patched) {
1197
+ return new Response(JSON.stringify(patched), init);
1198
+ }
1199
+ return new Response(text, init);
1200
+ }
1201
+ catch (error) {
1202
+ logAntigravityDebugResponse(debugContext, response, {
1203
+ error,
1204
+ note: "Failed to transform Antigravity response",
1205
+ });
1206
+ return response;
1207
+ }
1208
+ }
1209
+ export const __testExports = {
1210
+ buildSignatureSessionKey,
1211
+ hashConversationSeed,
1212
+ extractTextFromContent,
1213
+ extractConversationSeedFromMessages,
1214
+ extractConversationSeedFromContents,
1215
+ resolveConversationKey,
1216
+ resolveProjectKey,
1217
+ isGeminiToolUsePart,
1218
+ isGeminiThinkingPart,
1219
+ ensureThoughtSignature,
1220
+ hasSignedThinkingPart,
1221
+ hasSignedThinkingInContents,
1222
+ hasSignedThinkingInMessages,
1223
+ hasToolUseInContents,
1224
+ hasToolUseInMessages,
1225
+ ensureThinkingBeforeToolUseInContents,
1226
+ ensureThinkingBeforeToolUseInMessages,
1227
+ generateSyntheticProjectId,
1228
+ MIN_SIGNATURE_LENGTH,
1229
+ transformSseLine,
1230
+ transformStreamingPayload,
1231
+ createStreamingTransformer,
1232
+ };
1233
+ //# sourceMappingURL=request.js.map