@benjamolina/opencode-antigravity-guard 1.0.0

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 (243) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +773 -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 +171 -0
  10. package/dist/src/antigravity/oauth.js.map +1 -0
  11. package/dist/src/constants.d.ts +139 -0
  12. package/dist/src/constants.d.ts.map +1 -0
  13. package/dist/src/constants.js +220 -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 +234 -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 +122 -0
  30. package/dist/src/hooks/auto-update-checker/index.js.map +1 -0
  31. package/dist/src/hooks/auto-update-checker/logging.d.ts +3 -0
  32. package/dist/src/hooks/auto-update-checker/logging.d.ts.map +1 -0
  33. package/dist/src/hooks/auto-update-checker/logging.js +9 -0
  34. package/dist/src/hooks/auto-update-checker/logging.js.map +1 -0
  35. package/dist/src/hooks/auto-update-checker/types.d.ts +25 -0
  36. package/dist/src/hooks/auto-update-checker/types.d.ts.map +1 -0
  37. package/dist/src/hooks/auto-update-checker/types.js +1 -0
  38. package/dist/src/hooks/auto-update-checker/types.js.map +1 -0
  39. package/dist/src/plugin/accounts.d.ts +180 -0
  40. package/dist/src/plugin/accounts.d.ts.map +1 -0
  41. package/dist/src/plugin/accounts.js +1045 -0
  42. package/dist/src/plugin/accounts.js.map +1 -0
  43. package/dist/src/plugin/api-key.d.ts +90 -0
  44. package/dist/src/plugin/api-key.d.ts.map +1 -0
  45. package/dist/src/plugin/api-key.js +544 -0
  46. package/dist/src/plugin/api-key.js.map +1 -0
  47. package/dist/src/plugin/auth.d.ts +21 -0
  48. package/dist/src/plugin/auth.d.ts.map +1 -0
  49. package/dist/src/plugin/auth.js +46 -0
  50. package/dist/src/plugin/auth.js.map +1 -0
  51. package/dist/src/plugin/cache/index.d.ts +5 -0
  52. package/dist/src/plugin/cache/index.d.ts.map +1 -0
  53. package/dist/src/plugin/cache/index.js +5 -0
  54. package/dist/src/plugin/cache/index.js.map +1 -0
  55. package/dist/src/plugin/cache/signature-cache.d.ts +111 -0
  56. package/dist/src/plugin/cache/signature-cache.d.ts.map +1 -0
  57. package/dist/src/plugin/cache/signature-cache.js +375 -0
  58. package/dist/src/plugin/cache/signature-cache.js.map +1 -0
  59. package/dist/src/plugin/cache.d.ts +44 -0
  60. package/dist/src/plugin/cache.d.ts.map +1 -0
  61. package/dist/src/plugin/cache.js +200 -0
  62. package/dist/src/plugin/cache.js.map +1 -0
  63. package/dist/src/plugin/cli.d.ts +31 -0
  64. package/dist/src/plugin/cli.d.ts.map +1 -0
  65. package/dist/src/plugin/cli.js +135 -0
  66. package/dist/src/plugin/cli.js.map +1 -0
  67. package/dist/src/plugin/config/index.d.ts +16 -0
  68. package/dist/src/plugin/config/index.d.ts.map +1 -0
  69. package/dist/src/plugin/config/index.js +16 -0
  70. package/dist/src/plugin/config/index.js.map +1 -0
  71. package/dist/src/plugin/config/loader.d.ts +36 -0
  72. package/dist/src/plugin/config/loader.d.ts.map +1 -0
  73. package/dist/src/plugin/config/loader.js +140 -0
  74. package/dist/src/plugin/config/loader.js.map +1 -0
  75. package/dist/src/plugin/config/models.d.ts +43 -0
  76. package/dist/src/plugin/config/models.d.ts.map +1 -0
  77. package/dist/src/plugin/config/models.js +176 -0
  78. package/dist/src/plugin/config/models.js.map +1 -0
  79. package/dist/src/plugin/config/schema.d.ts +177 -0
  80. package/dist/src/plugin/config/schema.d.ts.map +1 -0
  81. package/dist/src/plugin/config/schema.js +507 -0
  82. package/dist/src/plugin/config/schema.js.map +1 -0
  83. package/dist/src/plugin/config/updater.d.ts +55 -0
  84. package/dist/src/plugin/config/updater.d.ts.map +1 -0
  85. package/dist/src/plugin/config/updater.js +125 -0
  86. package/dist/src/plugin/config/updater.js.map +1 -0
  87. package/dist/src/plugin/core/streaming/index.d.ts +3 -0
  88. package/dist/src/plugin/core/streaming/index.d.ts.map +1 -0
  89. package/dist/src/plugin/core/streaming/index.js +3 -0
  90. package/dist/src/plugin/core/streaming/index.js.map +1 -0
  91. package/dist/src/plugin/core/streaming/transformer.d.ts +10 -0
  92. package/dist/src/plugin/core/streaming/transformer.d.ts.map +1 -0
  93. package/dist/src/plugin/core/streaming/transformer.js +271 -0
  94. package/dist/src/plugin/core/streaming/transformer.js.map +1 -0
  95. package/dist/src/plugin/core/streaming/types.d.ts +27 -0
  96. package/dist/src/plugin/core/streaming/types.d.ts.map +1 -0
  97. package/dist/src/plugin/core/streaming/types.js +1 -0
  98. package/dist/src/plugin/core/streaming/types.js.map +1 -0
  99. package/dist/src/plugin/debug.d.ts +99 -0
  100. package/dist/src/plugin/debug.d.ts.map +1 -0
  101. package/dist/src/plugin/debug.js +400 -0
  102. package/dist/src/plugin/debug.js.map +1 -0
  103. package/dist/src/plugin/errors.d.ts +28 -0
  104. package/dist/src/plugin/errors.d.ts.map +1 -0
  105. package/dist/src/plugin/errors.js +42 -0
  106. package/dist/src/plugin/errors.js.map +1 -0
  107. package/dist/src/plugin/fingerprint.d.ts +70 -0
  108. package/dist/src/plugin/fingerprint.d.ts.map +1 -0
  109. package/dist/src/plugin/fingerprint.js +138 -0
  110. package/dist/src/plugin/fingerprint.js.map +1 -0
  111. package/dist/src/plugin/image-saver.d.ts +25 -0
  112. package/dist/src/plugin/image-saver.d.ts.map +1 -0
  113. package/dist/src/plugin/image-saver.js +86 -0
  114. package/dist/src/plugin/image-saver.js.map +1 -0
  115. package/dist/src/plugin/logger.d.ts +36 -0
  116. package/dist/src/plugin/logger.d.ts.map +1 -0
  117. package/dist/src/plugin/logger.js +71 -0
  118. package/dist/src/plugin/logger.js.map +1 -0
  119. package/dist/src/plugin/logging-utils.d.ts +23 -0
  120. package/dist/src/plugin/logging-utils.d.ts.map +1 -0
  121. package/dist/src/plugin/logging-utils.js +92 -0
  122. package/dist/src/plugin/logging-utils.js.map +1 -0
  123. package/dist/src/plugin/project.d.ts +33 -0
  124. package/dist/src/plugin/project.d.ts.map +1 -0
  125. package/dist/src/plugin/project.js +234 -0
  126. package/dist/src/plugin/project.js.map +1 -0
  127. package/dist/src/plugin/quota.d.ts +59 -0
  128. package/dist/src/plugin/quota.d.ts.map +1 -0
  129. package/dist/src/plugin/quota.js +295 -0
  130. package/dist/src/plugin/quota.js.map +1 -0
  131. package/dist/src/plugin/recovery/constants.d.ts +22 -0
  132. package/dist/src/plugin/recovery/constants.d.ts.map +1 -0
  133. package/dist/src/plugin/recovery/constants.js +43 -0
  134. package/dist/src/plugin/recovery/constants.js.map +1 -0
  135. package/dist/src/plugin/recovery/index.d.ts +12 -0
  136. package/dist/src/plugin/recovery/index.d.ts.map +1 -0
  137. package/dist/src/plugin/recovery/index.js +12 -0
  138. package/dist/src/plugin/recovery/index.js.map +1 -0
  139. package/dist/src/plugin/recovery/storage.d.ts +24 -0
  140. package/dist/src/plugin/recovery/storage.d.ts.map +1 -0
  141. package/dist/src/plugin/recovery/storage.js +354 -0
  142. package/dist/src/plugin/recovery/storage.js.map +1 -0
  143. package/dist/src/plugin/recovery/types.d.ts +116 -0
  144. package/dist/src/plugin/recovery/types.d.ts.map +1 -0
  145. package/dist/src/plugin/recovery/types.js +6 -0
  146. package/dist/src/plugin/recovery/types.js.map +1 -0
  147. package/dist/src/plugin/recovery.d.ts +61 -0
  148. package/dist/src/plugin/recovery.d.ts.map +1 -0
  149. package/dist/src/plugin/recovery.js +381 -0
  150. package/dist/src/plugin/recovery.js.map +1 -0
  151. package/dist/src/plugin/refresh-queue.d.ts +100 -0
  152. package/dist/src/plugin/refresh-queue.d.ts.map +1 -0
  153. package/dist/src/plugin/refresh-queue.js +247 -0
  154. package/dist/src/plugin/refresh-queue.js.map +1 -0
  155. package/dist/src/plugin/request-helpers.d.ts +270 -0
  156. package/dist/src/plugin/request-helpers.d.ts.map +1 -0
  157. package/dist/src/plugin/request-helpers.js +2384 -0
  158. package/dist/src/plugin/request-helpers.js.map +1 -0
  159. package/dist/src/plugin/request.d.ts +116 -0
  160. package/dist/src/plugin/request.d.ts.map +1 -0
  161. package/dist/src/plugin/request.js +1626 -0
  162. package/dist/src/plugin/request.js.map +1 -0
  163. package/dist/src/plugin/rotation.d.ts +169 -0
  164. package/dist/src/plugin/rotation.d.ts.map +1 -0
  165. package/dist/src/plugin/rotation.js +328 -0
  166. package/dist/src/plugin/rotation.js.map +1 -0
  167. package/dist/src/plugin/search.d.ts +32 -0
  168. package/dist/src/plugin/search.d.ts.map +1 -0
  169. package/dist/src/plugin/search.js +195 -0
  170. package/dist/src/plugin/search.js.map +1 -0
  171. package/dist/src/plugin/server.d.ts +23 -0
  172. package/dist/src/plugin/server.d.ts.map +1 -0
  173. package/dist/src/plugin/server.js +324 -0
  174. package/dist/src/plugin/server.js.map +1 -0
  175. package/dist/src/plugin/storage.d.ts +137 -0
  176. package/dist/src/plugin/storage.d.ts.map +1 -0
  177. package/dist/src/plugin/storage.js +637 -0
  178. package/dist/src/plugin/storage.js.map +1 -0
  179. package/dist/src/plugin/stores/signature-store.d.ts +5 -0
  180. package/dist/src/plugin/stores/signature-store.d.ts.map +1 -0
  181. package/dist/src/plugin/stores/signature-store.js +25 -0
  182. package/dist/src/plugin/stores/signature-store.js.map +1 -0
  183. package/dist/src/plugin/thinking-recovery.d.ts +90 -0
  184. package/dist/src/plugin/thinking-recovery.d.ts.map +1 -0
  185. package/dist/src/plugin/thinking-recovery.js +316 -0
  186. package/dist/src/plugin/thinking-recovery.js.map +1 -0
  187. package/dist/src/plugin/token.d.ts +19 -0
  188. package/dist/src/plugin/token.d.ts.map +1 -0
  189. package/dist/src/plugin/token.js +128 -0
  190. package/dist/src/plugin/token.js.map +1 -0
  191. package/dist/src/plugin/transform/claude.d.ts +80 -0
  192. package/dist/src/plugin/transform/claude.d.ts.map +1 -0
  193. package/dist/src/plugin/transform/claude.js +265 -0
  194. package/dist/src/plugin/transform/claude.js.map +1 -0
  195. package/dist/src/plugin/transform/cross-model-sanitizer.d.ts +35 -0
  196. package/dist/src/plugin/transform/cross-model-sanitizer.d.ts.map +1 -0
  197. package/dist/src/plugin/transform/cross-model-sanitizer.js +225 -0
  198. package/dist/src/plugin/transform/cross-model-sanitizer.js.map +1 -0
  199. package/dist/src/plugin/transform/gemini.d.ts +100 -0
  200. package/dist/src/plugin/transform/gemini.d.ts.map +1 -0
  201. package/dist/src/plugin/transform/gemini.js +482 -0
  202. package/dist/src/plugin/transform/gemini.js.map +1 -0
  203. package/dist/src/plugin/transform/index.d.ts +15 -0
  204. package/dist/src/plugin/transform/index.d.ts.map +1 -0
  205. package/dist/src/plugin/transform/index.js +14 -0
  206. package/dist/src/plugin/transform/index.js.map +1 -0
  207. package/dist/src/plugin/transform/model-resolver.d.ts +96 -0
  208. package/dist/src/plugin/transform/model-resolver.d.ts.map +1 -0
  209. package/dist/src/plugin/transform/model-resolver.js +444 -0
  210. package/dist/src/plugin/transform/model-resolver.js.map +1 -0
  211. package/dist/src/plugin/transform/types.d.ts +111 -0
  212. package/dist/src/plugin/transform/types.d.ts.map +1 -0
  213. package/dist/src/plugin/transform/types.js +1 -0
  214. package/dist/src/plugin/transform/types.js.map +1 -0
  215. package/dist/src/plugin/types.d.ts +105 -0
  216. package/dist/src/plugin/types.d.ts.map +1 -0
  217. package/dist/src/plugin/types.js +1 -0
  218. package/dist/src/plugin/types.js.map +1 -0
  219. package/dist/src/plugin/ui/ansi.d.ts +32 -0
  220. package/dist/src/plugin/ui/ansi.d.ts.map +1 -0
  221. package/dist/src/plugin/ui/ansi.js +52 -0
  222. package/dist/src/plugin/ui/ansi.js.map +1 -0
  223. package/dist/src/plugin/ui/auth-menu.d.ts +33 -0
  224. package/dist/src/plugin/ui/auth-menu.d.ts.map +1 -0
  225. package/dist/src/plugin/ui/auth-menu.js +110 -0
  226. package/dist/src/plugin/ui/auth-menu.js.map +1 -0
  227. package/dist/src/plugin/ui/confirm.d.ts +2 -0
  228. package/dist/src/plugin/ui/confirm.d.ts.map +1 -0
  229. package/dist/src/plugin/ui/confirm.js +15 -0
  230. package/dist/src/plugin/ui/confirm.js.map +1 -0
  231. package/dist/src/plugin/ui/select.d.ts +23 -0
  232. package/dist/src/plugin/ui/select.d.ts.map +1 -0
  233. package/dist/src/plugin/ui/select.js +254 -0
  234. package/dist/src/plugin/ui/select.js.map +1 -0
  235. package/dist/src/plugin/version.d.ts +19 -0
  236. package/dist/src/plugin/version.d.ts.map +1 -0
  237. package/dist/src/plugin/version.js +80 -0
  238. package/dist/src/plugin/version.js.map +1 -0
  239. package/dist/src/plugin.d.ts +50 -0
  240. package/dist/src/plugin.d.ts.map +1 -0
  241. package/dist/src/plugin.js +3378 -0
  242. package/dist/src/plugin.js.map +1 -0
  243. package/package.json +70 -0
