@expiren/opencode-antigravity-auth 1.6.0

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