@chroxy/server 0.11.0 → 0.11.11

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 (386) hide show
  1. package/CONFIG.md +206 -18
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +166 -11
  5. package/package.json +16 -12
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +958 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +304 -0
  14. package/src/agent-control/client.js +1645 -0
  15. package/src/agent-control/events.js +551 -0
  16. package/src/agent-control/local-connection.js +293 -0
  17. package/src/agent-control/mcp-server.js +547 -0
  18. package/src/anthropic-compatible-config.js +30 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-gemini-shim.js +444 -0
  21. package/src/anthropic-gemini-translate.js +1030 -0
  22. package/src/anthropic-openai-shim.js +0 -1
  23. package/src/archive-continuation.js +164 -0
  24. package/src/assistant-response.js +24 -0
  25. package/src/auth-probes.js +120 -13
  26. package/src/background-shell-tracker.js +27 -0
  27. package/src/base-session.js +1520 -36
  28. package/src/bearer-recheck.js +49 -0
  29. package/src/billing-budget.js +19 -0
  30. package/src/billing-class.js +40 -7
  31. package/src/binary-provenance-trust.js +11 -5
  32. package/src/bound-client-policy.js +291 -0
  33. package/src/built-in-tools/bash-exec.js +46 -7
  34. package/src/built-in-tools/file-ops.js +69 -5
  35. package/src/built-in-tools/tool-transforms.js +1113 -13
  36. package/src/byok-compose-state.js +6 -9
  37. package/src/byok-credentials.js +2 -3
  38. package/src/byok-mcp-client.js +92 -7
  39. package/src/byok-mcp-config.js +633 -122
  40. package/src/byok-mcp-fleet.js +49 -7
  41. package/src/byok-mcp-oauth-store.js +18 -16
  42. package/src/byok-mcp-trust.js +37 -23
  43. package/src/byok-session.js +707 -179
  44. package/src/byok-tool-executor.js +2742 -26
  45. package/src/byok-tools.js +9 -2
  46. package/src/channels/chroxy-channel-server.js +2 -3
  47. package/src/checkpoint-manager.js +64 -46
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-setting-sources.js +74 -0
  53. package/src/claude-stream-parser.js +53 -3
  54. package/src/claude-tui/diagnostic-tail.js +83 -0
  55. package/src/claude-tui/form-driver.js +44 -7
  56. package/src/claude-tui/model-error.js +41 -0
  57. package/src/claude-tui/pty-driver.js +215 -88
  58. package/src/claude-tui/sanitize-question-payload.js +109 -0
  59. package/src/claude-tui/usage-limit.js +239 -0
  60. package/src/claude-tui-session.js +3563 -284
  61. package/src/claude-tui-tool-response.js +300 -0
  62. package/src/cli/agent-cmd.js +236 -0
  63. package/src/cli/agent-control-cmd.js +65 -0
  64. package/src/cli/config-cmd.js +4 -4
  65. package/src/cli/config-dir-cmd.js +234 -0
  66. package/src/cli/connection-state.js +54 -0
  67. package/src/cli/deploy-cmd.js +45 -10
  68. package/src/cli/doctor-cmd.js +7 -3
  69. package/src/cli/freshness-cmd.js +53 -0
  70. package/src/cli/init-cmd.js +15 -16
  71. package/src/cli/pages-cmd.js +6 -4
  72. package/src/cli/pair-code-cmd.js +7 -6
  73. package/src/cli/pair-discord-cmd.js +7 -6
  74. package/src/cli/providers-cmd.js +3 -3
  75. package/src/cli/schedule-cmd.js +91 -40
  76. package/src/cli/server-cmd.js +54 -1
  77. package/src/cli/service-cmd.js +33 -10
  78. package/src/cli/session-cmd.js +227 -74
  79. package/src/cli/shared.js +162 -11
  80. package/src/cli/shell-cmd.js +7 -4
  81. package/src/cli/status-cmd.js +19 -5
  82. package/src/cli/tokens-cmd.js +4 -5
  83. package/src/cli/tunnel-cmd.js +255 -24
  84. package/src/cli/worktree-gc-cmd.js +2 -2
  85. package/src/cli-session.js +1250 -126
  86. package/src/cli.js +8 -0
  87. package/src/codex-app-server-client.js +36 -3
  88. package/src/codex-app-server-session.js +1517 -81
  89. package/src/codex-bundled-client.js +66 -0
  90. package/src/codex-error-text.js +114 -0
  91. package/src/codex-model-catalog.js +548 -0
  92. package/src/codex-model-rejections.js +87 -0
  93. package/src/codex-native-resume.js +104 -0
  94. package/src/codex-protocol-capabilities.js +188 -0
  95. package/src/codex-session.js +450 -27
  96. package/src/config-dir-migration.js +449 -0
  97. package/src/config-dir.js +108 -0
  98. package/src/config.js +306 -26
  99. package/src/connection-authority.js +48 -0
  100. package/src/connection-info.js +78 -23
  101. package/src/connection-locality.js +60 -0
  102. package/src/container-liveness-monitor.js +189 -0
  103. package/src/continuation-metadata-worker.js +17 -0
  104. package/src/continuations.js +227 -0
  105. package/src/control-room/host-prune.js +5 -0
  106. package/src/control-room/integrations.js +7 -20
  107. package/src/control-room/skills-inventory.js +2 -2
  108. package/src/conversation-scanner.js +42 -39
  109. package/src/conversation-scope.js +59 -39
  110. package/src/conversation-search.js +28 -39
  111. package/src/credential-store.js +23 -19
  112. package/src/daemon-commit.js +92 -0
  113. package/src/daemon-idle-state.js +171 -0
  114. package/src/daemon-update-status.js +314 -0
  115. package/src/dashboard-build.js +70 -0
  116. package/src/declared-status.js +90 -0
  117. package/src/deepseek-credentials.js +2 -3
  118. package/src/dev-preview.js +170 -182
  119. package/src/device-preferences.js +2 -2
  120. package/src/diff-parser.js +87 -0
  121. package/src/discord-credentials.js +2 -3
  122. package/src/docker-byok-pool.js +3 -1
  123. package/src/docker-byok-session.js +678 -78
  124. package/src/docker-image-allowlist.js +23 -1
  125. package/src/docker-sdk-session.js +172 -3
  126. package/src/docker-session.js +294 -11
  127. package/src/doctor.js +781 -64
  128. package/src/durable-write.js +35 -0
  129. package/src/edited-input.js +264 -0
  130. package/src/environment-manager.js +175 -36
  131. package/src/environments/authority.js +101 -0
  132. package/src/environments/backends/container-claude-spawn.js +94 -0
  133. package/src/environments/backends/docker.js +31 -10
  134. package/src/environments/backends/k8s.js +49 -24
  135. package/src/environments/destroy-with-sessions.js +142 -0
  136. package/src/event-ingest.js +118 -13
  137. package/src/event-normalizer.js +186 -235
  138. package/src/folder-trust-wire.js +137 -0
  139. package/src/folder-trust-worker.js +17 -0
  140. package/src/folder-trust.js +1572 -0
  141. package/src/freshness/activity-meter.js +101 -0
  142. package/src/freshness/adapter.js +199 -0
  143. package/src/freshness/checks.js +239 -0
  144. package/src/freshness/config.js +98 -0
  145. package/src/freshness/core.js +185 -0
  146. package/src/freshness/derive.js +680 -0
  147. package/src/freshness/exchange.js +305 -0
  148. package/src/freshness/file-ledger.js +400 -0
  149. package/src/freshness/grade.js +81 -0
  150. package/src/freshness/hash.js +45 -0
  151. package/src/freshness/inbox.js +163 -0
  152. package/src/freshness/index.js +20 -0
  153. package/src/freshness/investigation.js +474 -0
  154. package/src/freshness/keys.js +177 -0
  155. package/src/freshness/ledger.js +122 -0
  156. package/src/freshness/outbox.js +131 -0
  157. package/src/freshness/policy.js +599 -0
  158. package/src/freshness/queue.js +843 -0
  159. package/src/freshness/read-errors.js +23 -0
  160. package/src/freshness/render.js +153 -0
  161. package/src/freshness/runtime.js +113 -0
  162. package/src/freshness/session-registry-adapter.js +161 -0
  163. package/src/freshness/state-file-adapter.js +167 -0
  164. package/src/freshness-runner/build-info.js +139 -0
  165. package/src/freshness-runner/cli.js +105 -0
  166. package/src/freshness-runner/run-tick.js +109 -0
  167. package/src/freshness-runner/stamp.js +57 -0
  168. package/src/freshness-sources/claude-transcript-adapter.js +211 -0
  169. package/src/freshness-sources/codex-transcript-adapter.js +33 -0
  170. package/src/freshness-sources/index.js +8 -0
  171. package/src/gemini-byok-session.js +292 -0
  172. package/src/gemini-credentials.js +67 -0
  173. package/src/gemini-key-safety.js +246 -0
  174. package/src/gemini-models.js +386 -0
  175. package/src/gemini-session.js +81 -5
  176. package/src/handler-utils.js +540 -80
  177. package/src/handlers/checkpoint-handlers.js +47 -4
  178. package/src/handlers/control-room-handlers.js +51 -11
  179. package/src/handlers/conversation-handlers.js +469 -56
  180. package/src/handlers/daemon-update-handlers.js +81 -0
  181. package/src/handlers/evaluator-handlers.js +14 -1
  182. package/src/handlers/feature-handlers.js +186 -69
  183. package/src/handlers/file-handlers.js +57 -13
  184. package/src/handlers/folder-trust-handlers.js +90 -0
  185. package/src/handlers/input-handlers.js +714 -48
  186. package/src/handlers/orchestration-handlers.js +3 -3
  187. package/src/handlers/principal-admin-handlers.js +229 -0
  188. package/src/handlers/principal-handlers.js +262 -0
  189. package/src/handlers/scheduler-handlers.js +92 -18
  190. package/src/handlers/session-handlers.js +551 -20
  191. package/src/handlers/session-pr-status-handlers.js +283 -0
  192. package/src/handlers/session-pr-threads-handlers.js +247 -0
  193. package/src/handlers/settings-handlers.js +372 -50
  194. package/src/handlers/skills-handlers.js +20 -4
  195. package/src/handlers/summarize-handlers.js +32 -1
  196. package/src/handlers/survey-throttle.js +380 -0
  197. package/src/health-proof.js +40 -0
  198. package/src/history-page.js +112 -0
  199. package/src/http-routes.js +127 -8
  200. package/src/ide/search.js +24 -6
  201. package/src/ide/symbols.js +20 -6
  202. package/src/input-context.js +117 -0
  203. package/src/instruction-policy-compiler.js +229 -0
  204. package/src/instruction-policy.js +250 -0
  205. package/src/jsonl-reader.js +378 -91
  206. package/src/jsonl-subprocess-session.js +96 -9
  207. package/src/keychain.js +1 -1
  208. package/src/logger.js +166 -30
  209. package/src/mailbox-route.js +113 -22
  210. package/src/message-wire.js +386 -0
  211. package/src/model-discovery.js +43 -3
  212. package/src/models.js +1276 -174
  213. package/src/notification-prefs.js +27 -4
  214. package/src/notifications/discord-billing-sink.js +22 -5
  215. package/src/notifications/discord-ci-sink.js +243 -0
  216. package/src/notifications/discord-webhook-client.js +71 -0
  217. package/src/notifications/discord-webhook-sink.js +64 -23
  218. package/src/notifications/expo-push-sink.js +85 -6
  219. package/src/notifications/ready-body.js +16 -5
  220. package/src/ollama-session.js +34 -2
  221. package/src/orchestration/build-manager.js +9 -2
  222. package/src/orchestration/git-ops.js +41 -7
  223. package/src/orchestration/orchestration-manager.js +112 -36
  224. package/src/orchestration/permission-gate.js +17 -2
  225. package/src/orchestration/run-model.js +2 -1
  226. package/src/orchestration/run-record.js +11 -0
  227. package/src/orchestration/turn-driver.js +185 -43
  228. package/src/orphan-reaper.js +470 -0
  229. package/src/outgoing-policy.js +189 -0
  230. package/src/pairing.js +92 -13
  231. package/src/path-hash-trust-ledger.js +642 -25
  232. package/src/permission-deadlines.js +82 -0
  233. package/src/permission-floor.js +1410 -43
  234. package/src/permission-hook.js +180 -69
  235. package/src/permission-manager.js +737 -89
  236. package/src/permission-mode-support.js +35 -0
  237. package/src/permission-resolved-by.js +89 -0
  238. package/src/permission-resolver.js +126 -8
  239. package/src/permission-scope.js +43 -0
  240. package/src/platform.js +315 -47
  241. package/src/preview-ingress.js +54 -0
  242. package/src/preview-target.js +213 -0
  243. package/src/principal-audit.js +189 -0
  244. package/src/principal-binding.js +25 -0
  245. package/src/principal-brakes.js +21 -0
  246. package/src/principal-effect.js +101 -0
  247. package/src/principal-journal.js +905 -0
  248. package/src/principal-kill-switch.js +183 -0
  249. package/src/principal-label.js +5 -0
  250. package/src/principal-pending-permissions.js +177 -0
  251. package/src/principal-policy.js +1094 -0
  252. package/src/principal-sessions-snapshot.js +208 -0
  253. package/src/principal-store.js +488 -0
  254. package/src/principal-subscriptions.js +283 -0
  255. package/src/prompt-evaluator.js +34 -4
  256. package/src/provider-customization.js +180 -0
  257. package/src/providers.js +209 -4
  258. package/src/push.js +30 -4
  259. package/src/question-route-map.js +130 -0
  260. package/src/redaction.js +531 -20
  261. package/src/roster-broadcast.js +186 -0
  262. package/src/scheduled-task-store.js +330 -26
  263. package/src/scheduler.js +368 -11
  264. package/src/sdk-session.js +2114 -188
  265. package/src/server-cli/preview-shutdown.js +22 -0
  266. package/src/server-cli/push-notification-handler.js +17 -3
  267. package/src/server-cli/server-orchestrator.js +28 -5
  268. package/src/server-cli-child.js +33 -18
  269. package/src/server-cli.js +553 -38
  270. package/src/server-identity.js +15 -11
  271. package/src/service.js +396 -25
  272. package/src/session-archive-limits.js +15 -0
  273. package/src/session-archive.js +1029 -0
  274. package/src/session-busy-state.js +72 -0
  275. package/src/session-ci-watcher.js +1099 -0
  276. package/src/session-context.js +7 -2
  277. package/src/session-manager.js +4062 -312
  278. package/src/session-message-history.js +841 -16
  279. package/src/session-name-allocator.js +685 -0
  280. package/src/session-pr-status.js +654 -0
  281. package/src/session-pr-threads.js +271 -0
  282. package/src/session-preset-trust.js +3 -3
  283. package/src/session-preset.js +10 -5
  284. package/src/session-state-persistence.js +94 -17
  285. package/src/session-timeout-manager.js +20 -0
  286. package/src/session-token-store.js +17 -8
  287. package/src/session-wake.js +240 -0
  288. package/src/shell-approval-info.js +2 -2
  289. package/src/shell-approval-store.js +3 -1
  290. package/src/skills-loader.js +7 -4
  291. package/src/skills-manager.js +2 -2
  292. package/src/skills-trust.js +95 -13
  293. package/src/skills-usage.js +2 -3
  294. package/src/snapshots-store.js +2 -3
  295. package/src/statusline.js +100 -29
  296. package/src/summarize-session.js +53 -4
  297. package/src/supervisor.js +22 -11
  298. package/src/sweep-stale-provider-dirs.js +95 -0
  299. package/src/thinking-level-wire.js +39 -0
  300. package/src/thinking-stream.js +179 -0
  301. package/src/tool-result.js +61 -0
  302. package/src/transcript-sources.js +109 -0
  303. package/src/transcript-tasks.js +372 -25
  304. package/src/trusted-file-read.js +302 -0
  305. package/src/tunnel/base.js +0 -8
  306. package/src/tunnel/cloudflare.js +34 -31
  307. package/src/tunnel/index.js +9 -0
  308. package/src/tunnel/preview.js +64 -0
  309. package/src/turn-outcome.js +140 -0
  310. package/src/usage-normalize.js +9 -5
  311. package/src/user-shell-session.js +59 -5
  312. package/src/utils/agent-sdk-version.js +107 -0
  313. package/src/utils/argv-safety.js +770 -0
  314. package/src/utils/auth-cause.js +60 -0
  315. package/src/utils/binary-package-manifest.js +639 -0
  316. package/src/utils/binary-version.js +224 -0
  317. package/src/utils/bounded-regex-worker.js +29 -0
  318. package/src/utils/bounded-regex.js +162 -0
  319. package/src/utils/claude-binary.js +43 -0
  320. package/src/utils/claude-config-dir.js +245 -0
  321. package/src/utils/claude-login-command.js +16 -0
  322. package/src/utils/claude-native-route.js +81 -0
  323. package/src/utils/componentwise-resolver.js +133 -37
  324. package/src/utils/deploy-control-files.js +87 -0
  325. package/src/utils/exec-failure-reason.js +21 -0
  326. package/src/utils/git-repo.js +42 -0
  327. package/src/utils/is-entry-point.js +137 -0
  328. package/src/utils/node-pty-probe.js +95 -0
  329. package/src/utils/node-pty-support.js +118 -0
  330. package/src/utils/opened-file-path.js +167 -0
  331. package/src/utils/path-containment.js +165 -0
  332. package/src/utils/permission-mode-sidecar.js +51 -0
  333. package/src/utils/pid-liveness.js +47 -0
  334. package/src/utils/preflight.js +360 -16
  335. package/src/utils/read-limiter.js +217 -0
  336. package/src/utils/regular-file.js +375 -0
  337. package/src/utils/safe-regex.js +113 -0
  338. package/src/utils/small-file.js +129 -0
  339. package/src/utils/spawn-env.js +189 -4
  340. package/src/utils/stale-session-dirs.js +182 -0
  341. package/src/utils/stat-identity.js +43 -0
  342. package/src/utils/verify-provenance.js +406 -13
  343. package/src/web-task-manager.js +297 -16
  344. package/src/worktree-gc.js +202 -6
  345. package/src/ws-auth.js +163 -31
  346. package/src/ws-broadcaster.js +49 -5
  347. package/src/ws-client-manager.js +24 -1
  348. package/src/ws-client-sender.js +7 -0
  349. package/src/ws-file-ops/browser.js +363 -58
  350. package/src/ws-file-ops/common.js +320 -14
  351. package/src/ws-file-ops/git.js +395 -42
  352. package/src/ws-file-ops/index.js +2 -0
  353. package/src/ws-file-ops/memory.js +137 -35
  354. package/src/ws-file-ops/open-nofollow.js +354 -0
  355. package/src/ws-file-ops/reader.js +571 -113
  356. package/src/ws-forwarding.js +349 -39
  357. package/src/ws-handler-context.js +88 -2
  358. package/src/ws-history.js +1010 -175
  359. package/src/ws-message-handlers.js +25 -1
  360. package/src/ws-permissions.js +307 -37
  361. package/src/ws-schemas.js +5 -0
  362. package/src/ws-server.js +885 -98
  363. package/sidecar/node_modules/.package-lock.json +0 -29
  364. package/sidecar/node_modules/ws/LICENSE +0 -20
  365. package/sidecar/node_modules/ws/README.md +0 -548
  366. package/sidecar/node_modules/ws/browser.js +0 -8
  367. package/sidecar/node_modules/ws/index.js +0 -22
  368. package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
  369. package/sidecar/node_modules/ws/lib/constants.js +0 -19
  370. package/sidecar/node_modules/ws/lib/event-target.js +0 -292
  371. package/sidecar/node_modules/ws/lib/extension.js +0 -203
  372. package/sidecar/node_modules/ws/lib/limiter.js +0 -55
  373. package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
  374. package/sidecar/node_modules/ws/lib/receiver.js +0 -706
  375. package/sidecar/node_modules/ws/lib/sender.js +0 -602
  376. package/sidecar/node_modules/ws/lib/stream.js +0 -161
  377. package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
  378. package/sidecar/node_modules/ws/lib/validation.js +0 -152
  379. package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
  380. package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
  381. package/sidecar/node_modules/ws/package.json +0 -70
  382. package/sidecar/node_modules/ws/wrapper.mjs +0 -21
  383. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  384. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  385. package/src/dashboard-next/dist/index.html +0 -13
  386. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
