@chroxy/server 0.10.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 (275) hide show
  1. package/CONFIG.md +695 -0
  2. package/README.md +105 -0
  3. package/hooks/permission-hook.sh +285 -0
  4. package/package.json +69 -0
  5. package/scripts/fix-node-pty-helper.js +44 -0
  6. package/sidecar/Dockerfile +40 -0
  7. package/sidecar/PROTOCOL.md +691 -0
  8. package/sidecar/agent.js +1290 -0
  9. package/sidecar/package-lock.json +43 -0
  10. package/sidecar/package.json +17 -0
  11. package/src/activity-registry.js +491 -0
  12. package/src/anthropic-compatible-config.js +534 -0
  13. package/src/anthropic-compatible-session.js +579 -0
  14. package/src/anthropic-openai-shim.js +109 -0
  15. package/src/anthropic-openai-translate.js +377 -0
  16. package/src/auth-probes.js +296 -0
  17. package/src/background-shell-tracker.js +320 -0
  18. package/src/background-shells.js +125 -0
  19. package/src/base-session.js +1518 -0
  20. package/src/billing-budget.js +191 -0
  21. package/src/billing-canary-monitor.js +203 -0
  22. package/src/billing-class.js +149 -0
  23. package/src/bind-host.js +82 -0
  24. package/src/built-in-tools/bash-exec.js +167 -0
  25. package/src/built-in-tools/file-ops.js +198 -0
  26. package/src/built-in-tools/tool-transforms.js +179 -0
  27. package/src/builtin-commands.js +107 -0
  28. package/src/byok-compose-state-shared.js +31 -0
  29. package/src/byok-compose-state.js +234 -0
  30. package/src/byok-credentials.js +127 -0
  31. package/src/byok-event-translator.js +136 -0
  32. package/src/byok-mcp-client.js +404 -0
  33. package/src/byok-mcp-config.js +159 -0
  34. package/src/byok-mcp-fleet.js +214 -0
  35. package/src/byok-mcp-trust.js +175 -0
  36. package/src/byok-session.js +2019 -0
  37. package/src/byok-subagent-profiles.js +101 -0
  38. package/src/byok-tool-executor.js +813 -0
  39. package/src/byok-tools.js +271 -0
  40. package/src/channels/PACKAGING.md +181 -0
  41. package/src/channels/README.md +99 -0
  42. package/src/channels/chroxy-channel-server.js +248 -0
  43. package/src/checkpoint-manager.js +515 -0
  44. package/src/child-stream-guard.js +38 -0
  45. package/src/claude-channel-session.js +185 -0
  46. package/src/claude-model-catalog.js +266 -0
  47. package/src/claude-stream-parser.js +106 -0
  48. package/src/claude-tui/form-driver.js +874 -0
  49. package/src/claude-tui/pty-driver.js +520 -0
  50. package/src/claude-tui/tested-cli-version.js +22 -0
  51. package/src/claude-tui-attachments.js +342 -0
  52. package/src/claude-tui-session.js +4029 -0
  53. package/src/cli/config-cmd.js +34 -0
  54. package/src/cli/credentials-cmd.js +59 -0
  55. package/src/cli/deploy-cmd.js +167 -0
  56. package/src/cli/doctor-cmd.js +52 -0
  57. package/src/cli/identity-cmd.js +82 -0
  58. package/src/cli/init-cmd.js +209 -0
  59. package/src/cli/pages-cmd.js +167 -0
  60. package/src/cli/pair-code-cmd.js +108 -0
  61. package/src/cli/pair-discord-cmd.js +100 -0
  62. package/src/cli/providers-cmd.js +168 -0
  63. package/src/cli/server-cmd.js +94 -0
  64. package/src/cli/service-cmd.js +237 -0
  65. package/src/cli/session-cmd.js +143 -0
  66. package/src/cli/shared.js +194 -0
  67. package/src/cli/shell-cmd.js +130 -0
  68. package/src/cli/status-cmd.js +204 -0
  69. package/src/cli/tunnel-cmd.js +101 -0
  70. package/src/cli/update-cmd.js +45 -0
  71. package/src/cli/worktree-gc-cmd.js +195 -0
  72. package/src/cli-session.js +1820 -0
  73. package/src/cli.js +60 -0
  74. package/src/codex-app-server-client.js +156 -0
  75. package/src/codex-app-server-session.js +572 -0
  76. package/src/codex-session.js +604 -0
  77. package/src/config.js +1757 -0
  78. package/src/connection-info.js +42 -0
  79. package/src/connection-locality.js +55 -0
  80. package/src/content-blocks.js +42 -0
  81. package/src/control-room/byok-pool.js +130 -0
  82. package/src/control-room/constants.js +26 -0
  83. package/src/control-room/containers.js +258 -0
  84. package/src/control-room/emulators.js +279 -0
  85. package/src/control-room/handler-factory.js +142 -0
  86. package/src/control-room/host-prune.js +387 -0
  87. package/src/control-room/integrations.js +929 -0
  88. package/src/control-room/repo-runtime-config.js +239 -0
  89. package/src/control-room/repo-set.js +162 -0
  90. package/src/control-room/runners.js +479 -0
  91. package/src/control-room/simulators.js +223 -0
  92. package/src/control-room/skills-inventory.js +303 -0
  93. package/src/control-room/survey.js +685 -0
  94. package/src/control-room/wsl.js +182 -0
  95. package/src/conversation-scanner.js +270 -0
  96. package/src/conversation-scope.js +52 -0
  97. package/src/conversation-search.js +216 -0
  98. package/src/cost-budget-manager.js +190 -0
  99. package/src/credential-cipher.js +179 -0
  100. package/src/credential-store.js +786 -0
  101. package/src/credential-test.js +145 -0
  102. package/src/credentials-file.js +58 -0
  103. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
  104. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
  105. package/src/dashboard-next/dist/index.html +13 -0
  106. package/src/deepseek-credentials.js +58 -0
  107. package/src/deepseek-session.js +192 -0
  108. package/src/detect-thinking-keyword.js +67 -0
  109. package/src/dev-preview.js +227 -0
  110. package/src/devcontainer-config.js +269 -0
  111. package/src/device-preferences.js +267 -0
  112. package/src/diagnostics.js +187 -0
  113. package/src/diff-parser.js +157 -0
  114. package/src/discord-credentials.js +188 -0
  115. package/src/discord-pair-delivery.js +113 -0
  116. package/src/docker-byok-pool-stats.js +221 -0
  117. package/src/docker-byok-pool.js +841 -0
  118. package/src/docker-byok-session.js +2172 -0
  119. package/src/docker-image-allowlist.js +99 -0
  120. package/src/docker-sdk-session.js +396 -0
  121. package/src/docker-session.js +382 -0
  122. package/src/doctor-billing.js +179 -0
  123. package/src/doctor.js +667 -0
  124. package/src/duration.js +77 -0
  125. package/src/environment-manager.js +753 -0
  126. package/src/environment-statuses.js +20 -0
  127. package/src/environments/backends/docker.js +931 -0
  128. package/src/environments/backends/k8s.js +3030 -0
  129. package/src/environments/backends/rancher.js +326 -0
  130. package/src/environments/backends/types.js +332 -0
  131. package/src/event-ingest.js +546 -0
  132. package/src/event-normalizer.js +1083 -0
  133. package/src/external-session-registry.js +0 -0
  134. package/src/file-store.js +52 -0
  135. package/src/gemini-session.js +498 -0
  136. package/src/get-public-ip.js +52 -0
  137. package/src/git.js +15 -0
  138. package/src/github-webhook.js +256 -0
  139. package/src/handler-utils.js +663 -0
  140. package/src/handlers/checkpoint-handlers.js +202 -0
  141. package/src/handlers/control-room-handlers.js +1945 -0
  142. package/src/handlers/conversation-handlers.js +201 -0
  143. package/src/handlers/credential-handlers.js +247 -0
  144. package/src/handlers/evaluator-handlers.js +94 -0
  145. package/src/handlers/feature-handlers.js +332 -0
  146. package/src/handlers/file-handlers.js +142 -0
  147. package/src/handlers/ide-handlers.js +238 -0
  148. package/src/handlers/input-handlers.js +1048 -0
  149. package/src/handlers/pairing-handlers.js +94 -0
  150. package/src/handlers/repo-handlers.js +295 -0
  151. package/src/handlers/session-handlers.js +660 -0
  152. package/src/handlers/settings-handlers.js +818 -0
  153. package/src/handlers/skills-handlers.js +682 -0
  154. package/src/handlers/summarize-handlers.js +172 -0
  155. package/src/handlers/token-handlers.js +57 -0
  156. package/src/http-oversize.js +51 -0
  157. package/src/http-routes.js +1158 -0
  158. package/src/ide/search.js +268 -0
  159. package/src/ide/symbols.js +423 -0
  160. package/src/ip-utils.js +85 -0
  161. package/src/json-state-file.js +169 -0
  162. package/src/jsonl-reader.js +187 -0
  163. package/src/jsonl-subprocess-session.js +441 -0
  164. package/src/keychain.js +458 -0
  165. package/src/lan-ip.js +38 -0
  166. package/src/logger.js +388 -0
  167. package/src/mailbox-route.js +252 -0
  168. package/src/mcp-tools.js +46 -0
  169. package/src/message-transform.js +102 -0
  170. package/src/metrics.js +67 -0
  171. package/src/model-discovery.js +288 -0
  172. package/src/models.js +1426 -0
  173. package/src/notification-prefs.js +544 -0
  174. package/src/notifications/discord-billing-sink.js +323 -0
  175. package/src/notifications/discord-webhook-client.js +187 -0
  176. package/src/notifications/discord-webhook-sink.js +768 -0
  177. package/src/notifications/expo-push-sink.js +414 -0
  178. package/src/notifications/ready-body.js +177 -0
  179. package/src/notifications/sink-registry.js +98 -0
  180. package/src/notifications/sink.js +82 -0
  181. package/src/ollama-session.js +221 -0
  182. package/src/ollama-tags.js +238 -0
  183. package/src/openai-compatible-session.js +118 -0
  184. package/src/pages-store.js +255 -0
  185. package/src/pairing.js +836 -0
  186. package/src/path-hash-trust-ledger.js +311 -0
  187. package/src/per-session-settings.js +366 -0
  188. package/src/permission-audit.js +120 -0
  189. package/src/permission-hook.js +257 -0
  190. package/src/permission-manager.js +829 -0
  191. package/src/permission-resolver.js +144 -0
  192. package/src/platform.js +139 -0
  193. package/src/prompt-evaluator.js +386 -0
  194. package/src/providers.js +436 -0
  195. package/src/push.js +565 -0
  196. package/src/rate-limiter.js +433 -0
  197. package/src/redaction.js +206 -0
  198. package/src/sdk-session.js +1773 -0
  199. package/src/semver.js +92 -0
  200. package/src/server-cli/push-notification-handler.js +240 -0
  201. package/src/server-cli/server-orchestrator.js +168 -0
  202. package/src/server-cli/startup-display.js +146 -0
  203. package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
  204. package/src/server-cli-child.js +207 -0
  205. package/src/server-cli.js +1223 -0
  206. package/src/server-identity.js +383 -0
  207. package/src/service.js +835 -0
  208. package/src/session-context.js +49 -0
  209. package/src/session-lock.js +60 -0
  210. package/src/session-manager.js +3257 -0
  211. package/src/session-message-history.js +511 -0
  212. package/src/session-preset-trust.js +78 -0
  213. package/src/session-preset.js +458 -0
  214. package/src/session-state-persistence.js +307 -0
  215. package/src/session-timeout-manager.js +166 -0
  216. package/src/session-token-store.js +83 -0
  217. package/src/shell-approval-info.js +45 -0
  218. package/src/shell-approval-store.js +163 -0
  219. package/src/shell-audit.js +63 -0
  220. package/src/skills-budget.js +181 -0
  221. package/src/skills-content-validator.js +106 -0
  222. package/src/skills-frontmatter.js +422 -0
  223. package/src/skills-loader.js +1893 -0
  224. package/src/skills-manager.js +256 -0
  225. package/src/skills-trust.js +532 -0
  226. package/src/skills-usage.js +335 -0
  227. package/src/snapshots-store.js +345 -0
  228. package/src/ssrf-guard.js +130 -0
  229. package/src/subagent-counter.js +149 -0
  230. package/src/summarize-session.js +268 -0
  231. package/src/supervisor.js +929 -0
  232. package/src/test-client.js +131 -0
  233. package/src/token-compare.js +28 -0
  234. package/src/token-manager.js +220 -0
  235. package/src/tool-result.js +87 -0
  236. package/src/transcript-tasks.js +334 -0
  237. package/src/tunnel/base.js +294 -0
  238. package/src/tunnel/cloudflare.js +281 -0
  239. package/src/tunnel/index.js +54 -0
  240. package/src/tunnel-check.js +84 -0
  241. package/src/turn-tracker.js +0 -0
  242. package/src/user-shell-registry.js +218 -0
  243. package/src/user-shell-session.js +411 -0
  244. package/src/utils/check-dependencies.js +70 -0
  245. package/src/utils/concurrency.js +24 -0
  246. package/src/utils/context-window-learn.js +148 -0
  247. package/src/utils/error-message.js +25 -0
  248. package/src/utils/format-bytes.js +35 -0
  249. package/src/utils/preflight.js +143 -0
  250. package/src/utils/resolve-binary.js +91 -0
  251. package/src/utils/respawn-rate-limiter.js +59 -0
  252. package/src/utils/sleep.js +58 -0
  253. package/src/utils/spawn-env.js +193 -0
  254. package/src/utils/validation-patterns.js +23 -0
  255. package/src/utils/win-spawn.js +98 -0
  256. package/src/version-check.js +16 -0
  257. package/src/web-task-manager.js +383 -0
  258. package/src/worktree-gc.js +418 -0
  259. package/src/worktree-reaper.js +168 -0
  260. package/src/ws-auth.js +645 -0
  261. package/src/ws-broadcaster.js +385 -0
  262. package/src/ws-client-manager.js +476 -0
  263. package/src/ws-client-sender.js +115 -0
  264. package/src/ws-file-ops/browser.js +594 -0
  265. package/src/ws-file-ops/common.js +163 -0
  266. package/src/ws-file-ops/git.js +298 -0
  267. package/src/ws-file-ops/index.js +52 -0
  268. package/src/ws-file-ops/reader.js +595 -0
  269. package/src/ws-forwarding.js +543 -0
  270. package/src/ws-handler-context.js +196 -0
  271. package/src/ws-history.js +1251 -0
  272. package/src/ws-message-handlers.js +165 -0
  273. package/src/ws-permissions.js +676 -0
  274. package/src/ws-schemas.js +119 -0
  275. package/src/ws-server.js +2866 -0
