opencode-agy-auth 2.0.0

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