antigravity-auth 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 (256) hide show
  1. package/README.md +61 -0
  2. package/dist/antigravity/oauth.d.ts +30 -0
  3. package/dist/antigravity/oauth.js +170 -0
  4. package/dist/claude/login.d.ts +7 -0
  5. package/dist/claude/login.js +480 -0
  6. package/dist/claude/menu-helpers.d.ts +22 -0
  7. package/dist/claude/menu-helpers.js +281 -0
  8. package/dist/claude/proxy-manager.d.ts +11 -0
  9. package/dist/claude/proxy-manager.js +129 -0
  10. package/dist/claude/proxy.d.ts +1 -0
  11. package/dist/claude/proxy.js +733 -0
  12. package/dist/constants.d.ts +138 -0
  13. package/dist/constants.js +216 -0
  14. package/dist/hooks/auto-update-checker/cache.d.ts +2 -0
  15. package/dist/hooks/auto-update-checker/cache.js +70 -0
  16. package/dist/hooks/auto-update-checker/checker.d.ts +15 -0
  17. package/dist/hooks/auto-update-checker/checker.js +233 -0
  18. package/dist/hooks/auto-update-checker/constants.d.ts +8 -0
  19. package/dist/hooks/auto-update-checker/constants.js +22 -0
  20. package/dist/hooks/auto-update-checker/index.d.ts +33 -0
  21. package/dist/hooks/auto-update-checker/index.js +121 -0
  22. package/dist/hooks/auto-update-checker/logging.d.ts +2 -0
  23. package/dist/hooks/auto-update-checker/logging.js +8 -0
  24. package/dist/hooks/auto-update-checker/types.d.ts +24 -0
  25. package/dist/hooks/auto-update-checker/types.js +1 -0
  26. package/dist/index.d.ts +6 -0
  27. package/dist/index.js +5 -0
  28. package/dist/opencode/hooks/auto-update-checker/cache.d.ts +2 -0
  29. package/dist/opencode/hooks/auto-update-checker/cache.js +70 -0
  30. package/dist/opencode/hooks/auto-update-checker/checker.d.ts +15 -0
  31. package/dist/opencode/hooks/auto-update-checker/checker.js +233 -0
  32. package/dist/opencode/hooks/auto-update-checker/constants.d.ts +8 -0
  33. package/dist/opencode/hooks/auto-update-checker/constants.js +22 -0
  34. package/dist/opencode/hooks/auto-update-checker/index.d.ts +33 -0
  35. package/dist/opencode/hooks/auto-update-checker/index.js +121 -0
  36. package/dist/opencode/hooks/auto-update-checker/logging.d.ts +2 -0
  37. package/dist/opencode/hooks/auto-update-checker/logging.js +8 -0
  38. package/dist/opencode/hooks/auto-update-checker/types.d.ts +24 -0
  39. package/dist/opencode/hooks/auto-update-checker/types.js +1 -0
  40. package/dist/opencode/plugin.d.ts +29 -0
  41. package/dist/opencode/plugin.js +2954 -0
  42. package/dist/plugin/accounts.d.ts +173 -0
  43. package/dist/plugin/accounts.js +966 -0
  44. package/dist/plugin/auth.d.ts +20 -0
  45. package/dist/plugin/auth.js +44 -0
  46. package/dist/plugin/cache/index.d.ts +4 -0
  47. package/dist/plugin/cache/index.js +4 -0
  48. package/dist/plugin/cache/signature-cache.d.ts +110 -0
  49. package/dist/plugin/cache/signature-cache.js +347 -0
  50. package/dist/plugin/cache.d.ts +43 -0
  51. package/dist/plugin/cache.js +180 -0
  52. package/dist/plugin/cli.d.ts +26 -0
  53. package/dist/plugin/cli.js +126 -0
  54. package/dist/plugin/config/index.d.ts +15 -0
  55. package/dist/plugin/config/index.js +15 -0
  56. package/dist/plugin/config/loader.d.ts +38 -0
  57. package/dist/plugin/config/loader.js +150 -0
  58. package/dist/plugin/config/models.d.ts +26 -0
  59. package/dist/plugin/config/models.js +95 -0
  60. package/dist/plugin/config/schema.d.ts +144 -0
  61. package/dist/plugin/config/schema.js +458 -0
  62. package/dist/plugin/config/updater.d.ts +76 -0
  63. package/dist/plugin/config/updater.js +205 -0
  64. package/dist/plugin/core/streaming/index.d.ts +2 -0
  65. package/dist/plugin/core/streaming/index.js +2 -0
  66. package/dist/plugin/core/streaming/transformer.d.ts +9 -0
  67. package/dist/plugin/core/streaming/transformer.js +301 -0
  68. package/dist/plugin/core/streaming/types.d.ts +28 -0
  69. package/dist/plugin/core/streaming/types.js +1 -0
  70. package/dist/plugin/debug.d.ts +93 -0
  71. package/dist/plugin/debug.js +375 -0
  72. package/dist/plugin/errors.d.ts +27 -0
  73. package/dist/plugin/errors.js +41 -0
  74. package/dist/plugin/fingerprint.d.ts +69 -0
  75. package/dist/plugin/fingerprint.js +137 -0
  76. package/dist/plugin/image-saver.d.ts +24 -0
  77. package/dist/plugin/image-saver.js +78 -0
  78. package/dist/plugin/logger.d.ts +35 -0
  79. package/dist/plugin/logger.js +67 -0
  80. package/dist/plugin/logging-utils.d.ts +22 -0
  81. package/dist/plugin/logging-utils.js +91 -0
  82. package/dist/plugin/project.d.ts +32 -0
  83. package/dist/plugin/project.js +229 -0
  84. package/dist/plugin/quota.d.ts +34 -0
  85. package/dist/plugin/quota.js +261 -0
  86. package/dist/plugin/recovery/constants.d.ts +21 -0
  87. package/dist/plugin/recovery/constants.js +42 -0
  88. package/dist/plugin/recovery/index.d.ts +11 -0
  89. package/dist/plugin/recovery/index.js +11 -0
  90. package/dist/plugin/recovery/storage.d.ts +23 -0
  91. package/dist/plugin/recovery/storage.js +340 -0
  92. package/dist/plugin/recovery/types.d.ts +115 -0
  93. package/dist/plugin/recovery/types.js +6 -0
  94. package/dist/plugin/recovery.d.ts +60 -0
  95. package/dist/plugin/recovery.js +360 -0
  96. package/dist/plugin/refresh-queue.d.ts +99 -0
  97. package/dist/plugin/refresh-queue.js +235 -0
  98. package/dist/plugin/request-helpers.d.ts +281 -0
  99. package/dist/plugin/request-helpers.js +2200 -0
  100. package/dist/plugin/request.d.ts +110 -0
  101. package/dist/plugin/request.js +1489 -0
  102. package/dist/plugin/rotation.d.ts +182 -0
  103. package/dist/plugin/rotation.js +364 -0
  104. package/dist/plugin/search.d.ts +31 -0
  105. package/dist/plugin/search.js +185 -0
  106. package/dist/plugin/server.d.ts +22 -0
  107. package/dist/plugin/server.js +306 -0
  108. package/dist/plugin/storage.d.ts +136 -0
  109. package/dist/plugin/storage.js +599 -0
  110. package/dist/plugin/stores/signature-store.d.ts +4 -0
  111. package/dist/plugin/stores/signature-store.js +24 -0
  112. package/dist/plugin/thinking-recovery.d.ts +89 -0
  113. package/dist/plugin/thinking-recovery.js +289 -0
  114. package/dist/plugin/token.d.ts +18 -0
  115. package/dist/plugin/token.js +127 -0
  116. package/dist/plugin/transform/claude.d.ts +79 -0
  117. package/dist/plugin/transform/claude.js +256 -0
  118. package/dist/plugin/transform/cross-model-sanitizer.d.ts +34 -0
  119. package/dist/plugin/transform/cross-model-sanitizer.js +224 -0
  120. package/dist/plugin/transform/gemini.d.ts +132 -0
  121. package/dist/plugin/transform/gemini.js +659 -0
  122. package/dist/plugin/transform/index.d.ts +14 -0
  123. package/dist/plugin/transform/index.js +9 -0
  124. package/dist/plugin/transform/model-resolver.d.ts +98 -0
  125. package/dist/plugin/transform/model-resolver.js +320 -0
  126. package/dist/plugin/transform/types.d.ts +110 -0
  127. package/dist/plugin/transform/types.js +1 -0
  128. package/dist/plugin/types.d.ts +95 -0
  129. package/dist/plugin/types.js +1 -0
  130. package/dist/plugin/ui/ansi.d.ts +31 -0
  131. package/dist/plugin/ui/ansi.js +45 -0
  132. package/dist/plugin/ui/auth-menu.d.ts +47 -0
  133. package/dist/plugin/ui/auth-menu.js +199 -0
  134. package/dist/plugin/ui/confirm.d.ts +1 -0
  135. package/dist/plugin/ui/confirm.js +14 -0
  136. package/dist/plugin/ui/select.d.ts +22 -0
  137. package/dist/plugin/ui/select.js +243 -0
  138. package/dist/plugin/version.d.ts +18 -0
  139. package/dist/plugin/version.js +79 -0
  140. package/dist/src/antigravity/oauth.d.ts +30 -0
  141. package/dist/src/antigravity/oauth.js +170 -0
  142. package/dist/src/constants.d.ts +138 -0
  143. package/dist/src/constants.js +216 -0
  144. package/dist/src/hooks/auto-update-checker/cache.d.ts +2 -0
  145. package/dist/src/hooks/auto-update-checker/cache.js +70 -0
  146. package/dist/src/hooks/auto-update-checker/checker.d.ts +15 -0
  147. package/dist/src/hooks/auto-update-checker/checker.js +233 -0
  148. package/dist/src/hooks/auto-update-checker/constants.d.ts +8 -0
  149. package/dist/src/hooks/auto-update-checker/constants.js +22 -0
  150. package/dist/src/hooks/auto-update-checker/index.d.ts +33 -0
  151. package/dist/src/hooks/auto-update-checker/index.js +121 -0
  152. package/dist/src/hooks/auto-update-checker/logging.d.ts +2 -0
  153. package/dist/src/hooks/auto-update-checker/logging.js +8 -0
  154. package/dist/src/hooks/auto-update-checker/types.d.ts +24 -0
  155. package/dist/src/hooks/auto-update-checker/types.js +1 -0
  156. package/dist/src/index.d.ts +6 -0
  157. package/dist/src/index.js +5 -0
  158. package/dist/src/plugin/accounts.d.ts +173 -0
  159. package/dist/src/plugin/accounts.js +966 -0
  160. package/dist/src/plugin/auth.d.ts +20 -0
  161. package/dist/src/plugin/auth.js +44 -0
  162. package/dist/src/plugin/cache/index.d.ts +4 -0
  163. package/dist/src/plugin/cache/index.js +4 -0
  164. package/dist/src/plugin/cache/signature-cache.d.ts +110 -0
  165. package/dist/src/plugin/cache/signature-cache.js +347 -0
  166. package/dist/src/plugin/cache.d.ts +43 -0
  167. package/dist/src/plugin/cache.js +180 -0
  168. package/dist/src/plugin/cli.d.ts +26 -0
  169. package/dist/src/plugin/cli.js +126 -0
  170. package/dist/src/plugin/config/index.d.ts +15 -0
  171. package/dist/src/plugin/config/index.js +15 -0
  172. package/dist/src/plugin/config/loader.d.ts +38 -0
  173. package/dist/src/plugin/config/loader.js +150 -0
  174. package/dist/src/plugin/config/models.d.ts +26 -0
  175. package/dist/src/plugin/config/models.js +95 -0
  176. package/dist/src/plugin/config/schema.d.ts +144 -0
  177. package/dist/src/plugin/config/schema.js +458 -0
  178. package/dist/src/plugin/config/updater.d.ts +76 -0
  179. package/dist/src/plugin/config/updater.js +205 -0
  180. package/dist/src/plugin/core/streaming/index.d.ts +2 -0
  181. package/dist/src/plugin/core/streaming/index.js +2 -0
  182. package/dist/src/plugin/core/streaming/transformer.d.ts +9 -0
  183. package/dist/src/plugin/core/streaming/transformer.js +301 -0
  184. package/dist/src/plugin/core/streaming/types.d.ts +28 -0
  185. package/dist/src/plugin/core/streaming/types.js +1 -0
  186. package/dist/src/plugin/debug.d.ts +93 -0
  187. package/dist/src/plugin/debug.js +375 -0
  188. package/dist/src/plugin/errors.d.ts +27 -0
  189. package/dist/src/plugin/errors.js +41 -0
  190. package/dist/src/plugin/fingerprint.d.ts +69 -0
  191. package/dist/src/plugin/fingerprint.js +137 -0
  192. package/dist/src/plugin/image-saver.d.ts +24 -0
  193. package/dist/src/plugin/image-saver.js +78 -0
  194. package/dist/src/plugin/logger.d.ts +35 -0
  195. package/dist/src/plugin/logger.js +67 -0
  196. package/dist/src/plugin/logging-utils.d.ts +22 -0
  197. package/dist/src/plugin/logging-utils.js +91 -0
  198. package/dist/src/plugin/project.d.ts +32 -0
  199. package/dist/src/plugin/project.js +229 -0
  200. package/dist/src/plugin/quota.d.ts +34 -0
  201. package/dist/src/plugin/quota.js +261 -0
  202. package/dist/src/plugin/recovery/constants.d.ts +21 -0
  203. package/dist/src/plugin/recovery/constants.js +42 -0
  204. package/dist/src/plugin/recovery/index.d.ts +11 -0
  205. package/dist/src/plugin/recovery/index.js +11 -0
  206. package/dist/src/plugin/recovery/storage.d.ts +23 -0
  207. package/dist/src/plugin/recovery/storage.js +340 -0
  208. package/dist/src/plugin/recovery/types.d.ts +115 -0
  209. package/dist/src/plugin/recovery/types.js +6 -0
  210. package/dist/src/plugin/recovery.d.ts +60 -0
  211. package/dist/src/plugin/recovery.js +360 -0
  212. package/dist/src/plugin/refresh-queue.d.ts +99 -0
  213. package/dist/src/plugin/refresh-queue.js +235 -0
  214. package/dist/src/plugin/request-helpers.d.ts +281 -0
  215. package/dist/src/plugin/request-helpers.js +2200 -0
  216. package/dist/src/plugin/request.d.ts +110 -0
  217. package/dist/src/plugin/request.js +1489 -0
  218. package/dist/src/plugin/rotation.d.ts +182 -0
  219. package/dist/src/plugin/rotation.js +364 -0
  220. package/dist/src/plugin/search.d.ts +31 -0
  221. package/dist/src/plugin/search.js +185 -0
  222. package/dist/src/plugin/server.d.ts +22 -0
  223. package/dist/src/plugin/server.js +306 -0
  224. package/dist/src/plugin/storage.d.ts +136 -0
  225. package/dist/src/plugin/storage.js +599 -0
  226. package/dist/src/plugin/stores/signature-store.d.ts +4 -0
  227. package/dist/src/plugin/stores/signature-store.js +24 -0
  228. package/dist/src/plugin/thinking-recovery.d.ts +89 -0
  229. package/dist/src/plugin/thinking-recovery.js +289 -0
  230. package/dist/src/plugin/token.d.ts +18 -0
  231. package/dist/src/plugin/token.js +127 -0
  232. package/dist/src/plugin/transform/claude.d.ts +79 -0
  233. package/dist/src/plugin/transform/claude.js +256 -0
  234. package/dist/src/plugin/transform/cross-model-sanitizer.d.ts +34 -0
  235. package/dist/src/plugin/transform/cross-model-sanitizer.js +224 -0
  236. package/dist/src/plugin/transform/gemini.d.ts +132 -0
  237. package/dist/src/plugin/transform/gemini.js +659 -0
  238. package/dist/src/plugin/transform/index.d.ts +14 -0
  239. package/dist/src/plugin/transform/index.js +9 -0
  240. package/dist/src/plugin/transform/model-resolver.d.ts +98 -0
  241. package/dist/src/plugin/transform/model-resolver.js +320 -0
  242. package/dist/src/plugin/transform/types.d.ts +110 -0
  243. package/dist/src/plugin/transform/types.js +1 -0
  244. package/dist/src/plugin/types.d.ts +95 -0
  245. package/dist/src/plugin/types.js +1 -0
  246. package/dist/src/plugin/ui/ansi.d.ts +31 -0
  247. package/dist/src/plugin/ui/ansi.js +45 -0
  248. package/dist/src/plugin/ui/auth-menu.d.ts +47 -0
  249. package/dist/src/plugin/ui/auth-menu.js +199 -0
  250. package/dist/src/plugin/ui/confirm.d.ts +1 -0
  251. package/dist/src/plugin/ui/confirm.js +14 -0
  252. package/dist/src/plugin/ui/select.d.ts +22 -0
  253. package/dist/src/plugin/ui/select.js +243 -0
  254. package/dist/src/plugin/version.d.ts +18 -0
  255. package/dist/src/plugin/version.js +79 -0
  256. package/package.json +54 -0