Binary file
@@ -0,0 +1,52 @@
1
+ /**
2
+ * FileStore — consistent JSON file I/O utilities.
3
+ *
4
+ * Consolidates the read/write/mkdir patterns used across 16+ server files
5
+ * into a single module with predictable error handling:
6
+ *
7
+ * - readJsonFile: returns defaultValue for ENOENT, throws on corrupt JSON
8
+ * - writeJsonFile: ensures parent dirs exist, writes pretty-printed JSON
9
+ * - ensureDir: recursive mkdir
10
+ */
11
+
12
+ import { readFileSync, writeFileSync, mkdirSync } from 'node:fs'
13
+ import { dirname } from 'node:path'
14
+
15
+ /**
16
+ * Read and parse a JSON file.
17
+ *
18
+ * @param {string} path - Absolute path to JSON file
19
+ * @param {*} [defaultValue=null] - Value to return if file does not exist
20
+ * @returns {*} Parsed JSON data, or defaultValue if file is missing
21
+ * @throws {SyntaxError} If file exists but contains invalid JSON
22
+ * @throws {Error} For I/O errors other than ENOENT
23
+ */
24
+ export function readJsonFile(path, defaultValue = null) {
25
+ try {
26
+ return JSON.parse(readFileSync(path, 'utf-8'))
27
+ } catch (err) {
28
+ if (err.code === 'ENOENT') return defaultValue
29
+ throw err
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Write data as pretty-printed JSON to a file.
35
+ * Creates parent directories if they don't exist.
36
+ *
37
+ * @param {string} path - Absolute path to write
38
+ * @param {*} data - Data to serialize as JSON
39
+ */
40
+ export function writeJsonFile(path, data) {
41
+ mkdirSync(dirname(path), { recursive: true })
42
+ writeFileSync(path, JSON.stringify(data, null, 2) + '\n')
43
+ }
44
+
45
+ /**
46
+ * Ensure a directory exists, creating parent directories as needed.
47
+ *
48
+ * @param {string} path - Directory path to create
49
+ */
50
+ export function ensureDir(path) {
51
+ mkdirSync(path, { recursive: true })
52
+ }
@@ -0,0 +1,498 @@
1
+ import { JsonlSubprocessSession } from './jsonl-subprocess-session.js'
2
+ import { buildBaseSessionOpts } from './base-session.js'
3
+ import { homedir } from 'os'
4
+ import { join } from 'path'
5
+ import { resolveBinary } from './utils/resolve-binary.js'
6
+ import { buildSpawnEnv } from './utils/spawn-env.js'
7
+ import { hasGeminiOAuthCreds } from './auth-probes.js'
8
+ import {
9
+ CONTEXT_WINDOW_HEADROOM,
10
+ getRatchetCap,
11
+ maybeRatchetContextWindow,
12
+ } from './utils/context-window-learn.js'
13
+ import { BILLING_CLASSES } from './billing-class.js'
14
+
15
+ /**
16
+ * Manages a Gemini CLI session using `gemini -p --output-format stream-json`.
17
+ *
18
+ * Implements the same EventEmitter interface as SdkSession/CliSession so
19
+ * SessionManager and WsServer work identically regardless of provider.
20
+ *
21
+ * Gemini CLI supports `--output-format stream-json` which outputs NDJSON events.
22
+ * The exact event format depends on the Gemini CLI version; this provider
23
+ * maps the most common patterns to the standard Chroxy event stream.
24
+ *
25
+ * Events emitted (standard provider contract):
26
+ * ready { model }
27
+ * stream_start { messageId }
28
+ * stream_delta { messageId, delta }
29
+ * stream_end { messageId }
30
+ * tool_start { messageId, toolUseId, tool, input }
31
+ * tool_result { toolUseId, result }
32
+ * result { cost, duration, usage, sessionId }
33
+ * error { message }
34
+ */
35
+
36
+ const DEFAULT_MODEL = 'gemini-2.5-pro'
37
+
38
+ // Resolve the gemini binary once at module load. Under a GUI launch
39
+ // (e.g. Tauri on macOS) PATH is minimal and may exclude the user's
40
+ // install dir — fall through to known locations so `spawn()` succeeds.
41
+ // Covers curl|sh installers (~/.local/bin) and `npm install -g` without
42
+ // sudo (~/.npm-global/bin).
43
+ const BINARY_CANDIDATES = [
44
+ join(homedir(), '.local/bin/gemini'),
45
+ '/opt/homebrew/bin/gemini',
46
+ '/usr/local/bin/gemini',
47
+ '/usr/bin/gemini',
48
+ join(homedir(), '.npm-global/bin/gemini'),
49
+ ]
50
+
51
+ const GEMINI = resolveBinary('gemini', BINARY_CANDIDATES)
52
+
53
+ // Per-provider model metadata — #2956.
54
+ // Context windows come from the Gemini model docs. Kept explicit here so the
55
+ // per-provider registry (models.js#getRegistryForProvider) can surface
56
+ // accurate values in the dashboard without the generic 200k heuristic that
57
+ // ships with the Claude default registry.
58
+ const GEMINI_MODEL_METADATA = Object.freeze({
59
+ 'gemini-2.5-pro': { label: 'Gemini 2.5 Pro', contextWindow: 2_000_000 },
60
+ 'gemini-2.5-flash': { label: 'Gemini 2.5 Flash', contextWindow: 1_000_000 },
61
+ 'gemini-2.0-pro': { label: 'Gemini 2.0 Pro', contextWindow: 2_000_000 },
62
+ 'gemini-2.0-flash': { label: 'Gemini 2.0 Flash', contextWindow: 1_000_000 },
63
+ 'gemini-1.5-pro': { label: 'Gemini 1.5 Pro', contextWindow: 2_000_000 },
64
+ 'gemini-1.5-flash': { label: 'Gemini 1.5 Flash', contextWindow: 1_000_000 },
65
+ })
66
+
67
+ const GEMINI_ALLOWED_MODELS = Object.freeze(Object.keys(GEMINI_MODEL_METADATA))
68
+
69
+ const GEMINI_FALLBACK_MODELS = Object.freeze(GEMINI_ALLOWED_MODELS.map(id => {
70
+ const meta = GEMINI_MODEL_METADATA[id]
71
+ return Object.freeze({
72
+ id,
73
+ label: meta.label,
74
+ fullId: id,
75
+ contextWindow: meta.contextWindow,
76
+ })
77
+ }))
78
+
79
+ /**
80
+ * Headroom multiplier for the learn-loop (#4414). Re-exported from the
81
+ * shared `CONTEXT_WINDOW_HEADROOM` constant in `utils/context-window-learn.js`
82
+ * so Gemini and Codex stay aligned on the same value.
83
+ */
84
+ export const GEMINI_CONTEXT_WINDOW_HEADROOM = CONTEXT_WINDOW_HEADROOM
85
+
86
+ /**
87
+ * Sanity cap on the learn-loop ratchet target for the Gemini provider
88
+ * (#4414). A single `result` event with a corrupt or malicious
89
+ * `input_tokens` value (overflow, JSONL parse glitch, future Gemini CLI
90
+ * bug) must not be able to balloon the registered window to an absurd
91
+ * number. 4,000,000 tokens is double today's largest published Gemini
92
+ * window (2M for gemini-2.5-pro / gemini-2.0-pro / gemini-1.5-pro) —
93
+ * leaves room for the next-gen bump without needing another source change.
94
+ *
95
+ * Sourced from the per-provider cap table in `utils/context-window-learn.js`
96
+ * — bump it there if a legit future Gemini model exceeds 4M.
97
+ */
98
+ export const GEMINI_CONTEXT_WINDOW_RATCHET_CAP = getRatchetCap('gemini')
99
+
100
+ /**
101
+ * #4414 learn-loop helper. Thin Gemini-specific wrapper around the shared
102
+ * `maybeRatchetContextWindow` so unit tests can drive the helper directly
103
+ * without going through the JSONL readline pipeline.
104
+ *
105
+ * @param {import('events').EventEmitter} session The GeminiSession instance
106
+ * @param {string} modelId Short id or fullId of the active Gemini model
107
+ * @param {number} inputTokens `usage.input_tokens` from the `result` event
108
+ * @returns {boolean} true when the registry was updated, false when no-op
109
+ */
110
+ export function _maybeRatchetContextWindow(session, modelId, inputTokens) {
111
+ return maybeRatchetContextWindow('gemini', modelId, inputTokens, session.emit.bind(session))
112
+ }
113
+
114
+ export class GeminiSession extends JsonlSubprocessSession {
115
+ // ------------------------------------------------------------------
116
+ // Static provider identity — required by JsonlSubprocessSession
117
+ // ------------------------------------------------------------------
118
+
119
+ static get binaryCandidates() {
120
+ return BINARY_CANDIDATES
121
+ }
122
+
123
+ static get resolvedBinary() {
124
+ return GEMINI
125
+ }
126
+
127
+ static get apiKeyEnv() {
128
+ return 'GEMINI_API_KEY'
129
+ }
130
+
131
+ /**
132
+ * #6563 — Gemini authenticates via GEMINI_API_KEY / GOOGLE_API_KEY OR OAuth
133
+ * tokens cached under ~/.gemini by `gemini login`. Reuse the SAME probe
134
+ * resolveAuth() and the preflight use so all three layers (display, runtime,
135
+ * preflight) agree that a `gemini login`-only user is authenticated — start()
136
+ * must not throw for them just because the env key is unset.
137
+ */
138
+ static hasAlternativeCredentials() {
139
+ return hasGeminiOAuthCreds()
140
+ }
141
+
142
+ static get providerName() {
143
+ return 'gemini'
144
+ }
145
+
146
+ /**
147
+ * Human-readable label shown in the startup banner and anywhere else the
148
+ * server needs to name this provider (#2953). Each provider owns its own
149
+ * display name so `server-cli.js` no longer has to maintain a hardcoded
150
+ * `PROVIDER_LABELS` map that drifts every time a new provider lands.
151
+ */
152
+ static get displayLabel() {
153
+ return 'Google Gemini'
154
+ }
155
+
156
+ /**
157
+ * Root data directory for this provider (#2965).
158
+ * Consumers (conversation-scanner, ws-file-ops) use this to locate
159
+ * provider-specific subdirs (projects/, agents/, commands/) without
160
+ * hardcoding the path.
161
+ */
162
+ static get dataDir() {
163
+ return join(homedir(), '.gemini')
164
+ }
165
+
166
+ static get messageIdPrefix() {
167
+ return 'gemini'
168
+ }
169
+
170
+ static get capabilities() {
171
+ return {
172
+ permissions: false,
173
+ inProcessPermissions: false,
174
+ modelSwitch: true,
175
+ permissionModeSwitch: false,
176
+ planMode: false,
177
+ resume: false,
178
+ terminal: false,
179
+ thinkingLevel: false,
180
+ // #3932: declared explicitly so the capability matrix matches across
181
+ // providers — claude-tui is the only one that sets this to false.
182
+ streaming: true,
183
+ }
184
+ }
185
+
186
+ /**
187
+ * Model IDs this provider accepts in `set_model`. Returns a plain array so
188
+ * the settings handler can surface it to the client on rejection.
189
+ * @returns {string[]}
190
+ */
191
+ static getAllowedModels() {
192
+ return GEMINI_ALLOWED_MODELS
193
+ }
194
+
195
+ /**
196
+ * Minimal model list shown in the dashboard when the SDK has not pushed
197
+ * a dynamic update for this provider. Same shape as the Claude registry
198
+ * so `getRegistryForProvider('gemini')` can serve it directly (#2956).
199
+ *
200
+ * @returns {ReadonlyArray<{id:string,label:string,fullId:string,contextWindow:number}>}
201
+ */
202
+ static getFallbackModels() {
203
+ return GEMINI_FALLBACK_MODELS
204
+ }
205
+
206
+ /**
207
+ * Lookup metadata for a known Gemini model. Returns null for unknown
208
+ * ids so the registry can fall back to a generic heuristic.
209
+ *
210
+ * @param {string} modelId
211
+ * @returns {{id:string,label:string,fullId:string,contextWindow:number,description?:string}|null}
212
+ */
213
+ static getModelMetadata(modelId) {
214
+ const meta = GEMINI_MODEL_METADATA[modelId]
215
+ if (!meta) return null
216
+ return {
217
+ id: modelId,
218
+ label: meta.label,
219
+ fullId: modelId,
220
+ contextWindow: meta.contextWindow,
221
+ description: meta.description || '',
222
+ }
223
+ }
224
+
225
+ /**
226
+ * Preflight dependency spec used by `chroxy doctor`.
227
+ */
228
+ static get preflight() {
229
+ return {
230
+ label: 'Gemini',
231
+ binary: {
232
+ name: 'gemini',
233
+ args: ['--version'],
234
+ candidates: BINARY_CANDIDATES,
235
+ installHint: 'install Gemini CLI (see https://github.com/google-gemini/generative-ai-cli)',
236
+ },
237
+ credentials: {
238
+ // GOOGLE_API_KEY is also accepted by the Gemini CLI subprocess (see
239
+ // utils/spawn-env.js gemini allowlist). Keep both here so the
240
+ // preflight + #3404 audit auth surface match what the spawn allows.
241
+ envVars: ['GEMINI_API_KEY', 'GOOGLE_API_KEY'],
242
+ hint: 'set GEMINI_API_KEY or GOOGLE_API_KEY',
243
+ // #6563: the env var is OPTIONAL when OAuth creds exist (`gemini login`),
244
+ // so `chroxy doctor` downgrades the missing env var from fail→warn instead
245
+ // of a hard credentials failure — doctor can't read the OAuth token, but it
246
+ // must not report a false failure when resolveAuth() is ready on OAuth. Same
247
+ // probe as resolveAuth() + hasAlternativeCredentials() → one definition of
248
+ // "has a usable credential".
249
+ optional: hasGeminiOAuthCreds(),
250
+ },
251
+ }
252
+ }
253
+
254
+ /**
255
+ * Resolve runtime auth state for the dashboard (#4769).
256
+ *
257
+ * Gemini accepts GEMINI_API_KEY / GOOGLE_API_KEY env vars OR the OAuth
258
+ * state cached under `~/.gemini/` by `gemini login` (#4301). Filename
259
+ * varies between CLI versions — oauth_creds.json or google_accounts.json
260
+ * — the probe accepts either.
261
+ *
262
+ * @param {NodeJS.ProcessEnv} env
263
+ * @param {{ hasGeminiOAuthCreds: () => boolean }} helpers
264
+ * @returns {{ready:boolean, source:string, envVar:string|null, envVars:string[], hint:string, detail:string}}
265
+ */
266
+ static resolveAuth(env, helpers) {
267
+ const credSpec = this.preflight.credentials
268
+ const envVars = credSpec.envVars
269
+ const hint = credSpec.hint || `set ${envVars.join(' or ')}`
270
+
271
+ const matched = envVars.find(v => env[v])
272
+ if (matched) {
273
+ return {
274
+ ready: true,
275
+ source: 'env',
276
+ envVar: matched,
277
+ envVars,
278
+ hint: '',
279
+ detail: `Google API (${matched} set)`,
280
+ billingClass: BILLING_CLASSES.API_KEY,
281
+ }
282
+ }
283
+ if (helpers.hasGeminiOAuthCreds()) {
284
+ return {
285
+ ready: true,
286
+ source: 'oauth',
287
+ envVar: null,
288
+ envVars,
289
+ hint,
290
+ detail: 'Google API (OAuth from `gemini login`)',
291
+ billingClass: BILLING_CLASSES.API_KEY,
292
+ }
293
+ }
294
+ const resolvedHint = hint
295
+ ? `${hint} or run \`gemini login\``
296
+ : 'run `gemini login` or set GEMINI_API_KEY'
297
+ return {
298
+ ready: false,
299
+ source: 'none',
300
+ envVar: null,
301
+ envVars,
302
+ hint: resolvedHint,
303
+ detail: envVars.length ? `Not configured — ${resolvedHint}` : 'Not configured',
304
+ // Non-Claude provider — always per-token api-key billing, era-independent.
305
+ billingClass: BILLING_CLASSES.API_KEY,
306
+ }
307
+ }
308
+
309
+ constructor(opts = {}) {
310
+ // #5367: forward every BaseSession opt via the canonical picker (which
311
+ // preserves the #3899 hardTimeoutMs / #4790 streamStallTimeoutMs plumbing
312
+ // that used to be hand-maintained here). Overrides: provider default,
313
+ // `model || DEFAULT_MODEL`, and `resumeSessionId` — the last is a
314
+ // JsonlSubprocessSession-local opt (not a BaseSession key) so it must ride
315
+ // through the overrides bag to reach the middle layer.
316
+ super(buildBaseSessionOpts(opts, {
317
+ provider: opts.provider || 'gemini',
318
+ model: opts.model || DEFAULT_MODEL,
319
+ resumeSessionId: opts.resumeSessionId,
320
+ }))
321
+ }
322
+
323
+ // #5374: removed the no-op `setModel` override — it only forwarded to
324
+ // BaseSession.setModel, which now owns the guard + the (default no-op)
325
+ // _onModelChanged hook.
326
+
327
+ // ------------------------------------------------------------------
328
+ // JsonlSubprocessSession overrides
329
+ // ------------------------------------------------------------------
330
+
331
+ _buildArgs(text) {
332
+ const args = ['-p', text, '--output-format', 'stream-json', '-y']
333
+ if (this.model) {
334
+ args.push('-m', this.model)
335
+ }
336
+ return args
337
+ }
338
+
339
+ _buildChildEnv() {
340
+ return buildSpawnEnv('gemini')
341
+ }
342
+
343
+ /** Drop node DeprecationWarning noise from gemini stderr. */
344
+ _shouldSkipStderr(msg) {
345
+ return msg.includes('DeprecationWarning')
346
+ }
347
+
348
+ /**
349
+ * Map a Gemini JSONL event to the standard Chroxy event stream.
350
+ * Called once per JSONL line by the base class sendMessage() runtime.
351
+ *
352
+ * Handles the full event dispatch including assistant text streaming.
353
+ *
354
+ * @param {Object} event - Parsed Gemini JSONL event
355
+ * @param {Object} ctx - Shared per-sendMessage mutable context
356
+ */
357
+ _processJsonlLine(event, ctx) {
358
+ if (!event || !event.type) return
359
+
360
+ switch (event.type) {
361
+ case 'assistant': {
362
+ if (!event.content || !Array.isArray(event.content)) break
363
+ for (const block of event.content) {
364
+ if (block.type === 'text') {
365
+ if (!ctx.didStreamStart) {
366
+ this.emit('stream_start', { messageId: ctx.messageId })
367
+ ctx.didStreamStart = true
368
+ }
369
+ this.emit('stream_delta', { messageId: ctx.messageId, delta: block.text || '' })
370
+ } else if (block.type === 'tool_use') {
371
+ const toolMessageId = `gemini-tool-${++this._messageCounter}`
372
+ this.emit('tool_start', {
373
+ messageId: toolMessageId,
374
+ toolUseId: block.id || toolMessageId,
375
+ tool: block.name || 'unknown',
376
+ input: block.input || {},
377
+ })
378
+ }
379
+ }
380
+ break
381
+ }
382
+
383
+ case 'tool_result': {
384
+ const toolUseId = event.tool_use_id || event.id || `gemini-tool-${this._messageCounter}`
385
+ this.emit('tool_result', {
386
+ toolUseId,
387
+ result: event.content || event.output || '',
388
+ })
389
+ break
390
+ }
391
+
392
+ case 'result': {
393
+ ctx.didEmitResult = true
394
+ // Close any open stream before emitting result (provider contract)
395
+ if (ctx.didStreamStart) {
396
+ this.emit('stream_end', { messageId: ctx.messageId })
397
+ ctx.didStreamStart = false
398
+ }
399
+ const usage = event.usage || {}
400
+ const inputTokens = usage.input_tokens || 0
401
+ const outputTokens = usage.output_tokens || 0
402
+ // #4414 learn-loop: same drift pattern as Codex (#3857) — the static
403
+ // window in GEMINI_MODEL_METADATA will go stale as Google bumps the
404
+ // window for gemini-2.5-pro / future variants. When the observed
405
+ // `input_tokens` exceeds the registered window, ratchet the registry
406
+ // upward so the meter reflects reality, and emit `models_updated` so
407
+ // connected dashboards refresh.
408
+ //
409
+ // Only ratchets *up* — a single small turn must never shrink the
410
+ // registered window.
411
+ if (this.model && inputTokens > 0) {
412
+ _maybeRatchetContextWindow(this, this.model, inputTokens)
413
+ }
414
+ this.emit('result', {
415
+ cost: null,
416
+ duration: null,
417
+ usage: {
418
+ input_tokens: inputTokens,
419
+ output_tokens: outputTokens,
420
+ },
421
+ sessionId: null,
422
+ })
423
+ break
424
+ }
425
+
426
+ default:
427
+ // Unknown event — ignore
428
+ break
429
+ }
430
+ }
431
+
432
+ /**
433
+ * Map a Gemini event to the standard Chroxy event stream.
434
+ *
435
+ * Kept for backward compatibility with tests and any callers that invoke
436
+ * this method directly. Handles only non-text events (tool_use, tool_result,
437
+ * result); assistant text blocks are handled via _processJsonlLine/sendMessage.
438
+ *
439
+ * @param {Object} event - Parsed Gemini JSONL event
440
+ */
441
+ _processGeminiEvent(event) {
442
+ if (!event || !event.type) return
443
+
444
+ switch (event.type) {
445
+ case 'assistant': {
446
+ // Text blocks are handled via _processJsonlLine in sendMessage context.
447
+ // Only process tool_use blocks here.
448
+ if (!event.content || !Array.isArray(event.content)) break
449
+ for (const block of event.content) {
450
+ if (block.type === 'tool_use') {
451
+ const toolMessageId = `gemini-tool-${++this._messageCounter}`
452
+ this.emit('tool_start', {
453
+ messageId: toolMessageId,
454
+ toolUseId: block.id || toolMessageId,
455
+ tool: block.name || 'unknown',
456
+ input: block.input || {},
457
+ })
458
+ }
459
+ }
460
+ break
461
+ }
462
+
463
+ case 'tool_result': {
464
+ const toolUseId = event.tool_use_id || event.id || `gemini-tool-${this._messageCounter}`
465
+ this.emit('tool_result', {
466
+ toolUseId,
467
+ result: event.content || event.output || '',
468
+ })
469
+ break
470
+ }
471
+
472
+ case 'result': {
473
+ const usage = event.usage || {}
474
+ // NOTE: the context-window learn-loop (`maybeRatchetContextWindow`)
475
+ // is deliberately NOT wired in here. Production routes end-of-turn
476
+ // events through `_processJsonlLine`, which owns the ratchet call.
477
+ // This legacy path exists only for tests / direct callers and is
478
+ // intentionally minimal — duplicating the ratchet would risk
479
+ // double-emitting `models_updated` if both paths ever fire on the
480
+ // same event.
481
+ this.emit('result', {
482
+ cost: null,
483
+ duration: null,
484
+ usage: {
485
+ input_tokens: usage.input_tokens || 0,
486
+ output_tokens: usage.output_tokens || 0,
487
+ },
488
+ sessionId: null,
489
+ })
490
+ break
491
+ }
492
+
493
+ default:
494
+ // Unknown event — ignore
495
+ break
496
+ }
497
+ }
498
+ }
@@ -0,0 +1,52 @@
1
+ // get-public-ip.js — best-effort public egress IP lookup (#5828).
2
+ //
3
+ // Used ONLY when the operator opts into the billing canary's datacenter-egress
4
+ // check (`config.billing.egressCheck`). Off by default — this is the one place
5
+ // the daemon reaches out to a third-party service, so it's consent-gated.
6
+ //
7
+ // Fail-open by design: any error (timeout, network down, non-200, unparseable
8
+ // body) resolves to `null`, never throws. A missed lookup just means no egress
9
+ // warning — strictly better than crashing a periodic canary tick.
10
+
11
+ import { isIpv4, isIpv6 } from './ip-utils.js'
12
+
13
+ // ipify's api64 endpoint returns a bare IP string — the host's IPv6 when it
14
+ // egresses over IPv6, otherwise its IPv4. The dual-stack endpoint matters for
15
+ // #5831: an IPv6-only cloud host (Hetzner increasingly assigns these) cannot
16
+ // reach the IPv4-only `api.ipify.org`, so the datacenter-egress check would
17
+ // never fire on exactly the host it exists to catch. Kept as a default so the
18
+ // resolver works out of the box; injectable for tests / for an operator who'd
19
+ // rather point at their own echo service.
20
+ const DEFAULT_IP_ECHO_URL = 'https://api64.ipify.org'
21
+ const DEFAULT_TIMEOUT_MS = 5000
22
+
23
+ /**
24
+ * Resolve the daemon's public egress IP, best-effort.
25
+ *
26
+ * @param {object} [opts]
27
+ * @param {string} [opts.url] - IP-echo endpoint returning a bare IP string.
28
+ * @param {number} [opts.timeoutMs] - abort the request after this long.
29
+ * @param {typeof fetch} [opts.fetchImpl] - injectable for tests (defaults to global fetch).
30
+ * @returns {Promise<string|null>} the trimmed IPv4 or IPv6 string, or null on any failure.
31
+ */
32
+ export async function resolvePublicIp({ url = DEFAULT_IP_ECHO_URL, timeoutMs = DEFAULT_TIMEOUT_MS, fetchImpl = fetch } = {}) {
33
+ const controller = new AbortController()
34
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
35
+ try {
36
+ const res = await fetchImpl(url, { signal: controller.signal })
37
+ if (!res || !res.ok) return null
38
+ const text = (await res.text()).trim()
39
+ // Keep this strictly an IP-literal parser: a real IP literal is short (IPv6
40
+ // tops out at 45 chars), so cap the body BEFORE the validators — a large
41
+ // captive-portal / error page (which may contain `:`) must not be fed through
42
+ // isIpv6's splitting work. Over the cap → not an IP.
43
+ if (text.length > 45) return null
44
+ // Only accept a plausible IPv4 or IPv6 — the classifier handles both — so a
45
+ // junk/HTML body (captive portal, error page) is never treated as an IP.
46
+ return (isIpv4(text) || isIpv6(text)) ? text : null
47
+ } catch {
48
+ return null
49
+ } finally {
50
+ clearTimeout(timer)
51
+ }
52
+ }
package/src/git.js ADDED
@@ -0,0 +1,15 @@
1
+ import { resolveBinary } from './utils/resolve-binary.js'
2
+
3
+ /**
4
+ * Fully-resolved path to the git binary.
5
+ *
6
+ * When the process runs with a minimal PATH (e.g. only the Node bin
7
+ * directory), `execFileSync('git', ...)` fails with ENOENT. This
8
+ * module resolves the git path once at import time and exports it
9
+ * for all callers that need to spawn git.
10
+ */
11
+ export const GIT = resolveBinary('git', [
12
+ '/opt/homebrew/bin/git', // macOS ARM (Homebrew)
13
+ '/usr/local/bin/git', // macOS Intel / Linux manual install
14
+ '/usr/bin/git', // Linux package manager
15
+ ])