@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,185 @@
1
+ import { homedir } from 'os'
2
+ import { join } from 'path'
3
+ import { BaseSession, buildBaseSessionOpts } from './base-session.js'
4
+ import { ALLOWED_MODEL_IDS } from './models.js'
5
+ import { CLAUDE_FALLBACK_MODELS, claudeModelMetadata } from './claude-model-catalog.js'
6
+ import { BILLING_CLASSES } from './billing-class.js'
7
+
8
+ // Minimum `claude` CLI version that ships the `--channels` MCP transport.
9
+ // Verified present in v2.1.163 (the locally-installed CLI) and documented
10
+ // from v2.1.80+; permission relay needs ≥ v2.1.81 but that surface lands
11
+ // with sub 4 (#3955), so the scaffold gates on the channel-transport floor
12
+ // only. See docs/architecture/claude-channels-provider-spike.md.
13
+ export const CLAUDE_CHANNEL_MIN_VERSION = '2.1.80'
14
+
15
+ /**
16
+ * ClaudeChannelSession — provider scaffold for the `claude --channels` MCP
17
+ * transport (#3953, parent #3951). Research preview.
18
+ *
19
+ * This is intentionally a NO-OP session: `start()` throws "not yet
20
+ * implemented" so the bridge wiring (spawn + IPC round-trip) can land in
21
+ * isolation as sub 3 (#3954). Everything the dashboard and `chroxy doctor`
22
+ * need to LIST and reason about the provider — capabilities, displayLabel,
23
+ * dataDir, preflight (binary + minVersion + credentials), model metadata,
24
+ * and auth/billing detail — is fully wired here so the registry surface can
25
+ * be reviewed without any PTY spawning or MCP child process.
26
+ *
27
+ * Auth/billing mirrors `claude-tui`: a subscription/console-authenticated
28
+ * interactive `claude` session. The channel path bypasses programmatic
29
+ * credit metering for the same reason the TUI path does — the events arrive
30
+ * in a real interactive session, not a `claude -p` subprocess. It does NOT
31
+ * accept ANTHROPIC_API_KEY.
32
+ *
33
+ * Capability honesty (see the spike's matrix): channels win on `streaming`
34
+ * and a documented permission contract, but do NOT solve model switch or
35
+ * permission-mode switch — those stay `false`, same gap `claude-tui` has.
36
+ */
37
+ export class ClaudeChannelSession extends BaseSession {
38
+ // #5858: Claude-family flag — single source of truth for isClaudeProvider().
39
+ static claudeFamily = true
40
+
41
+ // Single source of truth for the scaffold's "not yet implemented" error
42
+ // so start()/sendMessage()/interrupt() stay in lockstep and tests can
43
+ // assert on the same string.
44
+ static get NOT_IMPLEMENTED_MESSAGE() {
45
+ return 'claude-channel provider not yet implemented (bridge wiring lands in #3954, see #3951)'
46
+ }
47
+
48
+ static get displayLabel() {
49
+ return 'Claude Code (Channel · subscription · research preview)'
50
+ }
51
+
52
+ static get dataDir() {
53
+ return join(homedir(), '.claude')
54
+ }
55
+
56
+ static get capabilities() {
57
+ return {
58
+ // Permissions land in sub 4 (#3955) via the first-party
59
+ // `claude/channel/permission` relay — declared true here so the
60
+ // capability matrix matches the spike + #3953, but the actual
61
+ // round-trip is not wired until the bridge exists.
62
+ permissions: true,
63
+ // Verdicts round-trip over IPC, not in-process — same as claude-tui.
64
+ inProcessPermissions: false,
65
+ // Channel surface does not expose model switching (spike R5).
66
+ modelSwitch: false,
67
+ // No documented channel mechanism for permission-mode switch (initially).
68
+ permissionModeSwitch: false,
69
+ planMode: false,
70
+ resume: false,
71
+ terminal: false,
72
+ thinkingLevel: false,
73
+ // Channel notifications stream as they arrive — the headline win
74
+ // over claude-tui's deliver-on-complete model.
75
+ streaming: true,
76
+ tools: true,
77
+ }
78
+ }
79
+
80
+ static get preflight() {
81
+ return {
82
+ label: 'Claude Channel',
83
+ binary: {
84
+ name: 'claude',
85
+ args: ['--version'],
86
+ // Gate on the channel-transport floor. The doctor's checkBinary
87
+ // comparator parses the leading semver out of `claude --version`
88
+ // (e.g. "2.1.163 (Claude Code)") and fails below this.
89
+ minVersion: CLAUDE_CHANNEL_MIN_VERSION,
90
+ candidates: [
91
+ join(homedir(), '.local/bin/claude'),
92
+ '/opt/homebrew/bin/claude',
93
+ '/usr/local/bin/claude',
94
+ join(homedir(), '.claude/local/node_modules/.bin/claude'),
95
+ join(homedir(), '.npm-global/bin/claude'),
96
+ ],
97
+ installHint: `install Claude Code CLI ≥ ${CLAUDE_CHANNEL_MIN_VERSION} (research preview — channels)`,
98
+ },
99
+ credentials: {
100
+ envVars: [],
101
+ hint: 'run `claude login` (subscription required — this provider does NOT accept ANTHROPIC_API_KEY)',
102
+ optional: true,
103
+ },
104
+ }
105
+ }
106
+
107
+ /**
108
+ * Resolve runtime auth state for the dashboard (#4769 pattern).
109
+ *
110
+ * Same path as claude-tui: subscription via OAuth/Keychain, never the
111
+ * API key. Marked ready up front because the on-disk OAuth probe can't
112
+ * see Keychain credentials. Detail flags the research-preview status and
113
+ * the credit-metering bypass so the dashboard billing panel reads true.
114
+ *
115
+ * @returns {{ready:boolean, source:string, envVar:string|null, envVars:string[], hint:string, detail:string, billingClass:string}}
116
+ */
117
+ static resolveAuth() {
118
+ const envVars = this.preflight.credentials.envVars
119
+ return {
120
+ ready: true,
121
+ source: 'oauth',
122
+ envVar: null,
123
+ envVars,
124
+ hint: 'run `claude login` if not yet authed',
125
+ detail: 'Claude subscription (channel MCP — bypasses programmatic credit metering · research preview)',
126
+ // Channel MCP bypasses credit metering — flat subscription billing in
127
+ // both eras (#5629 leaves this UNCHANGED).
128
+ billingClass: BILLING_CLASSES.SUBSCRIPTION,
129
+ }
130
+ }
131
+
132
+ static getFallbackModels() {
133
+ return CLAUDE_FALLBACK_MODELS
134
+ }
135
+
136
+ static getAllowedModels() {
137
+ return [...ALLOWED_MODEL_IDS]
138
+ }
139
+
140
+ static getModelMetadata(modelId) {
141
+ return claudeModelMetadata(modelId)
142
+ }
143
+
144
+ constructor(opts = {}) {
145
+ super(buildBaseSessionOpts(opts, { provider: opts.provider || 'claude-channel' }))
146
+ }
147
+
148
+ /**
149
+ * Scaffold no-op. The live bridge — spawn `claude --channels`, wire the
150
+ * stdio MCP child + IPC socket, normalize outbound events — is sub 3
151
+ * (#3954). Throwing here (rather than spawning anything) is the whole
152
+ * point of #3953: `chroxy --provider claude-channel` fails fast with a
153
+ * clear message, no PTY, no MCP child.
154
+ */
155
+ async start() {
156
+ throw new Error(ClaudeChannelSession.NOT_IMPLEMENTED_MESSAGE)
157
+ }
158
+
159
+ /**
160
+ * Required by the ProviderSession interface (validateProviderClass).
161
+ * Unlike start/destroy/setModel/setPermissionMode, BaseSession does not
162
+ * provide sendMessage/interrupt — each provider owns them — so the
163
+ * scaffold must define them or the registry validator rejects the class.
164
+ * Both throw the same not-implemented error until the bridge (#3954)
165
+ * gives them something to do. They should never be reached anyway: start()
166
+ * throws first, so no session ever becomes ready enough to message.
167
+ */
168
+ async sendMessage() {
169
+ throw new Error(ClaudeChannelSession.NOT_IMPLEMENTED_MESSAGE)
170
+ }
171
+
172
+ interrupt() {
173
+ throw new Error(ClaudeChannelSession.NOT_IMPLEMENTED_MESSAGE)
174
+ }
175
+
176
+ /**
177
+ * Safe no-op teardown. There is nothing to tear down (start() never
178
+ * spawns anything), and destroy() must not throw — SessionManager calls
179
+ * it on cleanup paths where a throw would mask the original error.
180
+ */
181
+ destroy() {
182
+ this._destroying = true
183
+ this._processReady = false
184
+ }
185
+ }
@@ -0,0 +1,266 @@
1
+ // Claude provider family's model catalog (#6201 OCP).
2
+ //
3
+ // Extracted VERBATIM from models.js so the generic models registry / overlay /
4
+ // cost engine in models.js no longer OWNS the Claude model roster — it merely
5
+ // consumes it. This is the inversion the #6201 audit wanted: adding a new
6
+ // Claude-family model is now a single-row edit HERE (MODEL_METADATA), not an
7
+ // edit to models.js's central tables. DeepSeek (#6365) was the first slice of
8
+ // the same move; this is the Claude slice.
9
+ //
10
+ // This module is a PURE LEAF: it imports nothing from models.js or any session
11
+ // class, so models.js can import it without a circular dependency, and all five
12
+ // Claude session classes (SdkSession / CliSession / ClaudeTuiSession /
13
+ // ClaudeChannelSession / ClaudeByokSession) can share one source of truth for
14
+ // their `getFallbackModels()` / `getModelMetadata()` statics — which were
15
+ // byte-identical copies before this consolidation.
16
+ //
17
+ // models.js re-exports DEFAULT_CONTEXT_WINDOW, ONE_M_SUFFIX, FALLBACK_MODELS,
18
+ // resolveClaudeContextWindow and claudeDeriveId under their original names, so
19
+ // every existing importer (and the test suites) is unaffected.
20
+
21
+ /** Default context window for unknown models. Also the floor of the Claude
22
+ * context-window heuristic below, and the generic registry fallback in
23
+ * models.js for providers that report no window. */
24
+ export const DEFAULT_CONTEXT_WINDOW = 200_000
25
+
26
+ /** Suffix the Claude CLI uses to mark the explicit 1M-context variant */
27
+ export const ONE_M_SUFFIX = '[1m]'
28
+
29
+ // Opus gained a 1M context window at 4.6. `[major, minor]` of the first opus
30
+ // release with a 1M window — opus at or above this (and any future opus major)
31
+ // is treated as 1M; earlier opus and every other family default to 200k. The
32
+ // SDK's authoritative modelUsage.contextWindow overrides this after turn 1, so a
33
+ // wrong cold-start guess only ever surfaces for the first turn.
34
+ const OPUS_ONE_M_MIN_VERSION = Object.freeze([4, 6])
35
+ // Matches an opus version token: `opus-<major>` with an OPTIONAL `-<minor>` /
36
+ // `.<minor>`, e.g. `claude-opus-4-8`, `claude-opus-4.8`, `claude-opus-5` (major
37
+ // only), or `claude-opus-4-7-20251201` (versioned + dated). Both major and minor
38
+ // are 1–2 digits NOT followed by another digit, so:
39
+ // - a DATED base id like `claude-opus-4-20250514` (opus 4.0, dated — 200k) does
40
+ // NOT read the date as a minor (the optional group fails → major-only 4.0);
41
+ // - a `claude-3-opus-20240229` id does NOT read the 8-digit date as a major
42
+ // (the major is capped at 2 digits + lookahead → no match → default).
43
+ const OPUS_VERSION_RE = /opus-(\d{1,2})(?!\d)(?:[-.](\d{1,2})(?!\d))?/
44
+
45
+ /**
46
+ * Static context-window heuristic used at cold start before the SDK reports.
47
+ * Opus 4.6+ has 1M (matched by family + version, so new minors/majors inherit it
48
+ * without a code change); most other Claude models have 200k. Any id carrying the
49
+ * explicit `[1m]` CLI suffix is a 1M-context variant regardless of the base
50
+ * model. The SDK sends authoritative values in
51
+ * `SDKResultSuccess.modelUsage[*].contextWindow` after each turn — registries
52
+ * opportunistically correct themselves via `updateContextWindow()` so wrong
53
+ * guesses only surface for the first turn.
54
+ *
55
+ * Exported so Claude providers (SdkSession/CliSession) can reuse it in
56
+ * their `getModelMetadata()` implementations.
57
+ */
58
+ export function resolveClaudeContextWindow(fullId) {
59
+ if (typeof fullId !== 'string') return DEFAULT_CONTEXT_WINDOW
60
+ if (fullId.endsWith(ONE_M_SUFFIX)) return 1_000_000
61
+ const m = OPUS_VERSION_RE.exec(fullId)
62
+ if (m) {
63
+ const major = Number(m[1])
64
+ const minor = m[2] === undefined ? null : Number(m[2])
65
+ const [minMajor, minMinor] = OPUS_ONE_M_MIN_VERSION
66
+ // A future major (opus 5+) is 1M with or without a minor; opus 4 needs an
67
+ // explicit minor >= 6 (bare `opus-4` is 4.0 → 200k, not assumed 4.6).
68
+ if (major > minMajor) return 1_000_000
69
+ if (major === minMajor && minor !== null && minor >= minMinor) return 1_000_000
70
+ }
71
+ return DEFAULT_CONTEXT_WINDOW
72
+ }
73
+
74
+
75
+ /**
76
+ * Default Claude ID converter: strips the `claude-` prefix to produce the
77
+ * short id while keeping the full id as-is. Exported so provider classes
78
+ * can compose it in their own `getModelMetadata()`.
79
+ */
80
+ export function claudeDeriveId(fullId) {
81
+ return typeof fullId === 'string' && fullId.startsWith('claude-') ? fullId.slice(7) : fullId
82
+ }
83
+
84
+ // Single source of truth for Claude model metadata (#5930 / #5631 DRY core).
85
+ // Each row describes one known Claude model family head; the two scattered
86
+ // data tables below — CLAUDE_FALLBACK_MODELS (cold-start / SDK-merge seed) and
87
+ // CLAUDE_PRICING_USD_PER_MTOK (per-fullId billing rates) — are DERIVED from
88
+ // this array, so adding a model is a single-row edit instead of edits in
89
+ // several hand-synced places. The regex/string heuristics
90
+ // (resolveClaudeContextWindow, humanizeModelId) intentionally stay separate:
91
+ // they are the graceful-degradation path for models NOT in this table.
92
+ //
93
+ // Per-row fields:
94
+ // shortId, label, fullId — the CLAUDE_FALLBACK_MODELS triple. The fullIds are
95
+ // versioned family heads WITHOUT a date suffix (e.g. `claude-opus-4-7`, not
96
+ // `claude-opus-4-7-20251201`): the short aliases (sonnet/opus/haiku) resolve
97
+ // to the latest version in the claude CLI, and the SDK's supportedModels()
98
+ // is the source of truth for concrete date-pinned identifiers. These rows
99
+ // also seed the merge step in updateModels() so a stale/minimal SDK response
100
+ // still surfaces the newer chip in the picker (#3075).
101
+ // contextWindow — OPTIONAL. When set it overrides the cold-start heuristic
102
+ // for that known model (symmetric with the on-disk overlay in
103
+ // computeFallbackModels); when absent (the case for every row today) it is
104
+ // derived via resolveClaudeContextWindow(fullId), so the derivation is
105
+ // byte-identical to the prior CLAUDE_FALLBACK_MODELS literals.
106
+ // pricing — base Anthropic rates in USD per million tokens
107
+ // {input, output, cacheRead, cacheWrite}. ABSENT (e.g. fable, shipped
108
+ // without verified pricing) emits NO pricing key, so resolveModelPricing
109
+ // returns null — never $0 — for it.
110
+ // oneM — the `[1m]` long-context variant's rates, including the `longContext`
111
+ // premium block (#4087). ABSENT emits no `<fullId>[1m]` pricing key. Kept a
112
+ // sibling of `pricing` so a [1m] form can carry distinct base rates.
113
+ //
114
+ // Cache-write rates are the 5-minute ephemeral tier (the default; chroxy
115
+ // doesn't opt into the pricier 1-hour tier). Source: Anthropic public pricing
116
+ // page — keep rates in sync on every model change; wrong numbers mislead
117
+ // cumulative-cost displays (#4054). The models.test.js snapshot pins the
118
+ // derived tables to literals, so any rate drift OR derivation regression fails
119
+ // loudly.
120
+ const MODEL_METADATA = Object.freeze([
121
+ Object.freeze({
122
+ shortId: 'sonnet', label: 'Sonnet', fullId: 'claude-sonnet-4-6',
123
+ pricing: { input: 3.00, output: 15.00, cacheRead: 0.30, cacheWrite: 3.75 },
124
+ }),
125
+ Object.freeze({
126
+ shortId: 'opus', label: 'Opus', fullId: 'claude-opus-4-8',
127
+ pricing: { input: 15.00, output: 75.00, cacheRead: 1.50, cacheWrite: 18.75 },
128
+ // #4087 — long-context (>200K input) premium tier. Below the 200K
129
+ // threshold the rates match the base entry; above it the published premium
130
+ // is a uniform 2× across all four rates. Today only Opus 4.x has a 1M
131
+ // variant in chroxy's set (resolveClaudeContextWindow). Verify against the
132
+ // Anthropic pricing page on the next periodic check.
133
+ oneM: {
134
+ input: 15.00, output: 75.00, cacheRead: 1.50, cacheWrite: 18.75,
135
+ longContext: {
136
+ thresholdInputTokens: 200_000,
137
+ input: 30.00, output: 150.00, cacheRead: 3.00, cacheWrite: 37.50,
138
+ },
139
+ },
140
+ }),
141
+ // #6219 — Fable (claude-fable-5) is disallowed for chroxy and removed from the
142
+ // roster. It is also filtered out of any SDK-returned list (DISALLOWED_MODEL_IDS
143
+ // in models.js) so it can't reappear in SDK/TUI modes, not just the CLI fallback.
144
+ Object.freeze({
145
+ shortId: 'haiku', label: 'Haiku', fullId: 'claude-haiku-4-5',
146
+ pricing: { input: 1.00, output: 5.00, cacheRead: 0.10, cacheWrite: 1.25 },
147
+ }),
148
+ ])
149
+
150
+ // Freeze a pricing block (incl. the nested longContext premium) IN PLACE so the
151
+ // derived CLAUDE_PRICING_USD_PER_MTOK keeps the deep-frozen contract callers
152
+ // relied on when the rates were hand-authored as Object.freeze literals. The
153
+ // derived table deliberately shares object identity with its MODEL_METADATA
154
+ // source row (both are frozen + read-only) — do NOT defensively deep-clone here,
155
+ // that would just reintroduce the two-copies-can-drift problem this consolidation
156
+ // removes.
157
+ function deepFreezePricing(rates) {
158
+ if (rates && typeof rates === 'object') {
159
+ for (const v of Object.values(rates)) {
160
+ if (v && typeof v === 'object') Object.freeze(v)
161
+ }
162
+ Object.freeze(rates)
163
+ }
164
+ return rates
165
+ }
166
+
167
+ // Minimal fallback used only when the SDK has never responded and no disk cache
168
+ // exists. Derived from MODEL_METADATA (source order preserved). Deep-frozen so
169
+ // callers of getModels() can't mutate the module-level constant via the
170
+ // returned array reference.
171
+ //
172
+ // Re-exported by models.js under the original name `FALLBACK_MODELS`.
173
+ export const CLAUDE_FALLBACK_MODELS = Object.freeze(
174
+ MODEL_METADATA.map((m) => Object.freeze({
175
+ id: m.shortId,
176
+ label: m.label,
177
+ fullId: m.fullId,
178
+ contextWindow: m.contextWindow ?? resolveClaudeContextWindow(m.fullId),
179
+ })),
180
+ )
181
+
182
+ // Public Anthropic pricing in USD per million tokens, derived from
183
+ // MODEL_METADATA: each row's `pricing` becomes the base `<fullId>` entry and
184
+ // each `oneM` becomes the `<fullId>[1m]` long-context entry (#4087).
185
+ // `computePromptCostUsd` selects between base and longContext rates based on
186
+ // the turn's total input tokens.
187
+ export const CLAUDE_PRICING_USD_PER_MTOK = Object.freeze(
188
+ MODEL_METADATA.reduce((table, m) => {
189
+ if (m.pricing) table[m.fullId] = deepFreezePricing(m.pricing)
190
+ if (m.oneM) table[`${m.fullId}${ONE_M_SUFFIX}`] = deepFreezePricing(m.oneM)
191
+ return table
192
+ }, {}),
193
+ )
194
+
195
+ // Short-id → fullId so callers can pass either form. The fallback set is
196
+ // the canonical mapping; new short aliases get picked up automatically.
197
+ //
198
+ // `[1m]` long-context variant (#4087): try the model id verbatim FIRST
199
+ // so an explicit `claude-opus-4-7[1m]` entry — with its longContext
200
+ // premium block — wins over the suffix-stripped fallback.
201
+ //
202
+ // Also normalises dated full IDs back to the family head: the Anthropic
203
+ // SDK's `Model` enum returns forms like `claude-opus-4-7-20251201`, which
204
+ // users may pin for reproducibility (#4084). The pricing table is keyed
205
+ // on family heads (`claude-opus-4-7`), so a regex strip of the trailing
206
+ // 8+-digit date suffix lets the lookup succeed for either form.
207
+ //
208
+ // [1m] re-attach after fallback (#4105 + #4107): when the input ended
209
+ // with `[1m]` and a non-verbatim match resolves to a family head, try
210
+ // `${head}[1m]` first so the explicit premium entry wins over the base.
211
+ // Otherwise short-form `opus[1m]` and dated-form `*-YYYYMMDD[1m]` would
212
+ // silently route to base rates and undercount >200K turns.
213
+ export function resolvePricingKey(modelId) {
214
+ if (typeof modelId !== 'string' || modelId.length === 0) return null
215
+ if (CLAUDE_PRICING_USD_PER_MTOK[modelId]) return modelId
216
+ const had1m = modelId.endsWith(ONE_M_SUFFIX)
217
+ const stripped = had1m ? modelId.slice(0, -ONE_M_SUFFIX.length) : modelId
218
+ // When the input carried [1m] AND a non-verbatim resolution lands on a
219
+ // family head with an explicit [1m] entry, prefer the [1m] entry so the
220
+ // longContext premium block is reachable.
221
+ const preferOneM = (key) => {
222
+ if (had1m) {
223
+ const oneMKey = `${key}${ONE_M_SUFFIX}`
224
+ if (CLAUDE_PRICING_USD_PER_MTOK[oneMKey]) return oneMKey
225
+ }
226
+ return key
227
+ }
228
+ if (CLAUDE_PRICING_USD_PER_MTOK[stripped]) return preferOneM(stripped)
229
+ // Dated full id? Strip the 8-digit date suffix and retry against the
230
+ // pricing table. The strip applies unconditionally; safety comes from
231
+ // the table itself — only `claude-*` keys exist, so a short-form like
232
+ // `opus-4-7-20251201` strips to `opus-4-7`, misses the table, and
233
+ // falls through to the CLAUDE_FALLBACK_MODELS short-id lookup (which expects
234
+ // the un-stripped id).
235
+ const dateStripped = stripped.replace(/-\d{8,}$/, '')
236
+ if (CLAUDE_PRICING_USD_PER_MTOK[dateStripped]) return preferOneM(dateStripped)
237
+ const fallback = CLAUDE_FALLBACK_MODELS.find((m) => m.id === stripped)
238
+ return fallback ? preferOneM(fallback.fullId) : null
239
+ }
240
+
241
+ /**
242
+ * Claude-style model metadata: strip the `claude-` prefix for the short id,
243
+ * reuse the shared context-window heuristic. The single source of truth for
244
+ * every Claude provider class's `static getModelMetadata()` — these were
245
+ * byte-identical copies across SdkSession / CliSession / ClaudeTuiSession /
246
+ * ClaudeChannelSession / ClaudeByokSession before #6201 consolidated them here.
247
+ *
248
+ * Called with the full model id as returned by the SDK (e.g. 'claude-sonnet-4-6').
249
+ * Short alias resolution is intentionally left to the caller — the registry
250
+ * always has the fullId available.
251
+ *
252
+ * @param {string} modelId - Full model id (e.g. 'claude-sonnet-4-6').
253
+ * @returns {{id:string,label:string,fullId:string,contextWindow:number,description:string}|null}
254
+ */
255
+ export function claudeModelMetadata(modelId) {
256
+ if (typeof modelId !== 'string' || modelId.length === 0) return null
257
+ const fullId = modelId
258
+ const id = claudeDeriveId(fullId)
259
+ return {
260
+ id,
261
+ label: id,
262
+ fullId,
263
+ contextWindow: resolveClaudeContextWindow(fullId),
264
+ description: '',
265
+ }
266
+ }
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Claude wire-format stream parser.
3
+ *
4
+ * Shared by CliSession (which parses `--include-partial-messages` JSON
5
+ * stream events from `claude -p`) and SdkSession (which receives full
6
+ * assistant message blocks from the Agent SDK) so the two providers
7
+ * cannot drift in how they interpret Anthropic streaming-protocol
8
+ * primitives.
9
+ *
10
+ * Pure functions only — no I/O, no state. Callers own the per-turn
11
+ * context and event emission; the parser just translates wire-format
12
+ * input into emit-ready payloads / semantic descriptors.
13
+ *
14
+ * Public API:
15
+ *
16
+ * extractToolInputSemantics(toolName, parsedInput)
17
+ * -> { kind, payload } | null
18
+ * Single source for Task / AskUserQuestion / EnterPlanMode /
19
+ * ExitPlanMode tool-input interpretation. `parsedInput` is the
20
+ * already-JSON-parsed object (CliSession parses accumulated
21
+ * partial_json chunks; SdkSession receives `block.input` directly).
22
+ *
23
+ * buildToolStartData(messageId, contentBlock)
24
+ * -> { messageId, toolUseId, tool, input, serverName? }
25
+ * Shape of the `tool_start` event for both providers. Reuses a
26
+ * single derived toolId for both `messageId` and `toolUseId` so
27
+ * the wire schema (`ServerToolStartSchema.toolUseId: z.string()`)
28
+ * holds even on the defensive fallback path when `content_block.id`
29
+ * is absent.
30
+ */
31
+
32
+ import { parseMcpToolName } from './mcp-tools.js'
33
+
34
+ /**
35
+ * Tools whose input fields drive session-level state (plan mode, agent
36
+ * tracking, user-question prompts). The semantics returned here are
37
+ * applied by the caller to its own state (CliSession or SdkSession)
38
+ * via the `kind` discriminator.
39
+ *
40
+ * @param {string} toolName
41
+ * @param {unknown} parsedInput - JSON-parsed tool input object, or null
42
+ * @returns {{ kind: 'ask_user_question' | 'task' | 'enter_plan' | 'exit_plan', payload: object } | null}
43
+ */
44
+ export function extractToolInputSemantics(toolName, parsedInput) {
45
+ if (!toolName) return null
46
+ const input = parsedInput && typeof parsedInput === 'object' ? parsedInput : {}
47
+
48
+ switch (toolName) {
49
+ case 'AskUserQuestion':
50
+ return {
51
+ kind: 'ask_user_question',
52
+ payload: { questions: input.questions },
53
+ }
54
+
55
+ case 'Task': {
56
+ const description = (typeof input.description === 'string'
57
+ ? input.description
58
+ : 'Background task').slice(0, 200)
59
+ return {
60
+ kind: 'task',
61
+ payload: { description },
62
+ }
63
+ }
64
+
65
+ case 'EnterPlanMode':
66
+ return { kind: 'enter_plan', payload: {} }
67
+
68
+ case 'ExitPlanMode': {
69
+ const allowedPrompts = Array.isArray(input.allowedPrompts)
70
+ ? input.allowedPrompts
71
+ : []
72
+ return { kind: 'exit_plan', payload: { allowedPrompts } }
73
+ }
74
+
75
+ default:
76
+ return null
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Build the `tool_start` event payload from a `content_block_start`
82
+ * event's content_block object.
83
+ *
84
+ * @param {string} messageId - The current turn-level messageId, used
85
+ * as the fallback toolId source when `contentBlock.id` is missing.
86
+ * @param {{ id?: string, name: string, type: string }} contentBlock
87
+ * @returns {{ messageId: string, toolUseId: string, tool: string, input: null, serverName?: string }}
88
+ */
89
+ export function buildToolStartData(messageId, contentBlock) {
90
+ // Use the tool's content_block.id as the tool_start messageId so each
91
+ // tool in a multi-tool turn has a distinct id. Sharing the turn-level
92
+ // messageId across tools collides with the post-tool stream_start id
93
+ // and corrupts client message state. Reused for toolUseId so the wire
94
+ // schema (`ServerToolStartSchema.toolUseId: z.string()`) holds even
95
+ // on the defensive fallback path.
96
+ const toolId = contentBlock.id || `${messageId}-tool`
97
+ const data = {
98
+ messageId: toolId,
99
+ toolUseId: toolId,
100
+ tool: contentBlock.name,
101
+ input: null,
102
+ }
103
+ const mcp = parseMcpToolName(contentBlock.name)
104
+ if (mcp) data.serverName = mcp.serverName
105
+ return data
106
+ }