@@ -0,0 +1,1626 @@
1
+ import crypto from "node:crypto";
2
+ import { ANTIGRAVITY_ENDPOINT, GEMINI_CLI_ENDPOINT, GEMINI_CLI_HEADERS, EMPTY_SCHEMA_PLACEHOLDER_NAME, EMPTY_SCHEMA_PLACEHOLDER_DESCRIPTION, SKIP_THOUGHT_SIGNATURE, getRandomizedHeaders, } from "../constants.js";
3
+ import { cacheSignature, getCachedSignature } from "./cache.js";
4
+ import { getKeepThinking } from "./config/index.js";
5
+ import { createStreamingTransformer, transformSseLine, transformStreamingPayload, } from "./core/streaming/index.js";
6
+ import { defaultSignatureStore } from "./stores/signature-store.js";
7
+ import { DEBUG_MESSAGE_PREFIX, isDebugTuiEnabled, logAntigravityDebugResponse, logCacheStats, } from "./debug.js";
8
+ import { createLogger } from "./logger.js";
9
+ import { cleanJSONSchemaForAntigravity, DEFAULT_THINKING_BUDGET, deepFilterThinkingBlocks, extractThinkingConfig, extractVariantThinkingConfig, extractUsageFromSsePayload, extractUsageMetadata, fixToolResponseGrouping, validateAndFixClaudeToolPairing, applyToolPairingFixes, injectParameterSignatures, injectToolHardeningInstruction, isThinkingCapableModel, normalizeThinkingConfig, parseAntigravityApiBody, resolveThinkingConfig, rewriteAntigravityPreviewAccessError, transformThinkingParts, } from "./request-helpers.js";
10
+ import { CLAUDE_TOOL_SYSTEM_INSTRUCTION, CLAUDE_DESCRIPTION_PROMPT, ANTIGRAVITY_SYSTEM_INSTRUCTION, } from "../constants.js";
11
+ import { analyzeConversationState, closeToolLoopForThinking, needsThinkingRecovery, } from "./thinking-recovery.js";
12
+ import { sanitizeCrossModelPayloadInPlace } from "./transform/cross-model-sanitizer.js";
13
+ import { isGemini3Model, isImageGenerationModel, buildImageGenerationConfig, applyGeminiTransforms } from "./transform/index.js";
14
+ import { resolveModelForHeaderStyle, resolveAntigravityGemini35FlashBackendModel, isClaudeModel, isClaudeThinkingModel, CLAUDE_THINKING_MAX_OUTPUT_TOKENS, } from "./transform/index.js";
15
+ import { detectErrorType } from "./recovery.js";
16
+ import { getSessionFingerprint, buildFingerprintHeaders } from "./fingerprint.js";
17
+ const log = createLogger("request");
18
+ const PLUGIN_SESSION_ID = `-${crypto.randomUUID()}`;
19
+ const sessionDisplayedThinkingHashes = new Set();
20
+ const MIN_SIGNATURE_LENGTH = 50;
21
+ function buildSignatureSessionKey(sessionId, model, conversationKey, projectKey) {
22
+ const modelKey = typeof model === "string" && model.trim() ? model.toLowerCase() : "unknown";
23
+ const projectPart = typeof projectKey === "string" && projectKey.trim()
24
+ ? projectKey.trim()
25
+ : "default";
26
+ const conversationPart = typeof conversationKey === "string" && conversationKey.trim()
27
+ ? conversationKey.trim()
28
+ : "default";
29
+ return `${sessionId}:${modelKey}:${projectPart}:${conversationPart}`;
30
+ }
31
+ function shouldCacheThinkingSignatures(model) {
32
+ if (typeof model !== "string")
33
+ return false;
34
+ const lower = model.toLowerCase();
35
+ // Both Claude and Gemini 3 models require thought signature caching
36
+ // for multi-turn conversations with function calling
37
+ return lower.includes("claude") || lower.includes("gemini-3");
38
+ }
39
+ /**
40
+ * Returns the project component to use in the thinking-signature cache key.
41
+ *
42
+ * Gemini 3 thought signatures are content-derived (not project/account-scoped)
43
+ * and the API only strictly validates function calls in the current turn, so we
44
+ * keep Gemini-3's signature cache key project-independent. This preserves
45
+ * reasoning continuity across quota-driven account/project switches: otherwise
46
+ * the key changes on a switch, the cache misses, the validation-bypass sentinel
47
+ * is sent instead of the real signature, and the model loses its chain-of-thought
48
+ * and re-plans the same step forever. Claude keeps project partitioning.
49
+ */
50
+ function signatureCacheProjectKey(model, projectKey) {
51
+ if (typeof model === "string" && model.toLowerCase().includes("gemini-3")) {
52
+ return undefined;
53
+ }
54
+ return projectKey;
55
+ }
56
+ function hashConversationSeed(seed) {
57
+ return crypto.createHash("sha256").update(seed, "utf8").digest("hex").slice(0, 16);
58
+ }
59
+ function extractTextFromContent(content) {
60
+ if (typeof content === "string") {
61
+ return content;
62
+ }
63
+ if (!Array.isArray(content)) {
64
+ return "";
65
+ }
66
+ for (const block of content) {
67
+ if (!block || typeof block !== "object") {
68
+ continue;
69
+ }
70
+ const anyBlock = block;
71
+ if (typeof anyBlock.text === "string") {
72
+ return anyBlock.text;
73
+ }
74
+ if (anyBlock.text && typeof anyBlock.text === "object" && typeof anyBlock.text.text === "string") {
75
+ return anyBlock.text.text;
76
+ }
77
+ }
78
+ return "";
79
+ }
80
+ function extractConversationSeedFromMessages(messages) {
81
+ const system = messages.find((message) => message?.role === "system");
82
+ const users = messages.filter((message) => message?.role === "user");
83
+ const firstUser = users[0];
84
+ const lastUser = users.length > 0 ? users[users.length - 1] : undefined;
85
+ const systemText = system ? extractTextFromContent(system.content) : "";
86
+ const userText = firstUser ? extractTextFromContent(firstUser.content) : "";
87
+ const fallbackUserText = !userText && lastUser ? extractTextFromContent(lastUser.content) : "";
88
+ return [systemText, userText || fallbackUserText].filter(Boolean).join("|");
89
+ }
90
+ function extractConversationSeedFromContents(contents) {
91
+ const users = contents.filter((content) => content?.role === "user");
92
+ const firstUser = users[0];
93
+ const lastUser = users.length > 0 ? users[users.length - 1] : undefined;
94
+ const primaryUser = firstUser && Array.isArray(firstUser.parts) ? extractTextFromContent(firstUser.parts) : "";
95
+ if (primaryUser) {
96
+ return primaryUser;
97
+ }
98
+ if (lastUser && Array.isArray(lastUser.parts)) {
99
+ return extractTextFromContent(lastUser.parts);
100
+ }
101
+ return "";
102
+ }
103
+ function resolveConversationKey(requestPayload) {
104
+ const anyPayload = requestPayload;
105
+ const candidates = [
106
+ anyPayload.conversationId,
107
+ anyPayload.conversation_id,
108
+ anyPayload.thread_id,
109
+ anyPayload.threadId,
110
+ anyPayload.chat_id,
111
+ anyPayload.chatId,
112
+ anyPayload.sessionId,
113
+ anyPayload.session_id,
114
+ anyPayload.metadata?.conversation_id,
115
+ anyPayload.metadata?.conversationId,
116
+ anyPayload.metadata?.thread_id,
117
+ anyPayload.metadata?.threadId,
118
+ ];
119
+ for (const candidate of candidates) {
120
+ if (typeof candidate === "string" && candidate.trim()) {
121
+ return candidate.trim();
122
+ }
123
+ }
124
+ const systemSeed = extractTextFromContent(anyPayload.systemInstruction?.parts
125
+ ?? anyPayload.systemInstruction
126
+ ?? anyPayload.system
127
+ ?? anyPayload.system_instruction);
128
+ const messageSeed = Array.isArray(anyPayload.messages)
129
+ ? extractConversationSeedFromMessages(anyPayload.messages)
130
+ : Array.isArray(anyPayload.contents)
131
+ ? extractConversationSeedFromContents(anyPayload.contents)
132
+ : "";
133
+ const seed = [systemSeed, messageSeed].filter(Boolean).join("|");
134
+ if (!seed) {
135
+ return undefined;
136
+ }
137
+ return `seed-${hashConversationSeed(seed)}`;
138
+ }
139
+ function resolveConversationKeyFromRequests(requestObjects) {
140
+ for (const req of requestObjects) {
141
+ const key = resolveConversationKey(req);
142
+ if (key) {
143
+ return key;
144
+ }
145
+ }
146
+ return undefined;
147
+ }
148
+ function resolveProjectKey(candidate, fallback) {
149
+ if (typeof candidate === "string" && candidate.trim()) {
150
+ return candidate.trim();
151
+ }
152
+ if (typeof fallback === "string" && fallback.trim()) {
153
+ return fallback.trim();
154
+ }
155
+ return undefined;
156
+ }
157
+ function formatDebugLinesForThinking(lines) {
158
+ const cleaned = lines
159
+ .map((line) => line.trim())
160
+ .filter((line) => line.length > 0)
161
+ .slice(-50);
162
+ const prelude = `[ThinkingResolution] source=debug_tui lines=${cleaned.length}`;
163
+ return `${DEBUG_MESSAGE_PREFIX}\n- ${prelude}\n${cleaned.map((line) => `- ${line}`).join("\n")}`;
164
+ }
165
+ function injectDebugThinking(response, debugText) {
166
+ if (!response || typeof response !== "object") {
167
+ return response;
168
+ }
169
+ const resp = response;
170
+ if (Array.isArray(resp.candidates) && resp.candidates.length > 0) {
171
+ const candidates = resp.candidates.slice();
172
+ const first = candidates[0];
173
+ if (first &&
174
+ typeof first === "object" &&
175
+ first.content &&
176
+ typeof first.content === "object" &&
177
+ Array.isArray(first.content.parts)) {
178
+ const parts = [{ thought: true, text: debugText }, ...first.content.parts];
179
+ candidates[0] = { ...first, content: { ...first.content, parts } };
180
+ return { ...resp, candidates };
181
+ }
182
+ return resp;
183
+ }
184
+ if (Array.isArray(resp.content)) {
185
+ const content = [{ type: "thinking", thinking: debugText }, ...resp.content];
186
+ return { ...resp, content };
187
+ }
188
+ if (!resp.reasoning_content) {
189
+ return { ...resp, reasoning_content: debugText };
190
+ }
191
+ return resp;
192
+ }
193
+ /**
194
+ * Synthetic thinking placeholder text used when keep_thinking=true but debug mode is off.
195
+ * Injected via the same path as debug text (injectDebugThinking) to ensure consistent
196
+ * signature caching and multi-turn handling.
197
+ */
198
+ const SYNTHETIC_THINKING_PLACEHOLDER = "[Thinking preserved]\n";
199
+ function stripInjectedDebugFromParts(parts) {
200
+ if (!Array.isArray(parts)) {
201
+ return parts;
202
+ }
203
+ return parts.filter((part) => {
204
+ if (!part || typeof part !== "object") {
205
+ return true;
206
+ }
207
+ const record = part;
208
+ const text = typeof record.text === "string"
209
+ ? record.text
210
+ : typeof record.thinking === "string"
211
+ ? record.thinking
212
+ : undefined;
213
+ // Strip debug blocks and synthetic thinking placeholders
214
+ if (text && (text.startsWith(DEBUG_MESSAGE_PREFIX) || text.startsWith(SYNTHETIC_THINKING_PLACEHOLDER.trim()))) {
215
+ return false;
216
+ }
217
+ return true;
218
+ });
219
+ }
220
+ function stripInjectedDebugFromRequestPayload(payload) {
221
+ const anyPayload = payload;
222
+ if (Array.isArray(anyPayload.contents)) {
223
+ anyPayload.contents = anyPayload.contents.map((content) => {
224
+ if (!content || typeof content !== "object") {
225
+ return content;
226
+ }
227
+ if (Array.isArray(content.parts)) {
228
+ return { ...content, parts: stripInjectedDebugFromParts(content.parts) };
229
+ }
230
+ if (Array.isArray(content.content)) {
231
+ return { ...content, content: stripInjectedDebugFromParts(content.content) };
232
+ }
233
+ return content;
234
+ });
235
+ }
236
+ if (Array.isArray(anyPayload.messages)) {
237
+ anyPayload.messages = anyPayload.messages.map((message) => {
238
+ if (!message || typeof message !== "object") {
239
+ return message;
240
+ }
241
+ if (Array.isArray(message.content)) {
242
+ return { ...message, content: stripInjectedDebugFromParts(message.content) };
243
+ }
244
+ return message;
245
+ });
246
+ }
247
+ }
248
+ function isValidRequestPart(part) {
249
+ if (!part || typeof part !== "object") {
250
+ return false;
251
+ }
252
+ const record = part;
253
+ return (Object.prototype.hasOwnProperty.call(record, "text") ||
254
+ Object.prototype.hasOwnProperty.call(record, "functionCall") ||
255
+ Object.prototype.hasOwnProperty.call(record, "functionResponse") ||
256
+ Object.prototype.hasOwnProperty.call(record, "inlineData") ||
257
+ Object.prototype.hasOwnProperty.call(record, "fileData") ||
258
+ Object.prototype.hasOwnProperty.call(record, "executableCode") ||
259
+ Object.prototype.hasOwnProperty.call(record, "codeExecutionResult") ||
260
+ Object.prototype.hasOwnProperty.call(record, "thought"));
261
+ }
262
+ function sanitizeRequestPayloadForAntigravity(payload, restore) {
263
+ const anyPayload = payload;
264
+ if (Array.isArray(anyPayload.contents)) {
265
+ anyPayload.contents = anyPayload.contents
266
+ .map((content) => {
267
+ if (!content || typeof content !== "object") {
268
+ return null;
269
+ }
270
+ const contentRecord = content;
271
+ const rawParts = Array.isArray(contentRecord.parts) ? contentRecord.parts : [];
272
+ let foundFirstFunctionCall = false;
273
+ // Gemini 3 multi-turn function calling requires the model's prior
274
+ // thoughtSignature to be replayed so it can continue its signed
275
+ // chain-of-thought. When enabled, recover the real signature we cached
276
+ // from the response (keyed by this block's thinking text) and use it
277
+ // instead of the validation-bypass sentinel. Without this the model
278
+ // loses reasoning continuity and re-plans the same step forever.
279
+ let restoredThoughtSignature;
280
+ if (restore?.sessionKey) {
281
+ for (const candidatePart of rawParts) {
282
+ if (!candidatePart || typeof candidatePart !== "object" || candidatePart.thought !== true) {
283
+ continue;
284
+ }
285
+ const thoughtText = getThinkingPartText(candidatePart);
286
+ if (!thoughtText) {
287
+ continue;
288
+ }
289
+ const cached = restore.getSignature(restore.sessionKey, thoughtText);
290
+ if (cached && cached.length >= MIN_SIGNATURE_LENGTH && cached !== SKIP_THOUGHT_SIGNATURE) {
291
+ restoredThoughtSignature = cached;
292
+ break;
293
+ }
294
+ }
295
+ }
296
+ const sanitizedParts = rawParts.filter(isValidRequestPart).map((part) => {
297
+ if (part && typeof part === "object" && part.functionCall) {
298
+ let sig = part.thoughtSignature || part.thought_signature;
299
+ // Only the first functionCall part in a block should have the signature.
300
+ // If it's the first one and missing a valid signature, inject the sentinel
301
+ // to prevent the API from rejecting the request with a 400 error.
302
+ if (!foundFirstFunctionCall) {
303
+ foundFirstFunctionCall = true;
304
+ if (!sig || sig.length < MIN_SIGNATURE_LENGTH) {
305
+ sig = restoredThoughtSignature ?? SKIP_THOUGHT_SIGNATURE;
306
+ }
307
+ }
308
+ else {
309
+ // Parallel function calls MUST NOT have a signature
310
+ sig = undefined;
311
+ }
312
+ if (sig) {
313
+ return { ...part, thought_signature: sig, thoughtSignature: sig };
314
+ }
315
+ // If not the first part, just return the part without adding any signature keys
316
+ const newPart = { ...part };
317
+ delete newPart.thoughtSignature;
318
+ delete newPart.thought_signature;
319
+ return newPart;
320
+ }
321
+ return part;
322
+ });
323
+ if (sanitizedParts.length === 0) {
324
+ return null;
325
+ }
326
+ return {
327
+ ...contentRecord,
328
+ parts: sanitizedParts,
329
+ };
330
+ })
331
+ .filter((content) => content !== null);
332
+ }
333
+ const systemInstruction = anyPayload.systemInstruction;
334
+ if (systemInstruction && typeof systemInstruction === "object" && !Array.isArray(systemInstruction)) {
335
+ const sys = systemInstruction;
336
+ if (Array.isArray(sys.parts)) {
337
+ const sanitizedSystemParts = sys.parts.filter(isValidRequestPart);
338
+ if (sanitizedSystemParts.length > 0) {
339
+ sys.parts = sanitizedSystemParts;
340
+ }
341
+ else {
342
+ delete anyPayload.systemInstruction;
343
+ }
344
+ }
345
+ }
346
+ }
347
+ function isGeminiToolUsePart(part) {
348
+ return !!(part && typeof part === "object" && (part.functionCall || part.tool_use || part.toolUse));
349
+ }
350
+ function isGeminiThinkingPart(part) {
351
+ return !!(part &&
352
+ typeof part === "object" &&
353
+ (part.thought === true || part.type === "thinking" || part.type === "reasoning"));
354
+ }
355
+ // Sentinel value used when signature recovery fails - allows Claude to handle gracefully
356
+ // by redacting the thinking block instead of rejecting the request entirely.
357
+ // Reference: LLM-API-Key-Proxy uses this pattern for Gemini 3 tool calls.
358
+ const SENTINEL_SIGNATURE = "skip_thought_signature_validator";
359
+ function getThinkingPartText(part) {
360
+ if (!part || typeof part !== "object") {
361
+ return "";
362
+ }
363
+ if (typeof part.text === "string") {
364
+ return part.text;
365
+ }
366
+ if (typeof part.thinking === "string") {
367
+ return part.thinking;
368
+ }
369
+ return "";
370
+ }
371
+ function hasCachedMatchingSignature(part, sessionId) {
372
+ if (!part || typeof part !== "object") {
373
+ return false;
374
+ }
375
+ const text = getThinkingPartText(part);
376
+ if (!text) {
377
+ return false;
378
+ }
379
+ const expectedSignature = getCachedSignature(sessionId, text);
380
+ if (!expectedSignature) {
381
+ return false;
382
+ }
383
+ if (part.thought === true) {
384
+ return part.thoughtSignature === expectedSignature;
385
+ }
386
+ return part.signature === expectedSignature;
387
+ }
388
+ function ensureThoughtSignature(part, sessionId) {
389
+ if (!part || typeof part !== "object") {
390
+ return part;
391
+ }
392
+ if (!sessionId) {
393
+ return part;
394
+ }
395
+ const text = getThinkingPartText(part);
396
+ if (!text) {
397
+ return part;
398
+ }
399
+ if (part.thought === true) {
400
+ return { ...part, thoughtSignature: SENTINEL_SIGNATURE };
401
+ }
402
+ if (part.type === "thinking" || part.type === "reasoning" || part.type === "redacted_thinking") {
403
+ return { ...part, signature: SENTINEL_SIGNATURE };
404
+ }
405
+ return part;
406
+ }
407
+ function hasSignedThinkingPart(part, sessionId) {
408
+ if (!part || typeof part !== "object") {
409
+ return false;
410
+ }
411
+ if (part.thought === true) {
412
+ if (part.thoughtSignature === SENTINEL_SIGNATURE || part.thoughtSignature === SKIP_THOUGHT_SIGNATURE) {
413
+ return true;
414
+ }
415
+ if (typeof part.thoughtSignature !== "string" || part.thoughtSignature.length < MIN_SIGNATURE_LENGTH) {
416
+ return false;
417
+ }
418
+ if (!sessionId) {
419
+ return true;
420
+ }
421
+ return hasCachedMatchingSignature(part, sessionId);
422
+ }
423
+ if (part.type === "thinking" || part.type === "reasoning" || part.type === "redacted_thinking") {
424
+ if (part.signature === SENTINEL_SIGNATURE || part.signature === SKIP_THOUGHT_SIGNATURE) {
425
+ return true;
426
+ }
427
+ if (typeof part.signature !== "string" || part.signature.length < MIN_SIGNATURE_LENGTH) {
428
+ return false;
429
+ }
430
+ if (!sessionId) {
431
+ return true;
432
+ }
433
+ return hasCachedMatchingSignature(part, sessionId);
434
+ }
435
+ return false;
436
+ }
437
+ function ensureThinkingBeforeToolUseInContents(contents, signatureSessionKey) {
438
+ return contents.map((content) => {
439
+ if (!content || typeof content !== "object" || !Array.isArray(content.parts)) {
440
+ return content;
441
+ }
442
+ const role = content.role;
443
+ if (role !== "model" && role !== "assistant") {
444
+ return content;
445
+ }
446
+ const parts = content.parts;
447
+ const hasToolUse = parts.some(isGeminiToolUsePart);
448
+ if (!hasToolUse) {
449
+ return content;
450
+ }
451
+ const thinkingParts = parts.filter(isGeminiThinkingPart).map((p) => ensureThoughtSignature(p, signatureSessionKey));
452
+ const otherParts = parts.filter((p) => !isGeminiThinkingPart(p));
453
+ const hasSignedThinking = thinkingParts.some((part) => hasSignedThinkingPart(part, signatureSessionKey));
454
+ if (hasSignedThinking) {
455
+ return { ...content, parts: [...thinkingParts, ...otherParts] };
456
+ }
457
+ const lastThinking = defaultSignatureStore.get(signatureSessionKey);
458
+ if (!lastThinking) {
459
+ // No cached signature available - strip thinking blocks entirely
460
+ // Claude requires valid signatures, and we can't fake them
461
+ // Return only tool_use parts without any thinking to avoid signature validation errors
462
+ log.debug("Stripping thinking from tool_use content (no valid cached signature)", { signatureSessionKey });
463
+ return { ...content, parts: otherParts };
464
+ }
465
+ const injected = {
466
+ thought: true,
467
+ text: lastThinking.text,
468
+ thoughtSignature: SENTINEL_SIGNATURE,
469
+ };
470
+ return { ...content, parts: [injected, ...otherParts] };
471
+ });
472
+ }
473
+ function ensureMessageThinkingSignature(block, sessionId) {
474
+ if (!block || typeof block !== "object") {
475
+ return block;
476
+ }
477
+ if (block.type !== "thinking" && block.type !== "redacted_thinking") {
478
+ return block;
479
+ }
480
+ const text = getThinkingPartText(block);
481
+ if (!text) {
482
+ return block;
483
+ }
484
+ if (!sessionId) {
485
+ return block;
486
+ }
487
+ return { ...block, signature: SKIP_THOUGHT_SIGNATURE };
488
+ }
489
+ function hasToolUseInContents(contents) {
490
+ return contents.some((content) => {
491
+ if (!content || typeof content !== "object" || !Array.isArray(content.parts)) {
492
+ return false;
493
+ }
494
+ return content.parts.some(isGeminiToolUsePart);
495
+ });
496
+ }
497
+ function hasSignedThinkingInContents(contents, sessionId) {
498
+ return contents.some((content) => {
499
+ if (!content || typeof content !== "object" || !Array.isArray(content.parts)) {
500
+ return false;
501
+ }
502
+ return content.parts.some((part) => hasSignedThinkingPart(part, sessionId));
503
+ });
504
+ }
505
+ function hasToolUseInMessages(messages) {
506
+ return messages.some((message) => {
507
+ if (!message || typeof message !== "object" || !Array.isArray(message.content)) {
508
+ return false;
509
+ }
510
+ return message.content.some((block) => block && typeof block === "object" && (block.type === "tool_use" || block.type === "tool_result"));
511
+ });
512
+ }
513
+ function hasSignedThinkingInMessages(messages, sessionId) {
514
+ return messages.some((message) => {
515
+ if (!message || typeof message !== "object" || !Array.isArray(message.content)) {
516
+ return false;
517
+ }
518
+ return message.content.some((block) => hasSignedThinkingPart(block, sessionId));
519
+ });
520
+ }
521
+ function ensureThinkingBeforeToolUseInMessages(messages, signatureSessionKey) {
522
+ return messages.map((message) => {
523
+ if (!message || typeof message !== "object" || !Array.isArray(message.content)) {
524
+ return message;
525
+ }
526
+ if (message.role !== "assistant") {
527
+ return message;
528
+ }
529
+ const blocks = message.content;
530
+ const hasToolUse = blocks.some((b) => b && typeof b === "object" && (b.type === "tool_use" || b.type === "tool_result"));
531
+ if (!hasToolUse) {
532
+ return message;
533
+ }
534
+ const thinkingBlocks = blocks
535
+ .filter((b) => b && typeof b === "object" && (b.type === "thinking" || b.type === "redacted_thinking"))
536
+ .map((b) => ensureMessageThinkingSignature(b, signatureSessionKey));
537
+ const otherBlocks = blocks.filter((b) => !(b && typeof b === "object" && (b.type === "thinking" || b.type === "redacted_thinking")));
538
+ const hasSignedThinking = thinkingBlocks.some((block) => hasSignedThinkingPart(block, signatureSessionKey));
539
+ if (hasSignedThinking) {
540
+ return { ...message, content: [...thinkingBlocks, ...otherBlocks] };
541
+ }
542
+ const lastThinking = defaultSignatureStore.get(signatureSessionKey);
543
+ if (!lastThinking) {
544
+ // No cached signature available - use sentinel to bypass validation
545
+ // This handles cache miss scenarios (restart, session mismatch, expiry)
546
+ const existingThinking = thinkingBlocks[0];
547
+ const thinkingText = existingThinking?.thinking || existingThinking?.text || "";
548
+ log.debug("Injecting sentinel signature (cache miss)", { signatureSessionKey });
549
+ const sentinelBlock = {
550
+ type: "thinking",
551
+ thinking: thinkingText,
552
+ signature: SKIP_THOUGHT_SIGNATURE,
553
+ };
554
+ return { ...message, content: [sentinelBlock, ...otherBlocks] };
555
+ }
556
+ const injected = {
557
+ type: "thinking",
558
+ thinking: lastThinking.text,
559
+ signature: SKIP_THOUGHT_SIGNATURE,
560
+ };
561
+ return { ...message, content: [injected, ...otherBlocks] };
562
+ });
563
+ }
564
+ /**
565
+ * Gets the stable session ID for this plugin instance.
566
+ */
567
+ export function getPluginSessionId() {
568
+ return PLUGIN_SESSION_ID;
569
+ }
570
+ function generateSyntheticProjectId() {
571
+ const adjectives = ["useful", "bright", "swift", "calm", "bold"];
572
+ const nouns = ["fuze", "wave", "spark", "flow", "core"];
573
+ const adj = adjectives[Math.floor(Math.random() * adjectives.length)];
574
+ const noun = nouns[Math.floor(Math.random() * nouns.length)];
575
+ const randomPart = crypto.randomUUID().slice(0, 5).toLowerCase();
576
+ return `${adj}-${noun}-${randomPart}`;
577
+ }
578
+ function ensureDefaultGemini3ThinkingLevel(requestPayload, effectiveModel, thinkingLevel) {
579
+ if (!effectiveModel.toLowerCase().includes("gemini-3") || isImageGenerationModel(effectiveModel)) {
580
+ return;
581
+ }
582
+ const generationConfig = requestPayload.generationConfig && typeof requestPayload.generationConfig === "object"
583
+ ? requestPayload.generationConfig
584
+ : {};
585
+ const thinkingConfig = generationConfig.thinkingConfig && typeof generationConfig.thinkingConfig === "object"
586
+ ? generationConfig.thinkingConfig
587
+ : {};
588
+ if (typeof thinkingConfig.thinkingLevel !== "string") {
589
+ thinkingConfig.thinkingLevel = thinkingLevel ?? "low";
590
+ }
591
+ if (typeof thinkingConfig.includeThoughts !== "boolean") {
592
+ thinkingConfig.includeThoughts = true;
593
+ }
594
+ generationConfig.thinkingConfig = thinkingConfig;
595
+ requestPayload.generationConfig = generationConfig;
596
+ }
597
+ const STREAM_ACTION = "streamGenerateContent";
598
+ function mergeRequestHeaders(requestHeaders, initHeaders) {
599
+ if (!requestHeaders && !initHeaders)
600
+ return undefined;
601
+ const headers = new Headers(requestHeaders);
602
+ if (initHeaders) {
603
+ new Headers(initHeaders).forEach((value, key) => {
604
+ headers.set(key, value);
605
+ });
606
+ }
607
+ return headers;
608
+ }
609
+ function initFromRequest(request, init, body) {
610
+ if (!request)
611
+ return { ...init };
612
+ const merged = {
613
+ method: request.method,
614
+ body: body ?? request.body,
615
+ signal: request.signal,
616
+ redirect: request.redirect,
617
+ credentials: request.credentials,
618
+ cache: request.cache,
619
+ referrer: request.referrer,
620
+ referrerPolicy: request.referrerPolicy,
621
+ mode: request.mode,
622
+ integrity: request.integrity,
623
+ keepalive: request.keepalive,
624
+ ...init,
625
+ headers: mergeRequestHeaders(request.headers, init?.headers),
626
+ };
627
+ if (merged.body instanceof ReadableStream && merged.duplex === undefined) {
628
+ merged.duplex = "half";
629
+ }
630
+ return merged;
631
+ }
632
+ /**
633
+ * Detects requests headed to the Google Generative Language API so we can intercept them.
634
+ */
635
+ export function isGenerativeLanguageRequest(input) {
636
+ try {
637
+ return new URL(requestInfoUrl(input)).hostname === "generativelanguage.googleapis.com";
638
+ }
639
+ catch {
640
+ return false;
641
+ }
642
+ }
643
+ function requestInfoUrl(input) {
644
+ if (typeof input === "string")
645
+ return input;
646
+ return input.url || input.toString();
647
+ }
648
+ export function prepareAntigravityRequest(input, init, accessToken, projectId, endpointOverride, headerStyle = "antigravity", forceThinkingRecovery = false, options) {
649
+ if (typeof input !== "string" && init?.body === undefined && input.body) {
650
+ const requestInput = input;
651
+ return requestInput.clone().text()
652
+ .then((body) => prepareAntigravityRequest(requestInput.url, initFromRequest(requestInput, init, body), accessToken, projectId, endpointOverride, headerStyle, forceThinkingRecovery, options))
653
+ .catch(() => prepareAntigravityRequest(requestInput.url, initFromRequest(requestInput, init), accessToken, projectId, endpointOverride, headerStyle, forceThinkingRecovery, options));
654
+ }
655
+ const requestUrl = requestInfoUrl(input);
656
+ const requestInput = typeof input === "string" ? undefined : input;
657
+ const baseInit = initFromRequest(requestInput, init);
658
+ const headers = new Headers(baseInit.headers);
659
+ let resolvedProjectId = projectId?.trim() || "";
660
+ let toolDebugMissing = 0;
661
+ const toolDebugSummaries = [];
662
+ let toolDebugPayload;
663
+ let sessionId;
664
+ let needsSignedThinkingWarmup = false;
665
+ let thinkingRecoveryMessage;
666
+ if (!isGenerativeLanguageRequest(input)) {
667
+ return {
668
+ request: input,
669
+ init: { ...baseInit, headers },
670
+ streaming: false,
671
+ headerStyle,
672
+ };
673
+ }
674
+ headers.set("Authorization", `Bearer ${accessToken}`);
675
+ headers.delete("x-api-key");
676
+ headers.delete("x-goog-api-key");
677
+ // Strip x-goog-user-project header to prevent 403 auth/license conflicts.
678
+ // This header is added by OpenCode/AI SDK and can force project-level checks
679
+ // that are not required for Antigravity/Gemini CLI OAuth requests.
680
+ headers.delete("x-goog-user-project");
681
+ const match = requestUrl.match(/\/models\/([^:]+):(\w+)/);
682
+ if (!match) {
683
+ return {
684
+ request: input,
685
+ init: { ...baseInit, headers },
686
+ streaming: false,
687
+ headerStyle,
688
+ };
689
+ }
690
+ const [, rawModel = "", rawAction = ""] = match;
691
+ const requestedModel = rawModel;
692
+ const resolved = resolveModelForHeaderStyle(rawModel, headerStyle);
693
+ let effectiveModel = resolved.actualModel;
694
+ const streaming = rawAction === STREAM_ACTION;
695
+ const defaultEndpoint = headerStyle === "gemini-cli" ? GEMINI_CLI_ENDPOINT : ANTIGRAVITY_ENDPOINT;
696
+ const baseEndpoint = endpointOverride ?? defaultEndpoint;
697
+ const transformedUrl = `${baseEndpoint}/v1internal:${rawAction}${streaming ? "?alt=sse" : ""}`;
698
+ const isClaude = isClaudeModel(resolved.actualModel);
699
+ const isClaudeThinking = isClaudeThinkingModel(resolved.actualModel);
700
+ const keepThinkingEnabled = getKeepThinking();
701
+ const enableClaudePromptAutoCaching = options?.claudePromptAutoCaching ?? false;
702
+ // Tier-based thinking configuration from model resolver (can be overridden by variant config)
703
+ let tierThinkingBudget = resolved.thinkingBudget;
704
+ let tierThinkingLevel = resolved.thinkingLevel;
705
+ let signatureSessionKey = buildSignatureSessionKey(PLUGIN_SESSION_ID, effectiveModel, undefined, signatureCacheProjectKey(effectiveModel, resolveProjectKey(projectId)));
706
+ let body = baseInit.body;
707
+ if (typeof baseInit.body === "string" && baseInit.body) {
708
+ try {
709
+ const parsedBody = JSON.parse(baseInit.body);
710
+ const isWrapped = typeof parsedBody.project === "string" && "request" in parsedBody;
711
+ if (isWrapped) {
712
+ const wrappedBody = {
713
+ ...parsedBody,
714
+ model: effectiveModel,
715
+ };
716
+ // Some callers may already send an Antigravity-wrapped body.
717
+ // We still need to sanitize Claude thinking blocks (remove cache_control)
718
+ // and attach a stable sessionId so multi-turn signature caching works.
719
+ const requestRoot = wrappedBody.request;
720
+ const requestObjects = [];
721
+ if (requestRoot && typeof requestRoot === "object") {
722
+ requestObjects.push(requestRoot);
723
+ const nested = requestRoot.request;
724
+ if (nested && typeof nested === "object") {
725
+ requestObjects.push(nested);
726
+ }
727
+ }
728
+ if (effectiveModel.toLowerCase().includes("gemini-3")) {
729
+ for (const req of requestObjects) {
730
+ const variantConfig = extractVariantThinkingConfig(req.providerOptions, req.generationConfig);
731
+ if (variantConfig?.thinkingLevel) {
732
+ tierThinkingLevel = variantConfig.thinkingLevel;
733
+ tierThinkingBudget = undefined;
734
+ break;
735
+ }
736
+ if (typeof variantConfig?.thinkingBudget === "number") {
737
+ tierThinkingLevel = variantConfig.thinkingBudget <= 8192 ? "low"
738
+ : variantConfig.thinkingBudget <= 16384 ? "medium" : "high";
739
+ tierThinkingBudget = undefined;
740
+ break;
741
+ }
742
+ }
743
+ }
744
+ if (headerStyle === "antigravity") {
745
+ const gemini35FlashBackendModel = resolveAntigravityGemini35FlashBackendModel(rawModel, tierThinkingLevel);
746
+ if (gemini35FlashBackendModel) {
747
+ effectiveModel = gemini35FlashBackendModel;
748
+ wrappedBody.model = gemini35FlashBackendModel;
749
+ }
750
+ }
751
+ const conversationKey = resolveConversationKeyFromRequests(requestObjects);
752
+ // Strip tier suffix from model for cache key to prevent cache misses on tier change
753
+ // e.g., "claude-opus-4-6-thinking-high" -> "claude-opus-4-6-thinking"
754
+ const modelForCacheKey = effectiveModel.replace(/-(minimal|low|medium|high)$/i, "");
755
+ signatureSessionKey = buildSignatureSessionKey(PLUGIN_SESSION_ID, modelForCacheKey, conversationKey, signatureCacheProjectKey(modelForCacheKey, resolveProjectKey(parsedBody.project)));
756
+ if (requestObjects.length > 0) {
757
+ sessionId = signatureSessionKey;
758
+ }
759
+ for (const req of requestObjects) {
760
+ // Use stable session ID for signature caching across multi-turn conversations
761
+ req.sessionId = signatureSessionKey;
762
+ stripInjectedDebugFromRequestPayload(req);
763
+ ensureDefaultGemini3ThinkingLevel(req, effectiveModel, tierThinkingLevel);
764
+ if (isClaude) {
765
+ // Step 0: Sanitize cross-model metadata (strips Gemini signatures when sending to Claude)
766
+ sanitizeCrossModelPayloadInPlace(req, { targetModel: effectiveModel });
767
+ // Step 1: Strip corrupted/unsigned thinking blocks FIRST
768
+ deepFilterThinkingBlocks(req, signatureSessionKey, getCachedSignature, true);
769
+ if (enableClaudePromptAutoCaching && req.cache_control === undefined) {
770
+ req.cache_control = { type: "ephemeral" };
771
+ }
772
+ // Step 2: THEN inject signed thinking from cache (after stripping)
773
+ if (isClaudeThinking && keepThinkingEnabled && Array.isArray(req.contents)) {
774
+ req.contents = ensureThinkingBeforeToolUseInContents(req.contents, signatureSessionKey);
775
+ }
776
+ if (isClaudeThinking && keepThinkingEnabled && Array.isArray(req.messages)) {
777
+ req.messages = ensureThinkingBeforeToolUseInMessages(req.messages, signatureSessionKey);
778
+ }
779
+ // Step 3: Apply tool pairing fixes (ID assignment, response matching, orphan recovery)
780
+ applyToolPairingFixes(req, true);
781
+ }
782
+ }
783
+ if (isClaudeThinking && keepThinkingEnabled && sessionId) {
784
+ const hasToolUse = requestObjects.some((req) => (Array.isArray(req.contents) && hasToolUseInContents(req.contents)) ||
785
+ (Array.isArray(req.messages) && hasToolUseInMessages(req.messages)));
786
+ const hasSignedThinking = requestObjects.some((req) => (Array.isArray(req.contents) && hasSignedThinkingInContents(req.contents, signatureSessionKey)) ||
787
+ (Array.isArray(req.messages) && hasSignedThinkingInMessages(req.messages, signatureSessionKey)));
788
+ const hasCachedThinking = defaultSignatureStore.has(signatureSessionKey);
789
+ needsSignedThinkingWarmup = hasToolUse && !hasSignedThinking && !hasCachedThinking;
790
+ }
791
+ body = JSON.stringify(wrappedBody);
792
+ }
793
+ else {
794
+ const requestPayload = { ...parsedBody };
795
+ const rawGenerationConfig = requestPayload.generationConfig;
796
+ const extraBody = requestPayload.extra_body;
797
+ const variantConfig = extractVariantThinkingConfig(requestPayload.providerOptions, rawGenerationConfig);
798
+ const isGemini3 = effectiveModel.toLowerCase().includes("gemini-3");
799
+ log.debug(`[ThinkingResolution] rawModel=${rawModel} resolvedModel=${effectiveModel} resolvedTier=${tierThinkingLevel ?? "none"} variantLevel=${variantConfig?.thinkingLevel ?? "none"} variantBudget=${variantConfig?.thinkingBudget ?? "none"} providerOptions.google=${JSON.stringify(requestPayload.providerOptions?.google ?? null)} generationConfig.thinkingConfig=${JSON.stringify(rawGenerationConfig?.thinkingConfig ?? null)}`);
800
+ if (variantConfig?.thinkingLevel && isGemini3) {
801
+ // Gemini 3 native format - use thinkingLevel directly
802
+ tierThinkingLevel = variantConfig.thinkingLevel;
803
+ tierThinkingBudget = undefined;
804
+ }
805
+ else if (variantConfig?.thinkingBudget) {
806
+ if (isGemini3) {
807
+ // Legacy format for Gemini 3 - convert with deprecation warning
808
+ log.warn("[Deprecated] Using thinkingBudget for Gemini 3 model. Use thinkingLevel instead.");
809
+ tierThinkingLevel = variantConfig.thinkingBudget <= 8192 ? "low"
810
+ : variantConfig.thinkingBudget <= 16384 ? "medium" : "high";
811
+ tierThinkingBudget = undefined;
812
+ }
813
+ else {
814
+ // Claude / Gemini 2.5 - use budget directly
815
+ tierThinkingBudget = variantConfig.thinkingBudget;
816
+ tierThinkingLevel = undefined;
817
+ }
818
+ }
819
+ if (headerStyle === "antigravity") {
820
+ const gemini35FlashBackendModel = resolveAntigravityGemini35FlashBackendModel(rawModel, tierThinkingLevel);
821
+ if (gemini35FlashBackendModel) {
822
+ effectiveModel = gemini35FlashBackendModel;
823
+ }
824
+ }
825
+ if (isClaude) {
826
+ if (!requestPayload.toolConfig) {
827
+ requestPayload.toolConfig = {};
828
+ }
829
+ if (typeof requestPayload.toolConfig === "object" && requestPayload.toolConfig !== null) {
830
+ const toolConfig = requestPayload.toolConfig;
831
+ if (!toolConfig.functionCallingConfig) {
832
+ toolConfig.functionCallingConfig = {};
833
+ }
834
+ if (typeof toolConfig.functionCallingConfig === "object" && toolConfig.functionCallingConfig !== null) {
835
+ toolConfig.functionCallingConfig.mode = "VALIDATED";
836
+ }
837
+ }
838
+ }
839
+ // Resolve thinking configuration based on user settings and model capabilities
840
+ // Image generation models don't support thinking - skip thinking config entirely
841
+ const isImageModel = isImageGenerationModel(effectiveModel);
842
+ const userThinkingConfig = isImageModel ? undefined : extractThinkingConfig(requestPayload, rawGenerationConfig, extraBody);
843
+ const hasAssistantHistory = Array.isArray(requestPayload.contents) &&
844
+ requestPayload.contents.some((c) => c?.role === "model" || c?.role === "assistant");
845
+ // Claude Sonnet 4.6 is non-thinking only.
846
+ // Ignore any client-provided thinkingConfig for this model.
847
+ const lowerEffective = effectiveModel.toLowerCase();
848
+ const isClaudeSonnetNonThinking = lowerEffective === "claude-sonnet-4-6";
849
+ const effectiveUserThinkingConfig = (isClaudeSonnetNonThinking || isImageModel) ? undefined : userThinkingConfig;
850
+ // For image models, add imageConfig instead of thinkingConfig
851
+ if (isImageModel) {
852
+ const imageConfig = buildImageGenerationConfig();
853
+ const generationConfig = (rawGenerationConfig ?? {});
854
+ generationConfig.imageConfig = imageConfig;
855
+ // Remove any thinkingConfig that might have been set
856
+ delete generationConfig.thinkingConfig;
857
+ // Set reasonable defaults for image generation
858
+ if (!generationConfig.candidateCount) {
859
+ generationConfig.candidateCount = 1;
860
+ }
861
+ requestPayload.generationConfig = generationConfig;
862
+ // Add safety settings for image generation (permissive to allow creative content)
863
+ if (!requestPayload.safetySettings) {
864
+ requestPayload.safetySettings = [
865
+ { category: "HARM_CATEGORY_HARASSMENT", threshold: "BLOCK_ONLY_HIGH" },
866
+ { category: "HARM_CATEGORY_HATE_SPEECH", threshold: "BLOCK_ONLY_HIGH" },
867
+ { category: "HARM_CATEGORY_SEXUALLY_EXPLICIT", threshold: "BLOCK_ONLY_HIGH" },
868
+ { category: "HARM_CATEGORY_DANGEROUS_CONTENT", threshold: "BLOCK_ONLY_HIGH" },
869
+ { category: "HARM_CATEGORY_CIVIC_INTEGRITY", threshold: "BLOCK_ONLY_HIGH" },
870
+ ];
871
+ }
872
+ // Image models don't support tools - remove them entirely
873
+ delete requestPayload.tools;
874
+ delete requestPayload.toolConfig;
875
+ // Replace system instruction with a simple image generation prompt
876
+ // Image models should not receive agentic coding assistant instructions
877
+ requestPayload.systemInstruction = {
878
+ parts: [{ text: "You are an AI image generator. Generate images based on user descriptions. Focus on creating high-quality, visually appealing images that match the user's request." }]
879
+ };
880
+ }
881
+ else {
882
+ const finalThinkingConfig = resolveThinkingConfig(effectiveUserThinkingConfig, isClaudeSonnetNonThinking ? false : (resolved.isThinkingModel ?? isThinkingCapableModel(effectiveModel)), isClaude, hasAssistantHistory);
883
+ const normalizedThinking = normalizeThinkingConfig(finalThinkingConfig);
884
+ if (normalizedThinking) {
885
+ // Use tier-based thinking budget if specified via model suffix, otherwise fall back to user config
886
+ const thinkingBudget = tierThinkingBudget ?? normalizedThinking.thinkingBudget;
887
+ // Build thinking config based on model type
888
+ let thinkingConfig;
889
+ if (isClaudeThinking) {
890
+ // Claude uses snake_case keys
891
+ thinkingConfig = {
892
+ include_thoughts: normalizedThinking.includeThoughts ?? true,
893
+ ...(typeof thinkingBudget === "number" && thinkingBudget > 0
894
+ ? { thinking_budget: thinkingBudget }
895
+ : {}),
896
+ };
897
+ }
898
+ else if (tierThinkingLevel) {
899
+ // Gemini 3 uses thinkingLevel string (low/medium/high)
900
+ thinkingConfig = {
901
+ includeThoughts: normalizedThinking.includeThoughts,
902
+ thinkingLevel: tierThinkingLevel,
903
+ };
904
+ }
905
+ else {
906
+ // Gemini 2.5 and others use numeric budget
907
+ thinkingConfig = {
908
+ includeThoughts: normalizedThinking.includeThoughts,
909
+ ...(typeof thinkingBudget === "number" && thinkingBudget > 0 ? { thinkingBudget } : {}),
910
+ };
911
+ }
912
+ if (rawGenerationConfig) {
913
+ rawGenerationConfig.thinkingConfig = thinkingConfig;
914
+ if (isClaudeThinking && typeof thinkingBudget === "number" && thinkingBudget > 0) {
915
+ const currentMax = (rawGenerationConfig.maxOutputTokens ?? rawGenerationConfig.max_output_tokens);
916
+ if (!currentMax || currentMax <= thinkingBudget) {
917
+ rawGenerationConfig.maxOutputTokens = CLAUDE_THINKING_MAX_OUTPUT_TOKENS;
918
+ if (rawGenerationConfig.max_output_tokens !== undefined) {
919
+ delete rawGenerationConfig.max_output_tokens;
920
+ }
921
+ }
922
+ }
923
+ requestPayload.generationConfig = rawGenerationConfig;
924
+ }
925
+ else {
926
+ const generationConfig = { thinkingConfig };
927
+ if (isClaudeThinking && typeof thinkingBudget === "number" && thinkingBudget > 0) {
928
+ generationConfig.maxOutputTokens = CLAUDE_THINKING_MAX_OUTPUT_TOKENS;
929
+ }
930
+ requestPayload.generationConfig = generationConfig;
931
+ }
932
+ }
933
+ else if (rawGenerationConfig?.thinkingConfig) {
934
+ delete rawGenerationConfig.thinkingConfig;
935
+ requestPayload.generationConfig = rawGenerationConfig;
936
+ }
937
+ } // End of else block for non-image models
938
+ // Clean up thinking fields from extra_body
939
+ if (extraBody) {
940
+ delete extraBody.thinkingConfig;
941
+ delete extraBody.thinking;
942
+ }
943
+ delete requestPayload.thinkingConfig;
944
+ delete requestPayload.thinking;
945
+ if ("system_instruction" in requestPayload) {
946
+ requestPayload.systemInstruction = requestPayload.system_instruction;
947
+ delete requestPayload.system_instruction;
948
+ }
949
+ if (isClaudeThinking && Array.isArray(requestPayload.tools) && requestPayload.tools.length > 0) {
950
+ 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.";
951
+ const existing = requestPayload.systemInstruction;
952
+ if (typeof existing === "string") {
953
+ requestPayload.systemInstruction = existing.trim().length > 0 ? `${existing}\n\n${hint}` : hint;
954
+ }
955
+ else if (existing && typeof existing === "object") {
956
+ const sys = existing;
957
+ const partsValue = sys.parts;
958
+ if (Array.isArray(partsValue)) {
959
+ const parts = partsValue;
960
+ let appended = false;
961
+ for (let i = parts.length - 1; i >= 0; i--) {
962
+ const part = parts[i];
963
+ if (part && typeof part === "object") {
964
+ const partRecord = part;
965
+ const text = partRecord.text;
966
+ if (typeof text === "string") {
967
+ partRecord.text = `${text}\n\n${hint}`;
968
+ appended = true;
969
+ break;
970
+ }
971
+ }
972
+ }
973
+ if (!appended) {
974
+ parts.push({ text: hint });
975
+ }
976
+ }
977
+ else {
978
+ sys.parts = [{ text: hint }];
979
+ }
980
+ requestPayload.systemInstruction = sys;
981
+ }
982
+ else if (Array.isArray(requestPayload.contents)) {
983
+ requestPayload.systemInstruction = { parts: [{ text: hint }] };
984
+ }
985
+ }
986
+ const cachedContentFromExtra = typeof requestPayload.extra_body === "object" && requestPayload.extra_body
987
+ ? requestPayload.extra_body.cached_content ??
988
+ requestPayload.extra_body.cachedContent
989
+ : undefined;
990
+ const cachedContent = requestPayload.cached_content ??
991
+ requestPayload.cachedContent ??
992
+ cachedContentFromExtra;
993
+ if (cachedContent) {
994
+ requestPayload.cachedContent = cachedContent;
995
+ }
996
+ delete requestPayload.cached_content;
997
+ delete requestPayload.cachedContent;
998
+ if (requestPayload.extra_body && typeof requestPayload.extra_body === "object") {
999
+ delete requestPayload.extra_body.cached_content;
1000
+ delete requestPayload.extra_body.cachedContent;
1001
+ if (Object.keys(requestPayload.extra_body).length === 0) {
1002
+ delete requestPayload.extra_body;
1003
+ }
1004
+ }
1005
+ // Normalize tools. For Claude models, keep full function declarations (names + schemas).
1006
+ const hasTools = Array.isArray(requestPayload.tools) && requestPayload.tools.length > 0;
1007
+ if (hasTools) {
1008
+ if (isClaude) {
1009
+ const functionDeclarations = [];
1010
+ const passthroughTools = [];
1011
+ const normalizeSchema = (schema) => {
1012
+ const createPlaceholderSchema = (base = {}) => ({
1013
+ ...base,
1014
+ type: "object",
1015
+ properties: {
1016
+ [EMPTY_SCHEMA_PLACEHOLDER_NAME]: {
1017
+ type: "boolean",
1018
+ description: EMPTY_SCHEMA_PLACEHOLDER_DESCRIPTION,
1019
+ },
1020
+ },
1021
+ required: [EMPTY_SCHEMA_PLACEHOLDER_NAME],
1022
+ });
1023
+ if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
1024
+ toolDebugMissing += 1;
1025
+ return createPlaceholderSchema();
1026
+ }
1027
+ const cleaned = cleanJSONSchemaForAntigravity(schema);
1028
+ if (!cleaned || typeof cleaned !== "object" || Array.isArray(cleaned)) {
1029
+ toolDebugMissing += 1;
1030
+ return createPlaceholderSchema();
1031
+ }
1032
+ // Claude VALIDATED mode requires tool parameters to be an object schema
1033
+ // with at least one property.
1034
+ const hasProperties = cleaned.properties &&
1035
+ typeof cleaned.properties === "object" &&
1036
+ Object.keys(cleaned.properties).length > 0;
1037
+ cleaned.type = "object";
1038
+ if (!hasProperties) {
1039
+ cleaned.properties = {
1040
+ [EMPTY_SCHEMA_PLACEHOLDER_NAME]: {
1041
+ type: "boolean",
1042
+ description: EMPTY_SCHEMA_PLACEHOLDER_DESCRIPTION,
1043
+ },
1044
+ };
1045
+ cleaned.required = Array.isArray(cleaned.required)
1046
+ ? Array.from(new Set([...cleaned.required, EMPTY_SCHEMA_PLACEHOLDER_NAME]))
1047
+ : [EMPTY_SCHEMA_PLACEHOLDER_NAME];
1048
+ }
1049
+ return cleaned;
1050
+ };
1051
+ requestPayload.tools.forEach((tool) => {
1052
+ const pushDeclaration = (decl, source) => {
1053
+ const schema = decl?.parameters ||
1054
+ decl?.parametersJsonSchema ||
1055
+ decl?.input_schema ||
1056
+ decl?.inputSchema ||
1057
+ tool.parameters ||
1058
+ tool.parametersJsonSchema ||
1059
+ tool.input_schema ||
1060
+ tool.inputSchema ||
1061
+ tool.function?.parameters ||
1062
+ tool.function?.parametersJsonSchema ||
1063
+ tool.function?.input_schema ||
1064
+ tool.function?.inputSchema ||
1065
+ tool.custom?.parameters ||
1066
+ tool.custom?.parametersJsonSchema ||
1067
+ tool.custom?.input_schema;
1068
+ let name = decl?.name ||
1069
+ tool.name ||
1070
+ tool.function?.name ||
1071
+ tool.custom?.name ||
1072
+ `tool-${functionDeclarations.length}`;
1073
+ // Sanitize tool name: must be alphanumeric with underscores, no special chars
1074
+ name = String(name).replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64);
1075
+ const description = decl?.description ||
1076
+ tool.description ||
1077
+ tool.function?.description ||
1078
+ tool.custom?.description ||
1079
+ "";
1080
+ functionDeclarations.push({
1081
+ name,
1082
+ description: String(description || ""),
1083
+ parameters: normalizeSchema(schema),
1084
+ });
1085
+ toolDebugSummaries.push(`decl=${name},src=${source},hasSchema=${schema ? "y" : "n"}`);
1086
+ };
1087
+ if (Array.isArray(tool.functionDeclarations) && tool.functionDeclarations.length > 0) {
1088
+ tool.functionDeclarations.forEach((decl) => {
1089
+ pushDeclaration(decl, "functionDeclarations");
1090
+ });
1091
+ return;
1092
+ }
1093
+ // Fall back to function/custom style definitions.
1094
+ if (tool.function ||
1095
+ tool.custom ||
1096
+ tool.parameters ||
1097
+ tool.input_schema ||
1098
+ tool.inputSchema) {
1099
+ pushDeclaration(tool.function ?? tool.custom ?? tool, "function/custom");
1100
+ return;
1101
+ }
1102
+ // Preserve any non-function tool entries (e.g., codeExecution) untouched.
1103
+ passthroughTools.push(tool);
1104
+ });
1105
+ const finalTools = [];
1106
+ if (functionDeclarations.length > 0) {
1107
+ finalTools.push({ functionDeclarations });
1108
+ }
1109
+ requestPayload.tools = finalTools.concat(passthroughTools);
1110
+ }
1111
+ else {
1112
+ // Gemini-specific tool normalization and feature injection
1113
+ const geminiResult = applyGeminiTransforms(requestPayload, {
1114
+ model: effectiveModel,
1115
+ normalizedThinking: undefined, // Thinking config already applied above (lines 816-880)
1116
+ tierThinkingBudget,
1117
+ tierThinkingLevel: tierThinkingLevel,
1118
+ });
1119
+ toolDebugMissing = geminiResult.toolDebugMissing;
1120
+ toolDebugSummaries.push(...geminiResult.toolDebugSummaries);
1121
+ }
1122
+ try {
1123
+ toolDebugPayload = JSON.stringify(requestPayload.tools);
1124
+ }
1125
+ catch {
1126
+ toolDebugPayload = undefined;
1127
+ }
1128
+ // Apply Claude tool hardening (ported from LLM-API-Key-Proxy)
1129
+ // Injects parameter signatures into descriptions and adds system instruction
1130
+ // Can be disabled via config.claude_tool_hardening = false to reduce context size
1131
+ const enableToolHardening = options?.claudeToolHardening ?? true;
1132
+ if (enableToolHardening && isClaude && Array.isArray(requestPayload.tools) && requestPayload.tools.length > 0) {
1133
+ // Inject parameter signatures into tool descriptions
1134
+ requestPayload.tools = injectParameterSignatures(requestPayload.tools, CLAUDE_DESCRIPTION_PROMPT);
1135
+ // Inject tool hardening system instruction
1136
+ injectToolHardeningInstruction(requestPayload, CLAUDE_TOOL_SYSTEM_INSTRUCTION);
1137
+ }
1138
+ }
1139
+ const conversationKey = resolveConversationKey(requestPayload);
1140
+ signatureSessionKey = buildSignatureSessionKey(PLUGIN_SESSION_ID, effectiveModel, conversationKey, signatureCacheProjectKey(effectiveModel, resolveProjectKey(projectId)));
1141
+ // For Claude models, filter out unsigned thinking blocks (required by Claude API)
1142
+ // Attempts to restore signatures from cache for multi-turn conversations
1143
+ // Handle both Gemini-style contents[] and Anthropic-style messages[] payloads.
1144
+ if (isClaude) {
1145
+ // Step 0: Sanitize cross-model metadata (strips Gemini signatures when sending to Claude)
1146
+ sanitizeCrossModelPayloadInPlace(requestPayload, { targetModel: effectiveModel });
1147
+ // Step 1: Strip corrupted/unsigned thinking blocks FIRST
1148
+ deepFilterThinkingBlocks(requestPayload, signatureSessionKey, getCachedSignature, true);
1149
+ if (enableClaudePromptAutoCaching && requestPayload.cache_control === undefined) {
1150
+ requestPayload.cache_control = { type: "ephemeral" };
1151
+ }
1152
+ // Step 2: THEN inject signed thinking from cache (after stripping)
1153
+ if (isClaudeThinking && keepThinkingEnabled && Array.isArray(requestPayload.contents)) {
1154
+ requestPayload.contents = ensureThinkingBeforeToolUseInContents(requestPayload.contents, signatureSessionKey);
1155
+ }
1156
+ if (isClaudeThinking && keepThinkingEnabled && Array.isArray(requestPayload.messages)) {
1157
+ requestPayload.messages = ensureThinkingBeforeToolUseInMessages(requestPayload.messages, signatureSessionKey);
1158
+ }
1159
+ // Step 3: Check if warmup needed (AFTER injection attempt)
1160
+ if (isClaudeThinking && keepThinkingEnabled) {
1161
+ const hasToolUse = (Array.isArray(requestPayload.contents) && hasToolUseInContents(requestPayload.contents)) ||
1162
+ (Array.isArray(requestPayload.messages) && hasToolUseInMessages(requestPayload.messages));
1163
+ const hasSignedThinking = (Array.isArray(requestPayload.contents) && hasSignedThinkingInContents(requestPayload.contents, signatureSessionKey)) ||
1164
+ (Array.isArray(requestPayload.messages) && hasSignedThinkingInMessages(requestPayload.messages, signatureSessionKey));
1165
+ const hasCachedThinking = defaultSignatureStore.has(signatureSessionKey);
1166
+ needsSignedThinkingWarmup = hasToolUse && !hasSignedThinking && !hasCachedThinking;
1167
+ }
1168
+ }
1169
+ // For Claude models, ensure functionCall/tool use parts carry IDs (required by Anthropic).
1170
+ // We use a two-pass approach: first collect all functionCalls and assign IDs,
1171
+ // then match functionResponses to their corresponding calls using a FIFO queue per function name.
1172
+ if (isClaude && Array.isArray(requestPayload.contents)) {
1173
+ let toolCallCounter = 0;
1174
+ // Track pending call IDs per function name as a FIFO queue
1175
+ const pendingCallIdsByName = new Map();
1176
+ // First pass: assign IDs to all functionCalls and collect them
1177
+ requestPayload.contents = requestPayload.contents.map((content) => {
1178
+ if (!content || !Array.isArray(content.parts)) {
1179
+ return content;
1180
+ }
1181
+ const newParts = content.parts.map((part) => {
1182
+ if (part && typeof part === "object" && part.functionCall) {
1183
+ const call = { ...part.functionCall };
1184
+ if (!call.id) {
1185
+ call.id = `tool-call-${++toolCallCounter}`;
1186
+ }
1187
+ const nameKey = typeof call.name === "string" ? call.name : `tool-${toolCallCounter}`;
1188
+ // Push to the queue for this function name
1189
+ const queue = pendingCallIdsByName.get(nameKey) || [];
1190
+ queue.push(call.id);
1191
+ pendingCallIdsByName.set(nameKey, queue);
1192
+ return { ...part, functionCall: call };
1193
+ }
1194
+ return part;
1195
+ });
1196
+ return { ...content, parts: newParts };
1197
+ });
1198
+ // Second pass: match functionResponses to their corresponding calls (FIFO order)
1199
+ requestPayload.contents = requestPayload.contents.map((content) => {
1200
+ if (!content || !Array.isArray(content.parts)) {
1201
+ return content;
1202
+ }
1203
+ const newParts = content.parts.map((part) => {
1204
+ if (part && typeof part === "object" && part.functionResponse) {
1205
+ const resp = { ...part.functionResponse };
1206
+ if (!resp.id && typeof resp.name === "string") {
1207
+ const queue = pendingCallIdsByName.get(resp.name);
1208
+ if (queue && queue.length > 0) {
1209
+ // Consume the first pending ID (FIFO order)
1210
+ resp.id = queue.shift();
1211
+ pendingCallIdsByName.set(resp.name, queue);
1212
+ }
1213
+ }
1214
+ return { ...part, functionResponse: resp };
1215
+ }
1216
+ return part;
1217
+ });
1218
+ return { ...content, parts: newParts };
1219
+ });
1220
+ // Third pass: Apply orphan recovery for mismatched tool IDs
1221
+ // This handles cases where context compaction or other processes
1222
+ // create ID mismatches between calls and responses.
1223
+ // Ported from LLM-API-Key-Proxy's _fix_tool_response_grouping()
1224
+ requestPayload.contents = fixToolResponseGrouping(requestPayload.contents);
1225
+ }
1226
+ // Fourth pass: Fix Claude format tool pairing (defense in depth)
1227
+ // Handles orphaned tool_use blocks in Claude's messages[] format
1228
+ if (Array.isArray(requestPayload.messages)) {
1229
+ requestPayload.messages = validateAndFixClaudeToolPairing(requestPayload.messages);
1230
+ }
1231
+ // =====================================================================
1232
+ // LAST RESORT RECOVERY: "Let it crash and start again"
1233
+ // =====================================================================
1234
+ // If after all our processing we're STILL in a bad state (tool loop without
1235
+ // thinking at turn start), don't try to fix it - just close the turn and
1236
+ // start fresh. This prevents permanent session breakage.
1237
+ //
1238
+ // This handles cases where:
1239
+ // - Context compaction stripped thinking blocks
1240
+ // - Signature cache miss
1241
+ // - Any other corruption we couldn't repair
1242
+ // - API error indicated thinking_block_order issue (forceThinkingRecovery=true)
1243
+ //
1244
+ // The synthetic messages allow Claude to generate fresh thinking on the
1245
+ // new turn instead of failing with "Expected thinking but found text".
1246
+ if (isClaudeThinking && Array.isArray(requestPayload.contents)) {
1247
+ const conversationState = analyzeConversationState(requestPayload.contents);
1248
+ // Force recovery if API returned thinking_block_order error (retry case)
1249
+ // or if proactive check detects we need recovery
1250
+ if (forceThinkingRecovery || needsThinkingRecovery(conversationState)) {
1251
+ // Set message for toast notification (shown in plugin.ts, respects quiet mode)
1252
+ thinkingRecoveryMessage = forceThinkingRecovery
1253
+ ? "Thinking recovery: retrying with fresh turn (API error)"
1254
+ : "Thinking recovery: restarting turn (corrupted context)";
1255
+ requestPayload.contents = closeToolLoopForThinking(requestPayload.contents);
1256
+ defaultSignatureStore.delete(signatureSessionKey);
1257
+ }
1258
+ }
1259
+ if ("model" in requestPayload) {
1260
+ delete requestPayload.model;
1261
+ }
1262
+ stripInjectedDebugFromRequestPayload(requestPayload);
1263
+ // Gemini 3 caches thought signatures on the response side but, unlike
1264
+ // Claude, had no request-side path to replay them — so restore the
1265
+ // cached signature here. Without it the model loses reasoning
1266
+ // continuity across turns (worsened by quota-driven account switches)
1267
+ // and re-plans the same step forever.
1268
+ const restoreGeminiThoughtSignatures = !isClaude && shouldCacheThinkingSignatures(effectiveModel);
1269
+ sanitizeRequestPayloadForAntigravity(requestPayload, restoreGeminiThoughtSignatures
1270
+ ? { sessionKey: signatureSessionKey, getSignature: getCachedSignature }
1271
+ : undefined);
1272
+ const effectiveProjectId = projectId?.trim() || (headerStyle === "antigravity" ? generateSyntheticProjectId() : "");
1273
+ resolvedProjectId = effectiveProjectId;
1274
+ // Inject Antigravity system instruction with role "user" (CLIProxyAPI v6.6.89 compatibility)
1275
+ // This sets request.systemInstruction.role = "user" and request.systemInstruction.parts[0].text
1276
+ if (headerStyle === "antigravity") {
1277
+ const existingSystemInstruction = requestPayload.systemInstruction;
1278
+ if (existingSystemInstruction && typeof existingSystemInstruction === "object") {
1279
+ const sys = existingSystemInstruction;
1280
+ sys.role = "user";
1281
+ if (Array.isArray(sys.parts) && sys.parts.length > 0) {
1282
+ const firstPart = sys.parts[0];
1283
+ if (firstPart && typeof firstPart.text === "string") {
1284
+ firstPart.text = ANTIGRAVITY_SYSTEM_INSTRUCTION + "\n\n" + firstPart.text;
1285
+ }
1286
+ else {
1287
+ sys.parts = [{ text: ANTIGRAVITY_SYSTEM_INSTRUCTION }, ...sys.parts];
1288
+ }
1289
+ }
1290
+ else {
1291
+ sys.parts = [{ text: ANTIGRAVITY_SYSTEM_INSTRUCTION }];
1292
+ }
1293
+ }
1294
+ else if (typeof existingSystemInstruction === "string") {
1295
+ requestPayload.systemInstruction = {
1296
+ role: "user",
1297
+ parts: [{ text: ANTIGRAVITY_SYSTEM_INSTRUCTION + "\n\n" + existingSystemInstruction }],
1298
+ };
1299
+ }
1300
+ else {
1301
+ requestPayload.systemInstruction = {
1302
+ role: "user",
1303
+ parts: [{ text: ANTIGRAVITY_SYSTEM_INSTRUCTION }],
1304
+ };
1305
+ }
1306
+ }
1307
+ const wrappedBody = {
1308
+ project: effectiveProjectId,
1309
+ model: effectiveModel,
1310
+ request: requestPayload,
1311
+ };
1312
+ if (headerStyle === "antigravity") {
1313
+ wrappedBody.requestType = "agent";
1314
+ wrappedBody.userAgent = "antigravity";
1315
+ wrappedBody.requestId = "agent-" + crypto.randomUUID();
1316
+ }
1317
+ if (wrappedBody.request && typeof wrappedBody.request === 'object') {
1318
+ // Use stable session ID for signature caching across multi-turn conversations
1319
+ sessionId = signatureSessionKey;
1320
+ wrappedBody.request.sessionId = signatureSessionKey;
1321
+ }
1322
+ body = JSON.stringify(wrappedBody);
1323
+ }
1324
+ }
1325
+ catch (error) {
1326
+ throw error;
1327
+ }
1328
+ }
1329
+ if (streaming) {
1330
+ headers.set("Accept", "text/event-stream");
1331
+ }
1332
+ // Add interleaved thinking header for Claude thinking models
1333
+ // This enables real-time streaming of thinking tokens
1334
+ if (isClaudeThinking) {
1335
+ const existing = headers.get("anthropic-beta");
1336
+ const interleavedHeader = "interleaved-thinking-2025-05-14";
1337
+ if (existing) {
1338
+ if (!existing.includes(interleavedHeader)) {
1339
+ headers.set("anthropic-beta", `${existing},${interleavedHeader}`);
1340
+ }
1341
+ }
1342
+ else {
1343
+ headers.set("anthropic-beta", interleavedHeader);
1344
+ }
1345
+ }
1346
+ if (headerStyle === "antigravity") {
1347
+ // Use randomized headers as the fallback pool for Antigravity mode
1348
+ const selectedHeaders = getRandomizedHeaders("antigravity", requestedModel);
1349
+ // Antigravity mode: Match Antigravity Manager behavior
1350
+ // AM only sends User-Agent on content requests — no X-Goog-Api-Client, no Client-Metadata header
1351
+ // (ideType=ANTIGRAVITY goes in request body metadata via project.ts, not as a header)
1352
+ const fingerprint = options?.fingerprint ?? getSessionFingerprint();
1353
+ const fingerprintHeaders = buildFingerprintHeaders(fingerprint);
1354
+ headers.set("User-Agent", fingerprintHeaders["User-Agent"] || selectedHeaders["User-Agent"]);
1355
+ }
1356
+ else {
1357
+ // Gemini CLI mode: match opencode-gemini-auth Code Assist header set exactly
1358
+ headers.set("User-Agent", GEMINI_CLI_HEADERS["User-Agent"]);
1359
+ headers.set("X-Goog-Api-Client", GEMINI_CLI_HEADERS["X-Goog-Api-Client"]);
1360
+ headers.set("Client-Metadata", GEMINI_CLI_HEADERS["Client-Metadata"]);
1361
+ }
1362
+ return {
1363
+ request: transformedUrl,
1364
+ init: {
1365
+ ...baseInit,
1366
+ headers,
1367
+ body,
1368
+ },
1369
+ streaming,
1370
+ requestedModel,
1371
+ effectiveModel: effectiveModel,
1372
+ projectId: resolvedProjectId,
1373
+ endpoint: transformedUrl,
1374
+ sessionId,
1375
+ toolDebugMissing,
1376
+ toolDebugSummary: toolDebugSummaries.slice(0, 20).join(" | "),
1377
+ toolDebugPayload,
1378
+ needsSignedThinkingWarmup,
1379
+ headerStyle,
1380
+ thinkingRecoveryMessage,
1381
+ };
1382
+ }
1383
+ export function buildThinkingWarmupBody(bodyText, isClaudeThinking) {
1384
+ if (!bodyText || !isClaudeThinking) {
1385
+ return null;
1386
+ }
1387
+ let parsed;
1388
+ try {
1389
+ parsed = JSON.parse(bodyText);
1390
+ }
1391
+ catch {
1392
+ return null;
1393
+ }
1394
+ const warmupPrompt = "Warmup request for thinking signature.";
1395
+ const updateRequest = (req) => {
1396
+ req.contents = [{ role: "user", parts: [{ text: warmupPrompt }] }];
1397
+ delete req.tools;
1398
+ delete req.toolConfig;
1399
+ const generationConfig = (req.generationConfig ?? {});
1400
+ generationConfig.thinkingConfig = {
1401
+ include_thoughts: true,
1402
+ thinking_budget: DEFAULT_THINKING_BUDGET,
1403
+ };
1404
+ generationConfig.maxOutputTokens = CLAUDE_THINKING_MAX_OUTPUT_TOKENS;
1405
+ req.generationConfig = generationConfig;
1406
+ };
1407
+ if (parsed.request && typeof parsed.request === "object") {
1408
+ updateRequest(parsed.request);
1409
+ const nested = parsed.request.request;
1410
+ if (nested && typeof nested === "object") {
1411
+ updateRequest(nested);
1412
+ }
1413
+ }
1414
+ else {
1415
+ updateRequest(parsed);
1416
+ }
1417
+ return JSON.stringify(parsed);
1418
+ }
1419
+ /**
1420
+ * Normalizes Antigravity responses: applies retry headers, extracts cache usage into headers,
1421
+ * rewrites preview errors, flattens streaming payloads, and logs debug metadata.
1422
+ *
1423
+ * For streaming SSE responses, uses TransformStream for true real-time incremental streaming.
1424
+ * Thinking/reasoning tokens are transformed and forwarded immediately as they arrive.
1425
+ */
1426
+ export async function transformAntigravityResponse(response, streaming, debugContext, requestedModel, projectId, endpoint, effectiveModel, sessionId, toolDebugMissing, toolDebugSummary, toolDebugPayload, debugLines) {
1427
+ const contentType = response.headers.get("content-type") ?? "";
1428
+ const isJsonResponse = contentType.includes("application/json");
1429
+ const isEventStreamResponse = contentType.includes("text/event-stream");
1430
+ // Generate text for thinking injection:
1431
+ // - If debug=true: inject full debug logs
1432
+ // - If keep_thinking=true (but no debug): inject placeholder to trigger signature caching
1433
+ // Both use the same injection path (injectDebugThinking) for consistent behavior
1434
+ const debugText = isDebugTuiEnabled() && Array.isArray(debugLines) && debugLines.length > 0
1435
+ ? formatDebugLinesForThinking(debugLines)
1436
+ : getKeepThinking()
1437
+ ? SYNTHETIC_THINKING_PLACEHOLDER
1438
+ : undefined;
1439
+ const cacheSignatures = shouldCacheThinkingSignatures(effectiveModel);
1440
+ if (!isJsonResponse && !isEventStreamResponse) {
1441
+ logAntigravityDebugResponse(debugContext, response, {
1442
+ note: "Non-JSON response (body omitted)",
1443
+ });
1444
+ return response;
1445
+ }
1446
+ // For successful streaming responses, use TransformStream to transform SSE events
1447
+ // while maintaining real-time streaming (no buffering of entire response).
1448
+ // This enables thinking tokens to be displayed as they arrive, like the Codex plugin.
1449
+ if (streaming && response.ok && isEventStreamResponse && response.body) {
1450
+ const headers = new Headers(response.headers);
1451
+ logAntigravityDebugResponse(debugContext, response, {
1452
+ note: "Streaming SSE response (real-time transform)",
1453
+ });
1454
+ const streamingTransformer = createStreamingTransformer(defaultSignatureStore, {
1455
+ onCacheSignature: cacheSignature,
1456
+ onInjectDebug: injectDebugThinking,
1457
+ // onInjectSyntheticThinking removed - keep_thinking now uses debugText path
1458
+ transformThinkingParts,
1459
+ }, {
1460
+ signatureSessionKey: sessionId,
1461
+ debugText,
1462
+ cacheSignatures,
1463
+ displayedThinkingHashes: effectiveModel && isGemini3Model(effectiveModel) ? sessionDisplayedThinkingHashes : undefined,
1464
+ // injectSyntheticThinking removed - keep_thinking now unified with debug via debugText
1465
+ });
1466
+ return new Response(response.body.pipeThrough(streamingTransformer), {
1467
+ status: response.status,
1468
+ statusText: response.statusText,
1469
+ headers,
1470
+ });
1471
+ }
1472
+ const responseFallback = response.clone();
1473
+ try {
1474
+ const headers = new Headers(response.headers);
1475
+ const text = await response.text();
1476
+ if (!response.ok) {
1477
+ let errorBody;
1478
+ try {
1479
+ errorBody = JSON.parse(text);
1480
+ }
1481
+ catch {
1482
+ errorBody = { error: { message: text } };
1483
+ }
1484
+ // Inject Debug Info
1485
+ if (errorBody?.error) {
1486
+ const rawErrorMessage = typeof errorBody.error.message === "string" && errorBody.error.message.length > 0
1487
+ ? errorBody.error.message
1488
+ : "Unknown error";
1489
+ const errorType = detectErrorType(rawErrorMessage);
1490
+ 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}` : ""}`;
1491
+ const injectedDebug = debugText ? `\n\n${debugText}` : "";
1492
+ errorBody.error.message = rawErrorMessage + debugInfo + injectedDebug;
1493
+ // Check if this is a recoverable thinking error - throw to trigger retry
1494
+ if (errorType === "thinking_block_order") {
1495
+ const recoveryError = new Error("THINKING_RECOVERY_NEEDED");
1496
+ recoveryError.recoveryType = errorType;
1497
+ recoveryError.originalError = errorBody;
1498
+ recoveryError.debugInfo = debugInfo;
1499
+ throw recoveryError;
1500
+ }
1501
+ // Detect context length / prompt too long errors - signal to caller for toast
1502
+ const errorMessage = errorBody.error.message?.toLowerCase() || "";
1503
+ if (errorMessage.includes("prompt is too long") ||
1504
+ errorMessage.includes("context length exceeded") ||
1505
+ errorMessage.includes("context_length_exceeded") ||
1506
+ errorMessage.includes("maximum context length")) {
1507
+ headers.set("x-antigravity-context-error", "prompt_too_long");
1508
+ }
1509
+ // Detect tool pairing errors - signal to caller for toast
1510
+ if (errorMessage.includes("tool_use") &&
1511
+ errorMessage.includes("tool_result") &&
1512
+ (errorMessage.includes("without") || errorMessage.includes("immediately after"))) {
1513
+ headers.set("x-antigravity-context-error", "tool_pairing");
1514
+ }
1515
+ return new Response(JSON.stringify(errorBody), {
1516
+ status: response.status,
1517
+ statusText: response.statusText,
1518
+ headers
1519
+ });
1520
+ }
1521
+ if (errorBody?.error?.details && Array.isArray(errorBody.error.details)) {
1522
+ const retryInfo = errorBody.error.details.find((detail) => detail['@type'] === 'type.googleapis.com/google.rpc.RetryInfo');
1523
+ if (typeof retryInfo?.retryDelay === "string") {
1524
+ const match = retryInfo.retryDelay.match(/^([\d.]+)s$/);
1525
+ if (match && match[1]) {
1526
+ const retrySeconds = parseFloat(match[1]);
1527
+ if (!isNaN(retrySeconds) && retrySeconds > 0) {
1528
+ const retryAfterSec = Math.ceil(retrySeconds).toString();
1529
+ const retryAfterMs = Math.ceil(retrySeconds * 1000).toString();
1530
+ headers.set('Retry-After', retryAfterSec);
1531
+ headers.set('retry-after-ms', retryAfterMs);
1532
+ }
1533
+ }
1534
+ }
1535
+ }
1536
+ }
1537
+ const init = {
1538
+ status: response.status,
1539
+ statusText: response.statusText,
1540
+ headers,
1541
+ };
1542
+ const usageFromSse = streaming && isEventStreamResponse ? extractUsageFromSsePayload(text) : null;
1543
+ const parsed = !streaming || !isEventStreamResponse ? parseAntigravityApiBody(text) : null;
1544
+ const patched = parsed ? rewriteAntigravityPreviewAccessError(parsed, response.status, requestedModel) : null;
1545
+ const effectiveBody = patched ?? parsed ?? undefined;
1546
+ const usage = usageFromSse ?? (effectiveBody ? extractUsageMetadata(effectiveBody) : null);
1547
+ // Log cache stats when available
1548
+ if (usage && effectiveModel) {
1549
+ logCacheStats(effectiveModel, usage.cachedContentTokenCount ?? 0, 0, // API doesn't provide cache write tokens separately
1550
+ usage.promptTokenCount ?? usage.totalTokenCount ?? 0);
1551
+ }
1552
+ if (usage?.cachedContentTokenCount !== undefined) {
1553
+ headers.set("x-antigravity-cached-content-token-count", String(usage.cachedContentTokenCount));
1554
+ if (usage.totalTokenCount !== undefined) {
1555
+ headers.set("x-antigravity-total-token-count", String(usage.totalTokenCount));
1556
+ }
1557
+ if (usage.promptTokenCount !== undefined) {
1558
+ headers.set("x-antigravity-prompt-token-count", String(usage.promptTokenCount));
1559
+ }
1560
+ if (usage.candidatesTokenCount !== undefined) {
1561
+ headers.set("x-antigravity-candidates-token-count", String(usage.candidatesTokenCount));
1562
+ }
1563
+ }
1564
+ logAntigravityDebugResponse(debugContext, response, {
1565
+ body: text,
1566
+ note: streaming ? "Streaming SSE payload (buffered fallback)" : undefined,
1567
+ headersOverride: headers,
1568
+ });
1569
+ // Note: successful streaming responses are handled above via TransformStream.
1570
+ // This path only handles non-streaming responses or failed streaming responses.
1571
+ if (!parsed) {
1572
+ return new Response(text, init);
1573
+ }
1574
+ if (effectiveBody?.response !== undefined) {
1575
+ let responseBody = effectiveBody.response;
1576
+ // Inject thinking text (debug logs or "[Thinking preserved]" placeholder)
1577
+ // Both debug=true and keep_thinking=true use the same path now
1578
+ if (debugText) {
1579
+ responseBody = injectDebugThinking(responseBody, debugText);
1580
+ }
1581
+ const transformed = transformThinkingParts(responseBody);
1582
+ return new Response(JSON.stringify(transformed), init);
1583
+ }
1584
+ if (patched) {
1585
+ return new Response(JSON.stringify(patched), init);
1586
+ }
1587
+ return new Response(text, init);
1588
+ }
1589
+ catch (error) {
1590
+ if (error instanceof Error && error.message === "THINKING_RECOVERY_NEEDED") {
1591
+ throw error;
1592
+ }
1593
+ logAntigravityDebugResponse(debugContext, response, {
1594
+ error,
1595
+ note: "Failed to transform Antigravity response",
1596
+ });
1597
+ return responseFallback;
1598
+ }
1599
+ }
1600
+ export const __testExports = {
1601
+ buildSignatureSessionKey,
1602
+ hashConversationSeed,
1603
+ extractTextFromContent,
1604
+ extractConversationSeedFromMessages,
1605
+ extractConversationSeedFromContents,
1606
+ resolveConversationKey,
1607
+ resolveProjectKey,
1608
+ isGeminiToolUsePart,
1609
+ isGeminiThinkingPart,
1610
+ ensureThoughtSignature,
1611
+ hasSignedThinkingPart,
1612
+ hasSignedThinkingInContents,
1613
+ hasSignedThinkingInMessages,
1614
+ hasToolUseInContents,
1615
+ hasToolUseInMessages,
1616
+ ensureThinkingBeforeToolUseInContents,
1617
+ ensureThinkingBeforeToolUseInMessages,
1618
+ sanitizeRequestPayloadForAntigravity,
1619
+ signatureCacheProjectKey,
1620
+ generateSyntheticProjectId,
1621
+ MIN_SIGNATURE_LENGTH,
1622
+ transformSseLine,
1623
+ transformStreamingPayload,
1624
+ createStreamingTransformer,
1625
+ };
1626
+ //# sourceMappingURL=request.js.map