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