@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
@@ -0,0 +1,82 @@
1
+ /**
2
+ * NotificationSink — the delivery-channel contract for chroxy notifications
3
+ * (#5413 Phase 1).
4
+ *
5
+ * The notification pipeline is layered:
6
+ *
7
+ * session events → category mapping (PushNotificationHandler)
8
+ * → prefs + rate limiting (PushManager — shared, sink-agnostic)
9
+ * → fan out to every configured sink (SinkRegistry)
10
+ * → channel-specific delivery (ExpoPushSink today,
11
+ * DiscordWebhookSink in #5413 Phase 2, ...)
12
+ *
13
+ * A sink is ONLY the last hop: it takes an already-approved notification and
14
+ * delivers it over one channel. Category enable/disable, quiet hours, and the
15
+ * per-category rate limits all happen upstream in PushManager so every sink
16
+ * gets identical gating for free. The one exception is per-DEVICE prefs:
17
+ * those are keyed by device identifiers only the sink knows about (Expo push
18
+ * tokens), so the pipeline passes evaluator callbacks down via `context` and
19
+ * the sink applies them to its own device list.
20
+ *
21
+ * Contract:
22
+ *
23
+ * - `name` — stable, unique, human-readable identifier (e.g. 'expo-push').
24
+ * Used in logs and (later) per-sink enable/disable config.
25
+ *
26
+ * - `isConfigured()` — synchronous, cheap, side-effect free. `true` when the
27
+ * sink currently has somewhere to deliver to (tokens registered, webhook
28
+ * URL configured, ...). The registry skips unconfigured sinks entirely, and
29
+ * the pipeline treats "no sink configured" as a silent no-op success.
30
+ *
31
+ * - `send(notification, context)` — deliver one notification. MUST NOT throw
32
+ * for ordinary delivery failures: catch them, log, and resolve `false`
33
+ * (the registry still guards against escapes defensively).
34
+ *
35
+ * `notification` is channel-agnostic:
36
+ * { category, title, body, data, categoryId }
37
+ * where `category` is one of the pipeline's notification categories
38
+ * (see RATE_LIMITS in push.js), `data` is an arbitrary payload object and
39
+ * `categoryId` is an optional iOS action-button category (sinks without an
40
+ * equivalent concept simply ignore it).
41
+ *
42
+ * `context` carries per-device prefs evaluators supplied by the pipeline:
43
+ * {
44
+ * now, // ms epoch, for quiet hours
45
+ * isCategoryEnabled(category, deviceId), // per-device mute
46
+ * isInQuietHours(now, deviceId), // quiet-hours window
47
+ * shouldBypassQuietHours(category, deviceId), // bypass list
48
+ * }
49
+ * All evaluators are optional — a sink must treat a missing evaluator as
50
+ * "allowed" (fail open), matching the pipeline's defaults.
51
+ *
52
+ * Resolves `true` when no hard delivery failure occurred (delivered, or
53
+ * nothing eligible to deliver — both are "no error" from the caller's
54
+ * view). Resolves `false` ONLY on a hard channel failure (non-2xx,
55
+ * network throw). Callers like the idle-push dedupe latch (#3870) rely on
56
+ * this distinction to retry later.
57
+ */
58
+
59
+ export class NotificationSink {
60
+ constructor({ name } = {}) {
61
+ this.name = name || this.constructor.name
62
+ }
63
+
64
+ /**
65
+ * Whether this sink currently has somewhere to deliver to. Subclasses
66
+ * override; the base class is honest about having no channel.
67
+ */
68
+ isConfigured() {
69
+ return false
70
+ }
71
+
72
+ /**
73
+ * Deliver one notification. Subclasses must override.
74
+ * @param {{ category: string, title: string, body: string, data?: object, categoryId?: string }} notification
75
+ * @param {object} [context]
76
+ * @returns {Promise<boolean>}
77
+ */
78
+ // eslint-disable-next-line no-unused-vars
79
+ async send(notification, context = {}) {
80
+ throw new Error(`NotificationSink '${this.name}' does not implement send()`)
81
+ }
82
+ }
@@ -0,0 +1,221 @@
1
+ /**
2
+ * Ollama provider — local models through Ollama's Anthropic-compatible
3
+ * Messages API (Ollama v0.14.0+, default `http://localhost:11434`; the
4
+ * Anthropic SDK appends `/v1/messages` itself). Reuses ClaudeByokSession's
5
+ * entire agent loop (streaming, tools, permissions, MCP, history, cost)
6
+ * by swapping the four seams (`_defaultModel`, `_resolveCredentials`,
7
+ * `_buildClient`, `_getPricing`) plus the static-side metadata — the
8
+ * same subclass-not-fork rationale as deepseek-session.js.
9
+ *
10
+ * What makes this provider different from the other BYOK subclasses:
11
+ * - No credentials. Ollama requires an api key field on the wire but
12
+ * ignores it; `_resolveCredentials` returns the documented dummy.
13
+ * `preflight.credentials.envVars` is empty so the preflight runner
14
+ * skips the credential gate entirely (utils/preflight.js:130).
15
+ * - No model allow-list. Models are whatever the user has `ollama pull`ed
16
+ * locally — a static list would reject valid local models, so
17
+ * `getAllowedModels()` returns null (session-manager treats a
18
+ * non-array as "no restriction"). `getFallbackModels()` seeds the
19
+ * dashboard picker with Ollama's recommended coder models; dynamic
20
+ * discovery via GET /api/tags (#5421, ollama-tags.js) replaces the
21
+ * seed with the actually-installed list when the daemon is reachable.
22
+ * Discovery is ADVISORY only — it feeds the picker, never validation.
23
+ * - Zero pricing. Local inference is free; `_getPricing` returns a
24
+ * zero-rate entry (not null) so byok-session's "no pricing entry"
25
+ * warn never fires and result.cost is an honest 0.
26
+ *
27
+ * Base URL resolution (first match wins; lives in ollama-tags.js since
28
+ * #5421 so the tags probe and the SDK client can't disagree — re-exported
29
+ * here for compatibility):
30
+ * 1. CHROXY_OLLAMA_BASE_URL — full URL, chroxy-specific override
31
+ * 2. OLLAMA_HOST — Ollama's own convention; may be `host:port` without
32
+ * a scheme, normalized to http:// here
33
+ * 3. http://localhost:11434 — Ollama's default bind
34
+ *
35
+ * Reachability is NOT probed at preflight (the daemon may start before
36
+ * Ollama does); a dead endpoint surfaces at session start through
37
+ * byok-session's existing client-error path with the base URL in the
38
+ * message.
39
+ */
40
+
41
+ import Anthropic from '@anthropic-ai/sdk'
42
+ import { ClaudeByokSession } from './byok-session.js'
43
+ import { resolveOllamaBaseUrl, ollamaEnvOverride, refreshOllamaModels } from './ollama-tags.js'
44
+ import { BILLING_CLASSES } from './billing-class.js'
45
+
46
+ // Compatibility re-export — resolution moved to ollama-tags.js (#5421).
47
+ export { resolveOllamaBaseUrl }
48
+
49
+ // Ollama's documented "required but ignored" placeholder key. The
50
+ // Anthropic SDK refuses an empty apiKey, so something must be sent.
51
+ const OLLAMA_DUMMY_API_KEY = 'ollama'
52
+
53
+ // Seed list for the dashboard model picker — Ollama's recommended coding
54
+ // models as of v0.14 (ollama.com/blog/claude). Deliberately short: the
55
+ // real catalogue is whatever the user pulled, and getAllowedModels()
56
+ // returns null so any local model id is accepted as-is. `contextWindow`
57
+ // is null because the effective window is decided by the local model
58
+ // file + num_ctx, not the provider — the wire schema tolerates null
59
+ // (protocol server.ts: contextWindow is optional/unknown) and the
60
+ // dashboard simply omits the chip.
61
+ const OLLAMA_FALLBACK_MODELS = Object.freeze([
62
+ Object.freeze({ id: 'qwen3-coder', label: 'Qwen3 Coder', fullId: 'qwen3-coder', contextWindow: null }),
63
+ Object.freeze({ id: 'glm-4.7', label: 'GLM 4.7', fullId: 'glm-4.7', contextWindow: null }),
64
+ Object.freeze({ id: 'minimax-m2.1', label: 'MiniMax M2.1', fullId: 'minimax-m2.1', contextWindow: null }),
65
+ ])
66
+
67
+ // Local inference: every rate is zero. A real (frozen) entry rather than
68
+ // null so byok-session's once-per-model "no pricing entry" warn (which
69
+ // tells operators to update CLAUDE_PRICING_USD_PER_MTOK) never fires for
70
+ // a provider where missing pricing is not a bug.
71
+ const OLLAMA_ZERO_PRICING = Object.freeze({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0 })
72
+
73
+ export class OllamaSession extends ClaudeByokSession {
74
+ // #5858: NOT Claude-family — Ollama rides ClaudeByokSession's agent loop but
75
+ // serves locally-pulled models (getAllowedModels() returns null, #5418), so
76
+ // override the inherited flag to false (never soft-fall-back to claude).
77
+ static claudeFamily = false
78
+
79
+ static get displayLabel() {
80
+ return 'Ollama (local)'
81
+ }
82
+
83
+ static get dataDir() {
84
+ // No `~/.claude` dependency — pure HTTP to the local Ollama daemon.
85
+ // getProviderDataDirs() skips providers that return null (#2965).
86
+ return null
87
+ }
88
+
89
+ static get preflight() {
90
+ return {
91
+ label: 'Ollama',
92
+ credentials: {
93
+ // Empty envVars → the preflight credential gate is skipped
94
+ // (utils/preflight.js requires envVars.length > 0 to check).
95
+ // No binary check either: Ollama is a daemon we talk HTTP to,
96
+ // not a CLI we spawn.
97
+ envVars: [],
98
+ hint: 'run a local Ollama (v0.14.0+) — `ollama serve`, then `ollama pull qwen3-coder`',
99
+ optional: true,
100
+ },
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Runtime auth state for the dashboard (#4769). There is no credential:
106
+ * always ready, with the resolved endpoint in `detail` so SettingsPanel
107
+ * shows where requests will go (and which env var redirected them).
108
+ *
109
+ * @param {NodeJS.ProcessEnv} env
110
+ * @returns {{ready:boolean, source:string, envVar:string|null, envVars:string[], hint:string, detail:string}}
111
+ */
112
+ static resolveAuth(env) {
113
+ const baseURL = resolveOllamaBaseUrl(env)
114
+ // Same predicate as resolveOllamaBaseUrl (via the shared helper) — a
115
+ // truthy-but-whitespace var must not be labelled as the active
116
+ // override while routing ignores it.
117
+ const overrideVar = ollamaEnvOverride(env)
118
+ return {
119
+ ready: true,
120
+ source: 'env',
121
+ envVar: overrideVar,
122
+ envVars: ['CHROXY_OLLAMA_BASE_URL', 'OLLAMA_HOST'],
123
+ hint: '',
124
+ detail: `Local Ollama at ${baseURL} (no API key — local inference)`,
125
+ // Local inference has no metered billing; classify api-key (the
126
+ // "your own infra / per-token" bucket) so the UI never mislabels it
127
+ // as a Claude subscription/credit pool. Era-independent.
128
+ billingClass: BILLING_CLASSES.API_KEY,
129
+ }
130
+ }
131
+
132
+ static getFallbackModels() {
133
+ return OLLAMA_FALLBACK_MODELS
134
+ }
135
+
136
+ static getAllowedModels() {
137
+ // null = no restriction. Valid models are whatever `ollama list`
138
+ // shows on this machine; the daemon can't know that statically, and
139
+ // rejecting unlisted ids would block every locally-pulled model.
140
+ // An unknown model surfaces as Ollama's own 404 at first message.
141
+ return null
142
+ }
143
+
144
+ static getModelMetadata(modelId) {
145
+ if (typeof modelId !== 'string' || modelId.length === 0) return null
146
+ const hit = OLLAMA_FALLBACK_MODELS.find((m) => m.id === modelId || m.fullId === modelId)
147
+ if (hit) {
148
+ return { id: hit.id, label: hit.label, fullId: hit.fullId, contextWindow: hit.contextWindow }
149
+ }
150
+ // #5421: any other non-empty id is a locally-pulled tag discovered via
151
+ // /api/tags (or a user-typed alias) — valid metadata with an UNKNOWN
152
+ // context window. `contextWindow: null` is deliberate and load-bearing:
153
+ // the registry hook in models.js preserves an explicit null instead of
154
+ // substituting DEFAULT_CONTEXT_WINDOW, so the dashboard omits the
155
+ // context chip rather than showing a fabricated 200k (#5418's
156
+ // never-fabricate rule). The raw tag doubles as the label — Ollama tags
157
+ // (`llama3.2:7b`) don't survive Claude-style humanization.
158
+ return { id: modelId, label: modelId, fullId: modelId, contextWindow: null }
159
+ }
160
+
161
+ /**
162
+ * Dynamic model discovery hook (#5421) — ws-history calls this (fire-and-
163
+ * forget) whenever it sends `available_models` for an ollama session, and
164
+ * pushes a refreshed list if discovery changed the registry. Resolves to
165
+ * the updated model list on change, null otherwise (failure / no change /
166
+ * TTL-cached). Never throws, never blocks validation: getAllowedModels()
167
+ * above stays null regardless of what discovery finds.
168
+ */
169
+ static refreshModels(opts) {
170
+ return refreshOllamaModels(opts)
171
+ }
172
+
173
+ constructor(opts = {}) {
174
+ // Force the registry name so the provider id on this session is
175
+ // always 'ollama' — independent of whatever the embedder passed.
176
+ super({ ...opts, provider: 'ollama' })
177
+ }
178
+
179
+ /**
180
+ * #5421: kick off model discovery when a session starts — the moment we
181
+ * know the user actually cares about this Ollama instance. Fire-and-
182
+ * forget: discovery must never delay or fail session start (byok's
183
+ * start() already emitted 'ready' by the time the probe resolves). On a
184
+ * changed list, emit `models_updated` — session-manager forwards it and
185
+ * ws-forwarding broadcasts a provider-tagged `available_models` to every
186
+ * connected client (same path the Claude SDK's supportedModels() push
187
+ * uses), so newly pulled models appear without a daemon restart.
188
+ */
189
+ async start() {
190
+ await super.start()
191
+ refreshOllamaModels()
192
+ .then((models) => {
193
+ if (Array.isArray(models) && models.length > 0) {
194
+ this.emit('models_updated', { models })
195
+ }
196
+ })
197
+ .catch(() => {})
198
+ }
199
+
200
+ // --- Seam overrides (see byok-session.js for the contract) ---
201
+
202
+ get _defaultModel() {
203
+ return 'qwen3-coder'
204
+ }
205
+
206
+ _resolveCredentials() {
207
+ // Required-but-ignored placeholder (docs.ollama.com/api/anthropic-compatibility).
208
+ return { key: OLLAMA_DUMMY_API_KEY, source: 'env' }
209
+ }
210
+
211
+ _buildClient(apiKey) {
212
+ return new Anthropic({
213
+ apiKey,
214
+ baseURL: resolveOllamaBaseUrl(),
215
+ })
216
+ }
217
+
218
+ _getPricing() {
219
+ return OLLAMA_ZERO_PRICING
220
+ }
221
+ }
@@ -0,0 +1,238 @@
1
+ /**
2
+ * Dynamic Ollama model discovery — GET /api/tags (#5421).
3
+ *
4
+ * Asks the local Ollama daemon which models are actually pulled and feeds
5
+ * the result into the per-provider models registry so the dashboard picker
6
+ * reflects `ollama list` instead of the static 3-model seed from #5418.
7
+ *
8
+ * Design constraints (issue #5421):
9
+ * - ADVISORY, NOT RESTRICTIVE. Discovery only populates the picker;
10
+ * `OllamaSession.getAllowedModels()` stays null (unrestricted) because
11
+ * a model can be `ollama pull`ed mid-session or addressed by an alias
12
+ * the tag list doesn't spell out. Validation never consults this module.
13
+ * - GRACEFUL FAILURE. Ollama down / slow / returning garbage must never
14
+ * delay session start or spam the logs: short timeout (800ms), debug-
15
+ * level logging only, and the picker keeps whatever it already had
16
+ * (the static fallback list on cold boot).
17
+ * - NO RETRY STORM. Results — including failures — are cached for a
18
+ * 30s TTL, and concurrent callers share one in-flight request. A
19
+ * dashboard reconnect loop can't hammer the daemon.
20
+ *
21
+ * This module also owns base-URL resolution (moved here from
22
+ * ollama-session.js, which re-exports it for compatibility) so the session
23
+ * seam, the auth-panel label, and the tags probe can never disagree about
24
+ * where Ollama lives. /api/tags is served at the Ollama ROOT — when an
25
+ * operator's override includes the Anthropic-compat `/v1` path suffix, it
26
+ * is stripped before appending /api/tags.
27
+ */
28
+
29
+ import { getRegistryForProvider } from './models.js'
30
+ import { createLogger } from './logger.js'
31
+
32
+ const log = createLogger('ollama')
33
+
34
+ const DEFAULT_OLLAMA_BASE_URL = 'http://localhost:11434'
35
+
36
+ // Bounded probe: Ollama is a local daemon — if it hasn't answered in 800ms
37
+ // it is down (or wedged), and the picker should just keep its current list.
38
+ export const OLLAMA_TAGS_TIMEOUT_MS = 800
39
+
40
+ // Cache window for discovery results (success AND failure). Keeps a
41
+ // reconnecting dashboard / multi-client handshake burst down to at most
42
+ // one HTTP probe per 30s while still picking up `ollama pull` quickly.
43
+ export const OLLAMA_TAGS_CACHE_TTL_MS = 30_000
44
+
45
+ /**
46
+ * Resolve the Ollama endpoint. Exported (and re-exported by
47
+ * ollama-session.js) for tests and for the auth panel's detail string —
48
+ * keep resolution in exactly one place.
49
+ *
50
+ * Resolution order (first match wins):
51
+ * 1. CHROXY_OLLAMA_BASE_URL — full URL, chroxy-specific override
52
+ * 2. OLLAMA_HOST — Ollama's own convention; may be `host:port` without
53
+ * a scheme, normalized to http:// here
54
+ * 3. http://localhost:11434 — Ollama's default bind
55
+ *
56
+ * @param {NodeJS.ProcessEnv} [env]
57
+ * @returns {string}
58
+ */
59
+ export function resolveOllamaBaseUrl(env = process.env) {
60
+ // Trimmed-non-empty is the single "is set" predicate — resolveAuth
61
+ // derives its override-var label from the same helper so the detail
62
+ // string and the actual routing can never disagree. An exported-but-
63
+ // empty (or whitespace) var counts as unset. Deliberately NO URL
64
+ // validation here: silently redirecting a typo'd override to localhost
65
+ // would mask the misconfig — a malformed value flows through and fails
66
+ // loudly in the SDK's request path, and resolveAuth's `detail` shows
67
+ // the exact string in the dashboard.
68
+ const explicit = ollamaEnvOverride(env)
69
+ if (explicit === 'CHROXY_OLLAMA_BASE_URL') return env.CHROXY_OLLAMA_BASE_URL.trim()
70
+ if (explicit === 'OLLAMA_HOST') {
71
+ const host = env.OLLAMA_HOST.trim()
72
+ // OLLAMA_HOST accepts bare `host`, `host:port`, or a full URL.
73
+ return /^[a-z][a-z0-9+.-]*:\/\//i.test(host) ? host : `http://${host}`
74
+ }
75
+ return DEFAULT_OLLAMA_BASE_URL
76
+ }
77
+
78
+ /**
79
+ * Which env var (if any) is overriding the endpoint. Shared by
80
+ * resolveOllamaBaseUrl (routing) and OllamaSession.resolveAuth (labelling)
81
+ * so the two can't drift.
82
+ *
83
+ * @param {NodeJS.ProcessEnv} env
84
+ * @returns {'CHROXY_OLLAMA_BASE_URL'|'OLLAMA_HOST'|null}
85
+ */
86
+ export function ollamaEnvOverride(env) {
87
+ if (typeof env.CHROXY_OLLAMA_BASE_URL === 'string' && env.CHROXY_OLLAMA_BASE_URL.trim().length > 0) {
88
+ return 'CHROXY_OLLAMA_BASE_URL'
89
+ }
90
+ if (typeof env.OLLAMA_HOST === 'string' && env.OLLAMA_HOST.trim().length > 0) {
91
+ return 'OLLAMA_HOST'
92
+ }
93
+ return null
94
+ }
95
+
96
+ /**
97
+ * Build the /api/tags URL from a resolved base URL. /api/tags lives at the
98
+ * Ollama root: trailing slashes and an Anthropic-compat `/v1` path suffix
99
+ * (some operators point CHROXY_OLLAMA_BASE_URL at the versioned path even
100
+ * though the SDK appends it itself) are stripped first.
101
+ *
102
+ * @param {string} baseUrl
103
+ * @returns {string}
104
+ */
105
+ export function buildOllamaTagsUrl(baseUrl) {
106
+ let root = typeof baseUrl === 'string' ? baseUrl.trim() : ''
107
+ root = root.replace(/\/+$/, '')
108
+ root = root.replace(/\/v1$/i, '')
109
+ return `${root}/api/tags`
110
+ }
111
+
112
+ /**
113
+ * GET <root>/api/tags and return the installed model tags as a normalized,
114
+ * deduplicated string array — or null on ANY failure (daemon down, non-2xx,
115
+ * malformed JSON, unexpected shape, timeout). Failures log at debug level
116
+ * only: an absent Ollama is a normal steady state, not an error.
117
+ *
118
+ * Normalization: a bare `:latest` suffix is stripped (Ollama treats
119
+ * `qwen3-coder` and `qwen3-coder:latest` as the same model, and the short
120
+ * form matches the curated fallback ids so the picker doesn't show
121
+ * duplicates). Other tags (`:7b`, `:q4_K_M`, …) identify distinct local
122
+ * variants and are kept verbatim.
123
+ *
124
+ * @param {Object} [opts]
125
+ * @param {NodeJS.ProcessEnv} [opts.env] - env for base-URL resolution
126
+ * @param {typeof fetch} [opts.fetchFn] - injectable fetch for tests
127
+ * @param {number} [opts.timeoutMs]
128
+ * @returns {Promise<string[]|null>}
129
+ */
130
+ export async function fetchOllamaTags({ env = process.env, fetchFn = fetch, timeoutMs = OLLAMA_TAGS_TIMEOUT_MS } = {}) {
131
+ const url = buildOllamaTagsUrl(resolveOllamaBaseUrl(env))
132
+ const controller = new AbortController()
133
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
134
+ try {
135
+ const res = await fetchFn(url, { signal: controller.signal })
136
+ if (!res?.ok) {
137
+ log.debug(`tags probe: ${url} answered ${res?.status ?? 'no response'}`)
138
+ return null
139
+ }
140
+ const body = await res.json()
141
+ if (!Array.isArray(body?.models)) {
142
+ log.debug(`tags probe: ${url} returned unexpected shape (no models array)`)
143
+ return null
144
+ }
145
+ const seen = new Set()
146
+ const tags = []
147
+ for (const m of body.models) {
148
+ // /api/tags entries carry both `name` and `model` (identical in
149
+ // practice); prefer `name`, fall back to `model` for forward-compat.
150
+ const raw = typeof m?.name === 'string' && m.name.trim().length > 0
151
+ ? m.name.trim()
152
+ : (typeof m?.model === 'string' ? m.model.trim() : '')
153
+ if (!raw) continue
154
+ const tag = raw.replace(/:latest$/, '')
155
+ if (!tag || seen.has(tag)) continue
156
+ seen.add(tag)
157
+ tags.push(tag)
158
+ }
159
+ return tags
160
+ } catch (err) {
161
+ // AbortError (timeout), ECONNREFUSED (daemon down), invalid JSON —
162
+ // all the same outcome: no discovery this round.
163
+ log.debug(`tags probe: ${url} failed (${err?.name === 'AbortError' ? `timeout after ${timeoutMs}ms` : err?.message || err})`)
164
+ return null
165
+ } finally {
166
+ clearTimeout(timer)
167
+ }
168
+ }
169
+
170
+ // --- TTL cache for refreshOllamaModels ---
171
+ // -Infinity (not 0) so the first call always probes even under an injected
172
+ // test clock that starts near zero.
173
+ let _lastProbeAt = -Infinity
174
+ let _inflight = null
175
+ // Stringified tag set last fed into the registry — lets a successful
176
+ // re-probe that found the SAME models skip the registry rebuild and the
177
+ // resulting available_models re-broadcast.
178
+ let _lastAppliedKey = null
179
+
180
+ /** Test hook: drop the TTL cache + change-detection state. */
181
+ export function _resetOllamaTagsStateForTests() {
182
+ _lastProbeAt = -Infinity
183
+ _inflight = null
184
+ _lastAppliedKey = null
185
+ }
186
+
187
+ /**
188
+ * Discover installed models and feed them into the ollama provider's
189
+ * models registry. Resolves to the registry's refreshed model list when
190
+ * the picker contents CHANGED, or null when there is nothing new to
191
+ * broadcast (probe failed, no models installed, same set as last time,
192
+ * or served from the TTL cache).
193
+ *
194
+ * Callers treat a non-null result as "push a fresh available_models to
195
+ * clients"; null means whatever was already sent is still accurate.
196
+ *
197
+ * Concurrency: one probe in flight at a time (joiners share its promise);
198
+ * results — including failures — are cached for OLLAMA_TAGS_CACHE_TTL_MS
199
+ * so handshake bursts and reconnect loops cost at most one HTTP GET per
200
+ * window.
201
+ *
202
+ * @param {Object} [opts] - forwarded to fetchOllamaTags; plus:
203
+ * @param {Object} [opts.registry] - injectable registry for tests.
204
+ * Defaults to getRegistryForProvider('ollama'). In production the
205
+ * provider is registered by providers.js at module load, well before
206
+ * any caller of this function exists.
207
+ * @param {number} [opts.ttlMs]
208
+ * @param {() => number} [opts.now] - injectable clock for tests
209
+ * @returns {Promise<Array<Object>|null>}
210
+ */
211
+ export async function refreshOllamaModels(opts = {}) {
212
+ const now = typeof opts.now === 'function' ? opts.now : Date.now
213
+ const ttlMs = typeof opts.ttlMs === 'number' ? opts.ttlMs : OLLAMA_TAGS_CACHE_TTL_MS
214
+ if (_inflight) return _inflight
215
+ if (now() - _lastProbeAt < ttlMs) return null
216
+ _inflight = (async () => {
217
+ try {
218
+ const tags = await fetchOllamaTags(opts)
219
+ _lastProbeAt = now()
220
+ // Failure or an empty install: keep the current picker contents
221
+ // (static fallback on cold boot, last successful discovery after).
222
+ if (!Array.isArray(tags) || tags.length === 0) return null
223
+ const key = JSON.stringify(tags)
224
+ if (key === _lastAppliedKey) return null
225
+ const registry = opts.registry ?? getRegistryForProvider('ollama')
226
+ // No displayName: labels come from OllamaSession.getModelMetadata
227
+ // (curated labels for the recommended models, the raw tag otherwise).
228
+ const converted = registry.updateModels(tags.map((tag) => ({ value: tag })))
229
+ if (!Array.isArray(converted) || converted.length === 0) return null
230
+ _lastAppliedKey = key
231
+ log.info(`discovered ${tags.length} installed Ollama model${tags.length === 1 ? '' : 's'} via /api/tags`)
232
+ return registry.getModels()
233
+ } finally {
234
+ _inflight = null
235
+ }
236
+ })()
237
+ return _inflight
238
+ }
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Config-driven OpenAI-compatible provider endpoints (#5420).
3
+ *
4
+ * The sibling of anthropic-compatible-session.js (#5419): anything that speaks
5
+ * the OpenAI Chat Completions API — OpenAI itself, OpenRouter, LM Studio, vLLM,
6
+ * llama.cpp server, Together, Groq, DeepInfra, any custom proxy — can be
7
+ * declared in config.json under `providers.openaiCompatible` and registered as
8
+ * a first-class provider at startup, without writing a per-service session class.
9
+ *
10
+ * The Anthropic↔OpenAI translation core (request shape + streaming-chunk fold
11
+ * into Anthropic SDK events + final Message) ships in anthropic-openai-translate.js
12
+ * (#6127); the network glue that exposes it as an `@anthropic-ai/sdk`-shaped
13
+ * client lives in anthropic-openai-shim.js. This module reuses the entire
14
+ * config-driven Anthropic-compatible factory (credential resolution, model
15
+ * allowlists / discovery, pricing, preflight, resolveAuth) and swaps exactly one
16
+ * seam: `_buildClient` returns the OpenAI shim client instead of a raw Anthropic
17
+ * client. Subclass, not fork — every byok-session fix and every
18
+ * anthropic-compatible improvement flows to every configured OpenAI endpoint.
19
+ *
20
+ * Entry shape is identical to `providers.anthropicCompatible`
21
+ * (id/label/baseUrl/defaultModel/models?/apiKeyEnv?/credentialsKey?/pricing?/
22
+ * contextWindow?/modelDiscovery?), validated by the same validator in
23
+ * anthropic-compatible-config.js. The ONLY difference is the wire dialect of
24
+ * `baseUrl`: it is the OpenAI API BASE URL — typically ending in `/v1` (e.g.
25
+ * `https://openrouter.ai/api/v1`, `http://localhost:1234/v1` for LM Studio) —
26
+ * which the `openai` SDK joins with `/chat/completions`, rather than an
27
+ * Anthropic `/v1/messages` base.
28
+ *
29
+ * Credentials never touch config.json: `apiKeyEnv` names an env var,
30
+ * `credentialsKey` names a field in ~/.chroxy/credentials.json (mode 0600).
31
+ * Env wins over file. Keys are never logged.
32
+ */
33
+
34
+ import { createAnthropicCompatibleSessionClass } from './anthropic-compatible-session.js'
35
+ import { validateOpenAiCompatibleProviders } from './anthropic-compatible-config.js'
36
+ import { createAnthropicShimClient } from './anthropic-openai-shim.js'
37
+ import { registerProvider, getRegisteredProviderNames } from './providers.js'
38
+ import { createLogger } from './logger.js'
39
+
40
+ const log = createLogger('openai-compatible')
41
+
42
+ /**
43
+ * Create a ClaudeByokSession subclass for one validated OpenAI-compatible config
44
+ * entry. Delegates the whole four-seam machinery to
45
+ * `createAnthropicCompatibleSessionClass` and overrides only `_buildClient` so
46
+ * the session talks chat-completions (via the shim) instead of Anthropic
47
+ * `/v1/messages`.
48
+ *
49
+ * The entry should be the NORMALIZED shape produced by
50
+ * `validateOpenAiCompatibleProviders`; the underlying Anthropic-compatible
51
+ * factory still applies the same defaults defensively so tests and embedders can
52
+ * pass a minimal raw entry.
53
+ *
54
+ * @param {object} rawEntry - Normalized config entry
55
+ * @returns {typeof import('./byok-session.js').ClaudeByokSession} Provider session class
56
+ */
57
+ export function createOpenAiCompatibleSessionClass(rawEntry) {
58
+ // Reuse the Anthropic-compatible factory wholesale: it validates id/baseUrl/
59
+ // defaultModel, freezes the entry, and wires every seam except the client.
60
+ // Pass our own block label so a malformed entry's construction error names
61
+ // `openaiCompatible`, not the delegated `anthropicCompatible` factory (#6253).
62
+ const AnthropicCompatibleSession = createAnthropicCompatibleSessionClass(rawEntry, { blockLabel: 'openaiCompatible' })
63
+ // The frozen, normalized entry the base factory built — single source of the
64
+ // baseUrl the shim needs.
65
+ const entry = AnthropicCompatibleSession.compatEntry
66
+
67
+ class OpenAiCompatibleSession extends AnthropicCompatibleSession {
68
+ /**
69
+ * The ONE swapped seam: build an OpenAI-shim client (chat-completions under
70
+ * an Anthropic-SDK-shaped surface) instead of a raw Anthropic client.
71
+ * Everything else — credential resolution, history rollback, parallel
72
+ * tools, MAX_TOOL_ROUNDS, pricing, model discovery — is inherited unchanged.
73
+ */
74
+ _buildClient(apiKey) {
75
+ return createAnthropicShimClient({ baseURL: entry.baseUrl, apiKey })
76
+ }
77
+ }
78
+
79
+ return OpenAiCompatibleSession
80
+ }
81
+
82
+ /**
83
+ * Register every valid `providers.openaiCompatible` entry from the merged config
84
+ * as a first-class provider (#5420). Called once at server startup
85
+ * (server-cli.js) right after `registerAnthropicCompatibleProviders`, before the
86
+ * default-provider resolution so `--provider <id>` can select an OpenAI endpoint.
87
+ *
88
+ * Invalid entries are logged and skipped; valid siblings still register.
89
+ * Collisions are checked against the static RESERVED_PROVIDER_IDS and the LIVE
90
+ * registry at call time (which already includes any anthropicCompatible ids
91
+ * registered moments earlier).
92
+ *
93
+ * @param {object | null | undefined} config - Merged server config
94
+ * @returns {string[]} The provider ids that were registered
95
+ */
96
+ export function registerOpenAiCompatibleProviders(config) {
97
+ const block = config?.providers
98
+ // Legacy form: `providers` as an array of provider-id strings — nothing here.
99
+ if (typeof block !== 'object' || block === null || Array.isArray(block)) return []
100
+ if (!Object.prototype.hasOwnProperty.call(block, 'openaiCompatible')) return []
101
+
102
+ const { entries, warnings } = validateOpenAiCompatibleProviders(block.openaiCompatible, {
103
+ reservedIds: getRegisteredProviderNames(),
104
+ })
105
+ for (const warning of warnings) {
106
+ log.warn(warning)
107
+ }
108
+
109
+ const registered = []
110
+ for (const entry of entries) {
111
+ registerProvider(entry.id, createOpenAiCompatibleSessionClass(entry))
112
+ registered.push(entry.id)
113
+ log.info(
114
+ `OpenAI-compatible provider registered: ${entry.id} → ${entry.baseUrl} (default model: ${entry.defaultModel}, models: ${entry.models ? entry.models.join(', ') : 'unrestricted'}, key: ${entry.apiKeyEnv || entry.credentialsKey || 'none'})`,
115
+ )
116
+ }
117
+ return registered
118
+ }