opencode-ag-auth 1.5.2

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