opencode-ag-auth 1.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (235) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +749 -0
  3. package/dist/index.d.ts +4 -0
  4. package/dist/index.d.ts.map +1 -0
  5. package/dist/index.js +3 -0
  6. package/dist/index.js.map +1 -0
  7. package/dist/src/antigravity/oauth.d.ts +31 -0
  8. package/dist/src/antigravity/oauth.d.ts.map +1 -0
  9. package/dist/src/antigravity/oauth.js +171 -0
  10. package/dist/src/antigravity/oauth.js.map +1 -0
  11. package/dist/src/constants.d.ts +138 -0
  12. package/dist/src/constants.d.ts.map +1 -0
  13. package/dist/src/constants.js +220 -0
  14. package/dist/src/constants.js.map +1 -0
  15. package/dist/src/hooks/auto-update-checker/cache.d.ts +3 -0
  16. package/dist/src/hooks/auto-update-checker/cache.d.ts.map +1 -0
  17. package/dist/src/hooks/auto-update-checker/cache.js +71 -0
  18. package/dist/src/hooks/auto-update-checker/cache.js.map +1 -0
  19. package/dist/src/hooks/auto-update-checker/checker.d.ts +16 -0
  20. package/dist/src/hooks/auto-update-checker/checker.d.ts.map +1 -0
  21. package/dist/src/hooks/auto-update-checker/checker.js +237 -0
  22. package/dist/src/hooks/auto-update-checker/checker.js.map +1 -0
  23. package/dist/src/hooks/auto-update-checker/constants.d.ts +9 -0
  24. package/dist/src/hooks/auto-update-checker/constants.d.ts.map +1 -0
  25. package/dist/src/hooks/auto-update-checker/constants.js +23 -0
  26. package/dist/src/hooks/auto-update-checker/constants.js.map +1 -0
  27. package/dist/src/hooks/auto-update-checker/index.d.ts +34 -0
  28. package/dist/src/hooks/auto-update-checker/index.d.ts.map +1 -0
  29. package/dist/src/hooks/auto-update-checker/index.js +125 -0
  30. package/dist/src/hooks/auto-update-checker/index.js.map +1 -0
  31. package/dist/src/hooks/auto-update-checker/types.d.ts +25 -0
  32. package/dist/src/hooks/auto-update-checker/types.d.ts.map +1 -0
  33. package/dist/src/hooks/auto-update-checker/types.js +1 -0
  34. package/dist/src/hooks/auto-update-checker/types.js.map +1 -0
  35. package/dist/src/plugin/accounts.d.ts +173 -0
  36. package/dist/src/plugin/accounts.d.ts.map +1 -0
  37. package/dist/src/plugin/accounts.js +1035 -0
  38. package/dist/src/plugin/accounts.js.map +1 -0
  39. package/dist/src/plugin/auth.d.ts +21 -0
  40. package/dist/src/plugin/auth.d.ts.map +1 -0
  41. package/dist/src/plugin/auth.js +46 -0
  42. package/dist/src/plugin/auth.js.map +1 -0
  43. package/dist/src/plugin/cache/index.d.ts +5 -0
  44. package/dist/src/plugin/cache/index.d.ts.map +1 -0
  45. package/dist/src/plugin/cache/index.js +5 -0
  46. package/dist/src/plugin/cache/index.js.map +1 -0
  47. package/dist/src/plugin/cache/signature-cache.d.ts +111 -0
  48. package/dist/src/plugin/cache/signature-cache.d.ts.map +1 -0
  49. package/dist/src/plugin/cache/signature-cache.js +375 -0
  50. package/dist/src/plugin/cache/signature-cache.js.map +1 -0
  51. package/dist/src/plugin/cache.d.ts +44 -0
  52. package/dist/src/plugin/cache.d.ts.map +1 -0
  53. package/dist/src/plugin/cache.js +200 -0
  54. package/dist/src/plugin/cache.js.map +1 -0
  55. package/dist/src/plugin/cli.d.ts +27 -0
  56. package/dist/src/plugin/cli.d.ts.map +1 -0
  57. package/dist/src/plugin/cli.js +130 -0
  58. package/dist/src/plugin/cli.js.map +1 -0
  59. package/dist/src/plugin/config/index.d.ts +16 -0
  60. package/dist/src/plugin/config/index.d.ts.map +1 -0
  61. package/dist/src/plugin/config/index.js +16 -0
  62. package/dist/src/plugin/config/index.js.map +1 -0
  63. package/dist/src/plugin/config/loader.d.ts +37 -0
  64. package/dist/src/plugin/config/loader.d.ts.map +1 -0
  65. package/dist/src/plugin/config/loader.js +196 -0
  66. package/dist/src/plugin/config/loader.js.map +1 -0
  67. package/dist/src/plugin/config/models.d.ts +27 -0
  68. package/dist/src/plugin/config/models.d.ts.map +1 -0
  69. package/dist/src/plugin/config/models.js +70 -0
  70. package/dist/src/plugin/config/models.js.map +1 -0
  71. package/dist/src/plugin/config/schema.d.ts +133 -0
  72. package/dist/src/plugin/config/schema.d.ts.map +1 -0
  73. package/dist/src/plugin/config/schema.js +438 -0
  74. package/dist/src/plugin/config/schema.js.map +1 -0
  75. package/dist/src/plugin/config/updater.d.ts +55 -0
  76. package/dist/src/plugin/config/updater.d.ts.map +1 -0
  77. package/dist/src/plugin/config/updater.js +125 -0
  78. package/dist/src/plugin/config/updater.js.map +1 -0
  79. package/dist/src/plugin/core/streaming/index.d.ts +3 -0
  80. package/dist/src/plugin/core/streaming/index.d.ts.map +1 -0
  81. package/dist/src/plugin/core/streaming/index.js +3 -0
  82. package/dist/src/plugin/core/streaming/index.js.map +1 -0
  83. package/dist/src/plugin/core/streaming/transformer.d.ts +10 -0
  84. package/dist/src/plugin/core/streaming/transformer.d.ts.map +1 -0
  85. package/dist/src/plugin/core/streaming/transformer.js +271 -0
  86. package/dist/src/plugin/core/streaming/transformer.js.map +1 -0
  87. package/dist/src/plugin/core/streaming/types.d.ts +27 -0
  88. package/dist/src/plugin/core/streaming/types.d.ts.map +1 -0
  89. package/dist/src/plugin/core/streaming/types.js +1 -0
  90. package/dist/src/plugin/core/streaming/types.js.map +1 -0
  91. package/dist/src/plugin/debug.d.ts +94 -0
  92. package/dist/src/plugin/debug.d.ts.map +1 -0
  93. package/dist/src/plugin/debug.js +418 -0
  94. package/dist/src/plugin/debug.js.map +1 -0
  95. package/dist/src/plugin/errors.d.ts +28 -0
  96. package/dist/src/plugin/errors.d.ts.map +1 -0
  97. package/dist/src/plugin/errors.js +42 -0
  98. package/dist/src/plugin/errors.js.map +1 -0
  99. package/dist/src/plugin/fingerprint.d.ts +64 -0
  100. package/dist/src/plugin/fingerprint.d.ts.map +1 -0
  101. package/dist/src/plugin/fingerprint.js +125 -0
  102. package/dist/src/plugin/fingerprint.js.map +1 -0
  103. package/dist/src/plugin/image-saver.d.ts +25 -0
  104. package/dist/src/plugin/image-saver.d.ts.map +1 -0
  105. package/dist/src/plugin/image-saver.js +86 -0
  106. package/dist/src/plugin/image-saver.js.map +1 -0
  107. package/dist/src/plugin/logger.d.ts +54 -0
  108. package/dist/src/plugin/logger.d.ts.map +1 -0
  109. package/dist/src/plugin/logger.js +120 -0
  110. package/dist/src/plugin/logger.js.map +1 -0
  111. package/dist/src/plugin/project.d.ts +33 -0
  112. package/dist/src/plugin/project.d.ts.map +1 -0
  113. package/dist/src/plugin/project.js +234 -0
  114. package/dist/src/plugin/project.js.map +1 -0
  115. package/dist/src/plugin/proxy.d.ts +2 -0
  116. package/dist/src/plugin/proxy.d.ts.map +1 -0
  117. package/dist/src/plugin/proxy.js +20 -0
  118. package/dist/src/plugin/proxy.js.map +1 -0
  119. package/dist/src/plugin/quota.d.ts +35 -0
  120. package/dist/src/plugin/quota.d.ts.map +1 -0
  121. package/dist/src/plugin/quota.js +273 -0
  122. package/dist/src/plugin/quota.js.map +1 -0
  123. package/dist/src/plugin/recovery/constants.d.ts +22 -0
  124. package/dist/src/plugin/recovery/constants.d.ts.map +1 -0
  125. package/dist/src/plugin/recovery/constants.js +43 -0
  126. package/dist/src/plugin/recovery/constants.js.map +1 -0
  127. package/dist/src/plugin/recovery/index.d.ts +12 -0
  128. package/dist/src/plugin/recovery/index.d.ts.map +1 -0
  129. package/dist/src/plugin/recovery/index.js +12 -0
  130. package/dist/src/plugin/recovery/index.js.map +1 -0
  131. package/dist/src/plugin/recovery/storage.d.ts +24 -0
  132. package/dist/src/plugin/recovery/storage.d.ts.map +1 -0
  133. package/dist/src/plugin/recovery/storage.js +354 -0
  134. package/dist/src/plugin/recovery/storage.js.map +1 -0
  135. package/dist/src/plugin/recovery/types.d.ts +116 -0
  136. package/dist/src/plugin/recovery/types.d.ts.map +1 -0
  137. package/dist/src/plugin/recovery/types.js +6 -0
  138. package/dist/src/plugin/recovery/types.js.map +1 -0
  139. package/dist/src/plugin/recovery.d.ts +61 -0
  140. package/dist/src/plugin/recovery.d.ts.map +1 -0
  141. package/dist/src/plugin/recovery.js +378 -0
  142. package/dist/src/plugin/recovery.js.map +1 -0
  143. package/dist/src/plugin/refresh-queue.d.ts +101 -0
  144. package/dist/src/plugin/refresh-queue.d.ts.map +1 -0
  145. package/dist/src/plugin/refresh-queue.js +248 -0
  146. package/dist/src/plugin/refresh-queue.js.map +1 -0
  147. package/dist/src/plugin/request-helpers.d.ts +282 -0
  148. package/dist/src/plugin/request-helpers.d.ts.map +1 -0
  149. package/dist/src/plugin/request-helpers.js +2319 -0
  150. package/dist/src/plugin/request-helpers.js.map +1 -0
  151. package/dist/src/plugin/request.d.ts +93 -0
  152. package/dist/src/plugin/request.d.ts.map +1 -0
  153. package/dist/src/plugin/request.js +1352 -0
  154. package/dist/src/plugin/request.js.map +1 -0
  155. package/dist/src/plugin/rotation.d.ts +169 -0
  156. package/dist/src/plugin/rotation.d.ts.map +1 -0
  157. package/dist/src/plugin/rotation.js +328 -0
  158. package/dist/src/plugin/rotation.js.map +1 -0
  159. package/dist/src/plugin/search.d.ts +32 -0
  160. package/dist/src/plugin/search.d.ts.map +1 -0
  161. package/dist/src/plugin/search.js +195 -0
  162. package/dist/src/plugin/search.js.map +1 -0
  163. package/dist/src/plugin/server.d.ts +23 -0
  164. package/dist/src/plugin/server.d.ts.map +1 -0
  165. package/dist/src/plugin/server.js +324 -0
  166. package/dist/src/plugin/server.js.map +1 -0
  167. package/dist/src/plugin/storage.d.ts +136 -0
  168. package/dist/src/plugin/storage.d.ts.map +1 -0
  169. package/dist/src/plugin/storage.js +588 -0
  170. package/dist/src/plugin/storage.js.map +1 -0
  171. package/dist/src/plugin/stores/signature-store.d.ts +5 -0
  172. package/dist/src/plugin/stores/signature-store.d.ts.map +1 -0
  173. package/dist/src/plugin/stores/signature-store.js +25 -0
  174. package/dist/src/plugin/stores/signature-store.js.map +1 -0
  175. package/dist/src/plugin/thinking-recovery.d.ts +90 -0
  176. package/dist/src/plugin/thinking-recovery.d.ts.map +1 -0
  177. package/dist/src/plugin/thinking-recovery.js +316 -0
  178. package/dist/src/plugin/thinking-recovery.js.map +1 -0
  179. package/dist/src/plugin/token.d.ts +19 -0
  180. package/dist/src/plugin/token.d.ts.map +1 -0
  181. package/dist/src/plugin/token.js +128 -0
  182. package/dist/src/plugin/token.js.map +1 -0
  183. package/dist/src/plugin/transform/claude.d.ts +80 -0
  184. package/dist/src/plugin/transform/claude.d.ts.map +1 -0
  185. package/dist/src/plugin/transform/claude.js +265 -0
  186. package/dist/src/plugin/transform/claude.js.map +1 -0
  187. package/dist/src/plugin/transform/cross-model-sanitizer.d.ts +35 -0
  188. package/dist/src/plugin/transform/cross-model-sanitizer.d.ts.map +1 -0
  189. package/dist/src/plugin/transform/cross-model-sanitizer.js +225 -0
  190. package/dist/src/plugin/transform/cross-model-sanitizer.js.map +1 -0
  191. package/dist/src/plugin/transform/gemini.d.ts +100 -0
  192. package/dist/src/plugin/transform/gemini.d.ts.map +1 -0
  193. package/dist/src/plugin/transform/gemini.js +465 -0
  194. package/dist/src/plugin/transform/gemini.js.map +1 -0
  195. package/dist/src/plugin/transform/index.d.ts +15 -0
  196. package/dist/src/plugin/transform/index.d.ts.map +1 -0
  197. package/dist/src/plugin/transform/index.js +14 -0
  198. package/dist/src/plugin/transform/index.js.map +1 -0
  199. package/dist/src/plugin/transform/model-resolver.d.ts +104 -0
  200. package/dist/src/plugin/transform/model-resolver.d.ts.map +1 -0
  201. package/dist/src/plugin/transform/model-resolver.js +361 -0
  202. package/dist/src/plugin/transform/model-resolver.js.map +1 -0
  203. package/dist/src/plugin/transform/types.d.ts +111 -0
  204. package/dist/src/plugin/transform/types.d.ts.map +1 -0
  205. package/dist/src/plugin/transform/types.js +1 -0
  206. package/dist/src/plugin/transform/types.js.map +1 -0
  207. package/dist/src/plugin/types.d.ts +97 -0
  208. package/dist/src/plugin/types.d.ts.map +1 -0
  209. package/dist/src/plugin/types.js +1 -0
  210. package/dist/src/plugin/types.js.map +1 -0
  211. package/dist/src/plugin/ui/ansi.d.ts +32 -0
  212. package/dist/src/plugin/ui/ansi.d.ts.map +1 -0
  213. package/dist/src/plugin/ui/ansi.js +52 -0
  214. package/dist/src/plugin/ui/ansi.js.map +1 -0
  215. package/dist/src/plugin/ui/auth-menu.d.ts +33 -0
  216. package/dist/src/plugin/ui/auth-menu.d.ts.map +1 -0
  217. package/dist/src/plugin/ui/auth-menu.js +110 -0
  218. package/dist/src/plugin/ui/auth-menu.js.map +1 -0
  219. package/dist/src/plugin/ui/confirm.d.ts +2 -0
  220. package/dist/src/plugin/ui/confirm.d.ts.map +1 -0
  221. package/dist/src/plugin/ui/confirm.js +15 -0
  222. package/dist/src/plugin/ui/confirm.js.map +1 -0
  223. package/dist/src/plugin/ui/select.d.ts +23 -0
  224. package/dist/src/plugin/ui/select.d.ts.map +1 -0
  225. package/dist/src/plugin/ui/select.js +254 -0
  226. package/dist/src/plugin/ui/select.js.map +1 -0
  227. package/dist/src/plugin/version.d.ts +19 -0
  228. package/dist/src/plugin/version.d.ts.map +1 -0
  229. package/dist/src/plugin/version.js +80 -0
  230. package/dist/src/plugin/version.js.map +1 -0
  231. package/dist/src/plugin.d.ts +30 -0
  232. package/dist/src/plugin.d.ts.map +1 -0
  233. package/dist/src/plugin.js +3050 -0
  234. package/dist/src/plugin.js.map +1 -0
  235. package/package.json +68 -0