@@ -0,0 +1,1030 @@
1
+ /**
2
+ * Pure translation between Anthropic Messages API shapes and Google Gemini
3
+ * `v1beta` `generateContent` / `streamGenerateContent` REST shapes.
4
+ *
5
+ * `ClaudeByokSession` drives an `@anthropic-ai/sdk`-shaped client
6
+ * (`client.messages.stream(...)`), consuming raw Anthropic SDK events
7
+ * (`message_start` / `content_block_*` / `message_delta` / `message_stop`) and
8
+ * reading `stream.finalMessage()`. To drive Google's Gemini API directly
9
+ * without forking the BYOK agent loop, this module handles the pure,
10
+ * side-effect-free request and stream translation; network I/O lives in
11
+ * `anthropic-gemini-shim.js`.
12
+ *
13
+ * Key Gemini-specific behaviours preserved here (which an OpenAI-compat shim
14
+ * drops):
15
+ * - `thought: true` parts stream as Anthropic `thinking_delta` blocks so
16
+ * Chroxy renders live thinking bubbles (`#6756`).
17
+ * - `thoughtSignature` on `functionCall`, `thought`, and `text` parts is
18
+ * preserved on assembled `finalMessage.content` blocks and round-tripped
19
+ * back into `contents` on subsequent tool rounds (required by Gemini
20
+ * thinking models during multi-turn tool use).
21
+ * - Model-aware `thinkingConfig`: Gemini 2.5 uses integer `thinkingBudget`,
22
+ * Gemini 3+/4+ uses `thinkingLevel`, and non-thinking Gemini 1.5/2.0 models
23
+ * omit `thinkingConfig` to avoid HTTP 400 rejections.
24
+ * - `usageMetadata.cachedContentTokenCount` maps onto
25
+ * `cache_read_input_tokens` and is subtracted from `input_tokens` so
26
+ * `computePromptCostUsd` never double-bills cached prompt tokens.
27
+ */
28
+
29
+ import { createHash, randomUUID } from 'node:crypto'
30
+ import { LEGACY_DEFAULT_THINKING_LEVEL } from '@chroxy/protocol'
31
+
32
+ // Strict allowlist of OpenAPI 3.0 Schema fields accepted by Gemini `v1beta`
33
+ // `FunctionDeclaration.parameters` protobuf JSON parsing.
34
+ const ALLOWED_SCALAR_SCHEMA_KEYS = new Set([
35
+ 'description',
36
+ 'minItems',
37
+ 'maxItems',
38
+ 'minimum',
39
+ 'maximum',
40
+ 'minLength',
41
+ 'maxLength',
42
+ 'pattern',
43
+ 'propertyOrdering',
44
+ ])
45
+
46
+ const ALLOWED_GEMINI_FORMATS = new Set([
47
+ 'float',
48
+ 'double',
49
+ 'int32',
50
+ 'int64',
51
+ 'enum',
52
+ 'date-time',
53
+ ])
54
+
55
+ const ALLOWED_GEMINI_TYPES = new Set([
56
+ 'string',
57
+ 'number',
58
+ 'integer',
59
+ 'boolean',
60
+ 'array',
61
+ 'object',
62
+ ])
63
+
64
+ /**
65
+ * Safe stand-in for a schema Gemini cannot express (`{}`, boolean schemas,
66
+ * a missing `items`). Gemini's OpenAPI subset has no "any" type, so offer the
67
+ * three scalar types rather than collapsing to `string`, which would
68
+ * advertise numbers and booleans as text.
69
+ */
70
+ function untypedSchemaDefault() {
71
+ return { anyOf: [{ type: 'string' }, { type: 'number' }, { type: 'boolean' }] }
72
+ }
73
+
74
+ function appendDescription(out, extra) {
75
+ out.description = typeof out.description === 'string' && out.description.length > 0
76
+ ? `${out.description} ${extra}`
77
+ : extra
78
+ }
79
+
80
+ function scalarTypeOf(values) {
81
+ if (values.every((v) => typeof v === 'boolean')) return 'boolean'
82
+ if (values.every((v) => typeof v === 'number' && Number.isInteger(v))) return 'integer'
83
+ if (values.every((v) => typeof v === 'number' && Number.isFinite(v))) return 'number'
84
+ return null
85
+ }
86
+
87
+ /**
88
+ * Normalize a JSON Schema (e.g. an Anthropic `input_schema` from built-in or
89
+ * MCP tools) into the strict OpenAPI 3.0 subset accepted by Gemini
90
+ * `functionDeclarations`. Pure and recursive; never mutates the input.
91
+ *
92
+ * Unlike a blacklist, an allowlist prevents unknown JSON Schema keywords
93
+ * (`$ref`, `allOf`, `additionalProperties`, `not`, `if`/`then`, unsupported
94
+ * `format` values) from causing Gemini HTTP 400 `Unknown name` rejections.
95
+ *
96
+ * Types are never rewritten: Gemini's `Schema.enum` is string-only, so a
97
+ * numeric or boolean `enum` / `const` keeps its `integer` / `number` /
98
+ * `boolean` type and the allowed values move into `description`. (This repo
99
+ * has no confirmed contract for `parametersJsonSchema`, so the OpenAPI-subset
100
+ * `parameters` path is kept.)
101
+ *
102
+ * @param {*} schema
103
+ * @returns {object}
104
+ */
105
+ export function sanitizeSchemaForGemini(schema) {
106
+ if (!schema || typeof schema !== 'object' || Array.isArray(schema)) {
107
+ return { type: 'object' }
108
+ }
109
+ const out = sanitizeNode(schema)
110
+ if (out.type === 'object') return out
111
+ // A root parameters schema must be an OBJECT. A typeless or non-object root
112
+ // (`{}`, `{ description }`) keeps only the object-compatible fields.
113
+ const root = { type: 'object' }
114
+ for (const key of ['description', 'properties', 'required']) {
115
+ if (out[key] !== undefined) root[key] = out[key]
116
+ }
117
+ return root
118
+ }
119
+
120
+ function sanitizeChild(schema) {
121
+ // Boolean / non-object nested schemas mean "anything" (or "nothing"); use the
122
+ // safe default rather than an empty object schema.
123
+ if (!schema || typeof schema !== 'object' || Array.isArray(schema)) return untypedSchemaDefault()
124
+ return sanitizeNode(schema)
125
+ }
126
+
127
+ function sanitizeNode(schema) {
128
+ const out = {}
129
+ let nullable = Boolean(schema.nullable)
130
+ const notes = []
131
+
132
+ // `const`: a string stays a one-element string `enum`; a number or boolean
133
+ // keeps its type and is described, since `Schema.enum` is string-only.
134
+ if (Object.prototype.hasOwnProperty.call(schema, 'const') && schema.const !== null && schema.const !== undefined) {
135
+ const c = schema.const
136
+ if (typeof c === 'string') {
137
+ out.type = 'string'
138
+ out.enum = [c]
139
+ } else if (scalarTypeOf([c])) {
140
+ out.type = scalarTypeOf([c])
141
+ notes.push(`Must be exactly ${JSON.stringify(c)}.`)
142
+ }
143
+ }
144
+
145
+ // Handle `type: ['string', 'null']` → `type: 'string', nullable: true`.
146
+ if (!out.type) {
147
+ if (Array.isArray(schema.type)) {
148
+ const nonNull = schema.type.filter((t) => t !== 'null' && ALLOWED_GEMINI_TYPES.has(t))
149
+ if (schema.type.includes('null')) nullable = true
150
+ if (nonNull.length > 0) out.type = nonNull[0]
151
+ } else if (typeof schema.type === 'string' && ALLOWED_GEMINI_TYPES.has(schema.type)) {
152
+ out.type = schema.type
153
+ }
154
+ }
155
+
156
+ // Handle simple `anyOf` / `oneOf` nullable unions (`[{ type: 'string' }, { type: 'null' }]`).
157
+ const union = Array.isArray(schema.anyOf) ? schema.anyOf : Array.isArray(schema.oneOf) ? schema.oneOf : null
158
+ if (union && !out.type) {
159
+ const nonNullBranches = union.filter((b) => b && typeof b === 'object' && b.type !== 'null')
160
+ if (nonNullBranches.length < union.length) nullable = true
161
+ if (nonNullBranches.length === 1) {
162
+ Object.assign(out, sanitizeNode(nonNullBranches[0]))
163
+ } else if (nonNullBranches.length > 1) {
164
+ out.anyOf = nonNullBranches.map((b) => sanitizeNode(b))
165
+ }
166
+ }
167
+
168
+ if (typeof schema.format === 'string' && ALLOWED_GEMINI_FORMATS.has(schema.format)) {
169
+ out.format = schema.format
170
+ }
171
+
172
+ for (const key of ALLOWED_SCALAR_SCHEMA_KEYS) {
173
+ if (!Object.prototype.hasOwnProperty.call(schema, key)) continue
174
+ const val = schema[key]
175
+ if (val === undefined || val === null) continue
176
+ out[key] = val
177
+ }
178
+
179
+ if (schema.properties && typeof schema.properties === 'object' && !Array.isArray(schema.properties)) {
180
+ const props = {}
181
+ for (const [propName, propSchema] of Object.entries(schema.properties)) {
182
+ props[propName] = sanitizeChild(propSchema)
183
+ }
184
+ if (Object.keys(props).length > 0) {
185
+ out.properties = props
186
+ if (!out.type) out.type = 'object'
187
+ }
188
+ }
189
+
190
+ if (schema.items && typeof schema.items === 'object') {
191
+ out.items = Array.isArray(schema.items) ? sanitizeChild(schema.items[0]) : sanitizeChild(schema.items)
192
+ if (!out.type) out.type = 'array'
193
+ } else if (out.type === 'array') {
194
+ out.items = untypedSchemaDefault()
195
+ }
196
+
197
+ if (Array.isArray(schema.required) && out.properties) {
198
+ const propKeys = new Set(Object.keys(out.properties))
199
+ const req = schema.required.filter((k) => typeof k === 'string' && propKeys.has(k))
200
+ if (req.length > 0) out.required = req
201
+ }
202
+
203
+ if (Array.isArray(schema.enum) && schema.enum.length > 0) {
204
+ const nonNull = schema.enum.filter((v) => v !== null)
205
+ if (nonNull.length < schema.enum.length) nullable = true
206
+ if (nonNull.length > 0 && nonNull.every((v) => typeof v === 'string')) {
207
+ out.type = 'string'
208
+ out.enum = nonNull
209
+ } else if (nonNull.length > 0) {
210
+ // Non-string enum: keep the underlying type, drop the (string-only) enum.
211
+ const t = scalarTypeOf(nonNull)
212
+ if (t && !out.type) out.type = t
213
+ notes.push(`Allowed values: ${nonNull.map((v) => JSON.stringify(v)).join(', ')}.`)
214
+ }
215
+ }
216
+
217
+ // Never emit a typeless schema: Gemini rejects `{}` properties.
218
+ if (!out.type && !out.anyOf) {
219
+ const fallback = untypedSchemaDefault()
220
+ out.anyOf = fallback.anyOf
221
+ }
222
+
223
+ for (const note of notes) appendDescription(out, note)
224
+ if (nullable) out.nullable = true
225
+ return out
226
+ }
227
+
228
+ // ---------------------------------------------------------------------------
229
+ // Function-name aliasing
230
+ // ---------------------------------------------------------------------------
231
+
232
+ // Gemini function names: start with a letter or underscore, then only
233
+ // [A-Za-z0-9_.:-], at most 64 characters.
234
+ const GEMINI_FN_NAME_MAX = 64
235
+ const GEMINI_FN_NAME_RE = /^[A-Za-z_][A-Za-z0-9_.:-]{0,63}$/
236
+ const ALIAS_HASH_LEN = 8
237
+
238
+ function hashSuffix(original, salt) {
239
+ return createHash('sha256').update(salt ? `${salt}\0${original}` : original).digest('hex').slice(0, ALIAS_HASH_LEN)
240
+ }
241
+
242
+ /**
243
+ * Build a per-request tool-name aliaser. Names that already satisfy Gemini's
244
+ * rules map to themselves; others get `<sanitised prefix>_<hash8>`, stable
245
+ * across requests and guaranteed distinct from every other name in the request.
246
+ *
247
+ * @param {Iterable<string>} names
248
+ * @returns {{ alias: (name: string) => string, reverse: Map<string, string> }}
249
+ */
250
+ function createToolNameAliaser(names) {
251
+ const forward = new Map()
252
+ const reverse = new Map()
253
+ const used = new Set()
254
+ const list = [...new Set([...names].filter((n) => typeof n === 'string' && n.length > 0))]
255
+ for (const n of list) {
256
+ if (GEMINI_FN_NAME_RE.test(n)) {
257
+ forward.set(n, n)
258
+ used.add(n)
259
+ }
260
+ }
261
+ for (const n of list) {
262
+ if (forward.has(n)) continue
263
+ let base = n.replace(/[^A-Za-z0-9_.:-]/g, '_')
264
+ if (!/^[A-Za-z_]/.test(base)) base = `_${base}`
265
+ base = base.slice(0, GEMINI_FN_NAME_MAX - ALIAS_HASH_LEN - 1)
266
+ let salt = ''
267
+ let candidate = `${base}_${hashSuffix(n, salt)}`
268
+ for (let i = 1; used.has(candidate); i++) {
269
+ salt = String(i)
270
+ candidate = `${base}_${hashSuffix(n, salt)}`
271
+ }
272
+ forward.set(n, candidate)
273
+ reverse.set(candidate, n)
274
+ used.add(candidate)
275
+ }
276
+ return {
277
+ alias: (name) => (typeof name === 'string' && forward.has(name) ? forward.get(name) : name),
278
+ reverse,
279
+ }
280
+ }
281
+
282
+ function collectToolNames(params) {
283
+ const names = []
284
+ for (const t of Array.isArray(params.tools) ? params.tools : []) {
285
+ if (typeof t?.name === 'string') names.push(t.name)
286
+ }
287
+ for (const msg of Array.isArray(params.messages) ? params.messages : []) {
288
+ if (!Array.isArray(msg?.content)) continue
289
+ for (const b of msg.content) {
290
+ if (b?.type === 'tool_use' && typeof b.name === 'string') names.push(b.name)
291
+ if (b?.type === 'tool_result' && typeof b.name === 'string') names.push(b.name)
292
+ }
293
+ }
294
+ if (typeof params.tool_choice?.name === 'string') names.push(params.tool_choice.name)
295
+ return names
296
+ }
297
+
298
+ /**
299
+ * Extract plain string text from an Anthropic `tool_result.content` field
300
+ * (which may be a string or an array of content blocks). Image blocks cannot be
301
+ * carried inside a `functionResponse` here, so they become a text placeholder
302
+ * that tells the model an image was omitted rather than vanishing silently.
303
+ */
304
+ function toolResultContentToString(content) {
305
+ if (typeof content === 'string') return content
306
+ if (Array.isArray(content)) {
307
+ return content
308
+ .map((b) => {
309
+ if (typeof b === 'string') return b
310
+ if (typeof b?.text === 'string') return b.text
311
+ if (b?.type === 'image') {
312
+ const mime = typeof b.source?.media_type === 'string' && b.source.media_type.length > 0
313
+ ? b.source.media_type
314
+ : 'unknown type'
315
+ return `[image omitted: ${mime}]`
316
+ }
317
+ return ''
318
+ })
319
+ .join('')
320
+ }
321
+ return ''
322
+ }
323
+
324
+ /**
325
+ * Build a `tool_use_id → tool_name` lookup across the Anthropic message history
326
+ * so Gemini `functionResponse` parts carry the matching function name.
327
+ */
328
+ function buildToolNameIndex(messages) {
329
+ const index = new Map()
330
+ for (const msg of messages || []) {
331
+ if (!Array.isArray(msg?.content)) continue
332
+ for (const block of msg.content) {
333
+ if (block?.type === 'tool_use' && typeof block.id === 'string' && typeof block.name === 'string') {
334
+ index.set(block.id, block.name)
335
+ }
336
+ }
337
+ }
338
+ return index
339
+ }
340
+
341
+ /**
342
+ * Convert a single Anthropic message into a Gemini `Content` object
343
+ * (`{ role: 'user' | 'model', parts: [...] }`).
344
+ */
345
+ function anthropicMessageToGemini(msg, toolNames, aliasName) {
346
+ const role = msg.role === 'assistant' ? 'model' : 'user'
347
+ const { content } = msg
348
+
349
+ // An assistant turn with nothing in it is not replayed (Gemini rejects an empty
350
+ // text part, and the turn carries no signal for the model); null drops it.
351
+ if (typeof content === 'string') {
352
+ if (role === 'model' && content.length === 0) return null
353
+ return { role, parts: [{ text: content }] }
354
+ }
355
+ if (!Array.isArray(content)) {
356
+ return role === 'model' ? null : { role, parts: [{ text: '' }] }
357
+ }
358
+
359
+ const parts = []
360
+ for (const block of content) {
361
+ if (!block || typeof block !== 'object') continue
362
+
363
+ if (block.type === 'thinking') {
364
+ const part = { thought: true, text: typeof block.thinking === 'string' ? block.thinking : '' }
365
+ if (typeof block.signature === 'string' && block.signature.length > 0) {
366
+ part.thoughtSignature = block.signature
367
+ }
368
+ parts.push(part)
369
+ } else if (block.type === 'text') {
370
+ const part = { text: typeof block.text === 'string' ? block.text : '' }
371
+ if (typeof block.thoughtSignature === 'string' && block.thoughtSignature.length > 0) {
372
+ part.thoughtSignature = block.thoughtSignature
373
+ }
374
+ parts.push(part)
375
+ } else if (block.type === 'image' && block.source?.type === 'base64') {
376
+ parts.push({
377
+ inlineData: {
378
+ mimeType: block.source.media_type || 'image/png',
379
+ data: block.source.data || '',
380
+ },
381
+ })
382
+ } else if (block.type === 'tool_use') {
383
+ const fnCall = {
384
+ name: aliasName(block.name || 'unknown'),
385
+ args: block.input && typeof block.input === 'object' && !Array.isArray(block.input) ? block.input : {},
386
+ }
387
+ if (typeof block.id === 'string' && block.id.length > 0) {
388
+ fnCall.id = block.id
389
+ }
390
+ const part = { functionCall: fnCall }
391
+ if (typeof block.thoughtSignature === 'string' && block.thoughtSignature.length > 0) {
392
+ part.thoughtSignature = block.thoughtSignature
393
+ }
394
+ parts.push(part)
395
+ } else if (block.type === 'tool_result') {
396
+ const name = aliasName((typeof block.tool_use_id === 'string' && toolNames.get(block.tool_use_id)) || block.name || 'unknown')
397
+ const text = toolResultContentToString(block.content)
398
+ const fnResp = {
399
+ name,
400
+ response: block.is_error ? { error: text } : { result: text },
401
+ }
402
+ if (typeof block.tool_use_id === 'string' && block.tool_use_id.length > 0) {
403
+ fnResp.id = block.tool_use_id
404
+ }
405
+ parts.push({ functionResponse: fnResp })
406
+ }
407
+ }
408
+
409
+ // Only a turn with NO content at all is dropped. An empty text block that carries
410
+ // a thoughtSignature (#9417) has content: the signature must replay.
411
+ if (role === 'model' && !parts.some(partHasContent)) return null
412
+ if (parts.length === 0) {
413
+ parts.push({ text: '' })
414
+ }
415
+ return { role, parts }
416
+ }
417
+
418
+ function partHasContent(part) {
419
+ return Boolean(
420
+ part.thoughtSignature
421
+ || part.functionCall
422
+ || part.functionResponse
423
+ || part.inlineData
424
+ || (typeof part.text === 'string' && part.text.length > 0),
425
+ )
426
+ }
427
+
428
+ /**
429
+ * Merge adjacent Gemini contents that share the same role. Gemini requires
430
+ * strictly alternating `user` / `model` turns in `contents`.
431
+ */
432
+ function mergeAdjacentRoles(contents) {
433
+ const merged = []
434
+ for (const item of contents) {
435
+ const prev = merged[merged.length - 1]
436
+ if (prev && prev.role === item.role) {
437
+ prev.parts.push(...item.parts)
438
+ } else {
439
+ merged.push({ role: item.role, parts: [...item.parts] })
440
+ }
441
+ }
442
+ return merged
443
+ }
444
+
445
+ /**
446
+ * Translate Anthropic `tool_choice` to Gemini `toolConfig.functionCallingConfig`.
447
+ */
448
+ function mapToolChoice(tc, aliasName = (n) => n) {
449
+ if (!tc || typeof tc !== 'object') return undefined
450
+ if (tc.type === 'auto') return { functionCallingConfig: { mode: 'AUTO' } }
451
+ if (tc.type === 'any') return { functionCallingConfig: { mode: 'ANY' } }
452
+ if (tc.type === 'none') return { functionCallingConfig: { mode: 'NONE' } }
453
+ if (tc.type === 'tool' && typeof tc.name === 'string') {
454
+ return { functionCallingConfig: { mode: 'ANY', allowedFunctionNames: [aliasName(tc.name)] } }
455
+ }
456
+ return undefined
457
+ }
458
+
459
+ // Gemini 2.5 takes an integer `thinkingBudget` and rejects `thinkingLevel`. This
460
+ // table is the level -> budget LOOKUP (unquoted keys, read with a fallback), not a
461
+ // roster: which levels a model OFFERS is `geminiThinkingRoster` below.
462
+ const GEMINI_25_THINKING_BUDGETS = Object.freeze({
463
+ none: 0,
464
+ minimal: 1024,
465
+ low: 2048,
466
+ medium: 8192,
467
+ high: 24576,
468
+ max: 32768,
469
+ })
470
+
471
+ // The levels each model family offers, as the keys of a support map. Unquoted
472
+ // keys on purpose: `scripts/lint-thinking-level-roster.sh` allows exactly one
473
+ // literal roster (the protocol's legacy fallback), and these are per-family
474
+ // facts that move with Google's releases.
475
+ const GEMINI_25_OFFERED = Object.freeze({ low: true, medium: true, high: true })
476
+ const GEMINI_3_PRO_OFFERED = Object.freeze({ low: true, high: true })
477
+ // Gemini 3.1 Pro (and later 3.x Pro minors) adds `medium`.
478
+ const GEMINI_3_1_PRO_OFFERED = Object.freeze({ low: true, medium: true, high: true })
479
+ const GEMINI_3_FLASH_OFFERED = Object.freeze({ minimal: true, low: true, medium: true, high: true })
480
+
481
+ /** Model id without a leading `models/`, lower-cased and trimmed. */
482
+ function normalizeGeminiModelFamilyId(model) {
483
+ return typeof model === 'string' ? model.trim().replace(/^models\//, '').toLowerCase() : ''
484
+ }
485
+
486
+ /** `2` for `gemini-2.5-pro`, `3` for `gemini-3-flash-preview`, null for anything else. */
487
+ function geminiMajorVersion(modelId) {
488
+ const m = /^gemini-(\d+)(?:[.-]|$)/.exec(modelId)
489
+ return m ? Number(m[1]) : null
490
+ }
491
+
492
+ const isGemini25 = (modelId) => /^gemini-2\.5(?:-|$)/.test(modelId)
493
+ const isGeminiFlashFamily = (modelId) => /-flash(?:-|$)/.test(modelId)
494
+
495
+ /**
496
+ * The thinking levels a Gemini model offers, in the shape the model registry
497
+ * carries them (`reasoningLevels` / `defaultReasoningLevel`), or `null` for a
498
+ * model that takes no thinking control (Gemini 1.5 / 2.0, and any id this table
499
+ * has no family for — it never guesses).
500
+ *
501
+ * `default` leads: no thinking override of our own, the model decides. Only the
502
+ * remaining levels are per-family, and each one is a value `mapThinkingConfig`
503
+ * turns into something the model accepts.
504
+ *
505
+ * @param {string} model
506
+ * @returns {{ reasoningLevels: string[], defaultReasoningLevel: string } | null}
507
+ */
508
+ export function geminiThinkingRoster(model) {
509
+ const modelId = normalizeGeminiModelFamilyId(model)
510
+ let offered = null
511
+ if (isGemini25(modelId)) {
512
+ offered = GEMINI_25_OFFERED
513
+ } else if ((geminiMajorVersion(modelId) ?? 0) >= 3) {
514
+ offered = isGeminiFlashFamily(modelId)
515
+ ? GEMINI_3_FLASH_OFFERED
516
+ : (/^gemini-3\.[1-9]/.test(modelId) ? GEMINI_3_1_PRO_OFFERED : GEMINI_3_PRO_OFFERED)
517
+ }
518
+ if (!offered) return null
519
+ return {
520
+ reasoningLevels: [LEGACY_DEFAULT_THINKING_LEVEL, ...Object.keys(offered)],
521
+ defaultReasoningLevel: LEGACY_DEFAULT_THINKING_LEVEL,
522
+ }
523
+ }
524
+
525
+ /**
526
+ * Map a symbolic thinking effort token to an integer token budget for Gemini
527
+ * 2.5 models (which accept `thinkingBudget` and reject `thinkingLevel`).
528
+ */
529
+ function thinkingLevelToGemini25Budget(level) {
530
+ return GEMINI_25_THINKING_BUDGETS[level.toLowerCase()] ?? GEMINI_25_THINKING_BUDGETS.medium
531
+ }
532
+
533
+ /**
534
+ * Translate Anthropic/Chroxy `thinking` config onto Gemini `thinkingConfig`,
535
+ * accounting for model-generation API differences:
536
+ * - Gemini 1.5 / 2.0 (non-thinking) → omit `thinkingConfig` (prevents HTTP 400)
537
+ * - Gemini 2.5 → translate effort levels to integer `thinkingBudget`
538
+ * - Gemini 3+ / 4+ / preview → send `thinkingLevel` directly
539
+ *
540
+ * `{ type: 'disabled' }` is model-aware too: a zero `thinkingBudget` is accepted
541
+ * by Gemini 2.5 Flash only. 2.5 Pro cannot switch thinking off, and Gemini 3+
542
+ * takes `thinkingLevel`, not a budget, so for those the config is omitted (the
543
+ * model's own default) rather than sending a value the API rejects.
544
+ *
545
+ * Accepts:
546
+ * - `{ thinkingLevel: string }` (model-defined effort token)
547
+ * - `{ type: 'enabled', budget_tokens: number }`
548
+ * - `{ type: 'disabled' }`
549
+ */
550
+ function mapThinkingConfig(thinking, model) {
551
+ if (!thinking || typeof thinking !== 'object') return undefined
552
+
553
+ const modelId = normalizeGeminiModelFamilyId(model)
554
+ // Legacy Gemini 1.5 and 2.0 (non-thinking) models reject thinkingConfig.
555
+ if (/^gemini-(?:1\.5|2\.0)(?:-|$)/.test(modelId) && !/thinking/.test(modelId)) {
556
+ return undefined
557
+ }
558
+
559
+ if (thinking.type === 'disabled') {
560
+ if (isGemini25(modelId)) {
561
+ return /-pro(?:-|$)/.test(modelId) ? undefined : { thinkingBudget: 0 }
562
+ }
563
+ if ((geminiMajorVersion(modelId) ?? 0) >= 3) {
564
+ return isGeminiFlashFamily(modelId) ? { thinkingLevel: 'MINIMAL' } : undefined
565
+ }
566
+ return undefined
567
+ }
568
+
569
+ const cfg = { includeThoughts: true }
570
+ if (typeof thinking.thinkingLevel === 'string' && thinking.thinkingLevel.length > 0) {
571
+ // Gemini 2.5 uses integer `thinkingBudget` rather than `thinkingLevel`.
572
+ if (isGemini25(modelId)) {
573
+ cfg.thinkingBudget = thinkingLevelToGemini25Budget(thinking.thinkingLevel)
574
+ return cfg
575
+ }
576
+ cfg.thinkingLevel = thinking.thinkingLevel.toUpperCase()
577
+ return cfg
578
+ }
579
+ if (typeof thinking.budget_tokens === 'number' && Number.isFinite(thinking.budget_tokens) && thinking.budget_tokens >= 0) {
580
+ cfg.thinkingBudget = Math.floor(thinking.budget_tokens)
581
+ return cfg
582
+ }
583
+ if (thinking.type === 'enabled' || thinking.type === 'adaptive') {
584
+ return cfg
585
+ }
586
+ return undefined
587
+ }
588
+
589
+ /**
590
+ * Translate Anthropic `messages.stream` params into a Gemini `generateContent`
591
+ * request body.
592
+ *
593
+ * @param {object} [params]
594
+ * @returns {object}
595
+ */
596
+ export function anthropicRequestToGemini(params = {}) {
597
+ const toolNames = buildToolNameIndex(params.messages)
598
+ const aliaser = createToolNameAliaser(collectToolNames(params))
599
+ const aliasName = aliaser.alias
600
+ const rawContents = (params.messages || [])
601
+ .map((m) => anthropicMessageToGemini(m, toolNames, aliasName))
602
+ .filter((c) => c !== null)
603
+ const out = {
604
+ contents: mergeAdjacentRoles(rawContents),
605
+ }
606
+
607
+ // System instruction: Anthropic passes a string or array of text blocks.
608
+ if (typeof params.system === 'string' && params.system.length > 0) {
609
+ out.systemInstruction = { parts: [{ text: params.system }] }
610
+ } else if (Array.isArray(params.system)) {
611
+ const sysText = params.system
612
+ .filter((b) => b?.type === 'text' && typeof b.text === 'string' && b.text.length > 0)
613
+ .map((b) => b.text)
614
+ .join('\n\n')
615
+ if (sysText.length > 0) {
616
+ out.systemInstruction = { parts: [{ text: sysText }] }
617
+ }
618
+ }
619
+
620
+ if (Array.isArray(params.tools) && params.tools.length > 0) {
621
+ out.tools = [
622
+ {
623
+ functionDeclarations: params.tools.map((t) => {
624
+ const decl = {
625
+ name: aliasName(t.name),
626
+ description: t.description || '',
627
+ }
628
+ if (t.input_schema) {
629
+ const sanitized = sanitizeSchemaForGemini(t.input_schema)
630
+ // Gemini `v1beta` rejects `OBJECT` parameter schemas with zero
631
+ // properties; omit `parameters` altogether for parameterless tools.
632
+ const isEmptyObject = sanitized.type === 'object'
633
+ && (!sanitized.properties || Object.keys(sanitized.properties).length === 0)
634
+ if (!isEmptyObject) {
635
+ decl.parameters = sanitized
636
+ }
637
+ }
638
+ return decl
639
+ }),
640
+ },
641
+ ]
642
+ }
643
+
644
+ const toolConfig = mapToolChoice(params.tool_choice, aliasName)
645
+ if (toolConfig) out.toolConfig = toolConfig
646
+
647
+ const generationConfig = {}
648
+ if (typeof params.max_tokens === 'number' && Number.isFinite(params.max_tokens) && params.max_tokens > 0) {
649
+ generationConfig.maxOutputTokens = params.max_tokens
650
+ }
651
+ if (typeof params.temperature === 'number' && Number.isFinite(params.temperature)) {
652
+ generationConfig.temperature = params.temperature
653
+ }
654
+ const thinkingConfig = mapThinkingConfig(params.thinking, params.model)
655
+ if (thinkingConfig) {
656
+ generationConfig.thinkingConfig = thinkingConfig
657
+ }
658
+ if (Object.keys(generationConfig).length > 0) {
659
+ out.generationConfig = generationConfig
660
+ }
661
+
662
+ // Non-enumerable so JSON.stringify(body) never sends it to Gemini.
663
+ Object.defineProperty(out, 'toolNameAliases', { value: aliaser.reverse, enumerable: false })
664
+
665
+ return out
666
+ }
667
+
668
+ // ---------------------------------------------------------------------------
669
+ // Response: Gemini SSE JSON chunks → Anthropic SDK event sequence
670
+ // ---------------------------------------------------------------------------
671
+
672
+ /** finishReasons where Gemini declined to answer; the turn ends as refused. */
673
+ const GEMINI_REFUSAL_REASONS = new Set(['SAFETY', 'RECITATION', 'BLOCKLIST', 'PROHIBITED_CONTENT', 'SPII'])
674
+
675
+ export const GEMINI_STREAM_TRUNCATED = 'GEMINI_STREAM_TRUNCATED'
676
+ export const GEMINI_UNSUCCESSFUL_FINISH = 'GEMINI_UNSUCCESSFUL_FINISH'
677
+
678
+ /**
679
+ * Map a Gemini `finishReason` onto an Anthropic `stop_reason`.
680
+ *
681
+ * `STOP` and `MAX_TOKENS` are the only successful endings. The declined-to-answer
682
+ * reasons map to `refusal` (which `turn-outcome.js` reads as `refused`). Anything
683
+ * else (`MALFORMED_FUNCTION_CALL`, `OTHER`, a reason this code has never seen)
684
+ * returns `null`: it is not a success and is not guessed at.
685
+ */
686
+ export function mapGeminiFinishReason(reason) {
687
+ if (reason === 'STOP') return 'end_turn'
688
+ if (reason === 'MAX_TOKENS') return 'max_tokens'
689
+ if (GEMINI_REFUSAL_REASONS.has(reason)) return 'refusal'
690
+ return null
691
+ }
692
+
693
+ // finishReason text is upstream-controlled: only a plain enum-shaped value is quoted.
694
+ const safeReasonLabel = (reason) => (typeof reason === 'string' && /^[A-Z][A-Z0-9_]{0,63}$/.test(reason) ? reason : 'an unrecognized reason')
695
+
696
+ function translatorError(code, message) {
697
+ const err = new Error(message)
698
+ err.code = code
699
+ return err
700
+ }
701
+
702
+ function finiteNonNeg(value) {
703
+ const n = Number(value)
704
+ return Number.isFinite(n) && n > 0 ? n : 0
705
+ }
706
+
707
+ /**
708
+ * Map Gemini `usageMetadata` onto Anthropic's usage shape.
709
+ *
710
+ * Gemini's `promptTokenCount` INCLUDES `cachedContentTokenCount`. Anthropic's
711
+ * `input_tokens` excludes `cache_read_input_tokens` (and `computePromptCostUsd`
712
+ * charges them at separate rates), so subtract cached tokens from `input_tokens`.
713
+ * Thinking tokens (`thoughtsTokenCount`) are billed as output tokens by Google.
714
+ */
715
+ export function mapGeminiUsage(usageMetadata) {
716
+ if (!usageMetadata || typeof usageMetadata !== 'object') {
717
+ return {
718
+ input_tokens: 0,
719
+ output_tokens: 0,
720
+ cache_read_input_tokens: 0,
721
+ cache_creation_input_tokens: 0,
722
+ }
723
+ }
724
+ const promptTokens = finiteNonNeg(usageMetadata.promptTokenCount)
725
+ const cachedTokens = finiteNonNeg(usageMetadata.cachedContentTokenCount)
726
+ const candidateTokens = finiteNonNeg(usageMetadata.candidatesTokenCount)
727
+ const thoughtTokens = finiteNonNeg(usageMetadata.thoughtsTokenCount)
728
+ // Tokens a tool (e.g. a built-in search) put into the prompt are billed as input
729
+ // and are NOT part of `promptTokenCount`.
730
+ const toolUsePromptTokens = finiteNonNeg(usageMetadata.toolUsePromptTokenCount)
731
+ return {
732
+ input_tokens: Math.max(0, promptTokens - cachedTokens) + toolUsePromptTokens,
733
+ output_tokens: candidateTokens + thoughtTokens,
734
+ cache_read_input_tokens: cachedTokens,
735
+ cache_creation_input_tokens: 0,
736
+ }
737
+ }
738
+
739
+ /**
740
+ * Stateful (I/O-free) fold of a Gemini `streamGenerateContent` SSE chunk stream
741
+ * into the Anthropic SDK event sequence consumed by `ClaudeByokSession`, plus
742
+ * the assembled `finalMessage`.
743
+ *
744
+ * @param {{ model?: string, makeToolCallId?: () => string }} [opts]
745
+ */
746
+ export function createGeminiStreamTranslator(opts = {}) {
747
+ let started = false
748
+ let nextBlockIndex = 0
749
+ let activeTextBlock = null // { index, text, thoughtSignature }
750
+ let activeThinkingBlock = null // { index, thinking, signature }
751
+ const blocks = [] // assembled content blocks in emission order
752
+ let hasToolCalls = false
753
+ // Tool-call events are held until the terminal reason is known: a call is only
754
+ // announced to the client (which opens a tool row) if the turn will run it. A call
755
+ // dropped on MAX_TOKENS or a refusal therefore never opens a row that nothing closes.
756
+ const heldToolEvents = []
757
+ let finishReason = null
758
+ let usageMetadata = null
759
+ let model = opts.model ?? null
760
+ let responseId = null
761
+ const toolNameMap = opts.toolNameMap instanceof Map ? opts.toolNameMap : null
762
+ const restoreToolName = (n) => toolNameMap?.get(n) ?? n
763
+ const makeToolCallId = typeof opts.makeToolCallId === 'function'
764
+ ? opts.makeToolCallId
765
+ : () => `gemini-call-${randomUUID()}`
766
+
767
+ function ensureStarted(chunk) {
768
+ if (started) return []
769
+ started = true
770
+ if (typeof chunk?.modelVersion === 'string' && chunk.modelVersion.length > 0) {
771
+ model = chunk.modelVersion
772
+ }
773
+ if (typeof chunk?.responseId === 'string' && chunk.responseId.length > 0) {
774
+ responseId = chunk.responseId
775
+ } else {
776
+ responseId = `gemini-msg-${randomUUID()}`
777
+ }
778
+ return [
779
+ {
780
+ type: 'message_start',
781
+ message: {
782
+ id: responseId,
783
+ model,
784
+ role: 'assistant',
785
+ content: [],
786
+ usage: mapGeminiUsage(null),
787
+ },
788
+ },
789
+ ]
790
+ }
791
+
792
+ function closeThinkingBlock() {
793
+ if (!activeThinkingBlock) return []
794
+ const ev = [{ type: 'content_block_stop', index: activeThinkingBlock.index }]
795
+ activeThinkingBlock = null
796
+ return ev
797
+ }
798
+
799
+ function closeTextBlock() {
800
+ if (!activeTextBlock) return []
801
+ const ev = [{ type: 'content_block_stop', index: activeTextBlock.index }]
802
+ activeTextBlock = null
803
+ return ev
804
+ }
805
+
806
+ function push(chunk) {
807
+ const events = []
808
+ if (!chunk || typeof chunk !== 'object') return events
809
+
810
+ events.push(...ensureStarted(chunk))
811
+
812
+ if (chunk.usageMetadata && typeof chunk.usageMetadata === 'object') {
813
+ usageMetadata = usageMetadata ? { ...usageMetadata, ...chunk.usageMetadata } : { ...chunk.usageMetadata }
814
+ }
815
+
816
+ const candidate = Array.isArray(chunk.candidates) ? chunk.candidates[0] : undefined
817
+ if (!candidate) return events
818
+
819
+ const parts = Array.isArray(candidate.content?.parts) ? candidate.content.parts : []
820
+ for (const part of parts) {
821
+ if (!part || typeof part !== 'object') continue
822
+
823
+ const partSig = typeof part.thoughtSignature === 'string' && part.thoughtSignature.length > 0
824
+ ? part.thoughtSignature
825
+ : null
826
+
827
+ // 1. Thinking part (`thought: true`). A signed part keeps its own block
828
+ // boundary: Gemini needs the signature back on the part that carried it,
829
+ // so it is never merged into a neighbour.
830
+ if (part.thought === true) {
831
+ events.push(...closeTextBlock())
832
+ const deltaText = typeof part.text === 'string' ? part.text : ''
833
+ if (partSig && activeThinkingBlock) events.push(...closeThinkingBlock())
834
+ if (!activeThinkingBlock) {
835
+ activeThinkingBlock = { index: nextBlockIndex++, thinking: '', signature: null }
836
+ blocks.push({ type: 'thinking', ref: activeThinkingBlock })
837
+ events.push({
838
+ type: 'content_block_start',
839
+ index: activeThinkingBlock.index,
840
+ content_block: { type: 'thinking', thinking: '' },
841
+ })
842
+ }
843
+ if (deltaText.length > 0) {
844
+ activeThinkingBlock.thinking += deltaText
845
+ events.push({
846
+ type: 'content_block_delta',
847
+ index: activeThinkingBlock.index,
848
+ delta: { type: 'thinking_delta', thinking: deltaText },
849
+ })
850
+ }
851
+ if (partSig) {
852
+ activeThinkingBlock.signature = partSig
853
+ events.push(...closeThinkingBlock())
854
+ }
855
+ continue
856
+ }
857
+
858
+ // 2. Function call part. Its signature belongs to it alone; a later
859
+ // signature-only part becomes its own block and never overwrites this one.
860
+ if (part.functionCall && typeof part.functionCall === 'object') {
861
+ events.push(...closeThinkingBlock())
862
+ events.push(...closeTextBlock())
863
+ hasToolCalls = true
864
+ const fc = part.functionCall
865
+ const id = typeof fc.id === 'string' && fc.id.length > 0
866
+ ? fc.id
867
+ : makeToolCallId()
868
+ const name = typeof fc.name === 'string' && fc.name.length > 0 ? restoreToolName(fc.name) : 'unknown'
869
+ const input = fc.args && typeof fc.args === 'object' && !Array.isArray(fc.args) ? fc.args : {}
870
+ const blockIndex = nextBlockIndex++
871
+ const toolEntry = {
872
+ index: blockIndex,
873
+ id,
874
+ name,
875
+ input,
876
+ thoughtSignature: partSig,
877
+ }
878
+ blocks.push({ type: 'tool_use', ref: toolEntry })
879
+ heldToolEvents.push({
880
+ type: 'content_block_start',
881
+ index: blockIndex,
882
+ content_block: { type: 'tool_use', id, name, input: {} },
883
+ })
884
+ const partialJson = JSON.stringify(input)
885
+ if (partialJson.length > 0) {
886
+ heldToolEvents.push({
887
+ type: 'content_block_delta',
888
+ index: blockIndex,
889
+ delta: { type: 'input_json_delta', partial_json: partialJson },
890
+ })
891
+ }
892
+ heldToolEvents.push({ type: 'content_block_stop', index: blockIndex })
893
+ continue
894
+ }
895
+
896
+ // 3. Regular assistant text part, or a signature-only part (kept as its
897
+ // own empty-text block so the signature round-trips on its own part).
898
+ if (typeof part.text === 'string' || partSig) {
899
+ events.push(...closeThinkingBlock())
900
+ const deltaText = typeof part.text === 'string' ? part.text : ''
901
+ if (partSig && activeTextBlock) events.push(...closeTextBlock())
902
+ if (!activeTextBlock && (deltaText.length > 0 || partSig)) {
903
+ activeTextBlock = { index: nextBlockIndex++, text: '', thoughtSignature: null }
904
+ blocks.push({ type: 'text', ref: activeTextBlock })
905
+ events.push({
906
+ type: 'content_block_start',
907
+ index: activeTextBlock.index,
908
+ content_block: { type: 'text', text: '' },
909
+ })
910
+ }
911
+ if (deltaText.length > 0) {
912
+ activeTextBlock.text += deltaText
913
+ events.push({
914
+ type: 'content_block_delta',
915
+ index: activeTextBlock.index,
916
+ delta: { type: 'text_delta', text: deltaText },
917
+ })
918
+ }
919
+ if (partSig) {
920
+ activeTextBlock.thoughtSignature = partSig
921
+ events.push(...closeTextBlock())
922
+ }
923
+ }
924
+ }
925
+
926
+ if (typeof candidate.finishReason === 'string' && candidate.finishReason.length > 0) {
927
+ finishReason = candidate.finishReason
928
+ }
929
+
930
+ return events
931
+ }
932
+
933
+ // A visible text block the model did not write (a refusal or cut-off notice).
934
+ function noticeBlock(text) {
935
+ const index = nextBlockIndex++
936
+ blocks.push({ type: 'text', ref: { text } })
937
+ return [
938
+ { type: 'content_block_start', index, content_block: { type: 'text', text: '' } },
939
+ { type: 'content_block_delta', index, delta: { type: 'text_delta', text } },
940
+ { type: 'content_block_stop', index },
941
+ ]
942
+ }
943
+
944
+ function finish() {
945
+ if (finishReason === null) {
946
+ // The stream ended with no terminal finishReason: it was cut short, so what
947
+ // arrived is a partial generation, not a finished one.
948
+ throw translatorError(GEMINI_STREAM_TRUNCATED, 'Gemini response ended before it finished (no finishReason); the reply is incomplete')
949
+ }
950
+ if (mapGeminiFinishReason(finishReason) === null) {
951
+ throw translatorError(GEMINI_UNSUCCESSFUL_FINISH, `Gemini ended the response unsuccessfully (finishReason: ${safeReasonLabel(finishReason)})`)
952
+ }
953
+ const events = []
954
+ if (!started) {
955
+ events.push(...ensureStarted({}))
956
+ }
957
+ events.push(...closeThinkingBlock())
958
+ events.push(...closeTextBlock())
959
+
960
+ const finalUsage = mapGeminiUsage(usageMetadata)
961
+ const mapped = mapGeminiFinishReason(finishReason)
962
+ // Validate the terminal reason BEFORE choosing `tool_use`: a stream cut short, or
963
+ // one that ended unsuccessfully, must never lead to tool execution.
964
+ const toolsRunnable = mapped === 'end_turn'
965
+ // Gemini sends finishReason='STOP' even when the turn ends with functionCalls.
966
+ // The BYOK loop decides whether to execute tools from `stop_reason === 'tool_use'`.
967
+ const effectiveStopReason = toolsRunnable && hasToolCalls ? 'tool_use' : mapped
968
+
969
+ if (effectiveStopReason === 'tool_use') {
970
+ events.push(...heldToolEvents)
971
+ } else {
972
+ // Held calls are dropped, never announced (see heldToolEvents).
973
+ const hasText = blocks.some((b) => b.type === 'text' && b.ref.text.length > 0)
974
+ if (mapped === 'refusal') {
975
+ // Name the reason so the turn does not end as an empty completion.
976
+ events.push(...noticeBlock(`Gemini declined to answer (finishReason: ${safeReasonLabel(finishReason)}).`))
977
+ } else if (mapped === 'max_tokens' && !hasText) {
978
+ events.push(...noticeBlock('Response cut off at the token limit.'))
979
+ }
980
+ }
981
+
982
+ events.push({
983
+ type: 'message_delta',
984
+ delta: { stop_reason: effectiveStopReason },
985
+ usage: finalUsage,
986
+ })
987
+ events.push({ type: 'message_stop' })
988
+
989
+ // Function calls are kept only when the turn will run them. On max_tokens or a
990
+ // refusal they are an incomplete generation, and a call with no result would be a
991
+ // dangling functionCall in the next request.
992
+ const content = blocks.filter((b) => b.type !== 'tool_use' || effectiveStopReason === 'tool_use').map((b) => {
993
+ if (b.type === 'thinking') {
994
+ return {
995
+ type: 'thinking',
996
+ thinking: b.ref.thinking,
997
+ ...(b.ref.signature ? { signature: b.ref.signature } : {}),
998
+ }
999
+ }
1000
+ if (b.type === 'tool_use') {
1001
+ return {
1002
+ type: 'tool_use',
1003
+ id: b.ref.id,
1004
+ name: b.ref.name,
1005
+ input: b.ref.input,
1006
+ ...(b.ref.thoughtSignature ? { thoughtSignature: b.ref.thoughtSignature } : {}),
1007
+ }
1008
+ }
1009
+ return {
1010
+ type: 'text',
1011
+ text: b.ref.text,
1012
+ ...(b.ref.thoughtSignature ? { thoughtSignature: b.ref.thoughtSignature } : {}),
1013
+ }
1014
+ })
1015
+
1016
+ const finalMessage = {
1017
+ id: responseId,
1018
+ type: 'message',
1019
+ role: 'assistant',
1020
+ model,
1021
+ content,
1022
+ stop_reason: effectiveStopReason,
1023
+ stop_sequence: null,
1024
+ usage: finalUsage,
1025
+ }
1026
+ return { events, finalMessage }
1027
+ }
1028
+
1029
+ return { push, finish }
1030
+ }