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