@@ -0,0 +1,2319 @@
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
+ * Removes trailing thinking blocks from a content array.
741
+ * Claude API requires that assistant messages don't end with thinking blocks.
742
+ * Only removes unsigned thinking blocks; preserves those with valid signatures.
743
+ */
744
+ function removeTrailingThinkingBlocks(contentArray, sessionId, getCachedSignatureFn) {
745
+ const result = [...contentArray];
746
+ while (result.length > 0 && isThinkingPart(result[result.length - 1])) {
747
+ const part = result[result.length - 1];
748
+ const isValid = sessionId && getCachedSignatureFn
749
+ ? isOurCachedSignature(part, sessionId, getCachedSignatureFn)
750
+ : hasValidSignature(part);
751
+ if (isValid) {
752
+ break;
753
+ }
754
+ result.pop();
755
+ }
756
+ return result;
757
+ }
758
+ /**
759
+ * Checks if a thinking part has a valid signature.
760
+ * A valid signature is a non-empty string with at least 50 characters.
761
+ */
762
+ function hasValidSignature(part) {
763
+ const signature = part.thought === true ? part.thoughtSignature : part.signature;
764
+ return typeof signature === "string" && signature.length >= 50;
765
+ }
766
+ /**
767
+ * Gets the signature from a thinking part, if present.
768
+ */
769
+ function getSignature(part) {
770
+ const signature = part.thought === true ? part.thoughtSignature : part.signature;
771
+ return typeof signature === "string" ? signature : undefined;
772
+ }
773
+ /**
774
+ * Checks if a thinking part's signature was generated by our plugin (exists in our cache).
775
+ * This prevents accepting signatures from other providers (e.g., direct Anthropic API, OpenAI)
776
+ * which would cause "Invalid signature" errors when sent to Antigravity Claude.
777
+ */
778
+ function isOurCachedSignature(part, sessionId, getCachedSignatureFn) {
779
+ if (!sessionId || !getCachedSignatureFn) {
780
+ return false;
781
+ }
782
+ const text = getThinkingText(part);
783
+ if (!text) {
784
+ return false;
785
+ }
786
+ const partSignature = getSignature(part);
787
+ if (!partSignature) {
788
+ return false;
789
+ }
790
+ const cachedSignature = getCachedSignatureFn(sessionId, text);
791
+ return cachedSignature === partSignature;
792
+ }
793
+ /**
794
+ * Gets the text content from a thinking part.
795
+ */
796
+ function getThinkingText(part) {
797
+ if (typeof part.text === "string")
798
+ return part.text;
799
+ if (typeof part.thinking === "string")
800
+ return part.thinking;
801
+ if (part.text && typeof part.text === "object") {
802
+ const maybeText = part.text.text;
803
+ if (typeof maybeText === "string")
804
+ return maybeText;
805
+ }
806
+ if (part.thinking && typeof part.thinking === "object") {
807
+ const maybeText = part.thinking.text ?? part.thinking.thinking;
808
+ if (typeof maybeText === "string")
809
+ return maybeText;
810
+ }
811
+ return "";
812
+ }
813
+ /**
814
+ * Recursively strips cache_control and providerOptions from any object.
815
+ * These fields can be injected by SDKs, but Claude rejects them inside thinking blocks.
816
+ */
817
+ function stripCacheControlRecursively(obj) {
818
+ if (obj === null || obj === undefined)
819
+ return obj;
820
+ if (typeof obj !== "object")
821
+ return obj;
822
+ if (Array.isArray(obj))
823
+ return obj.map(item => stripCacheControlRecursively(item));
824
+ const result = {};
825
+ for (const [key, value] of Object.entries(obj)) {
826
+ if (key === "cache_control" || key === "providerOptions")
827
+ continue;
828
+ result[key] = stripCacheControlRecursively(value);
829
+ }
830
+ return result;
831
+ }
832
+ /**
833
+ * Sanitizes a thinking part by keeping only the allowed fields.
834
+ * In particular, ensures `thinking` is a string (not an object with cache_control).
835
+ * Returns null if the thinking block has no valid content.
836
+ */
837
+ function sanitizeThinkingPart(part) {
838
+ // Gemini-style thought blocks: { thought: true, text, thoughtSignature }
839
+ if (part.thought === true) {
840
+ let textContent = part.text;
841
+ if (typeof textContent === "object" && textContent !== null) {
842
+ const maybeText = textContent.text;
843
+ textContent = typeof maybeText === "string" ? maybeText : undefined;
844
+ }
845
+ const hasContent = typeof textContent === "string" && textContent.trim().length > 0;
846
+ if (!hasContent && !part.thoughtSignature) {
847
+ return null;
848
+ }
849
+ const sanitized = { thought: true };
850
+ if (textContent !== undefined)
851
+ sanitized.text = textContent;
852
+ if (part.thoughtSignature !== undefined)
853
+ sanitized.thoughtSignature = part.thoughtSignature;
854
+ return sanitized;
855
+ }
856
+ // Anthropic-style thinking/redacted_thinking blocks: { type: "thinking"|"redacted_thinking", thinking, signature }
857
+ if (part.type === "thinking" || part.type === "redacted_thinking" || part.thinking !== undefined) {
858
+ let thinkingContent = part.thinking ?? part.text;
859
+ if (thinkingContent !== undefined && typeof thinkingContent === "object" && thinkingContent !== null) {
860
+ const maybeText = thinkingContent.text ?? thinkingContent.thinking;
861
+ thinkingContent = typeof maybeText === "string" ? maybeText : undefined;
862
+ }
863
+ const hasContent = typeof thinkingContent === "string" && thinkingContent.trim().length > 0;
864
+ if (!hasContent && !part.signature) {
865
+ return null;
866
+ }
867
+ const sanitized = { type: part.type === "redacted_thinking" ? "redacted_thinking" : "thinking" };
868
+ if (thinkingContent !== undefined)
869
+ sanitized.thinking = thinkingContent;
870
+ if (part.signature !== undefined)
871
+ sanitized.signature = part.signature;
872
+ return sanitized;
873
+ }
874
+ // Reasoning blocks (OpenCode format): { type: "reasoning", text, signature }
875
+ if (part.type === "reasoning") {
876
+ let textContent = part.text;
877
+ if (typeof textContent === "object" && textContent !== null) {
878
+ const maybeText = textContent.text;
879
+ textContent = typeof maybeText === "string" ? maybeText : undefined;
880
+ }
881
+ const hasContent = typeof textContent === "string" && textContent.trim().length > 0;
882
+ if (!hasContent && !part.signature) {
883
+ return null;
884
+ }
885
+ const sanitized = { type: "reasoning" };
886
+ if (textContent !== undefined)
887
+ sanitized.text = textContent;
888
+ if (part.signature !== undefined)
889
+ sanitized.signature = part.signature;
890
+ return sanitized;
891
+ }
892
+ // Fallback: strip cache_control recursively.
893
+ return stripCacheControlRecursively(part);
894
+ }
895
+ function findLastAssistantIndex(contents, roleValue) {
896
+ for (let i = contents.length - 1; i >= 0; i--) {
897
+ const content = contents[i];
898
+ if (content && typeof content === "object" && content.role === roleValue) {
899
+ return i;
900
+ }
901
+ }
902
+ return -1;
903
+ }
904
+ function filterContentArray(contentArray, sessionId, getCachedSignatureFn, isClaudeModel, isLastAssistantMessage = false) {
905
+ // For Claude models, strip thinking blocks by default for reliability
906
+ // User can opt-in to keep thinking via config: { "keep_thinking": true }
907
+ if (isClaudeModel && !getKeepThinking()) {
908
+ return stripAllThinkingBlocks(contentArray);
909
+ }
910
+ const filtered = [];
911
+ for (const item of contentArray) {
912
+ if (!item || typeof item !== "object") {
913
+ filtered.push(item);
914
+ continue;
915
+ }
916
+ if (isToolBlock(item)) {
917
+ filtered.push(item);
918
+ continue;
919
+ }
920
+ const isThinking = isThinkingPart(item);
921
+ const hasSignature = hasSignatureField(item);
922
+ if (!isThinking && !hasSignature) {
923
+ filtered.push(item);
924
+ continue;
925
+ }
926
+ // For the LAST assistant message with thinking blocks:
927
+ // - If signature is OUR cached signature, pass through unchanged
928
+ // - Otherwise inject sentinel to bypass Antigravity validation
929
+ // NOTE: We can't trust signatures just because they're >= 50 chars - Claude returns
930
+ // its own signatures which are long but invalid for Antigravity.
931
+ if (isLastAssistantMessage && (isThinking || hasSignature)) {
932
+ // First check if it's our cached signature
933
+ if (isOurCachedSignature(item, sessionId, getCachedSignatureFn)) {
934
+ const sanitized = sanitizeThinkingPart(item);
935
+ if (sanitized)
936
+ filtered.push(sanitized);
937
+ continue;
938
+ }
939
+ // Not our signature (or no signature) - inject sentinel
940
+ const thinkingText = getThinkingText(item) || "";
941
+ const existingSignature = item.signature || item.thoughtSignature;
942
+ const signatureInfo = existingSignature ? `foreign signature (${String(existingSignature).length} chars)` : "no signature";
943
+ log.debug(`Injecting sentinel for last-message thinking block with ${signatureInfo}`);
944
+ const sentinelPart = {
945
+ type: item.type || "thinking",
946
+ thinking: thinkingText,
947
+ signature: SKIP_THOUGHT_SIGNATURE,
948
+ };
949
+ filtered.push(sentinelPart);
950
+ continue;
951
+ }
952
+ if (isOurCachedSignature(item, sessionId, getCachedSignatureFn)) {
953
+ const sanitized = sanitizeThinkingPart(item);
954
+ if (sanitized)
955
+ filtered.push(sanitized);
956
+ continue;
957
+ }
958
+ if (sessionId && getCachedSignatureFn) {
959
+ const text = getThinkingText(item);
960
+ if (text) {
961
+ const cachedSignature = getCachedSignatureFn(sessionId, text);
962
+ if (cachedSignature && cachedSignature.length >= 50) {
963
+ const restoredPart = { ...item };
964
+ if (item.thought === true) {
965
+ restoredPart.thoughtSignature = cachedSignature;
966
+ }
967
+ else {
968
+ restoredPart.signature = cachedSignature;
969
+ }
970
+ const sanitized = sanitizeThinkingPart(restoredPart);
971
+ if (sanitized)
972
+ filtered.push(sanitized);
973
+ continue;
974
+ }
975
+ }
976
+ }
977
+ }
978
+ return filtered;
979
+ }
980
+ /**
981
+ * Filters thinking blocks from contents unless the signature matches our cache.
982
+ * Attempts to restore signatures from cache for thinking blocks that lack signatures.
983
+ *
984
+ * @param contents - The contents array from the request
985
+ * @param sessionId - Optional session ID for signature cache lookup
986
+ * @param getCachedSignatureFn - Optional function to retrieve cached signatures
987
+ */
988
+ export function filterUnsignedThinkingBlocks(contents, sessionId, getCachedSignatureFn, isClaudeModel) {
989
+ const lastAssistantIdx = findLastAssistantIndex(contents, "model");
990
+ return contents.map((content, idx) => {
991
+ if (!content || typeof content !== "object") {
992
+ return content;
993
+ }
994
+ const isLastAssistant = idx === lastAssistantIdx;
995
+ if (Array.isArray(content.parts)) {
996
+ const filteredParts = filterContentArray(content.parts, sessionId, getCachedSignatureFn, isClaudeModel, isLastAssistant);
997
+ const trimmedParts = content.role === "model" && !isClaudeModel
998
+ ? removeTrailingThinkingBlocks(filteredParts, sessionId, getCachedSignatureFn)
999
+ : filteredParts;
1000
+ return { ...content, parts: trimmedParts };
1001
+ }
1002
+ if (Array.isArray(content.content)) {
1003
+ const isAssistantRole = content.role === "assistant";
1004
+ const isLastAssistantContent = idx === lastAssistantIdx ||
1005
+ (isAssistantRole && idx === findLastAssistantIndex(contents, "assistant"));
1006
+ const filteredContent = filterContentArray(content.content, sessionId, getCachedSignatureFn, isClaudeModel, isLastAssistantContent);
1007
+ const trimmedContent = isAssistantRole && !isClaudeModel
1008
+ ? removeTrailingThinkingBlocks(filteredContent, sessionId, getCachedSignatureFn)
1009
+ : filteredContent;
1010
+ return { ...content, content: trimmedContent };
1011
+ }
1012
+ return content;
1013
+ });
1014
+ }
1015
+ /**
1016
+ * Filters thinking blocks from Anthropic-style messages[] payloads using cached signatures.
1017
+ */
1018
+ export function filterMessagesThinkingBlocks(messages, sessionId, getCachedSignatureFn, isClaudeModel) {
1019
+ const lastAssistantIdx = findLastAssistantIndex(messages, "assistant");
1020
+ return messages.map((message, idx) => {
1021
+ if (!message || typeof message !== "object") {
1022
+ return message;
1023
+ }
1024
+ if (Array.isArray(message.content)) {
1025
+ const isAssistantRole = message.role === "assistant";
1026
+ const isLastAssistant = isAssistantRole && idx === lastAssistantIdx;
1027
+ const filteredContent = filterContentArray(message.content, sessionId, getCachedSignatureFn, isClaudeModel, isLastAssistant);
1028
+ const trimmedContent = isAssistantRole && !isClaudeModel
1029
+ ? removeTrailingThinkingBlocks(filteredContent, sessionId, getCachedSignatureFn)
1030
+ : filteredContent;
1031
+ return { ...message, content: trimmedContent };
1032
+ }
1033
+ return message;
1034
+ });
1035
+ }
1036
+ export function deepFilterThinkingBlocks(payload, sessionId, getCachedSignatureFn, isClaudeModel) {
1037
+ const visited = new WeakSet();
1038
+ const walk = (value) => {
1039
+ if (!value || typeof value !== "object") {
1040
+ return;
1041
+ }
1042
+ if (visited.has(value)) {
1043
+ return;
1044
+ }
1045
+ visited.add(value);
1046
+ if (Array.isArray(value)) {
1047
+ value.forEach((item) => walk(item));
1048
+ return;
1049
+ }
1050
+ const obj = value;
1051
+ if (Array.isArray(obj.contents)) {
1052
+ obj.contents = filterUnsignedThinkingBlocks(obj.contents, sessionId, getCachedSignatureFn, isClaudeModel);
1053
+ }
1054
+ if (Array.isArray(obj.messages)) {
1055
+ obj.messages = filterMessagesThinkingBlocks(obj.messages, sessionId, getCachedSignatureFn, isClaudeModel);
1056
+ }
1057
+ Object.keys(obj).forEach((key) => walk(obj[key]));
1058
+ };
1059
+ walk(payload);
1060
+ return payload;
1061
+ }
1062
+ /**
1063
+ * Transforms Gemini-style thought parts (thought: true) and Anthropic-style
1064
+ * thinking parts (type: "thinking") to reasoning format.
1065
+ * Claude responses through Antigravity may use candidates structure with Anthropic-style parts.
1066
+ */
1067
+ function transformGeminiCandidate(candidate) {
1068
+ if (!candidate || typeof candidate !== "object") {
1069
+ return candidate;
1070
+ }
1071
+ const content = candidate.content;
1072
+ if (!content || typeof content !== "object" || !Array.isArray(content.parts)) {
1073
+ return candidate;
1074
+ }
1075
+ const thinkingTexts = [];
1076
+ const transformedParts = content.parts.map((part) => {
1077
+ if (!part || typeof part !== "object") {
1078
+ return part;
1079
+ }
1080
+ // Handle Gemini-style: thought: true
1081
+ if (part.thought === true) {
1082
+ const thinkingText = part.text || "";
1083
+ thinkingTexts.push(thinkingText);
1084
+ const transformed = { ...part, type: "reasoning" };
1085
+ if (part.cache_control)
1086
+ transformed.cache_control = part.cache_control;
1087
+ // Convert signature to providerMetadata format for OpenCode
1088
+ const sig = part.signature || part.thoughtSignature;
1089
+ if (sig) {
1090
+ transformed.providerMetadata = {
1091
+ anthropic: { signature: sig }
1092
+ };
1093
+ delete transformed.signature;
1094
+ delete transformed.thoughtSignature;
1095
+ }
1096
+ return transformed;
1097
+ }
1098
+ // Handle Anthropic-style in candidates: type: "thinking"
1099
+ if (part.type === "thinking") {
1100
+ const thinkingText = part.thinking || part.text || "";
1101
+ thinkingTexts.push(thinkingText);
1102
+ const transformed = {
1103
+ ...part,
1104
+ type: "reasoning",
1105
+ text: thinkingText,
1106
+ thought: true,
1107
+ };
1108
+ if (part.cache_control)
1109
+ transformed.cache_control = part.cache_control;
1110
+ // Convert signature to providerMetadata format for OpenCode
1111
+ const sig = part.signature || part.thoughtSignature;
1112
+ if (sig) {
1113
+ transformed.providerMetadata = {
1114
+ anthropic: { signature: sig }
1115
+ };
1116
+ delete transformed.signature;
1117
+ delete transformed.thoughtSignature;
1118
+ }
1119
+ return transformed;
1120
+ }
1121
+ // Handle functionCall: parse JSON strings in args and ensure args is always defined
1122
+ // (Ported from LLM-API-Key-Proxy's _extract_tool_call)
1123
+ // Fix: When Claude calls a tool with no parameters, args may be undefined.
1124
+ // opencode expects state.input to be a record, so we must ensure args: {} as fallback.
1125
+ if (part.functionCall) {
1126
+ const parsedArgs = part.functionCall.args
1127
+ ? recursivelyParseJsonStrings(part.functionCall.args)
1128
+ : {};
1129
+ return {
1130
+ ...part,
1131
+ functionCall: {
1132
+ ...part.functionCall,
1133
+ args: parsedArgs,
1134
+ },
1135
+ };
1136
+ }
1137
+ // Handle image data (inlineData) - save to disk and return file path
1138
+ if (part.inlineData) {
1139
+ const result = processImageData({
1140
+ mimeType: part.inlineData.mimeType,
1141
+ data: part.inlineData.data,
1142
+ });
1143
+ if (result) {
1144
+ return { text: result };
1145
+ }
1146
+ }
1147
+ return part;
1148
+ });
1149
+ return {
1150
+ ...candidate,
1151
+ content: { ...content, parts: transformedParts },
1152
+ ...(thinkingTexts.length > 0 ? { reasoning_content: thinkingTexts.join("\n\n") } : {}),
1153
+ };
1154
+ }
1155
+ /**
1156
+ * Transforms thinking/reasoning content in response parts to OpenCode's expected format.
1157
+ * Handles both Gemini-style (thought: true) and Anthropic-style (type: "thinking") formats.
1158
+ * Also extracts reasoning_content for Anthropic-style responses.
1159
+ */
1160
+ export function transformThinkingParts(response) {
1161
+ if (!response || typeof response !== "object") {
1162
+ return response;
1163
+ }
1164
+ const resp = response;
1165
+ const result = { ...resp };
1166
+ const reasoningTexts = [];
1167
+ // Handle Anthropic-style content array (type: "thinking")
1168
+ if (Array.isArray(resp.content)) {
1169
+ const transformedContent = [];
1170
+ for (const block of resp.content) {
1171
+ if (block && typeof block === "object" && block.type === "thinking") {
1172
+ const thinkingText = block.thinking || block.text || "";
1173
+ reasoningTexts.push(thinkingText);
1174
+ const transformed = {
1175
+ ...block,
1176
+ type: "reasoning",
1177
+ text: thinkingText,
1178
+ thought: true,
1179
+ };
1180
+ // Convert signature to providerMetadata format for OpenCode
1181
+ const sig = block.signature || block.thoughtSignature;
1182
+ if (sig) {
1183
+ transformed.providerMetadata = {
1184
+ anthropic: { signature: sig }
1185
+ };
1186
+ delete transformed.signature;
1187
+ delete transformed.thoughtSignature;
1188
+ }
1189
+ transformedContent.push(transformed);
1190
+ }
1191
+ else {
1192
+ transformedContent.push(block);
1193
+ }
1194
+ }
1195
+ result.content = transformedContent;
1196
+ }
1197
+ // Handle Gemini-style candidates array
1198
+ if (Array.isArray(resp.candidates)) {
1199
+ result.candidates = resp.candidates.map(transformGeminiCandidate);
1200
+ }
1201
+ // Add reasoning_content if we found any thinking blocks (for Anthropic-style)
1202
+ if (reasoningTexts.length > 0 && !result.reasoning_content) {
1203
+ result.reasoning_content = reasoningTexts.join("\n\n");
1204
+ }
1205
+ return result;
1206
+ }
1207
+ /**
1208
+ * Ensures thinkingConfig is valid: includeThoughts only allowed when budget > 0.
1209
+ */
1210
+ export function normalizeThinkingConfig(config) {
1211
+ if (!config || typeof config !== "object") {
1212
+ return undefined;
1213
+ }
1214
+ const record = config;
1215
+ const budgetRaw = record.thinkingBudget ?? record.thinking_budget;
1216
+ const includeRaw = record.includeThoughts ?? record.include_thoughts;
1217
+ const thinkingBudget = typeof budgetRaw === "number" && Number.isFinite(budgetRaw) ? budgetRaw : undefined;
1218
+ const includeThoughts = typeof includeRaw === "boolean" ? includeRaw : undefined;
1219
+ const enableThinking = thinkingBudget !== undefined && thinkingBudget > 0;
1220
+ const finalInclude = enableThinking ? includeThoughts ?? false : false;
1221
+ if (!enableThinking && finalInclude === false && thinkingBudget === undefined && includeThoughts === undefined) {
1222
+ return undefined;
1223
+ }
1224
+ const normalized = {};
1225
+ if (thinkingBudget !== undefined) {
1226
+ normalized.thinkingBudget = thinkingBudget;
1227
+ }
1228
+ if (finalInclude !== undefined) {
1229
+ normalized.includeThoughts = finalInclude;
1230
+ }
1231
+ return normalized;
1232
+ }
1233
+ /**
1234
+ * Parses an Antigravity API body; handles array-wrapped responses the API sometimes returns.
1235
+ */
1236
+ export function parseAntigravityApiBody(rawText) {
1237
+ try {
1238
+ const parsed = JSON.parse(rawText);
1239
+ if (Array.isArray(parsed)) {
1240
+ const firstObject = parsed.find((item) => typeof item === "object" && item !== null);
1241
+ if (firstObject && typeof firstObject === "object") {
1242
+ return firstObject;
1243
+ }
1244
+ return null;
1245
+ }
1246
+ if (parsed && typeof parsed === "object") {
1247
+ return parsed;
1248
+ }
1249
+ return null;
1250
+ }
1251
+ catch {
1252
+ return null;
1253
+ }
1254
+ }
1255
+ /**
1256
+ * Extracts usageMetadata from a response object, guarding types.
1257
+ */
1258
+ export function extractUsageMetadata(body) {
1259
+ const usage = (body.response && typeof body.response === "object"
1260
+ ? body.response.usageMetadata
1261
+ : undefined);
1262
+ if (!usage || typeof usage !== "object") {
1263
+ return null;
1264
+ }
1265
+ const asRecord = usage;
1266
+ const toNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : undefined;
1267
+ return {
1268
+ totalTokenCount: toNumber(asRecord.totalTokenCount),
1269
+ promptTokenCount: toNumber(asRecord.promptTokenCount),
1270
+ candidatesTokenCount: toNumber(asRecord.candidatesTokenCount),
1271
+ cachedContentTokenCount: toNumber(asRecord.cachedContentTokenCount),
1272
+ thoughtsTokenCount: toNumber(asRecord.thoughtsTokenCount),
1273
+ };
1274
+ }
1275
+ /**
1276
+ * Walks SSE lines to find a usage-bearing response chunk.
1277
+ */
1278
+ export function extractUsageFromSsePayload(payload) {
1279
+ const lines = payload.split("\n");
1280
+ for (const line of lines) {
1281
+ if (!line.startsWith("data:")) {
1282
+ continue;
1283
+ }
1284
+ const jsonText = line.slice(5).trim();
1285
+ if (!jsonText) {
1286
+ continue;
1287
+ }
1288
+ try {
1289
+ const parsed = JSON.parse(jsonText);
1290
+ if (parsed && typeof parsed === "object") {
1291
+ const usage = extractUsageMetadata({ response: parsed.response });
1292
+ if (usage) {
1293
+ return usage;
1294
+ }
1295
+ }
1296
+ }
1297
+ catch {
1298
+ continue;
1299
+ }
1300
+ }
1301
+ return null;
1302
+ }
1303
+ /**
1304
+ * Enhances 404 errors for Antigravity models with a direct preview-access message.
1305
+ */
1306
+ export function rewriteAntigravityPreviewAccessError(body, status, requestedModel) {
1307
+ if (!needsPreviewAccessOverride(status, body, requestedModel)) {
1308
+ return null;
1309
+ }
1310
+ const error = body.error ?? {};
1311
+ const trimmedMessage = typeof error.message === "string" ? error.message.trim() : "";
1312
+ const messagePrefix = trimmedMessage.length > 0
1313
+ ? trimmedMessage
1314
+ : "Antigravity preview features are not enabled for this account.";
1315
+ const enhancedMessage = `${messagePrefix} Request preview access at ${ANTIGRAVITY_PREVIEW_LINK} before using this model.`;
1316
+ return {
1317
+ ...body,
1318
+ error: {
1319
+ ...error,
1320
+ message: enhancedMessage,
1321
+ },
1322
+ };
1323
+ }
1324
+ function needsPreviewAccessOverride(status, body, requestedModel) {
1325
+ if (status !== 404) {
1326
+ return false;
1327
+ }
1328
+ if (isAntigravityModel(requestedModel)) {
1329
+ return true;
1330
+ }
1331
+ const errorMessage = typeof body.error?.message === "string" ? body.error.message : "";
1332
+ return isAntigravityModel(errorMessage);
1333
+ }
1334
+ function isAntigravityModel(target) {
1335
+ if (!target) {
1336
+ return false;
1337
+ }
1338
+ // Check for Antigravity models instead of Gemini 3
1339
+ return /antigravity/i.test(target) || /opus/i.test(target) || /claude/i.test(target);
1340
+ }
1341
+ // ============================================================================
1342
+ // EMPTY RESPONSE DETECTION (Ported from LLM-API-Key-Proxy)
1343
+ // ============================================================================
1344
+ /**
1345
+ * Checks if a JSON response body represents an empty response.
1346
+ *
1347
+ * Empty responses occur when:
1348
+ * - No candidates in Gemini format
1349
+ * - No choices in OpenAI format
1350
+ * - Candidates/choices exist but have no content
1351
+ *
1352
+ * @param text - The response body text (should be valid JSON)
1353
+ * @returns true if the response is empty
1354
+ */
1355
+ export function isEmptyResponseBody(text) {
1356
+ if (!text || !text.trim()) {
1357
+ return true;
1358
+ }
1359
+ try {
1360
+ const parsed = JSON.parse(text);
1361
+ // Check for empty candidates (Gemini/Antigravity format)
1362
+ if (parsed.candidates !== undefined) {
1363
+ if (!Array.isArray(parsed.candidates) || parsed.candidates.length === 0) {
1364
+ return true;
1365
+ }
1366
+ // Check if first candidate has empty content
1367
+ const firstCandidate = parsed.candidates[0];
1368
+ if (!firstCandidate) {
1369
+ return true;
1370
+ }
1371
+ // Check for empty parts in content
1372
+ const content = firstCandidate.content;
1373
+ if (!content || typeof content !== "object") {
1374
+ return true;
1375
+ }
1376
+ const parts = content.parts;
1377
+ if (!Array.isArray(parts) || parts.length === 0) {
1378
+ return true;
1379
+ }
1380
+ // Check if all parts are empty (no text, no functionCall)
1381
+ const hasContent = parts.some((part) => {
1382
+ if (!part || typeof part !== "object")
1383
+ return false;
1384
+ if (typeof part.text === "string" && part.text.length > 0)
1385
+ return true;
1386
+ if (part.functionCall)
1387
+ return true;
1388
+ if (part.thought === true && typeof part.text === "string")
1389
+ return true;
1390
+ return false;
1391
+ });
1392
+ if (!hasContent) {
1393
+ return true;
1394
+ }
1395
+ }
1396
+ // Check for empty choices (OpenAI format - shouldn't occur but handle it)
1397
+ if (parsed.choices !== undefined) {
1398
+ if (!Array.isArray(parsed.choices) || parsed.choices.length === 0) {
1399
+ return true;
1400
+ }
1401
+ const firstChoice = parsed.choices[0];
1402
+ if (!firstChoice) {
1403
+ return true;
1404
+ }
1405
+ // Check for empty message/delta
1406
+ const message = firstChoice.message || firstChoice.delta;
1407
+ if (!message) {
1408
+ return true;
1409
+ }
1410
+ // Check if message has content or tool_calls
1411
+ if (!message.content && !message.tool_calls && !message.reasoning_content) {
1412
+ return true;
1413
+ }
1414
+ }
1415
+ // Check response wrapper (Antigravity envelope)
1416
+ if (parsed.response !== undefined) {
1417
+ const response = parsed.response;
1418
+ if (!response || typeof response !== "object") {
1419
+ return true;
1420
+ }
1421
+ return isEmptyResponseBody(JSON.stringify(response));
1422
+ }
1423
+ return false;
1424
+ }
1425
+ catch {
1426
+ // JSON parse error - treat as empty
1427
+ return true;
1428
+ }
1429
+ }
1430
+ export function createStreamingChunkCounter() {
1431
+ let count = 0;
1432
+ let hasRealContent = false;
1433
+ return {
1434
+ increment: () => {
1435
+ count++;
1436
+ },
1437
+ getCount: () => count,
1438
+ hasContent: () => hasRealContent || count > 0,
1439
+ };
1440
+ }
1441
+ /**
1442
+ * Checks if an SSE line contains meaningful content.
1443
+ *
1444
+ * @param line - A single SSE line (e.g., "data: {...}")
1445
+ * @returns true if the line contains content worth counting
1446
+ */
1447
+ export function isMeaningfulSseLine(line) {
1448
+ if (!line.startsWith("data: ")) {
1449
+ return false;
1450
+ }
1451
+ const data = line.slice(6).trim();
1452
+ if (data === "[DONE]") {
1453
+ return false;
1454
+ }
1455
+ if (!data) {
1456
+ return false;
1457
+ }
1458
+ try {
1459
+ const parsed = JSON.parse(data);
1460
+ // Check for candidates with content
1461
+ if (parsed.candidates && Array.isArray(parsed.candidates)) {
1462
+ for (const candidate of parsed.candidates) {
1463
+ const parts = candidate?.content?.parts;
1464
+ if (Array.isArray(parts) && parts.length > 0) {
1465
+ for (const part of parts) {
1466
+ if (typeof part?.text === "string" && part.text.length > 0)
1467
+ return true;
1468
+ if (part?.functionCall)
1469
+ return true;
1470
+ }
1471
+ }
1472
+ }
1473
+ }
1474
+ // Check response wrapper
1475
+ if (parsed.response?.candidates) {
1476
+ return isMeaningfulSseLine(`data: ${JSON.stringify(parsed.response)}`);
1477
+ }
1478
+ return false;
1479
+ }
1480
+ catch {
1481
+ return false;
1482
+ }
1483
+ }
1484
+ // ============================================================================
1485
+ // RECURSIVE JSON STRING AUTO-PARSING (Ported from LLM-API-Key-Proxy)
1486
+ // ============================================================================
1487
+ /**
1488
+ * Recursively parses JSON strings in nested data structures.
1489
+ *
1490
+ * This is a port of LLM-API-Key-Proxy's _recursively_parse_json_strings() function.
1491
+ *
1492
+ * Handles:
1493
+ * - JSON-stringified values: {"files": "[{...}]"} → {"files": [{...}]}
1494
+ * - Malformed double-encoded JSON (extra trailing chars)
1495
+ * - Escaped control characters (\\n → \n, \\t → \t)
1496
+ *
1497
+ * This is useful because Antigravity sometimes returns JSON-stringified values
1498
+ * in tool arguments, which can cause downstream parsing issues.
1499
+ *
1500
+ * @param obj - The object to recursively parse
1501
+ * @param skipParseKeys - Set of keys whose values should NOT be parsed as JSON (preserved as strings)
1502
+ * @param currentKey - The current key being processed (internal use)
1503
+ * @returns The parsed object with JSON strings expanded
1504
+ */
1505
+ // Keys whose string values should NOT be parsed as JSON - they contain literal text content
1506
+ const SKIP_PARSE_KEYS = new Set([
1507
+ "oldString",
1508
+ "newString",
1509
+ "content",
1510
+ "filePath",
1511
+ "path",
1512
+ "text",
1513
+ "code",
1514
+ "source",
1515
+ "data",
1516
+ "body",
1517
+ "message",
1518
+ "prompt",
1519
+ "input",
1520
+ "output",
1521
+ "result",
1522
+ "value",
1523
+ "query",
1524
+ "pattern",
1525
+ "replacement",
1526
+ "template",
1527
+ "script",
1528
+ "command",
1529
+ "snippet",
1530
+ ]);
1531
+ export function recursivelyParseJsonStrings(obj, skipParseKeys = SKIP_PARSE_KEYS, currentKey) {
1532
+ if (obj === null || obj === undefined) {
1533
+ return obj;
1534
+ }
1535
+ if (Array.isArray(obj)) {
1536
+ return obj.map((item) => recursivelyParseJsonStrings(item, skipParseKeys));
1537
+ }
1538
+ if (typeof obj === "object") {
1539
+ const result = {};
1540
+ for (const [key, value] of Object.entries(obj)) {
1541
+ result[key] = recursivelyParseJsonStrings(value, skipParseKeys, key);
1542
+ }
1543
+ return result;
1544
+ }
1545
+ if (typeof obj !== "string") {
1546
+ return obj;
1547
+ }
1548
+ if (currentKey && skipParseKeys.has(currentKey)) {
1549
+ return obj;
1550
+ }
1551
+ const stripped = obj.trim();
1552
+ // Check if string contains control character escape sequences
1553
+ // that need unescaping (\\n, \\t but NOT \\" or \\\\)
1554
+ const hasControlCharEscapes = obj.includes("\\n") || obj.includes("\\t");
1555
+ const hasIntentionalEscapes = obj.includes('\\"') || obj.includes("\\\\");
1556
+ if (hasControlCharEscapes && !hasIntentionalEscapes) {
1557
+ try {
1558
+ // Use JSON.parse with quotes to unescape the string
1559
+ return JSON.parse(`"${obj}"`);
1560
+ }
1561
+ catch {
1562
+ // Continue with original processing
1563
+ }
1564
+ }
1565
+ // Check if it looks like JSON (starts with { or [)
1566
+ if (stripped && (stripped[0] === "{" || stripped[0] === "[")) {
1567
+ // Try standard parsing first
1568
+ if ((stripped.startsWith("{") && stripped.endsWith("}")) ||
1569
+ (stripped.startsWith("[") && stripped.endsWith("]"))) {
1570
+ try {
1571
+ const parsed = JSON.parse(obj);
1572
+ return recursivelyParseJsonStrings(parsed);
1573
+ }
1574
+ catch {
1575
+ // Continue
1576
+ }
1577
+ }
1578
+ // Handle malformed JSON: array that doesn't end with ]
1579
+ if (stripped.startsWith("[") && !stripped.endsWith("]")) {
1580
+ try {
1581
+ const lastBracket = stripped.lastIndexOf("]");
1582
+ if (lastBracket > 0) {
1583
+ const cleaned = stripped.slice(0, lastBracket + 1);
1584
+ const parsed = JSON.parse(cleaned);
1585
+ log.debug("Auto-corrected malformed JSON array", {
1586
+ truncatedChars: stripped.length - cleaned.length,
1587
+ });
1588
+ return recursivelyParseJsonStrings(parsed);
1589
+ }
1590
+ }
1591
+ catch {
1592
+ // Continue
1593
+ }
1594
+ }
1595
+ // Handle malformed JSON: object that doesn't end with }
1596
+ if (stripped.startsWith("{") && !stripped.endsWith("}")) {
1597
+ try {
1598
+ const lastBrace = stripped.lastIndexOf("}");
1599
+ if (lastBrace > 0) {
1600
+ const cleaned = stripped.slice(0, lastBrace + 1);
1601
+ const parsed = JSON.parse(cleaned);
1602
+ log.debug("Auto-corrected malformed JSON object", {
1603
+ truncatedChars: stripped.length - cleaned.length,
1604
+ });
1605
+ return recursivelyParseJsonStrings(parsed);
1606
+ }
1607
+ }
1608
+ catch {
1609
+ // Continue
1610
+ }
1611
+ }
1612
+ }
1613
+ return obj;
1614
+ }
1615
+ // ============================================================================
1616
+ // TOOL ID ORPHAN RECOVERY (Ported from LLM-API-Key-Proxy)
1617
+ // ============================================================================
1618
+ /**
1619
+ * Groups function calls with their responses, handling ID mismatches.
1620
+ *
1621
+ * This is a port of LLM-API-Key-Proxy's _fix_tool_response_grouping() function.
1622
+ *
1623
+ * When context compaction or other processes strip tool responses, the tool call
1624
+ * IDs become orphaned. This function attempts to recover by:
1625
+ *
1626
+ * 1. Pass 1: Match by exact ID (normal case)
1627
+ * 2. Pass 2: Match by function name (for ID mismatches)
1628
+ * 3. Pass 3: Match "unknown_function" orphans or take first available
1629
+ * 4. Fallback: Create placeholder responses for missing tool results
1630
+ *
1631
+ * @param contents - Array of Gemini-style content messages
1632
+ * @returns Fixed contents array with matched tool responses
1633
+ */
1634
+ export function fixToolResponseGrouping(contents) {
1635
+ if (!Array.isArray(contents) || contents.length === 0) {
1636
+ return contents;
1637
+ }
1638
+ const newContents = [];
1639
+ // Track pending tool call groups that need responses
1640
+ const pendingGroups = [];
1641
+ // Collected orphan responses (by ID)
1642
+ const collectedResponses = new Map();
1643
+ for (const content of contents) {
1644
+ const role = content.role;
1645
+ const parts = content.parts || [];
1646
+ // Check if this is a tool response message
1647
+ const responseParts = parts.filter((p) => p?.functionResponse);
1648
+ if (responseParts.length > 0) {
1649
+ // Collect responses by ID (skip duplicates)
1650
+ for (const resp of responseParts) {
1651
+ const respId = resp.functionResponse?.id || "";
1652
+ if (respId && !collectedResponses.has(respId)) {
1653
+ collectedResponses.set(respId, resp);
1654
+ }
1655
+ }
1656
+ // Try to satisfy the most recent pending group
1657
+ for (let i = pendingGroups.length - 1; i >= 0; i--) {
1658
+ const group = pendingGroups[i];
1659
+ if (group.ids.every(id => collectedResponses.has(id))) {
1660
+ // All IDs found - build the response group
1661
+ const groupResponses = group.ids.map(id => {
1662
+ const resp = collectedResponses.get(id);
1663
+ collectedResponses.delete(id);
1664
+ return resp;
1665
+ });
1666
+ newContents.push({ parts: groupResponses, role: "user" });
1667
+ pendingGroups.splice(i, 1);
1668
+ break; // Only satisfy one group at a time
1669
+ }
1670
+ }
1671
+ continue; // Don't add the original response message
1672
+ }
1673
+ if (role === "model") {
1674
+ // Check for function calls in this model message
1675
+ const funcCalls = parts.filter((p) => p?.functionCall);
1676
+ newContents.push(content);
1677
+ if (funcCalls.length > 0) {
1678
+ const callIds = funcCalls
1679
+ .map((fc) => fc.functionCall?.id || "")
1680
+ .filter(Boolean);
1681
+ const funcNames = funcCalls
1682
+ .map((fc) => fc.functionCall?.name || "");
1683
+ if (callIds.length > 0) {
1684
+ pendingGroups.push({
1685
+ ids: callIds,
1686
+ funcNames,
1687
+ insertAfterIdx: newContents.length - 1,
1688
+ });
1689
+ }
1690
+ }
1691
+ }
1692
+ else {
1693
+ newContents.push(content);
1694
+ }
1695
+ }
1696
+ // Handle remaining pending groups with orphan recovery
1697
+ // Process in reverse order so insertions don't shift indices
1698
+ pendingGroups.sort((a, b) => b.insertAfterIdx - a.insertAfterIdx);
1699
+ for (const group of pendingGroups) {
1700
+ const groupResponses = [];
1701
+ for (let i = 0; i < group.ids.length; i++) {
1702
+ const expectedId = group.ids[i];
1703
+ const expectedName = group.funcNames[i] || "";
1704
+ if (collectedResponses.has(expectedId)) {
1705
+ // Direct ID match - ideal case
1706
+ groupResponses.push(collectedResponses.get(expectedId));
1707
+ collectedResponses.delete(expectedId);
1708
+ }
1709
+ else if (collectedResponses.size > 0) {
1710
+ // Need to find an orphan response
1711
+ let matchedId = null;
1712
+ // Pass 1: Match by function name
1713
+ for (const [orphanId, orphanResp] of collectedResponses) {
1714
+ const orphanName = orphanResp.functionResponse?.name || "";
1715
+ if (orphanName === expectedName) {
1716
+ matchedId = orphanId;
1717
+ break;
1718
+ }
1719
+ }
1720
+ // Pass 2: Match "unknown_function" orphans
1721
+ if (!matchedId) {
1722
+ for (const [orphanId, orphanResp] of collectedResponses) {
1723
+ if (orphanResp.functionResponse?.name === "unknown_function") {
1724
+ matchedId = orphanId;
1725
+ break;
1726
+ }
1727
+ }
1728
+ }
1729
+ // Pass 3: Take first available
1730
+ if (!matchedId) {
1731
+ matchedId = collectedResponses.keys().next().value ?? null;
1732
+ }
1733
+ if (matchedId) {
1734
+ const orphanResp = collectedResponses.get(matchedId);
1735
+ collectedResponses.delete(matchedId);
1736
+ // Fix the ID and name to match expected
1737
+ orphanResp.functionResponse.id = expectedId;
1738
+ if (orphanResp.functionResponse.name === "unknown_function" && expectedName) {
1739
+ orphanResp.functionResponse.name = expectedName;
1740
+ }
1741
+ log.debug("Auto-repaired tool ID mismatch", {
1742
+ mappedFrom: matchedId,
1743
+ mappedTo: expectedId,
1744
+ functionName: expectedName,
1745
+ });
1746
+ groupResponses.push(orphanResp);
1747
+ }
1748
+ }
1749
+ else {
1750
+ // No responses available - create placeholder
1751
+ const placeholder = {
1752
+ functionResponse: {
1753
+ name: expectedName || "unknown_function",
1754
+ response: {
1755
+ result: {
1756
+ error: "Tool response was lost during context processing. " +
1757
+ "This is a recovered placeholder.",
1758
+ recovered: true,
1759
+ },
1760
+ },
1761
+ id: expectedId,
1762
+ },
1763
+ };
1764
+ log.debug("Created placeholder response for missing tool", {
1765
+ id: expectedId,
1766
+ name: expectedName,
1767
+ });
1768
+ groupResponses.push(placeholder);
1769
+ }
1770
+ }
1771
+ if (groupResponses.length > 0) {
1772
+ // Insert at correct position (after the model message that made the calls)
1773
+ newContents.splice(group.insertAfterIdx + 1, 0, {
1774
+ parts: groupResponses,
1775
+ role: "user",
1776
+ });
1777
+ }
1778
+ }
1779
+ return newContents;
1780
+ }
1781
+ /**
1782
+ * Checks if contents have any tool call/response ID mismatches.
1783
+ *
1784
+ * @param contents - Array of Gemini-style content messages
1785
+ * @returns Object with mismatch details
1786
+ */
1787
+ export function detectToolIdMismatches(contents) {
1788
+ const expectedIds = [];
1789
+ const foundIds = [];
1790
+ for (const content of contents) {
1791
+ const parts = content.parts || [];
1792
+ for (const part of parts) {
1793
+ if (part?.functionCall?.id) {
1794
+ expectedIds.push(part.functionCall.id);
1795
+ }
1796
+ if (part?.functionResponse?.id) {
1797
+ foundIds.push(part.functionResponse.id);
1798
+ }
1799
+ }
1800
+ }
1801
+ const expectedSet = new Set(expectedIds);
1802
+ const foundSet = new Set(foundIds);
1803
+ const missingIds = expectedIds.filter(id => !foundSet.has(id));
1804
+ const orphanIds = foundIds.filter(id => !expectedSet.has(id));
1805
+ return {
1806
+ hasMismatches: missingIds.length > 0 || orphanIds.length > 0,
1807
+ expectedIds,
1808
+ foundIds,
1809
+ missingIds,
1810
+ orphanIds,
1811
+ };
1812
+ }
1813
+ // ============================================================================
1814
+ // CLAUDE FORMAT TOOL PAIRING (Defense in Depth)
1815
+ // ============================================================================
1816
+ /**
1817
+ * Find orphaned tool_use IDs (tool_use without matching tool_result).
1818
+ * Works on Claude format messages.
1819
+ */
1820
+ export function findOrphanedToolUseIds(messages) {
1821
+ const toolUseIds = new Set();
1822
+ const toolResultIds = new Set();
1823
+ for (const msg of messages) {
1824
+ if (Array.isArray(msg.content)) {
1825
+ for (const block of msg.content) {
1826
+ if (block.type === "tool_use" && block.id) {
1827
+ toolUseIds.add(block.id);
1828
+ }
1829
+ if (block.type === "tool_result" && block.tool_use_id) {
1830
+ toolResultIds.add(block.tool_use_id);
1831
+ }
1832
+ }
1833
+ }
1834
+ }
1835
+ return new Set([...toolUseIds].filter((id) => !toolResultIds.has(id)));
1836
+ }
1837
+ /**
1838
+ * Fix orphaned tool_use blocks in Claude format messages.
1839
+ * Mirrors fixToolResponseGrouping() but for Claude's messages[] format.
1840
+ *
1841
+ * Claude format:
1842
+ * - assistant message with content[]: { type: 'tool_use', id, name, input }
1843
+ * - user message with content[]: { type: 'tool_result', tool_use_id, content }
1844
+ *
1845
+ * @param messages - Claude format messages array
1846
+ * @returns Fixed messages with placeholder tool_results for orphans
1847
+ */
1848
+ export function fixClaudeToolPairing(messages) {
1849
+ if (!Array.isArray(messages) || messages.length === 0) {
1850
+ return messages;
1851
+ }
1852
+ // 1. Collect all tool_use IDs from assistant messages
1853
+ const toolUseMap = new Map();
1854
+ for (let i = 0; i < messages.length; i++) {
1855
+ const msg = messages[i];
1856
+ if (msg.role === "assistant" && Array.isArray(msg.content)) {
1857
+ for (const block of msg.content) {
1858
+ if (block.type === "tool_use" && block.id) {
1859
+ toolUseMap.set(block.id, { name: block.name || `tool-${toolUseMap.size}`, msgIndex: i });
1860
+ }
1861
+ }
1862
+ }
1863
+ }
1864
+ // 2. Collect all tool_result IDs from user messages
1865
+ const toolResultIds = new Set();
1866
+ for (const msg of messages) {
1867
+ if (msg.role === "user" && Array.isArray(msg.content)) {
1868
+ for (const block of msg.content) {
1869
+ if (block.type === "tool_result" && block.tool_use_id) {
1870
+ toolResultIds.add(block.tool_use_id);
1871
+ }
1872
+ }
1873
+ }
1874
+ }
1875
+ // 3. Find orphaned tool_use (no matching tool_result)
1876
+ const orphans = [];
1877
+ for (const [id, info] of toolUseMap) {
1878
+ if (!toolResultIds.has(id)) {
1879
+ orphans.push({ id, ...info });
1880
+ }
1881
+ }
1882
+ if (orphans.length === 0) {
1883
+ return messages;
1884
+ }
1885
+ // 4. Group orphans by message index (insert after each assistant message)
1886
+ const orphansByMsgIndex = new Map();
1887
+ for (const orphan of orphans) {
1888
+ const existing = orphansByMsgIndex.get(orphan.msgIndex) || [];
1889
+ existing.push(orphan);
1890
+ orphansByMsgIndex.set(orphan.msgIndex, existing);
1891
+ }
1892
+ // 5. Build new messages array with injected tool_results
1893
+ const result = [];
1894
+ for (let i = 0; i < messages.length; i++) {
1895
+ result.push(messages[i]);
1896
+ const orphansForMsg = orphansByMsgIndex.get(i);
1897
+ if (orphansForMsg && orphansForMsg.length > 0) {
1898
+ // Check if next message is user with tool_result - if so, merge into it
1899
+ const nextMsg = messages[i + 1];
1900
+ if (nextMsg?.role === "user" && Array.isArray(nextMsg.content)) {
1901
+ // Will be handled when we push nextMsg - add to its content
1902
+ const placeholders = orphansForMsg.map((o) => ({
1903
+ type: "tool_result",
1904
+ tool_use_id: o.id,
1905
+ content: `[Tool "${o.name}" execution was cancelled or failed]`,
1906
+ is_error: true,
1907
+ }));
1908
+ // Prepend placeholders to next message's content
1909
+ nextMsg.content = [...placeholders, ...nextMsg.content];
1910
+ }
1911
+ else {
1912
+ // Inject new user message with placeholder tool_results
1913
+ result.push({
1914
+ role: "user",
1915
+ content: orphansForMsg.map((o) => ({
1916
+ type: "tool_result",
1917
+ tool_use_id: o.id,
1918
+ content: `[Tool "${o.name}" execution was cancelled or failed]`,
1919
+ is_error: true,
1920
+ })),
1921
+ });
1922
+ }
1923
+ }
1924
+ }
1925
+ return result;
1926
+ }
1927
+ /**
1928
+ * Nuclear option: Remove orphaned tool_use blocks entirely.
1929
+ * Called when fixClaudeToolPairing() fails to pair all tools.
1930
+ */
1931
+ function removeOrphanedToolUse(messages, orphanIds) {
1932
+ return messages
1933
+ .map((msg) => {
1934
+ if (msg.role === "assistant" && Array.isArray(msg.content)) {
1935
+ return {
1936
+ ...msg,
1937
+ content: msg.content.filter((block) => block.type !== "tool_use" || !orphanIds.has(block.id)),
1938
+ };
1939
+ }
1940
+ return msg;
1941
+ })
1942
+ .filter((msg) =>
1943
+ // Remove empty assistant messages
1944
+ !(msg.role === "assistant" && Array.isArray(msg.content) && msg.content.length === 0));
1945
+ }
1946
+ /**
1947
+ * Validate and fix tool pairing with fallback nuclear option.
1948
+ * Defense in depth: tries gentle fix first, then nuclear removal.
1949
+ */
1950
+ export function validateAndFixClaudeToolPairing(messages) {
1951
+ if (!Array.isArray(messages) || messages.length === 0) {
1952
+ return messages;
1953
+ }
1954
+ // First: Try gentle fix (inject placeholder tool_results)
1955
+ let fixed = fixClaudeToolPairing(messages);
1956
+ // Second: Validate - find any remaining orphans
1957
+ const orphanIds = findOrphanedToolUseIds(fixed);
1958
+ if (orphanIds.size === 0) {
1959
+ return fixed;
1960
+ }
1961
+ // Third: Nuclear option - remove orphaned tool_use entirely
1962
+ // This should rarely happen, but provides defense in depth
1963
+ console.warn("[antigravity] fixClaudeToolPairing left orphans, applying nuclear option", {
1964
+ orphanIds: [...orphanIds],
1965
+ });
1966
+ return removeOrphanedToolUse(fixed, orphanIds);
1967
+ }
1968
+ // ============================================================================
1969
+ // TOOL HALLUCINATION PREVENTION (Ported from LLM-API-Key-Proxy)
1970
+ // ============================================================================
1971
+ /**
1972
+ * Formats a type hint for a property schema.
1973
+ * Port of LLM-API-Key-Proxy's _format_type_hint()
1974
+ */
1975
+ function formatTypeHint(propData, depth = 0) {
1976
+ const type = propData.type ?? "unknown";
1977
+ // Handle enum values
1978
+ if (propData.enum && Array.isArray(propData.enum)) {
1979
+ const enumVals = propData.enum;
1980
+ if (enumVals.length <= 5) {
1981
+ return `string ENUM[${enumVals.map(v => JSON.stringify(v)).join(", ")}]`;
1982
+ }
1983
+ return `string ENUM[${enumVals.length} options]`;
1984
+ }
1985
+ // Handle const values
1986
+ if (propData.const !== undefined) {
1987
+ return `string CONST=${JSON.stringify(propData.const)}`;
1988
+ }
1989
+ if (type === "array") {
1990
+ const items = propData.items;
1991
+ if (items && typeof items === "object") {
1992
+ const itemType = items.type ?? "unknown";
1993
+ if (itemType === "object") {
1994
+ const nestedProps = items.properties;
1995
+ const nestedReq = items.required ?? [];
1996
+ if (nestedProps && depth < 1) {
1997
+ const nestedList = Object.entries(nestedProps).map(([n, d]) => {
1998
+ const t = d.type ?? "unknown";
1999
+ const req = nestedReq.includes(n) ? " REQUIRED" : "";
2000
+ return `${n}: ${t}${req}`;
2001
+ });
2002
+ return `ARRAY_OF_OBJECTS[${nestedList.join(", ")}]`;
2003
+ }
2004
+ return "ARRAY_OF_OBJECTS";
2005
+ }
2006
+ return `ARRAY_OF_${itemType.toUpperCase()}`;
2007
+ }
2008
+ return "ARRAY";
2009
+ }
2010
+ if (type === "object") {
2011
+ const nestedProps = propData.properties;
2012
+ const nestedReq = propData.required ?? [];
2013
+ if (nestedProps && depth < 1) {
2014
+ const nestedList = Object.entries(nestedProps).map(([n, d]) => {
2015
+ const t = d.type ?? "unknown";
2016
+ const req = nestedReq.includes(n) ? " REQUIRED" : "";
2017
+ return `${n}: ${t}${req}`;
2018
+ });
2019
+ return `object{${nestedList.join(", ")}}`;
2020
+ }
2021
+ }
2022
+ return type;
2023
+ }
2024
+ /**
2025
+ * Injects parameter signatures into tool descriptions.
2026
+ * Port of LLM-API-Key-Proxy's _inject_signature_into_descriptions()
2027
+ *
2028
+ * This helps prevent tool hallucination by explicitly listing parameters
2029
+ * in the description, making it harder for the model to hallucinate
2030
+ * parameters from its training data.
2031
+ *
2032
+ * @param tools - Array of tool definitions (Gemini format)
2033
+ * @param promptTemplate - Template for the signature (default: "\\n\\nSTRICT PARAMETERS: {params}.")
2034
+ * @returns Modified tools array with signatures injected
2035
+ */
2036
+ export function injectParameterSignatures(tools, promptTemplate = "\n\n⚠️ STRICT PARAMETERS: {params}.") {
2037
+ if (!tools || !Array.isArray(tools))
2038
+ return tools;
2039
+ return tools.map((tool) => {
2040
+ const declarations = tool.functionDeclarations;
2041
+ if (!Array.isArray(declarations))
2042
+ return tool;
2043
+ const newDeclarations = declarations.map((decl) => {
2044
+ // Skip if signature already injected (avoids duplicate injection)
2045
+ if (decl.description?.includes("STRICT PARAMETERS:")) {
2046
+ return decl;
2047
+ }
2048
+ const schema = decl.parameters || decl.parametersJsonSchema;
2049
+ if (!schema)
2050
+ return decl;
2051
+ const required = schema.required ?? [];
2052
+ const properties = schema.properties ?? {};
2053
+ if (Object.keys(properties).length === 0)
2054
+ return decl;
2055
+ const paramList = Object.entries(properties).map(([propName, propData]) => {
2056
+ const typeHint = formatTypeHint(propData);
2057
+ const isRequired = required.includes(propName);
2058
+ return `${propName} (${typeHint}${isRequired ? ", REQUIRED" : ""})`;
2059
+ });
2060
+ const sigStr = promptTemplate.replace("{params}", paramList.join(", "));
2061
+ return {
2062
+ ...decl,
2063
+ description: (decl.description || "") + sigStr,
2064
+ };
2065
+ });
2066
+ return { ...tool, functionDeclarations: newDeclarations };
2067
+ });
2068
+ }
2069
+ /**
2070
+ * Injects a tool hardening system instruction into the request payload.
2071
+ * Port of LLM-API-Key-Proxy's _inject_tool_hardening_instruction()
2072
+ *
2073
+ * @param payload - The Gemini request payload
2074
+ * @param instructionText - The instruction text to inject
2075
+ */
2076
+ export function injectToolHardeningInstruction(payload, instructionText) {
2077
+ if (!instructionText)
2078
+ return;
2079
+ // Skip if instruction already present (avoids duplicate injection)
2080
+ const existing = payload.systemInstruction;
2081
+ if (existing && typeof existing === "object" && "parts" in existing) {
2082
+ const parts = existing.parts;
2083
+ if (Array.isArray(parts) && parts.some(p => p.text?.includes("CRITICAL TOOL USAGE INSTRUCTIONS"))) {
2084
+ return;
2085
+ }
2086
+ }
2087
+ const instructionPart = { text: instructionText };
2088
+ if (payload.systemInstruction) {
2089
+ if (existing && typeof existing === "object" && "parts" in existing) {
2090
+ const parts = existing.parts;
2091
+ if (Array.isArray(parts)) {
2092
+ parts.unshift(instructionPart);
2093
+ }
2094
+ }
2095
+ else if (typeof existing === "string") {
2096
+ payload.systemInstruction = {
2097
+ role: "user",
2098
+ parts: [instructionPart, { text: existing }],
2099
+ };
2100
+ }
2101
+ else {
2102
+ payload.systemInstruction = {
2103
+ role: "user",
2104
+ parts: [instructionPart],
2105
+ };
2106
+ }
2107
+ }
2108
+ else {
2109
+ payload.systemInstruction = {
2110
+ role: "user",
2111
+ parts: [instructionPart],
2112
+ };
2113
+ }
2114
+ }
2115
+ // ============================================================================
2116
+ // TOOL PROCESSING FOR WRAPPED REQUESTS
2117
+ // Shared logic for assigning tool IDs and fixing tool pairing
2118
+ // ============================================================================
2119
+ /**
2120
+ * Assigns IDs to functionCall parts and returns the pending call IDs by name.
2121
+ * This is the first pass of tool ID assignment.
2122
+ *
2123
+ * @param contents - Gemini-style contents array
2124
+ * @returns Object with modified contents and pending call IDs map
2125
+ */
2126
+ export function assignToolIdsToContents(contents) {
2127
+ if (!Array.isArray(contents)) {
2128
+ return { contents, pendingCallIdsByName: new Map(), toolCallCounter: 0 };
2129
+ }
2130
+ let toolCallCounter = 0;
2131
+ const pendingCallIdsByName = new Map();
2132
+ const newContents = contents.map((content) => {
2133
+ if (!content || !Array.isArray(content.parts)) {
2134
+ return content;
2135
+ }
2136
+ const newParts = content.parts.map((part) => {
2137
+ if (part && typeof part === "object" && part.functionCall) {
2138
+ const call = { ...part.functionCall };
2139
+ if (!call.id) {
2140
+ call.id = `tool-call-${++toolCallCounter}`;
2141
+ }
2142
+ const nameKey = typeof call.name === "string" ? call.name : `tool-${toolCallCounter}`;
2143
+ const queue = pendingCallIdsByName.get(nameKey) || [];
2144
+ queue.push(call.id);
2145
+ pendingCallIdsByName.set(nameKey, queue);
2146
+ return { ...part, functionCall: call };
2147
+ }
2148
+ return part;
2149
+ });
2150
+ return { ...content, parts: newParts };
2151
+ });
2152
+ return { contents: newContents, pendingCallIdsByName, toolCallCounter };
2153
+ }
2154
+ /**
2155
+ * Matches functionResponse IDs to their corresponding functionCall IDs.
2156
+ * This is the second pass of tool ID assignment.
2157
+ *
2158
+ * @param contents - Gemini-style contents array
2159
+ * @param pendingCallIdsByName - Map of function names to pending call IDs
2160
+ * @returns Modified contents with matched response IDs
2161
+ */
2162
+ export function matchResponseIdsToContents(contents, pendingCallIdsByName) {
2163
+ if (!Array.isArray(contents)) {
2164
+ return contents;
2165
+ }
2166
+ return contents.map((content) => {
2167
+ if (!content || !Array.isArray(content.parts)) {
2168
+ return content;
2169
+ }
2170
+ const newParts = content.parts.map((part) => {
2171
+ if (part && typeof part === "object" && part.functionResponse) {
2172
+ const resp = { ...part.functionResponse };
2173
+ if (!resp.id && typeof resp.name === "string") {
2174
+ const queue = pendingCallIdsByName.get(resp.name);
2175
+ if (queue && queue.length > 0) {
2176
+ resp.id = queue.shift();
2177
+ pendingCallIdsByName.set(resp.name, queue);
2178
+ }
2179
+ }
2180
+ return { ...part, functionResponse: resp };
2181
+ }
2182
+ return part;
2183
+ });
2184
+ return { ...content, parts: newParts };
2185
+ });
2186
+ }
2187
+ /**
2188
+ * Applies all tool fixes to a request payload for Claude models.
2189
+ * This includes:
2190
+ * 1. Tool ID assignment for functionCalls
2191
+ * 2. Response ID matching for functionResponses
2192
+ * 3. Orphan recovery via fixToolResponseGrouping
2193
+ * 4. Claude format pairing fix via validateAndFixClaudeToolPairing
2194
+ *
2195
+ * @param payload - Request payload object
2196
+ * @param isClaude - Whether this is a Claude model request
2197
+ * @returns Object with fix applied status
2198
+ */
2199
+ export function applyToolPairingFixes(payload, isClaude) {
2200
+ let contentsFixed = false;
2201
+ let messagesFixed = false;
2202
+ if (!isClaude) {
2203
+ return { contentsFixed, messagesFixed };
2204
+ }
2205
+ // Fix Gemini format (contents[])
2206
+ if (Array.isArray(payload.contents)) {
2207
+ // First pass: assign IDs to functionCalls
2208
+ const { contents: contentsWithIds, pendingCallIdsByName } = assignToolIdsToContents(payload.contents);
2209
+ // Second pass: match functionResponse IDs
2210
+ const contentsWithMatchedIds = matchResponseIdsToContents(contentsWithIds, pendingCallIdsByName);
2211
+ // Third pass: fix orphan recovery
2212
+ payload.contents = fixToolResponseGrouping(contentsWithMatchedIds);
2213
+ contentsFixed = true;
2214
+ log.debug("Applied tool pairing fixes to contents[]", {
2215
+ originalLength: payload.contents.length,
2216
+ });
2217
+ }
2218
+ // Fix Claude format (messages[])
2219
+ if (Array.isArray(payload.messages)) {
2220
+ payload.messages = validateAndFixClaudeToolPairing(payload.messages);
2221
+ messagesFixed = true;
2222
+ log.debug("Applied tool pairing fixes to messages[]", {
2223
+ originalLength: payload.messages.length,
2224
+ });
2225
+ }
2226
+ return { contentsFixed, messagesFixed };
2227
+ }
2228
+ // ============================================================================
2229
+ // SYNTHETIC CLAUDE SSE RESPONSE
2230
+ // Used to return error messages as "successful" responses to avoid locking
2231
+ // the OpenCode session when unrecoverable errors (like 400 Prompt Too Long) occur.
2232
+ // ============================================================================
2233
+ /**
2234
+ * Creates a synthetic Claude SSE streaming response with error content.
2235
+ *
2236
+ * When returning HTTP 400/500 errors to OpenCode, the session becomes locked
2237
+ * and the user cannot use /compact or other commands. This function creates
2238
+ * a fake "successful" SSE response (200 OK) with the error message as text content,
2239
+ * allowing the user to continue using the session.
2240
+ *
2241
+ * @param errorMessage - The error message to include in the response
2242
+ * @param requestedModel - The model that was requested
2243
+ * @returns A Response object with synthetic SSE stream
2244
+ */
2245
+ export function createSyntheticErrorResponse(errorMessage, requestedModel = "unknown") {
2246
+ // Generate a unique message ID
2247
+ const messageId = `msg_synthetic_${Date.now()}`;
2248
+ // Build Claude SSE events that represent a complete message with error text
2249
+ const events = [];
2250
+ // 1. message_start event
2251
+ events.push(`event: message_start
2252
+ data: ${JSON.stringify({
2253
+ type: "message_start",
2254
+ message: {
2255
+ id: messageId,
2256
+ type: "message",
2257
+ role: "assistant",
2258
+ content: [],
2259
+ model: requestedModel,
2260
+ stop_reason: null,
2261
+ stop_sequence: null,
2262
+ usage: { input_tokens: 0, output_tokens: 0 },
2263
+ },
2264
+ })}
2265
+
2266
+ `);
2267
+ // 2. content_block_start event
2268
+ events.push(`event: content_block_start
2269
+ data: ${JSON.stringify({
2270
+ type: "content_block_start",
2271
+ index: 0,
2272
+ content_block: { type: "text", text: "" },
2273
+ })}
2274
+
2275
+ `);
2276
+ // 3. content_block_delta event with the error message
2277
+ events.push(`event: content_block_delta
2278
+ data: ${JSON.stringify({
2279
+ type: "content_block_delta",
2280
+ index: 0,
2281
+ delta: { type: "text_delta", text: errorMessage },
2282
+ })}
2283
+
2284
+ `);
2285
+ // 4. content_block_stop event
2286
+ events.push(`event: content_block_stop
2287
+ data: ${JSON.stringify({
2288
+ type: "content_block_stop",
2289
+ index: 0,
2290
+ })}
2291
+
2292
+ `);
2293
+ // 5. message_delta event (end_turn)
2294
+ events.push(`event: message_delta
2295
+ data: ${JSON.stringify({
2296
+ type: "message_delta",
2297
+ delta: { stop_reason: "end_turn", stop_sequence: null },
2298
+ usage: { output_tokens: Math.ceil(errorMessage.length / 4) },
2299
+ })}
2300
+
2301
+ `);
2302
+ // 6. message_stop event
2303
+ events.push(`event: message_stop
2304
+ data: ${JSON.stringify({ type: "message_stop" })}
2305
+
2306
+ `);
2307
+ const body = events.join("");
2308
+ return new Response(body, {
2309
+ status: 200,
2310
+ headers: {
2311
+ "Content-Type": "text/event-stream",
2312
+ "Cache-Control": "no-cache",
2313
+ "Connection": "keep-alive",
2314
+ "X-Antigravity-Synthetic": "true",
2315
+ "X-Antigravity-Error-Type": "prompt_too_long",
2316
+ },
2317
+ });
2318
+ }
2319
+ //# sourceMappingURL=request-helpers.js.map