@@ -0,0 +1,2200 @@
1
+ import { getKeepThinking } from "./config";
2
+ import { createLogger } from "./logger";
3
+ import { EMPTY_SCHEMA_PLACEHOLDER_NAME, EMPTY_SCHEMA_PLACEHOLDER_DESCRIPTION, SKIP_THOUGHT_SIGNATURE, } from "../constants";
4
+ import { processImageData } from "./image-saver";
5
+ const log = createLogger("request-helpers");
6
+ const ANTIGRAVITY_PREVIEW_LINK = "https://goo.gle/enable-preview-features"; // TODO: Update to Antigravity link if available
7
+ // ============================================================================
8
+ // Ported from CLIProxyAPI's CleanJSONSchemaForAntigravity (gemini_schema.go)
9
+ // ============================================================================
10
+ /**
11
+ * Unsupported constraint keywords that should be moved to description hints.
12
+ * Claude/Gemini reject these in VALIDATED mode.
13
+ */
14
+ const UNSUPPORTED_CONSTRAINTS = [
15
+ "minLength", "maxLength", "exclusiveMinimum", "exclusiveMaximum",
16
+ "pattern", "minItems", "maxItems", "format",
17
+ "default", "examples",
18
+ ];
19
+ /**
20
+ * Keywords that should be removed after hint extraction.
21
+ */
22
+ const UNSUPPORTED_KEYWORDS = [
23
+ ...UNSUPPORTED_CONSTRAINTS,
24
+ "$schema", "$defs", "definitions", "const", "$ref", "additionalProperties",
25
+ "propertyNames", "title", "$id", "$comment",
26
+ ];
27
+ /**
28
+ * Appends a hint to a schema's description field.
29
+ */
30
+ function appendDescriptionHint(schema, hint) {
31
+ if (!schema || typeof schema !== "object") {
32
+ return schema;
33
+ }
34
+ const existing = typeof schema.description === "string" ? schema.description : "";
35
+ const newDescription = existing ? `${existing} (${hint})` : hint;
36
+ return { ...schema, description: newDescription };
37
+ }
38
+ /**
39
+ * Phase 1a: Converts $ref to description hints.
40
+ * $ref: "#/$defs/Foo" → { type: "object", description: "See: Foo" }
41
+ */
42
+ function convertRefsToHints(schema) {
43
+ if (!schema || typeof schema !== "object") {
44
+ return schema;
45
+ }
46
+ if (Array.isArray(schema)) {
47
+ return schema.map(item => convertRefsToHints(item));
48
+ }
49
+ if (typeof schema.$ref === "string") {
50
+ const refVal = schema.$ref;
51
+ const defName = refVal.includes("/") ? refVal.split("/").pop() : refVal;
52
+ const hint = `See: ${defName}`;
53
+ const existingDesc = typeof schema.description === "string" ? schema.description : "";
54
+ const newDescription = existingDesc ? `${existingDesc} (${hint})` : hint;
55
+ return { type: "object", description: newDescription };
56
+ }
57
+ const result = {};
58
+ for (const [key, value] of Object.entries(schema)) {
59
+ result[key] = convertRefsToHints(value);
60
+ }
61
+ return result;
62
+ }
63
+ /**
64
+ * Phase 1b: Converts const to enum.
65
+ * { const: "foo" } → { enum: ["foo"] }
66
+ */
67
+ function convertConstToEnum(schema) {
68
+ if (!schema || typeof schema !== "object") {
69
+ return schema;
70
+ }
71
+ if (Array.isArray(schema)) {
72
+ return schema.map(item => convertConstToEnum(item));
73
+ }
74
+ const result = {};
75
+ for (const [key, value] of Object.entries(schema)) {
76
+ if (key === "const" && !schema.enum) {
77
+ result.enum = [value];
78
+ }
79
+ else {
80
+ result[key] = convertConstToEnum(value);
81
+ }
82
+ }
83
+ return result;
84
+ }
85
+ /**
86
+ * Phase 1c: Adds enum hints to description.
87
+ * { enum: ["a", "b", "c"] } → adds "(Allowed: a, b, c)" to description
88
+ */
89
+ function addEnumHints(schema) {
90
+ if (!schema || typeof schema !== "object") {
91
+ return schema;
92
+ }
93
+ if (Array.isArray(schema)) {
94
+ return schema.map(item => addEnumHints(item));
95
+ }
96
+ let result = { ...schema };
97
+ if (Array.isArray(result.enum) && result.enum.length > 1 && result.enum.length <= 10) {
98
+ const vals = result.enum.map((v) => String(v)).join(", ");
99
+ result = appendDescriptionHint(result, `Allowed: ${vals}`);
100
+ }
101
+ for (const [key, value] of Object.entries(result)) {
102
+ if (key !== "enum" && typeof value === "object" && value !== null) {
103
+ result[key] = addEnumHints(value);
104
+ }
105
+ }
106
+ return result;
107
+ }
108
+ /**
109
+ * Phase 1d: Adds additionalProperties hints.
110
+ * { additionalProperties: false } → adds "(No extra properties allowed)" to description
111
+ */
112
+ function addAdditionalPropertiesHints(schema) {
113
+ if (!schema || typeof schema !== "object") {
114
+ return schema;
115
+ }
116
+ if (Array.isArray(schema)) {
117
+ return schema.map(item => addAdditionalPropertiesHints(item));
118
+ }
119
+ let result = { ...schema };
120
+ if (result.additionalProperties === false) {
121
+ result = appendDescriptionHint(result, "No extra properties allowed");
122
+ }
123
+ for (const [key, value] of Object.entries(result)) {
124
+ if (key !== "additionalProperties" && typeof value === "object" && value !== null) {
125
+ result[key] = addAdditionalPropertiesHints(value);
126
+ }
127
+ }
128
+ return result;
129
+ }
130
+ /**
131
+ * Phase 1e: Moves unsupported constraints to description hints.
132
+ * { minLength: 1, maxLength: 100 } → adds "(minLength: 1) (maxLength: 100)" to description
133
+ */
134
+ function moveConstraintsToDescription(schema) {
135
+ if (!schema || typeof schema !== "object") {
136
+ return schema;
137
+ }
138
+ if (Array.isArray(schema)) {
139
+ return schema.map(item => moveConstraintsToDescription(item));
140
+ }
141
+ let result = { ...schema };
142
+ for (const constraint of UNSUPPORTED_CONSTRAINTS) {
143
+ if (result[constraint] !== undefined && typeof result[constraint] !== "object") {
144
+ result = appendDescriptionHint(result, `${constraint}: ${result[constraint]}`);
145
+ }
146
+ }
147
+ for (const [key, value] of Object.entries(result)) {
148
+ if (typeof value === "object" && value !== null) {
149
+ result[key] = moveConstraintsToDescription(value);
150
+ }
151
+ }
152
+ return result;
153
+ }
154
+ /**
155
+ * Phase 2a: Merges allOf schemas into a single object.
156
+ * { allOf: [{ properties: { a: ... } }, { properties: { b: ... } }] }
157
+ * → { properties: { a: ..., b: ... } }
158
+ */
159
+ function mergeAllOf(schema) {
160
+ if (!schema || typeof schema !== "object") {
161
+ return schema;
162
+ }
163
+ if (Array.isArray(schema)) {
164
+ return schema.map(item => mergeAllOf(item));
165
+ }
166
+ let result = { ...schema };
167
+ if (Array.isArray(result.allOf)) {
168
+ const merged = {};
169
+ const mergedRequired = [];
170
+ for (const item of result.allOf) {
171
+ if (!item || typeof item !== "object")
172
+ continue;
173
+ if (item.properties && typeof item.properties === "object") {
174
+ merged.properties = { ...merged.properties, ...item.properties };
175
+ }
176
+ if (Array.isArray(item.required)) {
177
+ for (const req of item.required) {
178
+ if (!mergedRequired.includes(req)) {
179
+ mergedRequired.push(req);
180
+ }
181
+ }
182
+ }
183
+ for (const [key, value] of Object.entries(item)) {
184
+ if (key !== "properties" && key !== "required" && merged[key] === undefined) {
185
+ merged[key] = value;
186
+ }
187
+ }
188
+ }
189
+ if (merged.properties) {
190
+ result.properties = { ...result.properties, ...merged.properties };
191
+ }
192
+ if (mergedRequired.length > 0) {
193
+ const existingRequired = Array.isArray(result.required) ? result.required : [];
194
+ result.required = Array.from(new Set([...existingRequired, ...mergedRequired]));
195
+ }
196
+ for (const [key, value] of Object.entries(merged)) {
197
+ if (key !== "properties" && key !== "required" && result[key] === undefined) {
198
+ result[key] = value;
199
+ }
200
+ }
201
+ delete result.allOf;
202
+ }
203
+ for (const [key, value] of Object.entries(result)) {
204
+ if (typeof value === "object" && value !== null) {
205
+ result[key] = mergeAllOf(value);
206
+ }
207
+ }
208
+ return result;
209
+ }
210
+ /**
211
+ * Scores a schema option for selection in anyOf/oneOf flattening.
212
+ * Higher score = more preferred.
213
+ */
214
+ function scoreSchemaOption(schema) {
215
+ if (!schema || typeof schema !== "object") {
216
+ return { score: 0, typeName: "unknown" };
217
+ }
218
+ const type = schema.type;
219
+ if (type === "object" || schema.properties) {
220
+ return { score: 3, typeName: "object" };
221
+ }
222
+ if (type === "array" || schema.items) {
223
+ return { score: 2, typeName: "array" };
224
+ }
225
+ if (type && type !== "null") {
226
+ return { score: 1, typeName: type };
227
+ }
228
+ return { score: 0, typeName: type || "null" };
229
+ }
230
+ /**
231
+ * Checks if an anyOf/oneOf array represents enum choices.
232
+ * Returns the merged enum values if so, otherwise null.
233
+ *
234
+ * Handles patterns like:
235
+ * - anyOf: [{ const: "a" }, { const: "b" }]
236
+ * - anyOf: [{ enum: ["a"] }, { enum: ["b"] }]
237
+ * - anyOf: [{ type: "string", const: "a" }, { type: "string", const: "b" }]
238
+ */
239
+ function tryMergeEnumFromUnion(options) {
240
+ if (!Array.isArray(options) || options.length === 0) {
241
+ return null;
242
+ }
243
+ const enumValues = [];
244
+ for (const option of options) {
245
+ if (!option || typeof option !== "object") {
246
+ return null;
247
+ }
248
+ if (option.const !== undefined) {
249
+ enumValues.push(String(option.const));
250
+ continue;
251
+ }
252
+ if (Array.isArray(option.enum) && option.enum.length === 1) {
253
+ enumValues.push(String(option.enum[0]));
254
+ continue;
255
+ }
256
+ if (Array.isArray(option.enum) && option.enum.length > 0) {
257
+ for (const val of option.enum) {
258
+ enumValues.push(String(val));
259
+ }
260
+ continue;
261
+ }
262
+ if (option.properties || option.items || option.anyOf || option.oneOf || option.allOf) {
263
+ return null;
264
+ }
265
+ if (option.type && !option.const && !option.enum) {
266
+ return null;
267
+ }
268
+ }
269
+ return enumValues.length > 0 ? enumValues : null;
270
+ }
271
+ /**
272
+ * Phase 2b: Flattens anyOf/oneOf to the best option with type hints.
273
+ * { anyOf: [{ type: "string" }, { type: "number" }] }
274
+ * → { type: "string", description: "(Accepts: string | number)" }
275
+ *
276
+ * Special handling for enum patterns:
277
+ * { anyOf: [{ const: "a" }, { const: "b" }] }
278
+ * → { type: "string", enum: ["a", "b"] }
279
+ */
280
+ function flattenAnyOfOneOf(schema) {
281
+ if (!schema || typeof schema !== "object") {
282
+ return schema;
283
+ }
284
+ if (Array.isArray(schema)) {
285
+ return schema.map(item => flattenAnyOfOneOf(item));
286
+ }
287
+ let result = { ...schema };
288
+ for (const unionKey of ["anyOf", "oneOf"]) {
289
+ if (Array.isArray(result[unionKey]) && result[unionKey].length > 0) {
290
+ const options = result[unionKey];
291
+ const parentDesc = typeof result.description === "string" ? result.description : "";
292
+ // This is crucial for tools like WebFetch where format: anyOf[{const:"text"},{const:"markdown"},{const:"html"}]
293
+ const mergedEnum = tryMergeEnumFromUnion(options);
294
+ if (mergedEnum !== null) {
295
+ const { [unionKey]: _, ...rest } = result;
296
+ result = {
297
+ ...rest,
298
+ type: "string",
299
+ enum: mergedEnum,
300
+ };
301
+ if (parentDesc) {
302
+ result.description = parentDesc;
303
+ }
304
+ continue;
305
+ }
306
+ let bestIdx = 0;
307
+ let bestScore = -1;
308
+ const allTypes = [];
309
+ for (let i = 0; i < options.length; i++) {
310
+ const { score, typeName } = scoreSchemaOption(options[i]);
311
+ if (typeName) {
312
+ allTypes.push(typeName);
313
+ }
314
+ if (score > bestScore) {
315
+ bestScore = score;
316
+ bestIdx = i;
317
+ }
318
+ }
319
+ let selected = flattenAnyOfOneOf(options[bestIdx]) || { type: "string" };
320
+ if (parentDesc) {
321
+ const childDesc = typeof selected.description === "string" ? selected.description : "";
322
+ if (childDesc && childDesc !== parentDesc) {
323
+ selected = { ...selected, description: `${parentDesc} (${childDesc})` };
324
+ }
325
+ else if (!childDesc) {
326
+ selected = { ...selected, description: parentDesc };
327
+ }
328
+ }
329
+ if (allTypes.length > 1) {
330
+ const uniqueTypes = Array.from(new Set(allTypes));
331
+ const hint = `Accepts: ${uniqueTypes.join(" | ")}`;
332
+ selected = appendDescriptionHint(selected, hint);
333
+ }
334
+ const { [unionKey]: _, description: __, ...rest } = result;
335
+ result = { ...rest, ...selected };
336
+ }
337
+ }
338
+ for (const [key, value] of Object.entries(result)) {
339
+ if (typeof value === "object" && value !== null) {
340
+ result[key] = flattenAnyOfOneOf(value);
341
+ }
342
+ }
343
+ return result;
344
+ }
345
+ /**
346
+ * Phase 2c: Flattens type arrays to single type with nullable hint.
347
+ * { type: ["string", "null"] } → { type: "string", description: "(nullable)" }
348
+ */
349
+ function flattenTypeArrays(schema, nullableFields, currentPath) {
350
+ if (!schema || typeof schema !== "object") {
351
+ return schema;
352
+ }
353
+ if (Array.isArray(schema)) {
354
+ return schema.map((item, idx) => flattenTypeArrays(item, nullableFields, `${currentPath || ""}[${idx}]`));
355
+ }
356
+ let result = { ...schema };
357
+ const localNullableFields = nullableFields || new Map();
358
+ if (Array.isArray(result.type)) {
359
+ const types = result.type;
360
+ const hasNull = types.includes("null");
361
+ const nonNullTypes = types.filter(t => t !== "null" && t);
362
+ const firstType = nonNullTypes.length > 0 ? nonNullTypes[0] : "string";
363
+ result.type = firstType;
364
+ if (nonNullTypes.length > 1) {
365
+ result = appendDescriptionHint(result, `Accepts: ${nonNullTypes.join(" | ")}`);
366
+ }
367
+ if (hasNull) {
368
+ result = appendDescriptionHint(result, "nullable");
369
+ }
370
+ }
371
+ if (result.properties && typeof result.properties === "object") {
372
+ const newProps = {};
373
+ for (const [propKey, propValue] of Object.entries(result.properties)) {
374
+ const propPath = currentPath ? `${currentPath}.properties.${propKey}` : `properties.${propKey}`;
375
+ const processed = flattenTypeArrays(propValue, localNullableFields, propPath);
376
+ newProps[propKey] = processed;
377
+ if (processed && typeof processed === "object" &&
378
+ typeof processed.description === "string" &&
379
+ processed.description.includes("nullable")) {
380
+ const objectPath = currentPath || "";
381
+ const existing = localNullableFields.get(objectPath) || [];
382
+ existing.push(propKey);
383
+ localNullableFields.set(objectPath, existing);
384
+ }
385
+ }
386
+ result.properties = newProps;
387
+ }
388
+ if (Array.isArray(result.required) && !nullableFields) {
389
+ const nullableAtRoot = localNullableFields.get("") || [];
390
+ if (nullableAtRoot.length > 0) {
391
+ result.required = result.required.filter((r) => !nullableAtRoot.includes(r));
392
+ if (result.required.length === 0) {
393
+ delete result.required;
394
+ }
395
+ }
396
+ }
397
+ for (const [key, value] of Object.entries(result)) {
398
+ if (key !== "properties" && typeof value === "object" && value !== null) {
399
+ result[key] = flattenTypeArrays(value, localNullableFields, `${currentPath || ""}.${key}`);
400
+ }
401
+ }
402
+ return result;
403
+ }
404
+ /**
405
+ * Phase 3: Removes unsupported keywords after hints have been extracted.
406
+ * @param insideProperties - When true, keys are property NAMES (preserve); when false, keys are JSON Schema keywords (filter).
407
+ */
408
+ function removeUnsupportedKeywords(schema, insideProperties = false) {
409
+ if (!schema || typeof schema !== "object") {
410
+ return schema;
411
+ }
412
+ if (Array.isArray(schema)) {
413
+ return schema.map(item => removeUnsupportedKeywords(item, false));
414
+ }
415
+ const result = {};
416
+ for (const [key, value] of Object.entries(schema)) {
417
+ if (!insideProperties && UNSUPPORTED_KEYWORDS.includes(key)) {
418
+ continue;
419
+ }
420
+ if (typeof value === "object" && value !== null) {
421
+ if (key === "properties") {
422
+ const propertiesResult = {};
423
+ for (const [propName, propSchema] of Object.entries(value)) {
424
+ propertiesResult[propName] = removeUnsupportedKeywords(propSchema, false);
425
+ }
426
+ result[key] = propertiesResult;
427
+ }
428
+ else {
429
+ result[key] = removeUnsupportedKeywords(value, false);
430
+ }
431
+ }
432
+ else {
433
+ result[key] = value;
434
+ }
435
+ }
436
+ return result;
437
+ }
438
+ /**
439
+ * Phase 3b: Cleans up required fields - removes entries that don't exist in properties.
440
+ */
441
+ function cleanupRequiredFields(schema) {
442
+ if (!schema || typeof schema !== "object") {
443
+ return schema;
444
+ }
445
+ if (Array.isArray(schema)) {
446
+ return schema.map(item => cleanupRequiredFields(item));
447
+ }
448
+ let result = { ...schema };
449
+ if (Array.isArray(result.required) && result.properties && typeof result.properties === "object") {
450
+ const validRequired = result.required.filter((req) => Object.prototype.hasOwnProperty.call(result.properties, req));
451
+ if (validRequired.length === 0) {
452
+ delete result.required;
453
+ }
454
+ else if (validRequired.length !== result.required.length) {
455
+ result.required = validRequired;
456
+ }
457
+ }
458
+ for (const [key, value] of Object.entries(result)) {
459
+ if (typeof value === "object" && value !== null) {
460
+ result[key] = cleanupRequiredFields(value);
461
+ }
462
+ }
463
+ return result;
464
+ }
465
+ /**
466
+ * Phase 4: Adds placeholder property for empty object schemas.
467
+ * Claude VALIDATED mode requires at least one property.
468
+ */
469
+ function addEmptySchemaPlaceholder(schema) {
470
+ if (!schema || typeof schema !== "object") {
471
+ return schema;
472
+ }
473
+ if (Array.isArray(schema)) {
474
+ return schema.map(item => addEmptySchemaPlaceholder(item));
475
+ }
476
+ let result = { ...schema };
477
+ const isObjectType = result.type === "object";
478
+ if (isObjectType) {
479
+ const hasProperties = result.properties &&
480
+ typeof result.properties === "object" &&
481
+ Object.keys(result.properties).length > 0;
482
+ if (!hasProperties) {
483
+ result.properties = {
484
+ [EMPTY_SCHEMA_PLACEHOLDER_NAME]: {
485
+ type: "boolean",
486
+ description: EMPTY_SCHEMA_PLACEHOLDER_DESCRIPTION,
487
+ },
488
+ };
489
+ result.required = [EMPTY_SCHEMA_PLACEHOLDER_NAME];
490
+ }
491
+ }
492
+ for (const [key, value] of Object.entries(result)) {
493
+ if (typeof value === "object" && value !== null) {
494
+ result[key] = addEmptySchemaPlaceholder(value);
495
+ }
496
+ }
497
+ return result;
498
+ }
499
+ /**
500
+ * Cleans a JSON schema for Antigravity API compatibility.
501
+ * Transforms unsupported features into description hints while preserving semantic information.
502
+ *
503
+ * Ported from CLIProxyAPI's CleanJSONSchemaForAntigravity (gemini_schema.go)
504
+ */
505
+ export function cleanJSONSchemaForAntigravity(schema) {
506
+ if (!schema || typeof schema !== "object") {
507
+ return schema;
508
+ }
509
+ let result = schema;
510
+ result = convertRefsToHints(result);
511
+ result = convertConstToEnum(result);
512
+ result = addEnumHints(result);
513
+ result = addAdditionalPropertiesHints(result);
514
+ result = moveConstraintsToDescription(result);
515
+ result = mergeAllOf(result);
516
+ result = flattenAnyOfOneOf(result);
517
+ result = flattenTypeArrays(result);
518
+ result = removeUnsupportedKeywords(result);
519
+ result = cleanupRequiredFields(result);
520
+ result = addEmptySchemaPlaceholder(result);
521
+ return result;
522
+ }
523
+ /**
524
+ * Default token budget for thinking/reasoning. 16000 tokens provides sufficient
525
+ * space for complex reasoning while staying within typical model limits.
526
+ */
527
+ export const DEFAULT_THINKING_BUDGET = 16000;
528
+ /**
529
+ * Checks if a model name indicates thinking/reasoning capability.
530
+ * Models with "thinking", "gemini-3", or "opus" in their name support extended thinking.
531
+ */
532
+ export function isThinkingCapableModel(modelName) {
533
+ const lowerModel = modelName.toLowerCase();
534
+ return lowerModel.includes("thinking")
535
+ || lowerModel.includes("gemini-3")
536
+ || lowerModel.includes("opus");
537
+ }
538
+ /**
539
+ * Extracts thinking configuration from various possible request locations.
540
+ * Supports both Gemini-style thinkingConfig and Anthropic-style thinking options.
541
+ */
542
+ export function extractThinkingConfig(requestPayload, rawGenerationConfig, extraBody) {
543
+ const thinkingConfig = rawGenerationConfig?.thinkingConfig
544
+ ?? extraBody?.thinkingConfig
545
+ ?? requestPayload.thinkingConfig;
546
+ if (thinkingConfig && typeof thinkingConfig === "object") {
547
+ const config = thinkingConfig;
548
+ return {
549
+ includeThoughts: Boolean(config.includeThoughts),
550
+ thinkingBudget: typeof config.thinkingBudget === "number" ? config.thinkingBudget : DEFAULT_THINKING_BUDGET,
551
+ };
552
+ }
553
+ // Convert Anthropic-style "thinking" option: { type: "enabled", budgetTokens: N }
554
+ const anthropicThinking = extraBody?.thinking ?? requestPayload.thinking;
555
+ if (anthropicThinking && typeof anthropicThinking === "object") {
556
+ const thinking = anthropicThinking;
557
+ if (thinking.type === "enabled" || thinking.budgetTokens) {
558
+ return {
559
+ includeThoughts: true,
560
+ thinkingBudget: typeof thinking.budgetTokens === "number" ? thinking.budgetTokens : DEFAULT_THINKING_BUDGET,
561
+ };
562
+ }
563
+ }
564
+ return undefined;
565
+ }
566
+ /**
567
+ * Extracts variant thinking config from OpenCode's providerOptions.
568
+ *
569
+ * All Antigravity models route through the Google provider, so we only check
570
+ * providerOptions.google. Supports two formats:
571
+ *
572
+ * 1. Gemini 3 native: { google: { thinkingLevel: "high", includeThoughts: true } }
573
+ * 2. Budget-based (Claude/Gemini 2.5): { google: { thinkingConfig: { thinkingBudget: 32000 } } }
574
+ *
575
+ * When providerOptions is missing or has no thinking config (common with OpenCode
576
+ * model variants), falls back to extracting from generationConfig directly:
577
+ * 3. generationConfig fallback: { thinkingConfig: { thinkingBudget: 8192 } }
578
+ */
579
+ export function extractVariantThinkingConfig(providerOptions, generationConfig) {
580
+ const result = {};
581
+ const google = (providerOptions?.google);
582
+ if (google) {
583
+ // Gemini 3 native format: { google: { thinkingLevel: "high", includeThoughts: true } }
584
+ if (typeof google.thinkingLevel === "string") {
585
+ result.thinkingLevel = google.thinkingLevel;
586
+ result.includeThoughts = typeof google.includeThoughts === "boolean" ? google.includeThoughts : undefined;
587
+ }
588
+ else if (google.thinkingConfig && typeof google.thinkingConfig === "object") {
589
+ // Budget-based format (Claude/Gemini 2.5): { google: { thinkingConfig: { thinkingBudget } } }
590
+ const tc = google.thinkingConfig;
591
+ if (typeof tc.thinkingBudget === "number") {
592
+ result.thinkingBudget = tc.thinkingBudget;
593
+ }
594
+ }
595
+ if (google.googleSearch && typeof google.googleSearch === "object") {
596
+ const search = google.googleSearch;
597
+ result.googleSearch = {
598
+ mode: search.mode === 'auto' || search.mode === 'off' ? search.mode : undefined,
599
+ threshold: typeof search.threshold === 'number' ? search.threshold : undefined,
600
+ };
601
+ }
602
+ }
603
+ if (result.thinkingBudget === undefined && !result.thinkingLevel && generationConfig) {
604
+ if (generationConfig.thinkingConfig && typeof generationConfig.thinkingConfig === "object") {
605
+ const tc = generationConfig.thinkingConfig;
606
+ if (typeof tc.thinkingLevel === "string") {
607
+ result.thinkingLevel = tc.thinkingLevel;
608
+ result.includeThoughts = typeof tc.includeThoughts === "boolean" ? tc.includeThoughts : undefined;
609
+ }
610
+ else if (typeof tc.thinkingBudget === "number") {
611
+ result.thinkingBudget = tc.thinkingBudget;
612
+ }
613
+ }
614
+ }
615
+ return Object.keys(result).length > 0 ? result : undefined;
616
+ }
617
+ /**
618
+ * Determines the final thinking configuration based on model capabilities and user settings.
619
+ * For Claude thinking models, we keep thinking enabled even in multi-turn conversations.
620
+ * The filterUnsignedThinkingBlocks function will handle signature validation/restoration.
621
+ */
622
+ export function resolveThinkingConfig(userConfig, isThinkingModel, _isClaudeModel, _hasAssistantHistory) {
623
+ if (isThinkingModel && !userConfig) {
624
+ return { includeThoughts: true, thinkingBudget: DEFAULT_THINKING_BUDGET };
625
+ }
626
+ return userConfig;
627
+ }
628
+ /**
629
+ * Checks if a part is a thinking/reasoning block (Anthropic or Gemini style).
630
+ */
631
+ function isThinkingPart(part) {
632
+ return part.type === "thinking"
633
+ || part.type === "redacted_thinking"
634
+ || part.type === "reasoning"
635
+ || part.thinking !== undefined
636
+ || part.thought === true;
637
+ }
638
+ /**
639
+ * Checks if a part has a signature field (thinking block signature).
640
+ * Used to detect foreign thinking blocks that might have unknown type values.
641
+ */
642
+ function hasSignatureField(part) {
643
+ return part.signature !== undefined || part.thoughtSignature !== undefined;
644
+ }
645
+ /**
646
+ * Checks if a part is a tool block (tool_use or tool_result).
647
+ * Tool blocks must never be filtered - they're required for tool call/result pairing.
648
+ * Handles multiple formats:
649
+ * - Anthropic: { type: "tool_use" }, { type: "tool_result", tool_use_id }
650
+ * - Nested: { tool_result: { tool_use_id } }, { tool_use: { id } }
651
+ * - Gemini: { functionCall }, { functionResponse }
652
+ */
653
+ function isToolBlock(part) {
654
+ return part.type === "tool_use"
655
+ || part.type === "tool_result"
656
+ || part.tool_use_id !== undefined
657
+ || part.tool_call_id !== undefined
658
+ || part.tool_result !== undefined
659
+ || part.tool_use !== undefined
660
+ || part.toolUse !== undefined
661
+ || part.functionCall !== undefined
662
+ || part.functionResponse !== undefined;
663
+ }
664
+ /**
665
+ * Unconditionally strips ALL thinking/reasoning blocks from a content array.
666
+ * Used for Claude models to avoid signature validation errors entirely.
667
+ * Claude will generate fresh thinking for each turn.
668
+ */
669
+ function stripAllThinkingBlocks(contentArray) {
670
+ return contentArray.filter(item => {
671
+ if (!item || typeof item !== "object")
672
+ return true;
673
+ if (isToolBlock(item))
674
+ return true;
675
+ if (isThinkingPart(item))
676
+ return false;
677
+ if (hasSignatureField(item))
678
+ return false;
679
+ return true;
680
+ });
681
+ }
682
+ /**
683
+ * Removes trailing thinking blocks from a content array.
684
+ * Claude API requires that assistant messages don't end with thinking blocks.
685
+ * Only removes unsigned thinking blocks; preserves those with valid signatures.
686
+ */
687
+ function removeTrailingThinkingBlocks(contentArray, sessionId, getCachedSignatureFn) {
688
+ const result = [...contentArray];
689
+ while (result.length > 0 && isThinkingPart(result[result.length - 1])) {
690
+ const part = result[result.length - 1];
691
+ const isValid = sessionId && getCachedSignatureFn
692
+ ? isOurCachedSignature(part, sessionId, getCachedSignatureFn)
693
+ : hasValidSignature(part);
694
+ if (isValid) {
695
+ break;
696
+ }
697
+ result.pop();
698
+ }
699
+ return result;
700
+ }
701
+ /**
702
+ * Checks if a thinking part has a valid signature.
703
+ * A valid signature is a non-empty string with at least 50 characters.
704
+ */
705
+ function hasValidSignature(part) {
706
+ const signature = part.thought === true ? part.thoughtSignature : part.signature;
707
+ return typeof signature === "string" && signature.length >= 50;
708
+ }
709
+ /**
710
+ * Gets the signature from a thinking part, if present.
711
+ */
712
+ function getSignature(part) {
713
+ const signature = part.thought === true ? part.thoughtSignature : part.signature;
714
+ return typeof signature === "string" ? signature : undefined;
715
+ }
716
+ /**
717
+ * Checks if a thinking part's signature was generated by our plugin (exists in our cache).
718
+ * This prevents accepting signatures from other providers (e.g., direct Anthropic API, OpenAI)
719
+ * which would cause "Invalid signature" errors when sent to Antigravity Claude.
720
+ */
721
+ function isOurCachedSignature(part, sessionId, getCachedSignatureFn) {
722
+ if (!sessionId || !getCachedSignatureFn) {
723
+ return false;
724
+ }
725
+ const text = getThinkingText(part);
726
+ if (!text) {
727
+ return false;
728
+ }
729
+ const partSignature = getSignature(part);
730
+ if (!partSignature) {
731
+ return false;
732
+ }
733
+ const cachedSignature = getCachedSignatureFn(sessionId, text);
734
+ return cachedSignature === partSignature;
735
+ }
736
+ /**
737
+ * Gets the text content from a thinking part.
738
+ */
739
+ function getThinkingText(part) {
740
+ if (typeof part.text === "string")
741
+ return part.text;
742
+ if (typeof part.thinking === "string")
743
+ return part.thinking;
744
+ if (part.text && typeof part.text === "object") {
745
+ const maybeText = part.text.text;
746
+ if (typeof maybeText === "string")
747
+ return maybeText;
748
+ }
749
+ if (part.thinking && typeof part.thinking === "object") {
750
+ const maybeText = part.thinking.text ?? part.thinking.thinking;
751
+ if (typeof maybeText === "string")
752
+ return maybeText;
753
+ }
754
+ return "";
755
+ }
756
+ /**
757
+ * Recursively strips cache_control and providerOptions from any object.
758
+ * These fields can be injected by SDKs, but Claude rejects them inside thinking blocks.
759
+ */
760
+ function stripCacheControlRecursively(obj) {
761
+ if (obj === null || obj === undefined)
762
+ return obj;
763
+ if (typeof obj !== "object")
764
+ return obj;
765
+ if (Array.isArray(obj))
766
+ return obj.map(item => stripCacheControlRecursively(item));
767
+ const result = {};
768
+ for (const [key, value] of Object.entries(obj)) {
769
+ if (key === "cache_control" || key === "providerOptions")
770
+ continue;
771
+ result[key] = stripCacheControlRecursively(value);
772
+ }
773
+ return result;
774
+ }
775
+ /**
776
+ * Sanitizes a thinking part by keeping only the allowed fields.
777
+ * In particular, ensures `thinking` is a string (not an object with cache_control).
778
+ * Returns null if the thinking block has no valid content.
779
+ */
780
+ function sanitizeThinkingPart(part) {
781
+ // Gemini-style thought blocks: { thought: true, text, thoughtSignature }
782
+ if (part.thought === true) {
783
+ let textContent = part.text;
784
+ if (typeof textContent === "object" && textContent !== null) {
785
+ const maybeText = textContent.text;
786
+ textContent = typeof maybeText === "string" ? maybeText : undefined;
787
+ }
788
+ const hasContent = typeof textContent === "string" && textContent.trim().length > 0;
789
+ if (!hasContent && !part.thoughtSignature) {
790
+ return null;
791
+ }
792
+ const sanitized = { thought: true };
793
+ if (textContent !== undefined)
794
+ sanitized.text = textContent;
795
+ if (part.thoughtSignature !== undefined)
796
+ sanitized.thoughtSignature = part.thoughtSignature;
797
+ return sanitized;
798
+ }
799
+ // Anthropic-style thinking/redacted_thinking blocks: { type: "thinking"|"redacted_thinking", thinking, signature }
800
+ if (part.type === "thinking" || part.type === "redacted_thinking" || part.thinking !== undefined) {
801
+ let thinkingContent = part.thinking ?? part.text;
802
+ if (thinkingContent !== undefined && typeof thinkingContent === "object" && thinkingContent !== null) {
803
+ const maybeText = thinkingContent.text ?? thinkingContent.thinking;
804
+ thinkingContent = typeof maybeText === "string" ? maybeText : undefined;
805
+ }
806
+ const hasContent = typeof thinkingContent === "string" && thinkingContent.trim().length > 0;
807
+ if (!hasContent && !part.signature) {
808
+ return null;
809
+ }
810
+ const sanitized = { type: part.type === "redacted_thinking" ? "redacted_thinking" : "thinking" };
811
+ if (thinkingContent !== undefined)
812
+ sanitized.thinking = thinkingContent;
813
+ if (part.signature !== undefined)
814
+ sanitized.signature = part.signature;
815
+ return sanitized;
816
+ }
817
+ // Reasoning blocks (OpenCode format): { type: "reasoning", text, signature }
818
+ if (part.type === "reasoning") {
819
+ let textContent = part.text;
820
+ if (typeof textContent === "object" && textContent !== null) {
821
+ const maybeText = textContent.text;
822
+ textContent = typeof maybeText === "string" ? maybeText : undefined;
823
+ }
824
+ const hasContent = typeof textContent === "string" && textContent.trim().length > 0;
825
+ if (!hasContent && !part.signature) {
826
+ return null;
827
+ }
828
+ const sanitized = { type: "reasoning" };
829
+ if (textContent !== undefined)
830
+ sanitized.text = textContent;
831
+ if (part.signature !== undefined)
832
+ sanitized.signature = part.signature;
833
+ return sanitized;
834
+ }
835
+ // Fallback: strip cache_control recursively.
836
+ return stripCacheControlRecursively(part);
837
+ }
838
+ function findLastAssistantIndex(contents, roleValue) {
839
+ for (let i = contents.length - 1; i >= 0; i--) {
840
+ const content = contents[i];
841
+ if (content && typeof content === "object" && content.role === roleValue) {
842
+ return i;
843
+ }
844
+ }
845
+ return -1;
846
+ }
847
+ function filterContentArray(contentArray, sessionId, getCachedSignatureFn, isClaudeModel, isLastAssistantMessage = false) {
848
+ // User can opt-in to keep thinking via config: { "keep_thinking": true }
849
+ if (isClaudeModel && !getKeepThinking()) {
850
+ return stripAllThinkingBlocks(contentArray);
851
+ }
852
+ const filtered = [];
853
+ for (const item of contentArray) {
854
+ if (!item || typeof item !== "object") {
855
+ filtered.push(item);
856
+ continue;
857
+ }
858
+ if (isToolBlock(item)) {
859
+ if (!isClaudeModel) {
860
+ filtered.push(item);
861
+ continue;
862
+ }
863
+ const sanitizedToolBlock = { ...item };
864
+ delete sanitizedToolBlock.signature;
865
+ delete sanitizedToolBlock.thoughtSignature;
866
+ delete sanitizedToolBlock.thought_signature;
867
+ delete sanitizedToolBlock.thought;
868
+ filtered.push(sanitizedToolBlock);
869
+ continue;
870
+ }
871
+ const isThinking = isThinkingPart(item);
872
+ const hasSignature = hasSignatureField(item);
873
+ if (!isThinking && !hasSignature) {
874
+ filtered.push(item);
875
+ continue;
876
+ }
877
+ if (isClaudeModel && (isThinking || hasSignature)) {
878
+ const thinkingText = getThinkingText(item) || "";
879
+ const sentinelPart = {
880
+ type: item.type === "redacted_thinking" ? "redacted_thinking" : "thinking",
881
+ thinking: thinkingText,
882
+ signature: SKIP_THOUGHT_SIGNATURE,
883
+ };
884
+ filtered.push(sentinelPart);
885
+ continue;
886
+ }
887
+ // - If signature is OUR cached signature, pass through unchanged
888
+ // - Otherwise inject sentinel to bypass Antigravity validation
889
+ if (isLastAssistantMessage && (isThinking || hasSignature)) {
890
+ if (isOurCachedSignature(item, sessionId, getCachedSignatureFn)) {
891
+ const sanitized = sanitizeThinkingPart(item);
892
+ if (sanitized)
893
+ filtered.push(sanitized);
894
+ continue;
895
+ }
896
+ const thinkingText = getThinkingText(item) || "";
897
+ const existingSignature = item.signature || item.thoughtSignature;
898
+ const signatureInfo = existingSignature ? `foreign signature (${String(existingSignature).length} chars)` : "no signature";
899
+ log.debug(`Injecting sentinel for last-message thinking block with ${signatureInfo}`);
900
+ const sentinelPart = {
901
+ type: item.type || "thinking",
902
+ thinking: thinkingText,
903
+ signature: SKIP_THOUGHT_SIGNATURE,
904
+ };
905
+ filtered.push(sentinelPart);
906
+ continue;
907
+ }
908
+ if (isOurCachedSignature(item, sessionId, getCachedSignatureFn)) {
909
+ const sanitized = sanitizeThinkingPart(item);
910
+ if (sanitized)
911
+ filtered.push(sanitized);
912
+ continue;
913
+ }
914
+ if (sessionId && getCachedSignatureFn) {
915
+ const text = getThinkingText(item);
916
+ if (text) {
917
+ const cachedSignature = getCachedSignatureFn(sessionId, text);
918
+ if (cachedSignature && cachedSignature.length >= 50) {
919
+ const restoredPart = { ...item };
920
+ if (item.thought === true) {
921
+ restoredPart.thoughtSignature = cachedSignature;
922
+ }
923
+ else {
924
+ restoredPart.signature = cachedSignature;
925
+ }
926
+ const sanitized = sanitizeThinkingPart(restoredPart);
927
+ if (sanitized)
928
+ filtered.push(sanitized);
929
+ continue;
930
+ }
931
+ }
932
+ }
933
+ }
934
+ return filtered;
935
+ }
936
+ /**
937
+ * Filters thinking blocks from contents unless the signature matches our cache.
938
+ * Attempts to restore signatures from cache for thinking blocks that lack signatures.
939
+ *
940
+ * @param contents - The contents array from the request
941
+ * @param sessionId - Optional session ID for signature cache lookup
942
+ * @param getCachedSignatureFn - Optional function to retrieve cached signatures
943
+ */
944
+ export function filterUnsignedThinkingBlocks(contents, sessionId, getCachedSignatureFn, isClaudeModel) {
945
+ const lastAssistantIdx = findLastAssistantIndex(contents, "model");
946
+ return contents.map((content, idx) => {
947
+ if (!content || typeof content !== "object") {
948
+ return content;
949
+ }
950
+ const isLastAssistant = idx === lastAssistantIdx;
951
+ if (Array.isArray(content.parts)) {
952
+ const filteredParts = filterContentArray(content.parts, sessionId, getCachedSignatureFn, isClaudeModel, isLastAssistant);
953
+ const trimmedParts = content.role === "model" && !isClaudeModel
954
+ ? removeTrailingThinkingBlocks(filteredParts, sessionId, getCachedSignatureFn)
955
+ : filteredParts;
956
+ return { ...content, parts: trimmedParts };
957
+ }
958
+ if (Array.isArray(content.content)) {
959
+ const isAssistantRole = content.role === "assistant";
960
+ const isLastAssistantContent = idx === lastAssistantIdx ||
961
+ (isAssistantRole && idx === findLastAssistantIndex(contents, "assistant"));
962
+ const filteredContent = filterContentArray(content.content, sessionId, getCachedSignatureFn, isClaudeModel, isLastAssistantContent);
963
+ const trimmedContent = isAssistantRole && !isClaudeModel
964
+ ? removeTrailingThinkingBlocks(filteredContent, sessionId, getCachedSignatureFn)
965
+ : filteredContent;
966
+ return { ...content, content: trimmedContent };
967
+ }
968
+ return content;
969
+ });
970
+ }
971
+ /**
972
+ * Filters thinking blocks from Anthropic-style messages[] payloads using cached signatures.
973
+ */
974
+ export function filterMessagesThinkingBlocks(messages, sessionId, getCachedSignatureFn, isClaudeModel) {
975
+ const lastAssistantIdx = findLastAssistantIndex(messages, "assistant");
976
+ return messages.map((message, idx) => {
977
+ if (!message || typeof message !== "object") {
978
+ return message;
979
+ }
980
+ if (Array.isArray(message.content)) {
981
+ const isAssistantRole = message.role === "assistant";
982
+ const isLastAssistant = isAssistantRole && idx === lastAssistantIdx;
983
+ const filteredContent = filterContentArray(message.content, sessionId, getCachedSignatureFn, isClaudeModel, isLastAssistant);
984
+ const trimmedContent = isAssistantRole && !isClaudeModel
985
+ ? removeTrailingThinkingBlocks(filteredContent, sessionId, getCachedSignatureFn)
986
+ : filteredContent;
987
+ return { ...message, content: trimmedContent };
988
+ }
989
+ return message;
990
+ });
991
+ }
992
+ export function deepFilterThinkingBlocks(payload, sessionId, getCachedSignatureFn, isClaudeModel) {
993
+ const visited = new WeakSet();
994
+ const walk = (value) => {
995
+ if (!value || typeof value !== "object") {
996
+ return;
997
+ }
998
+ if (visited.has(value)) {
999
+ return;
1000
+ }
1001
+ visited.add(value);
1002
+ if (Array.isArray(value)) {
1003
+ value.forEach((item) => walk(item));
1004
+ return;
1005
+ }
1006
+ const obj = value;
1007
+ if (Array.isArray(obj.contents)) {
1008
+ obj.contents = filterUnsignedThinkingBlocks(obj.contents, sessionId, getCachedSignatureFn, isClaudeModel);
1009
+ }
1010
+ if (Array.isArray(obj.messages)) {
1011
+ obj.messages = filterMessagesThinkingBlocks(obj.messages, sessionId, getCachedSignatureFn, isClaudeModel);
1012
+ }
1013
+ Object.keys(obj).forEach((key) => walk(obj[key]));
1014
+ };
1015
+ walk(payload);
1016
+ return payload;
1017
+ }
1018
+ /**
1019
+ * Transforms Gemini-style thought parts (thought: true) and Anthropic-style
1020
+ * thinking parts (type: "thinking") to reasoning format.
1021
+ * Claude responses through Antigravity may use candidates structure with Anthropic-style parts.
1022
+ */
1023
+ function transformGeminiCandidate(candidate) {
1024
+ if (!candidate || typeof candidate !== "object") {
1025
+ return candidate;
1026
+ }
1027
+ const content = candidate.content;
1028
+ if (!content || typeof content !== "object" || !Array.isArray(content.parts)) {
1029
+ return candidate;
1030
+ }
1031
+ const thinkingTexts = [];
1032
+ const transformedParts = content.parts.map((part) => {
1033
+ if (!part || typeof part !== "object") {
1034
+ return part;
1035
+ }
1036
+ if (part.thought === true) {
1037
+ const thinkingText = part.text || "";
1038
+ thinkingTexts.push(thinkingText);
1039
+ const transformed = { ...part, type: "reasoning" };
1040
+ if (part.cache_control)
1041
+ transformed.cache_control = part.cache_control;
1042
+ const sig = part.signature || part.thoughtSignature;
1043
+ if (sig) {
1044
+ transformed.providerMetadata = {
1045
+ anthropic: { signature: sig }
1046
+ };
1047
+ delete transformed.signature;
1048
+ delete transformed.thoughtSignature;
1049
+ }
1050
+ return transformed;
1051
+ }
1052
+ if (part.type === "thinking") {
1053
+ const thinkingText = part.thinking || part.text || "";
1054
+ thinkingTexts.push(thinkingText);
1055
+ const transformed = {
1056
+ ...part,
1057
+ type: "reasoning",
1058
+ text: thinkingText,
1059
+ thought: true,
1060
+ };
1061
+ if (part.cache_control)
1062
+ transformed.cache_control = part.cache_control;
1063
+ const sig = part.signature || part.thoughtSignature;
1064
+ if (sig) {
1065
+ transformed.providerMetadata = {
1066
+ anthropic: { signature: sig }
1067
+ };
1068
+ delete transformed.signature;
1069
+ delete transformed.thoughtSignature;
1070
+ }
1071
+ return transformed;
1072
+ }
1073
+ // (Ported from LLM-API-Key-Proxy's _extract_tool_call)
1074
+ // opencode expects state.input to be a record, so we must ensure args: {} as fallback.
1075
+ if (part.functionCall) {
1076
+ const parsedArgs = part.functionCall.args
1077
+ ? recursivelyParseJsonStrings(part.functionCall.args)
1078
+ : {};
1079
+ return {
1080
+ ...part,
1081
+ functionCall: {
1082
+ ...part.functionCall,
1083
+ args: parsedArgs,
1084
+ },
1085
+ };
1086
+ }
1087
+ if (part.inlineData) {
1088
+ const result = processImageData({
1089
+ mimeType: part.inlineData.mimeType,
1090
+ data: part.inlineData.data,
1091
+ });
1092
+ if (result) {
1093
+ return { text: result };
1094
+ }
1095
+ }
1096
+ return part;
1097
+ });
1098
+ return {
1099
+ ...candidate,
1100
+ content: { ...content, parts: transformedParts },
1101
+ ...(thinkingTexts.length > 0 ? { reasoning_content: thinkingTexts.join("\n\n") } : {}),
1102
+ };
1103
+ }
1104
+ /**
1105
+ * Transforms thinking/reasoning content in response parts to OpenCode's expected format.
1106
+ * Handles both Gemini-style (thought: true) and Anthropic-style (type: "thinking") formats.
1107
+ * Also extracts reasoning_content for Anthropic-style responses.
1108
+ */
1109
+ export function transformThinkingParts(response) {
1110
+ if (!response || typeof response !== "object") {
1111
+ return response;
1112
+ }
1113
+ const resp = response;
1114
+ const result = { ...resp };
1115
+ const reasoningTexts = [];
1116
+ if (Array.isArray(resp.content)) {
1117
+ const transformedContent = [];
1118
+ for (const block of resp.content) {
1119
+ if (block && typeof block === "object" && block.type === "thinking") {
1120
+ const thinkingText = block.thinking || block.text || "";
1121
+ reasoningTexts.push(thinkingText);
1122
+ const transformed = {
1123
+ ...block,
1124
+ type: "reasoning",
1125
+ text: thinkingText,
1126
+ thought: true,
1127
+ };
1128
+ const sig = block.signature || block.thoughtSignature;
1129
+ if (sig) {
1130
+ transformed.providerMetadata = {
1131
+ anthropic: { signature: sig }
1132
+ };
1133
+ delete transformed.signature;
1134
+ delete transformed.thoughtSignature;
1135
+ }
1136
+ transformedContent.push(transformed);
1137
+ }
1138
+ else {
1139
+ transformedContent.push(block);
1140
+ }
1141
+ }
1142
+ result.content = transformedContent;
1143
+ }
1144
+ if (Array.isArray(resp.candidates)) {
1145
+ result.candidates = resp.candidates.map(transformGeminiCandidate);
1146
+ }
1147
+ // Add reasoning_content if we found any thinking blocks (for Anthropic-style)
1148
+ if (reasoningTexts.length > 0 && !result.reasoning_content) {
1149
+ result.reasoning_content = reasoningTexts.join("\n\n");
1150
+ }
1151
+ return result;
1152
+ }
1153
+ /**
1154
+ * Ensures thinkingConfig is valid: includeThoughts only allowed when budget > 0.
1155
+ */
1156
+ export function normalizeThinkingConfig(config) {
1157
+ if (!config || typeof config !== "object") {
1158
+ return undefined;
1159
+ }
1160
+ const record = config;
1161
+ const budgetRaw = record.thinkingBudget ?? record.thinking_budget;
1162
+ const includeRaw = record.includeThoughts ?? record.include_thoughts;
1163
+ const thinkingBudget = typeof budgetRaw === "number" && Number.isFinite(budgetRaw) ? budgetRaw : undefined;
1164
+ const includeThoughts = typeof includeRaw === "boolean" ? includeRaw : undefined;
1165
+ const enableThinking = thinkingBudget !== undefined && thinkingBudget > 0;
1166
+ const finalInclude = enableThinking ? includeThoughts ?? false : false;
1167
+ if (!enableThinking && finalInclude === false && thinkingBudget === undefined && includeThoughts === undefined) {
1168
+ return undefined;
1169
+ }
1170
+ const normalized = {};
1171
+ if (thinkingBudget !== undefined) {
1172
+ normalized.thinkingBudget = thinkingBudget;
1173
+ }
1174
+ if (finalInclude !== undefined) {
1175
+ normalized.includeThoughts = finalInclude;
1176
+ }
1177
+ return normalized;
1178
+ }
1179
+ /**
1180
+ * Parses an Antigravity API body; handles array-wrapped responses the API sometimes returns.
1181
+ */
1182
+ export function parseAntigravityApiBody(rawText) {
1183
+ try {
1184
+ const parsed = JSON.parse(rawText);
1185
+ if (Array.isArray(parsed)) {
1186
+ const firstObject = parsed.find((item) => typeof item === "object" && item !== null);
1187
+ if (firstObject && typeof firstObject === "object") {
1188
+ return firstObject;
1189
+ }
1190
+ return null;
1191
+ }
1192
+ if (parsed && typeof parsed === "object") {
1193
+ return parsed;
1194
+ }
1195
+ return null;
1196
+ }
1197
+ catch {
1198
+ return null;
1199
+ }
1200
+ }
1201
+ /**
1202
+ * Extracts usageMetadata from a response object, guarding types.
1203
+ */
1204
+ export function extractUsageMetadata(body) {
1205
+ const usage = (body.response && typeof body.response === "object"
1206
+ ? body.response.usageMetadata
1207
+ : undefined);
1208
+ if (!usage || typeof usage !== "object") {
1209
+ return null;
1210
+ }
1211
+ const asRecord = usage;
1212
+ const toNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : undefined;
1213
+ return {
1214
+ totalTokenCount: toNumber(asRecord.totalTokenCount),
1215
+ promptTokenCount: toNumber(asRecord.promptTokenCount),
1216
+ candidatesTokenCount: toNumber(asRecord.candidatesTokenCount),
1217
+ cachedContentTokenCount: toNumber(asRecord.cachedContentTokenCount),
1218
+ thoughtsTokenCount: toNumber(asRecord.thoughtsTokenCount),
1219
+ };
1220
+ }
1221
+ /**
1222
+ * Walks SSE lines to find a usage-bearing response chunk.
1223
+ */
1224
+ export function extractUsageFromSsePayload(payload) {
1225
+ const lines = payload.split("\n");
1226
+ for (const line of lines) {
1227
+ if (!line.startsWith("data:")) {
1228
+ continue;
1229
+ }
1230
+ const jsonText = line.slice(5).trim();
1231
+ if (!jsonText) {
1232
+ continue;
1233
+ }
1234
+ try {
1235
+ const parsed = JSON.parse(jsonText);
1236
+ if (parsed && typeof parsed === "object") {
1237
+ const usage = extractUsageMetadata({ response: parsed.response });
1238
+ if (usage) {
1239
+ return usage;
1240
+ }
1241
+ }
1242
+ }
1243
+ catch {
1244
+ continue;
1245
+ }
1246
+ }
1247
+ return null;
1248
+ }
1249
+ /**
1250
+ * Enhances 404 errors for Antigravity models with a direct preview-access message.
1251
+ */
1252
+ export function rewriteAntigravityPreviewAccessError(body, status, requestedModel) {
1253
+ if (!needsPreviewAccessOverride(status, body, requestedModel)) {
1254
+ return null;
1255
+ }
1256
+ const error = body.error ?? {};
1257
+ const trimmedMessage = typeof error.message === "string" ? error.message.trim() : "";
1258
+ const messagePrefix = trimmedMessage.length > 0
1259
+ ? trimmedMessage
1260
+ : "Antigravity preview features are not enabled for this account.";
1261
+ const enhancedMessage = `${messagePrefix} Request preview access at ${ANTIGRAVITY_PREVIEW_LINK} before using this model.`;
1262
+ return {
1263
+ ...body,
1264
+ error: {
1265
+ ...error,
1266
+ message: enhancedMessage,
1267
+ },
1268
+ };
1269
+ }
1270
+ function needsPreviewAccessOverride(status, body, requestedModel) {
1271
+ if (status !== 404) {
1272
+ return false;
1273
+ }
1274
+ if (isAntigravityModel(requestedModel)) {
1275
+ return true;
1276
+ }
1277
+ const errorMessage = typeof body.error?.message === "string" ? body.error.message : "";
1278
+ return isAntigravityModel(errorMessage);
1279
+ }
1280
+ function isAntigravityModel(target) {
1281
+ if (!target) {
1282
+ return false;
1283
+ }
1284
+ return /antigravity/i.test(target) || /opus/i.test(target) || /claude/i.test(target);
1285
+ }
1286
+ // ============================================================================
1287
+ // ============================================================================
1288
+ /**
1289
+ * Checks if a JSON response body represents an empty response.
1290
+ *
1291
+ * Empty responses occur when:
1292
+ * - No candidates in Gemini format
1293
+ * - No choices in OpenAI format
1294
+ * - Candidates/choices exist but have no content
1295
+ *
1296
+ * @param text - The response body text (should be valid JSON)
1297
+ * @returns true if the response is empty
1298
+ */
1299
+ export function isEmptyResponseBody(text) {
1300
+ if (!text || !text.trim()) {
1301
+ return true;
1302
+ }
1303
+ try {
1304
+ const parsed = JSON.parse(text);
1305
+ if (parsed.candidates !== undefined) {
1306
+ if (!Array.isArray(parsed.candidates) || parsed.candidates.length === 0) {
1307
+ return true;
1308
+ }
1309
+ const firstCandidate = parsed.candidates[0];
1310
+ if (!firstCandidate) {
1311
+ return true;
1312
+ }
1313
+ const content = firstCandidate.content;
1314
+ if (!content || typeof content !== "object") {
1315
+ return true;
1316
+ }
1317
+ const parts = content.parts;
1318
+ if (!Array.isArray(parts) || parts.length === 0) {
1319
+ return true;
1320
+ }
1321
+ const hasContent = parts.some((part) => {
1322
+ if (!part || typeof part !== "object")
1323
+ return false;
1324
+ if (typeof part.text === "string" && part.text.length > 0)
1325
+ return true;
1326
+ if (part.functionCall)
1327
+ return true;
1328
+ if (part.thought === true && typeof part.text === "string")
1329
+ return true;
1330
+ return false;
1331
+ });
1332
+ if (!hasContent) {
1333
+ return true;
1334
+ }
1335
+ }
1336
+ if (parsed.choices !== undefined) {
1337
+ if (!Array.isArray(parsed.choices) || parsed.choices.length === 0) {
1338
+ return true;
1339
+ }
1340
+ const firstChoice = parsed.choices[0];
1341
+ if (!firstChoice) {
1342
+ return true;
1343
+ }
1344
+ const message = firstChoice.message || firstChoice.delta;
1345
+ if (!message) {
1346
+ return true;
1347
+ }
1348
+ // Check if message has content or tool_calls
1349
+ if (!message.content && !message.tool_calls && !message.reasoning_content) {
1350
+ return true;
1351
+ }
1352
+ }
1353
+ if (parsed.response !== undefined) {
1354
+ const response = parsed.response;
1355
+ if (!response || typeof response !== "object") {
1356
+ return true;
1357
+ }
1358
+ return isEmptyResponseBody(JSON.stringify(response));
1359
+ }
1360
+ return false;
1361
+ }
1362
+ catch {
1363
+ return true;
1364
+ }
1365
+ }
1366
+ export function createStreamingChunkCounter() {
1367
+ let count = 0;
1368
+ let hasRealContent = false;
1369
+ return {
1370
+ increment: () => {
1371
+ count++;
1372
+ },
1373
+ getCount: () => count,
1374
+ hasContent: () => hasRealContent || count > 0,
1375
+ };
1376
+ }
1377
+ /**
1378
+ * Checks if an SSE line contains meaningful content.
1379
+ *
1380
+ * @param line - A single SSE line (e.g., "data: {...}")
1381
+ * @returns true if the line contains content worth counting
1382
+ */
1383
+ export function isMeaningfulSseLine(line) {
1384
+ if (!line.startsWith("data: ")) {
1385
+ return false;
1386
+ }
1387
+ const data = line.slice(6).trim();
1388
+ if (data === "[DONE]") {
1389
+ return false;
1390
+ }
1391
+ if (!data) {
1392
+ return false;
1393
+ }
1394
+ try {
1395
+ const parsed = JSON.parse(data);
1396
+ if (parsed.candidates && Array.isArray(parsed.candidates)) {
1397
+ for (const candidate of parsed.candidates) {
1398
+ const parts = candidate?.content?.parts;
1399
+ if (Array.isArray(parts) && parts.length > 0) {
1400
+ for (const part of parts) {
1401
+ if (typeof part?.text === "string" && part.text.length > 0)
1402
+ return true;
1403
+ if (part?.functionCall)
1404
+ return true;
1405
+ }
1406
+ }
1407
+ }
1408
+ }
1409
+ if (parsed.response?.candidates) {
1410
+ return isMeaningfulSseLine(`data: ${JSON.stringify(parsed.response)}`);
1411
+ }
1412
+ return false;
1413
+ }
1414
+ catch {
1415
+ return false;
1416
+ }
1417
+ }
1418
+ // ============================================================================
1419
+ // ============================================================================
1420
+ /**
1421
+ * Recursively parses JSON strings in nested data structures.
1422
+ *
1423
+ * This is a port of LLM-API-Key-Proxy's _recursively_parse_json_strings() function.
1424
+ *
1425
+ * Handles:
1426
+ * - JSON-stringified values: {"files": "[{...}]"} → {"files": [{...}]}
1427
+ * - Malformed double-encoded JSON (extra trailing chars)
1428
+ * - Escaped control characters (\\n → \n, \\t → \t)
1429
+ *
1430
+ * This is useful because Antigravity sometimes returns JSON-stringified values
1431
+ * in tool arguments, which can cause downstream parsing issues.
1432
+ *
1433
+ * @param obj - The object to recursively parse
1434
+ * @param skipParseKeys - Set of keys whose values should NOT be parsed as JSON (preserved as strings)
1435
+ * @param currentKey - The current key being processed (internal use)
1436
+ * @returns The parsed object with JSON strings expanded
1437
+ */
1438
+ const SKIP_PARSE_KEYS = new Set([
1439
+ "oldString",
1440
+ "newString",
1441
+ "content",
1442
+ "filePath",
1443
+ "path",
1444
+ "text",
1445
+ "code",
1446
+ "source",
1447
+ "data",
1448
+ "body",
1449
+ "message",
1450
+ "prompt",
1451
+ "input",
1452
+ "output",
1453
+ "result",
1454
+ "value",
1455
+ "query",
1456
+ "pattern",
1457
+ "replacement",
1458
+ "template",
1459
+ "script",
1460
+ "command",
1461
+ "snippet",
1462
+ ]);
1463
+ export function recursivelyParseJsonStrings(obj, skipParseKeys = SKIP_PARSE_KEYS, currentKey) {
1464
+ if (obj === null || obj === undefined) {
1465
+ return obj;
1466
+ }
1467
+ if (Array.isArray(obj)) {
1468
+ return obj.map((item) => recursivelyParseJsonStrings(item, skipParseKeys));
1469
+ }
1470
+ if (typeof obj === "object") {
1471
+ const result = {};
1472
+ for (const [key, value] of Object.entries(obj)) {
1473
+ result[key] = recursivelyParseJsonStrings(value, skipParseKeys, key);
1474
+ }
1475
+ return result;
1476
+ }
1477
+ if (typeof obj !== "string") {
1478
+ return obj;
1479
+ }
1480
+ if (currentKey && skipParseKeys.has(currentKey)) {
1481
+ return obj;
1482
+ }
1483
+ const stripped = obj.trim();
1484
+ const hasControlCharEscapes = obj.includes("\\n") || obj.includes("\\t");
1485
+ const hasIntentionalEscapes = obj.includes('\\"') || obj.includes("\\\\");
1486
+ if (hasControlCharEscapes && !hasIntentionalEscapes) {
1487
+ try {
1488
+ return JSON.parse(`"${obj}"`);
1489
+ }
1490
+ catch {
1491
+ }
1492
+ }
1493
+ // Check if it looks like JSON (starts with { or [)
1494
+ if (stripped && (stripped[0] === "{" || stripped[0] === "[")) {
1495
+ if ((stripped.startsWith("{") && stripped.endsWith("}")) ||
1496
+ (stripped.startsWith("[") && stripped.endsWith("]"))) {
1497
+ try {
1498
+ const parsed = JSON.parse(obj);
1499
+ return recursivelyParseJsonStrings(parsed);
1500
+ }
1501
+ catch {
1502
+ }
1503
+ }
1504
+ if (stripped.startsWith("[") && !stripped.endsWith("]")) {
1505
+ try {
1506
+ const lastBracket = stripped.lastIndexOf("]");
1507
+ if (lastBracket > 0) {
1508
+ const cleaned = stripped.slice(0, lastBracket + 1);
1509
+ const parsed = JSON.parse(cleaned);
1510
+ log.debug("Auto-corrected malformed JSON array", {
1511
+ truncatedChars: stripped.length - cleaned.length,
1512
+ });
1513
+ return recursivelyParseJsonStrings(parsed);
1514
+ }
1515
+ }
1516
+ catch {
1517
+ }
1518
+ }
1519
+ // Handle malformed JSON: object that doesn't end with }
1520
+ if (stripped.startsWith("{") && !stripped.endsWith("}")) {
1521
+ try {
1522
+ const lastBrace = stripped.lastIndexOf("}");
1523
+ if (lastBrace > 0) {
1524
+ const cleaned = stripped.slice(0, lastBrace + 1);
1525
+ const parsed = JSON.parse(cleaned);
1526
+ log.debug("Auto-corrected malformed JSON object", {
1527
+ truncatedChars: stripped.length - cleaned.length,
1528
+ });
1529
+ return recursivelyParseJsonStrings(parsed);
1530
+ }
1531
+ }
1532
+ catch {
1533
+ }
1534
+ }
1535
+ }
1536
+ return obj;
1537
+ }
1538
+ // ============================================================================
1539
+ // ============================================================================
1540
+ /**
1541
+ * Groups function calls with their responses, handling ID mismatches.
1542
+ *
1543
+ * This is a port of LLM-API-Key-Proxy's _fix_tool_response_grouping() function.
1544
+ *
1545
+ * When context compaction or other processes strip tool responses, the tool call
1546
+ * IDs become orphaned. This function attempts to recover by:
1547
+ *
1548
+ * 1. Pass 1: Match by exact ID (normal case)
1549
+ * 2. Pass 2: Match by function name (for ID mismatches)
1550
+ * 3. Pass 3: Match "unknown_function" orphans or take first available
1551
+ * 4. Fallback: Create placeholder responses for missing tool results
1552
+ *
1553
+ * @param contents - Array of Gemini-style content messages
1554
+ * @returns Fixed contents array with matched tool responses
1555
+ */
1556
+ export function fixToolResponseGrouping(contents) {
1557
+ if (!Array.isArray(contents) || contents.length === 0) {
1558
+ return contents;
1559
+ }
1560
+ const newContents = [];
1561
+ const pendingGroups = [];
1562
+ const collectedResponses = new Map();
1563
+ for (const content of contents) {
1564
+ const role = content.role;
1565
+ const parts = content.parts || [];
1566
+ const responseParts = parts.filter((p) => p?.functionResponse);
1567
+ if (responseParts.length > 0) {
1568
+ for (const resp of responseParts) {
1569
+ const respId = resp.functionResponse?.id || "";
1570
+ if (respId && !collectedResponses.has(respId)) {
1571
+ collectedResponses.set(respId, resp);
1572
+ }
1573
+ }
1574
+ for (let i = pendingGroups.length - 1; i >= 0; i--) {
1575
+ const group = pendingGroups[i];
1576
+ if (group.ids.every(id => collectedResponses.has(id))) {
1577
+ const groupResponses = group.ids.map(id => {
1578
+ const resp = collectedResponses.get(id);
1579
+ collectedResponses.delete(id);
1580
+ return resp;
1581
+ });
1582
+ newContents.push({ parts: groupResponses, role: "user" });
1583
+ pendingGroups.splice(i, 1);
1584
+ break; // Only satisfy one group at a time
1585
+ }
1586
+ }
1587
+ continue; // Don't add the original response message
1588
+ }
1589
+ if (role === "model") {
1590
+ const funcCalls = parts.filter((p) => p?.functionCall);
1591
+ newContents.push(content);
1592
+ if (funcCalls.length > 0) {
1593
+ const callIds = funcCalls
1594
+ .map((fc) => fc.functionCall?.id || "")
1595
+ .filter(Boolean);
1596
+ const funcNames = funcCalls
1597
+ .map((fc) => fc.functionCall?.name || "");
1598
+ if (callIds.length > 0) {
1599
+ pendingGroups.push({
1600
+ ids: callIds,
1601
+ funcNames,
1602
+ insertAfterIdx: newContents.length - 1,
1603
+ });
1604
+ }
1605
+ }
1606
+ }
1607
+ else {
1608
+ newContents.push(content);
1609
+ }
1610
+ }
1611
+ pendingGroups.sort((a, b) => b.insertAfterIdx - a.insertAfterIdx);
1612
+ for (const group of pendingGroups) {
1613
+ const groupResponses = [];
1614
+ for (let i = 0; i < group.ids.length; i++) {
1615
+ const expectedId = group.ids[i];
1616
+ const expectedName = group.funcNames[i] || "";
1617
+ if (collectedResponses.has(expectedId)) {
1618
+ groupResponses.push(collectedResponses.get(expectedId));
1619
+ collectedResponses.delete(expectedId);
1620
+ }
1621
+ else if (collectedResponses.size > 0) {
1622
+ let matchedId = null;
1623
+ for (const [orphanId, orphanResp] of collectedResponses) {
1624
+ const orphanName = orphanResp.functionResponse?.name || "";
1625
+ if (orphanName === expectedName) {
1626
+ matchedId = orphanId;
1627
+ break;
1628
+ }
1629
+ }
1630
+ // Pass 2: Match "unknown_function" orphans
1631
+ if (!matchedId) {
1632
+ for (const [orphanId, orphanResp] of collectedResponses) {
1633
+ if (orphanResp.functionResponse?.name === "unknown_function") {
1634
+ matchedId = orphanId;
1635
+ break;
1636
+ }
1637
+ }
1638
+ }
1639
+ if (!matchedId) {
1640
+ matchedId = collectedResponses.keys().next().value ?? null;
1641
+ }
1642
+ if (matchedId) {
1643
+ const orphanResp = collectedResponses.get(matchedId);
1644
+ collectedResponses.delete(matchedId);
1645
+ orphanResp.functionResponse.id = expectedId;
1646
+ if (orphanResp.functionResponse.name === "unknown_function" && expectedName) {
1647
+ orphanResp.functionResponse.name = expectedName;
1648
+ }
1649
+ log.debug("Auto-repaired tool ID mismatch", {
1650
+ mappedFrom: matchedId,
1651
+ mappedTo: expectedId,
1652
+ functionName: expectedName,
1653
+ });
1654
+ groupResponses.push(orphanResp);
1655
+ }
1656
+ }
1657
+ else {
1658
+ const placeholder = {
1659
+ functionResponse: {
1660
+ name: expectedName || "unknown_function",
1661
+ response: {
1662
+ result: {
1663
+ error: "Tool response was lost during context processing. " +
1664
+ "This is a recovered placeholder.",
1665
+ recovered: true,
1666
+ },
1667
+ },
1668
+ id: expectedId,
1669
+ },
1670
+ };
1671
+ log.debug("Created placeholder response for missing tool", {
1672
+ id: expectedId,
1673
+ name: expectedName,
1674
+ });
1675
+ groupResponses.push(placeholder);
1676
+ }
1677
+ }
1678
+ if (groupResponses.length > 0) {
1679
+ newContents.splice(group.insertAfterIdx + 1, 0, {
1680
+ parts: groupResponses,
1681
+ role: "user",
1682
+ });
1683
+ }
1684
+ }
1685
+ return newContents;
1686
+ }
1687
+ /**
1688
+ * Checks if contents have any tool call/response ID mismatches.
1689
+ *
1690
+ * @param contents - Array of Gemini-style content messages
1691
+ * @returns Object with mismatch details
1692
+ */
1693
+ export function detectToolIdMismatches(contents) {
1694
+ const expectedIds = [];
1695
+ const foundIds = [];
1696
+ for (const content of contents) {
1697
+ const parts = content.parts || [];
1698
+ for (const part of parts) {
1699
+ if (part?.functionCall?.id) {
1700
+ expectedIds.push(part.functionCall.id);
1701
+ }
1702
+ if (part?.functionResponse?.id) {
1703
+ foundIds.push(part.functionResponse.id);
1704
+ }
1705
+ }
1706
+ }
1707
+ const expectedSet = new Set(expectedIds);
1708
+ const foundSet = new Set(foundIds);
1709
+ const missingIds = expectedIds.filter(id => !foundSet.has(id));
1710
+ const orphanIds = foundIds.filter(id => !expectedSet.has(id));
1711
+ return {
1712
+ hasMismatches: missingIds.length > 0 || orphanIds.length > 0,
1713
+ expectedIds,
1714
+ foundIds,
1715
+ missingIds,
1716
+ orphanIds,
1717
+ };
1718
+ }
1719
+ // ============================================================================
1720
+ // ============================================================================
1721
+ /**
1722
+ * Find orphaned tool_use IDs (tool_use without matching tool_result).
1723
+ * Works on Claude format messages.
1724
+ */
1725
+ export function findOrphanedToolUseIds(messages) {
1726
+ const toolUseIds = new Set();
1727
+ const toolResultIds = new Set();
1728
+ for (const msg of messages) {
1729
+ if (Array.isArray(msg.content)) {
1730
+ for (const block of msg.content) {
1731
+ if (block.type === "tool_use" && block.id) {
1732
+ toolUseIds.add(block.id);
1733
+ }
1734
+ if (block.type === "tool_result" && block.tool_use_id) {
1735
+ toolResultIds.add(block.tool_use_id);
1736
+ }
1737
+ }
1738
+ }
1739
+ }
1740
+ return new Set([...toolUseIds].filter((id) => !toolResultIds.has(id)));
1741
+ }
1742
+ /**
1743
+ * Fix orphaned tool_use blocks in Claude format messages.
1744
+ * Mirrors fixToolResponseGrouping() but for Claude's messages[] format.
1745
+ *
1746
+ * Claude format:
1747
+ * - assistant message with content[]: { type: 'tool_use', id, name, input }
1748
+ * - user message with content[]: { type: 'tool_result', tool_use_id, content }
1749
+ *
1750
+ * @param messages - Claude format messages array
1751
+ * @returns Fixed messages with placeholder tool_results for orphans
1752
+ */
1753
+ export function fixClaudeToolPairing(messages) {
1754
+ if (!Array.isArray(messages) || messages.length === 0) {
1755
+ return messages;
1756
+ }
1757
+ // 1. Collect all tool_use IDs from assistant messages
1758
+ const toolUseMap = new Map();
1759
+ for (let i = 0; i < messages.length; i++) {
1760
+ const msg = messages[i];
1761
+ if (msg.role === "assistant" && Array.isArray(msg.content)) {
1762
+ for (const block of msg.content) {
1763
+ if (block.type === "tool_use" && block.id) {
1764
+ toolUseMap.set(block.id, { name: block.name || `tool-${toolUseMap.size}`, msgIndex: i });
1765
+ }
1766
+ }
1767
+ }
1768
+ }
1769
+ // 2. Collect all tool_result IDs from user messages
1770
+ const toolResultIds = new Set();
1771
+ for (const msg of messages) {
1772
+ if (msg.role === "user" && Array.isArray(msg.content)) {
1773
+ for (const block of msg.content) {
1774
+ if (block.type === "tool_result" && block.tool_use_id) {
1775
+ toolResultIds.add(block.tool_use_id);
1776
+ }
1777
+ }
1778
+ }
1779
+ }
1780
+ // 3. Find orphaned tool_use (no matching tool_result)
1781
+ const orphans = [];
1782
+ for (const [id, info] of toolUseMap) {
1783
+ if (!toolResultIds.has(id)) {
1784
+ orphans.push({ id, ...info });
1785
+ }
1786
+ }
1787
+ if (orphans.length === 0) {
1788
+ return messages;
1789
+ }
1790
+ // 4. Group orphans by message index (insert after each assistant message)
1791
+ const orphansByMsgIndex = new Map();
1792
+ for (const orphan of orphans) {
1793
+ const existing = orphansByMsgIndex.get(orphan.msgIndex) || [];
1794
+ existing.push(orphan);
1795
+ orphansByMsgIndex.set(orphan.msgIndex, existing);
1796
+ }
1797
+ // 5. Build new messages array with injected tool_results
1798
+ const result = [];
1799
+ for (let i = 0; i < messages.length; i++) {
1800
+ result.push(messages[i]);
1801
+ const orphansForMsg = orphansByMsgIndex.get(i);
1802
+ if (orphansForMsg && orphansForMsg.length > 0) {
1803
+ // Check if next message is user with tool_result - if so, merge into it
1804
+ const nextMsg = messages[i + 1];
1805
+ if (nextMsg?.role === "user" && Array.isArray(nextMsg.content)) {
1806
+ const placeholders = orphansForMsg.map((o) => ({
1807
+ type: "tool_result",
1808
+ tool_use_id: o.id,
1809
+ content: `[Tool "${o.name}" execution was cancelled or failed]`,
1810
+ is_error: true,
1811
+ }));
1812
+ nextMsg.content = [...placeholders, ...nextMsg.content];
1813
+ }
1814
+ else {
1815
+ // Inject new user message with placeholder tool_results
1816
+ result.push({
1817
+ role: "user",
1818
+ content: orphansForMsg.map((o) => ({
1819
+ type: "tool_result",
1820
+ tool_use_id: o.id,
1821
+ content: `[Tool "${o.name}" execution was cancelled or failed]`,
1822
+ is_error: true,
1823
+ })),
1824
+ });
1825
+ }
1826
+ }
1827
+ }
1828
+ return result;
1829
+ }
1830
+ /**
1831
+ * Nuclear option: Remove orphaned tool_use blocks entirely.
1832
+ * Called when fixClaudeToolPairing() fails to pair all tools.
1833
+ */
1834
+ function removeOrphanedToolUse(messages, orphanIds) {
1835
+ return messages
1836
+ .map((msg) => {
1837
+ if (msg.role === "assistant" && Array.isArray(msg.content)) {
1838
+ return {
1839
+ ...msg,
1840
+ content: msg.content.filter((block) => block.type !== "tool_use" || !orphanIds.has(block.id)),
1841
+ };
1842
+ }
1843
+ return msg;
1844
+ })
1845
+ .filter((msg) => !(msg.role === "assistant" && Array.isArray(msg.content) && msg.content.length === 0));
1846
+ }
1847
+ /**
1848
+ * Validate and fix tool pairing with fallback nuclear option.
1849
+ * Defense in depth: tries gentle fix first, then nuclear removal.
1850
+ */
1851
+ export function validateAndFixClaudeToolPairing(messages) {
1852
+ if (!Array.isArray(messages) || messages.length === 0) {
1853
+ return messages;
1854
+ }
1855
+ // First: Try gentle fix (inject placeholder tool_results)
1856
+ let fixed = fixClaudeToolPairing(messages);
1857
+ const orphanIds = findOrphanedToolUseIds(fixed);
1858
+ if (orphanIds.size === 0) {
1859
+ return fixed;
1860
+ }
1861
+ // Third: Nuclear option - remove orphaned tool_use entirely
1862
+ console.warn("[antigravity] fixClaudeToolPairing left orphans, applying nuclear option", {
1863
+ orphanIds: [...orphanIds],
1864
+ });
1865
+ return removeOrphanedToolUse(fixed, orphanIds);
1866
+ }
1867
+ // ============================================================================
1868
+ // ============================================================================
1869
+ /**
1870
+ * Formats a type hint for a property schema.
1871
+ * Port of LLM-API-Key-Proxy's _format_type_hint()
1872
+ */
1873
+ function formatTypeHint(propData, depth = 0) {
1874
+ const type = propData.type ?? "unknown";
1875
+ if (propData.enum && Array.isArray(propData.enum)) {
1876
+ const enumVals = propData.enum;
1877
+ if (enumVals.length <= 5) {
1878
+ return `string ENUM[${enumVals.map(v => JSON.stringify(v)).join(", ")}]`;
1879
+ }
1880
+ return `string ENUM[${enumVals.length} options]`;
1881
+ }
1882
+ if (propData.const !== undefined) {
1883
+ return `string CONST=${JSON.stringify(propData.const)}`;
1884
+ }
1885
+ if (type === "array") {
1886
+ const items = propData.items;
1887
+ if (items && typeof items === "object") {
1888
+ const itemType = items.type ?? "unknown";
1889
+ if (itemType === "object") {
1890
+ const nestedProps = items.properties;
1891
+ const nestedReq = items.required ?? [];
1892
+ if (nestedProps && depth < 1) {
1893
+ const nestedList = Object.entries(nestedProps).map(([n, d]) => {
1894
+ const t = d.type ?? "unknown";
1895
+ const req = nestedReq.includes(n) ? " REQUIRED" : "";
1896
+ return `${n}: ${t}${req}`;
1897
+ });
1898
+ return `ARRAY_OF_OBJECTS[${nestedList.join(", ")}]`;
1899
+ }
1900
+ return "ARRAY_OF_OBJECTS";
1901
+ }
1902
+ return `ARRAY_OF_${itemType.toUpperCase()}`;
1903
+ }
1904
+ return "ARRAY";
1905
+ }
1906
+ if (type === "object") {
1907
+ const nestedProps = propData.properties;
1908
+ const nestedReq = propData.required ?? [];
1909
+ if (nestedProps && depth < 1) {
1910
+ const nestedList = Object.entries(nestedProps).map(([n, d]) => {
1911
+ const t = d.type ?? "unknown";
1912
+ const req = nestedReq.includes(n) ? " REQUIRED" : "";
1913
+ return `${n}: ${t}${req}`;
1914
+ });
1915
+ return `object{${nestedList.join(", ")}}`;
1916
+ }
1917
+ }
1918
+ return type;
1919
+ }
1920
+ /**
1921
+ * Injects parameter signatures into tool descriptions.
1922
+ * Port of LLM-API-Key-Proxy's _inject_signature_into_descriptions()
1923
+ *
1924
+ * This helps prevent tool hallucination by explicitly listing parameters
1925
+ * in the description, making it harder for the model to hallucinate
1926
+ * parameters from its training data.
1927
+ *
1928
+ * @param tools - Array of tool definitions (Gemini format)
1929
+ * @param promptTemplate - Template for the signature (default: "\\n\\nSTRICT PARAMETERS: {params}.")
1930
+ * @returns Modified tools array with signatures injected
1931
+ */
1932
+ export function injectParameterSignatures(tools, promptTemplate = "\n\n⚠️ STRICT PARAMETERS: {params}.") {
1933
+ if (!tools || !Array.isArray(tools))
1934
+ return tools;
1935
+ return tools.map((tool) => {
1936
+ const declarations = tool.functionDeclarations;
1937
+ if (!Array.isArray(declarations))
1938
+ return tool;
1939
+ const newDeclarations = declarations.map((decl) => {
1940
+ if (decl.description?.includes("STRICT PARAMETERS:")) {
1941
+ return decl;
1942
+ }
1943
+ const schema = decl.parameters || decl.parametersJsonSchema;
1944
+ if (!schema)
1945
+ return decl;
1946
+ const required = schema.required ?? [];
1947
+ const properties = schema.properties ?? {};
1948
+ if (Object.keys(properties).length === 0)
1949
+ return decl;
1950
+ const paramList = Object.entries(properties).map(([propName, propData]) => {
1951
+ const typeHint = formatTypeHint(propData);
1952
+ const isRequired = required.includes(propName);
1953
+ return `${propName} (${typeHint}${isRequired ? ", REQUIRED" : ""})`;
1954
+ });
1955
+ const sigStr = promptTemplate.replace("{params}", paramList.join(", "));
1956
+ return {
1957
+ ...decl,
1958
+ description: (decl.description || "") + sigStr,
1959
+ };
1960
+ });
1961
+ return { ...tool, functionDeclarations: newDeclarations };
1962
+ });
1963
+ }
1964
+ /**
1965
+ * Injects a tool hardening system instruction into the request payload.
1966
+ * Port of LLM-API-Key-Proxy's _inject_tool_hardening_instruction()
1967
+ *
1968
+ * @param payload - The Gemini request payload
1969
+ * @param instructionText - The instruction text to inject
1970
+ */
1971
+ export function injectToolHardeningInstruction(payload, instructionText) {
1972
+ if (!instructionText)
1973
+ return;
1974
+ const existing = payload.systemInstruction;
1975
+ if (existing && typeof existing === "object" && "parts" in existing) {
1976
+ const parts = existing.parts;
1977
+ if (Array.isArray(parts) && parts.some(p => p.text?.includes("CRITICAL TOOL USAGE INSTRUCTIONS"))) {
1978
+ return;
1979
+ }
1980
+ }
1981
+ const instructionPart = { text: instructionText };
1982
+ if (payload.systemInstruction) {
1983
+ if (existing && typeof existing === "object" && "parts" in existing) {
1984
+ const parts = existing.parts;
1985
+ if (Array.isArray(parts)) {
1986
+ parts.unshift(instructionPart);
1987
+ }
1988
+ }
1989
+ else if (typeof existing === "string") {
1990
+ payload.systemInstruction = {
1991
+ role: "user",
1992
+ parts: [instructionPart, { text: existing }],
1993
+ };
1994
+ }
1995
+ else {
1996
+ payload.systemInstruction = {
1997
+ role: "user",
1998
+ parts: [instructionPart],
1999
+ };
2000
+ }
2001
+ }
2002
+ else {
2003
+ payload.systemInstruction = {
2004
+ role: "user",
2005
+ parts: [instructionPart],
2006
+ };
2007
+ }
2008
+ }
2009
+ // ============================================================================
2010
+ // ============================================================================
2011
+ /**
2012
+ * Assigns IDs to functionCall parts and returns the pending call IDs by name.
2013
+ * This is the first pass of tool ID assignment.
2014
+ *
2015
+ * @param contents - Gemini-style contents array
2016
+ * @returns Object with modified contents and pending call IDs map
2017
+ */
2018
+ export function assignToolIdsToContents(contents) {
2019
+ if (!Array.isArray(contents)) {
2020
+ return { contents, pendingCallIdsByName: new Map(), toolCallCounter: 0 };
2021
+ }
2022
+ let toolCallCounter = 0;
2023
+ const pendingCallIdsByName = new Map();
2024
+ const newContents = contents.map((content) => {
2025
+ if (!content || !Array.isArray(content.parts)) {
2026
+ return content;
2027
+ }
2028
+ const newParts = content.parts.map((part) => {
2029
+ if (part && typeof part === "object" && part.functionCall) {
2030
+ const call = { ...part.functionCall };
2031
+ if (!call.id) {
2032
+ call.id = `tool-call-${++toolCallCounter}`;
2033
+ }
2034
+ const nameKey = typeof call.name === "string" ? call.name : `tool-${toolCallCounter}`;
2035
+ const queue = pendingCallIdsByName.get(nameKey) || [];
2036
+ queue.push(call.id);
2037
+ pendingCallIdsByName.set(nameKey, queue);
2038
+ return { ...part, functionCall: call };
2039
+ }
2040
+ return part;
2041
+ });
2042
+ return { ...content, parts: newParts };
2043
+ });
2044
+ return { contents: newContents, pendingCallIdsByName, toolCallCounter };
2045
+ }
2046
+ /**
2047
+ * Matches functionResponse IDs to their corresponding functionCall IDs.
2048
+ * This is the second pass of tool ID assignment.
2049
+ *
2050
+ * @param contents - Gemini-style contents array
2051
+ * @param pendingCallIdsByName - Map of function names to pending call IDs
2052
+ * @returns Modified contents with matched response IDs
2053
+ */
2054
+ export function matchResponseIdsToContents(contents, pendingCallIdsByName) {
2055
+ if (!Array.isArray(contents)) {
2056
+ return contents;
2057
+ }
2058
+ return contents.map((content) => {
2059
+ if (!content || !Array.isArray(content.parts)) {
2060
+ return content;
2061
+ }
2062
+ const newParts = content.parts.map((part) => {
2063
+ if (part && typeof part === "object" && part.functionResponse) {
2064
+ const resp = { ...part.functionResponse };
2065
+ if (!resp.id && typeof resp.name === "string") {
2066
+ const queue = pendingCallIdsByName.get(resp.name);
2067
+ if (queue && queue.length > 0) {
2068
+ resp.id = queue.shift();
2069
+ pendingCallIdsByName.set(resp.name, queue);
2070
+ }
2071
+ }
2072
+ return { ...part, functionResponse: resp };
2073
+ }
2074
+ return part;
2075
+ });
2076
+ return { ...content, parts: newParts };
2077
+ });
2078
+ }
2079
+ /**
2080
+ * Applies all tool fixes to a request payload for Claude models.
2081
+ * This includes:
2082
+ * 1. Tool ID assignment for functionCalls
2083
+ * 2. Response ID matching for functionResponses
2084
+ * 3. Orphan recovery via fixToolResponseGrouping
2085
+ * 4. Claude format pairing fix via validateAndFixClaudeToolPairing
2086
+ *
2087
+ * @param payload - Request payload object
2088
+ * @param isClaude - Whether this is a Claude model request
2089
+ * @returns Object with fix applied status
2090
+ */
2091
+ export function applyToolPairingFixes(payload, isClaude) {
2092
+ let contentsFixed = false;
2093
+ let messagesFixed = false;
2094
+ if (!isClaude) {
2095
+ return { contentsFixed, messagesFixed };
2096
+ }
2097
+ if (Array.isArray(payload.contents)) {
2098
+ const { contents: contentsWithIds, pendingCallIdsByName } = assignToolIdsToContents(payload.contents);
2099
+ const contentsWithMatchedIds = matchResponseIdsToContents(contentsWithIds, pendingCallIdsByName);
2100
+ payload.contents = fixToolResponseGrouping(contentsWithMatchedIds);
2101
+ contentsFixed = true;
2102
+ log.debug("Applied tool pairing fixes to contents[]", {
2103
+ originalLength: payload.contents.length,
2104
+ });
2105
+ }
2106
+ if (Array.isArray(payload.messages)) {
2107
+ payload.messages = validateAndFixClaudeToolPairing(payload.messages);
2108
+ messagesFixed = true;
2109
+ log.debug("Applied tool pairing fixes to messages[]", {
2110
+ originalLength: payload.messages.length,
2111
+ });
2112
+ }
2113
+ return { contentsFixed, messagesFixed };
2114
+ }
2115
+ // ============================================================================
2116
+ // ============================================================================
2117
+ /**
2118
+ * Creates a synthetic Claude SSE streaming response with error content.
2119
+ *
2120
+ * When returning HTTP 400/500 errors to OpenCode, the session becomes locked
2121
+ * and the user cannot use /compact or other commands. This function creates
2122
+ * a fake "successful" SSE response (200 OK) with the error message as text content,
2123
+ * allowing the user to continue using the session.
2124
+ *
2125
+ * @param errorMessage - The error message to include in the response
2126
+ * @param requestedModel - The model that was requested
2127
+ * @returns A Response object with synthetic SSE stream
2128
+ */
2129
+ export function createSyntheticErrorResponse(errorMessage, requestedModel = "unknown") {
2130
+ const messageId = `msg_synthetic_${Date.now()}`;
2131
+ const events = [];
2132
+ // 1. message_start event
2133
+ events.push(`event: message_start
2134
+ data: ${JSON.stringify({
2135
+ type: "message_start",
2136
+ message: {
2137
+ id: messageId,
2138
+ type: "message",
2139
+ role: "assistant",
2140
+ content: [],
2141
+ model: requestedModel,
2142
+ stop_reason: null,
2143
+ stop_sequence: null,
2144
+ usage: { input_tokens: 0, output_tokens: 0 },
2145
+ },
2146
+ })}
2147
+
2148
+ `);
2149
+ // 2. content_block_start event
2150
+ events.push(`event: content_block_start
2151
+ data: ${JSON.stringify({
2152
+ type: "content_block_start",
2153
+ index: 0,
2154
+ content_block: { type: "text", text: "" },
2155
+ })}
2156
+
2157
+ `);
2158
+ // 3. content_block_delta event with the error message
2159
+ events.push(`event: content_block_delta
2160
+ data: ${JSON.stringify({
2161
+ type: "content_block_delta",
2162
+ index: 0,
2163
+ delta: { type: "text_delta", text: errorMessage },
2164
+ })}
2165
+
2166
+ `);
2167
+ // 4. content_block_stop event
2168
+ events.push(`event: content_block_stop
2169
+ data: ${JSON.stringify({
2170
+ type: "content_block_stop",
2171
+ index: 0,
2172
+ })}
2173
+
2174
+ `);
2175
+ // 5. message_delta event (end_turn)
2176
+ events.push(`event: message_delta
2177
+ data: ${JSON.stringify({
2178
+ type: "message_delta",
2179
+ delta: { stop_reason: "end_turn", stop_sequence: null },
2180
+ usage: { output_tokens: Math.ceil(errorMessage.length / 4) },
2181
+ })}
2182
+
2183
+ `);
2184
+ // 6. message_stop event
2185
+ events.push(`event: message_stop
2186
+ data: ${JSON.stringify({ type: "message_stop" })}
2187
+
2188
+ `);
2189
+ const body = events.join("");
2190
+ return new Response(body, {
2191
+ status: 200,
2192
+ headers: {
2193
+ "Content-Type": "text/event-stream",
2194
+ "Cache-Control": "no-cache",
2195
+ "Connection": "keep-alive",
2196
+ "X-Antigravity-Synthetic": "true",
2197
+ "X-Antigravity-Error-Type": "prompt_too_long",
2198
+ },
2199
+ });
2200
+ }