@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,192 @@
1
+ /**
2
+ * DeepSeek provider (#4656) — talks to DeepSeek's Anthropic-compatible
3
+ * endpoint at `https://api.deepseek.com/anthropic` using the existing
4
+ * `@anthropic-ai/sdk` client. Reuses ClaudeByokSession's entire agent
5
+ * loop (streaming, tools, permissions, MCP, history, cost) by swapping
6
+ * the four seams (`_defaultModel`, `_resolveCredentials`, `_buildClient`,
7
+ * `_getPricing`) plus the static-side metadata.
8
+ *
9
+ * Why subclass instead of fork: every fix that lands in byok-session
10
+ * (history rollback semantics, parallel-tool execution, MAX_TOOL_ROUNDS
11
+ * summary, `tool_input_delta` flicker suppression, MCP fleet teardown)
12
+ * is correctness work that DeepSeek users want too. A fork would have
13
+ * to be hand-merged on every byok change; subclassing keeps the
14
+ * tracking automatic.
15
+ *
16
+ * Onboarding: the user gets a key at platform.deepseek.com, exports
17
+ * `DEEPSEEK_API_KEY` OR drops `{"deepseekApiKey":"sk-..."}` into
18
+ * `~/.chroxy/credentials.json` (chmod 600), then picks the "deepseek"
19
+ * provider in the dashboard / mobile app. See the issue tracker for the
20
+ * full onboarding doc.
21
+ */
22
+
23
+ import Anthropic from '@anthropic-ai/sdk'
24
+ import { ClaudeByokSession } from './byok-session.js'
25
+ import { getRegistryForProvider } from './models.js'
26
+ import { resolveDeepSeekApiKey } from './deepseek-credentials.js'
27
+ import { BILLING_CLASSES } from './billing-class.js'
28
+
29
+ // Override point for self-hosted or pinned-version endpoints. Defaults
30
+ // to DeepSeek's Anthropic-compatible endpoint, which they explicitly
31
+ // publish so Claude Code clients can point at it without translation.
32
+ const DEFAULT_DEEPSEEK_BASE_URL = 'https://api.deepseek.com/anthropic'
33
+
34
+ // DeepSeek pricing in USD per million tokens (#6201 OCP — owned by this provider
35
+ // class rather than bolted into models.js's central tables; relocated verbatim from
36
+ // models.js getDeepSeekPricing). DeepSeek reports usage in the Anthropic shape and
37
+ // maps its cache-hit metric onto `cache_read_input_tokens`; it never reports cache
38
+ // writes, so the zero `cacheWrite` rate is correct, not a placeholder. Verbatim-only
39
+ // lookup — DeepSeek doesn't ship date-suffixed model ids the way Anthropic does, so
40
+ // the strip-and-retry dance from models.js's resolvePricingKey isn't warranted here
41
+ // (if they ever do, extend along the same shape).
42
+ const DEEPSEEK_PRICING_USD_PER_MTOK = Object.freeze({
43
+ // V3 chat — general-purpose model.
44
+ 'deepseek-chat': Object.freeze({ input: 0.27, output: 1.10, cacheRead: 0.07, cacheWrite: 0 }),
45
+ // R1 reasoning — emits a reasoning trace before the final answer.
46
+ 'deepseek-reasoner': Object.freeze({ input: 0.55, output: 2.19, cacheRead: 0.14, cacheWrite: 0 }),
47
+ })
48
+
49
+ // DeepSeek's published context window for both `deepseek-chat` (V3) and
50
+ // `deepseek-reasoner` (R1). If they ever ship a larger-context variant,
51
+ // extend the metadata map below and the chip will surface automatically.
52
+ const DEEPSEEK_CONTEXT_WINDOW = 128_000
53
+
54
+ // Static model registry. `id` matches `fullId` because DeepSeek doesn't
55
+ // use a `claude-` style prefix — the registry's deriveId hook for
56
+ // non-Claude providers defaults to identity, so this stays consistent
57
+ // with what providers.js installs.
58
+ const DEEPSEEK_MODELS = Object.freeze([
59
+ Object.freeze({
60
+ id: 'deepseek-chat',
61
+ label: 'DeepSeek V3 (Chat)',
62
+ fullId: 'deepseek-chat',
63
+ contextWindow: DEEPSEEK_CONTEXT_WINDOW,
64
+ }),
65
+ Object.freeze({
66
+ id: 'deepseek-reasoner',
67
+ label: 'DeepSeek R1 (Reasoner)',
68
+ fullId: 'deepseek-reasoner',
69
+ contextWindow: DEEPSEEK_CONTEXT_WINDOW,
70
+ }),
71
+ ])
72
+
73
+ const DEEPSEEK_MODEL_IDS = Object.freeze(DEEPSEEK_MODELS.map((m) => m.id))
74
+
75
+ export class DeepSeekSession extends ClaudeByokSession {
76
+ // #5858: NOT Claude-family — DeepSeek rides ClaudeByokSession's agent loop but
77
+ // has its own static model allowlist, so override the inherited flag to false
78
+ // (its model ids must validate strictly, never soft-fall-back to claude).
79
+ static claudeFamily = false
80
+
81
+ static get displayLabel() {
82
+ return 'DeepSeek (API key)'
83
+ }
84
+
85
+ static get dataDir() {
86
+ // No `~/.claude` dependency — pure HTTPS to api.deepseek.com.
87
+ // getProviderDataDirs() skips providers that return null (#2965).
88
+ return null
89
+ }
90
+
91
+ static get preflight() {
92
+ return {
93
+ label: 'DeepSeek',
94
+ credentials: {
95
+ envVars: ['DEEPSEEK_API_KEY'],
96
+ hint: 'set DEEPSEEK_API_KEY or save it as "deepseekApiKey" in ~/.chroxy/credentials.json (mode 0600)',
97
+ optional: false,
98
+ },
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Resolve runtime auth state for the dashboard (#4769). Mirrors the BYOK
104
+ * flow: DEEPSEEK_API_KEY env OR `deepseekApiKey` field in
105
+ * ~/.chroxy/credentials.json. Both surface as source: 'env' so the
106
+ * dashboard's SettingsPanel tone legend renders the right chip; `detail`
107
+ * disambiguates which path supplied the key.
108
+ *
109
+ * @param {NodeJS.ProcessEnv} env
110
+ * @param {{ cachedResolveCredentialFile: Function }} helpers
111
+ * @returns {{ready:boolean, source:string, envVar:string|null, envVars:string[], hint:string, detail:string}}
112
+ */
113
+ static resolveAuth(env, helpers) {
114
+ const credSpec = this.preflight.credentials
115
+ const envVars = credSpec.envVars
116
+ const hint = credSpec.hint || `set ${envVars.join(' or ')}`
117
+ const resolved = helpers.cachedResolveCredentialFile(
118
+ 'deepseek',
119
+ env.DEEPSEEK_API_KEY,
120
+ resolveDeepSeekApiKey,
121
+ )
122
+ if (resolved.key) {
123
+ return {
124
+ ready: true,
125
+ source: 'env',
126
+ envVar: resolved.source === 'env' ? 'DEEPSEEK_API_KEY' : null,
127
+ envVars,
128
+ hint: '',
129
+ detail: `DeepSeek API (${resolved.source === 'env' ? 'DEEPSEEK_API_KEY set' : '~/.chroxy/credentials.json'} — per-token billing)`,
130
+ billingClass: BILLING_CLASSES.API_KEY,
131
+ }
132
+ }
133
+ return {
134
+ ready: false,
135
+ source: 'none',
136
+ envVar: null,
137
+ envVars,
138
+ hint,
139
+ detail: `DeepSeek API (${resolved.reason})`,
140
+ // Non-Claude provider — always per-token api-key billing, era-independent.
141
+ billingClass: BILLING_CLASSES.API_KEY,
142
+ }
143
+ }
144
+
145
+ static getFallbackModels() {
146
+ return DEEPSEEK_MODELS
147
+ }
148
+
149
+ static getAllowedModels() {
150
+ return [...DEEPSEEK_MODEL_IDS]
151
+ }
152
+
153
+ static getModelMetadata(modelId) {
154
+ if (typeof modelId !== 'string' || modelId.length === 0) return null
155
+ const hit = DEEPSEEK_MODELS.find((m) => m.id === modelId || m.fullId === modelId)
156
+ if (!hit) return null
157
+ return { id: hit.id, label: hit.label, fullId: hit.fullId, contextWindow: hit.contextWindow }
158
+ }
159
+
160
+ constructor(opts = {}) {
161
+ // Force the registry name so the provider id on this session is
162
+ // always 'deepseek' — independent of whatever the embedder passed.
163
+ super({ ...opts, provider: 'deepseek' })
164
+ }
165
+
166
+ // --- Seam overrides (see byok-session.js for the contract) ---
167
+
168
+ get _defaultModel() {
169
+ return 'deepseek-chat'
170
+ }
171
+
172
+ _resolveCredentials() {
173
+ return resolveDeepSeekApiKey()
174
+ }
175
+
176
+ _buildClient(apiKey) {
177
+ return new Anthropic({
178
+ apiKey,
179
+ baseURL: process.env.DEEPSEEK_BASE_URL || DEFAULT_DEEPSEEK_BASE_URL,
180
+ })
181
+ }
182
+
183
+ _getPricing(model) {
184
+ if (typeof model !== 'string' || model.length === 0) return null
185
+ // #6381: a `provider: "deepseek"` entry in ~/.chroxy/models.json can re-price
186
+ // a model with no release (e.g. when DeepSeek changes published rates). The
187
+ // operator overlay wins over the shipped static table; absent → static.
188
+ const fromOverlay = getRegistryForProvider(this._provider).getOverlayPricing(model)
189
+ if (fromOverlay) return fromOverlay
190
+ return DEEPSEEK_PRICING_USD_PER_MTOK[model] || null
191
+ }
192
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Detect Claude Code "thinking keywords" in a user prompt.
3
+ *
4
+ * The native Claude Code CLI's interactive REPL scans for magic keywords
5
+ * (`think`, `think hard`, `think harder`, `megathink`, `ultrathink`) and
6
+ * escalates the model's `maxThinkingTokens` budget for that turn. The
7
+ * `query()` path Chroxy's SdkSession uses does NOT do this — the scanner
8
+ * lives in the REPL, not the SDK. Issue #4306 makes the same affordance
9
+ * work through Chroxy: detect the keyword server-side, bump
10
+ * `maxThinkingTokens` for the turn via the existing escalation path.
11
+ *
12
+ * Matching rules:
13
+ * - case-insensitive
14
+ * - whole-word match (word boundaries) so `unthinkingly` does NOT match
15
+ * - longest match wins so `think harder` is preferred over `think`
16
+ *
17
+ * Budget mapping mirrors the native CLI rough buckets:
18
+ * - `think` → 4_000 (low)
19
+ * - `think hard` → 10_000 (medium)
20
+ * - `think harder` → 32_000 (high — same as SdkSession's `high` level)
21
+ * - `megathink` → 32_000 (alias often documented alongside `think harder`)
22
+ * - `ultrathink` → 128_000 (max — same as SdkSession's `max` level)
23
+ *
24
+ * @typedef {Object} DetectedThinkingKeyword
25
+ * @property {string} keyword - The matched keyword (lowercased, canonical form)
26
+ * @property {number} budget - Token budget to pass to setMaxThinkingTokens
27
+ *
28
+ * @param {string} text
29
+ * @returns {DetectedThinkingKeyword | null}
30
+ */
31
+ export function detectThinkingKeyword(text) {
32
+ if (typeof text !== 'string' || text.length === 0) return null
33
+
34
+ // Longest first so `think harder` wins over `think hard` wins over `think`.
35
+ // Each entry is `[canonicalKeyword, regex, budget]`. The regex uses
36
+ // word-boundary anchors on both sides; the multi-word entries allow a
37
+ // run of horizontal whitespace (space/tab only — NOT `\s`) between
38
+ // words so `think harder` (double space) still matches but
39
+ // `think\n\nharder` (paragraph boundary) does not. See #4402: `\s+`
40
+ // matched arbitrary newline runs and false-positived on unrelated
41
+ // thoughts the user happened to type on consecutive lines.
42
+ const PATTERNS = [
43
+ ['ultrathink', /\bultrathink\b/i, 128_000],
44
+ ['megathink', /\bmegathink\b/i, 32_000],
45
+ ['think harder', /\bthink[ \t]+harder\b/i, 32_000],
46
+ ['think hard', /\bthink[ \t]+hard\b/i, 10_000],
47
+ ['think', /\bthink\b/i, 4_000],
48
+ ]
49
+
50
+ for (const [keyword, regex, budget] of PATTERNS) {
51
+ if (regex.test(text)) return { keyword, budget }
52
+ }
53
+ return null
54
+ }
55
+
56
+ /**
57
+ * Token-budget map keyed by canonical keyword. Useful when callers already
58
+ * know the keyword (e.g. dashboard wants to render the badge) and just need
59
+ * the budget without re-running the regex sweep.
60
+ */
61
+ export const THINKING_KEYWORD_BUDGETS = Object.freeze({
62
+ 'think': 4_000,
63
+ 'think hard': 10_000,
64
+ 'think harder': 32_000,
65
+ 'megathink': 32_000,
66
+ 'ultrathink': 128_000,
67
+ })
@@ -0,0 +1,227 @@
1
+ import { EventEmitter } from 'events'
2
+ import { CloudflareTunnelAdapter } from './tunnel/cloudflare.js'
3
+ import { createLogger } from './logger.js'
4
+
5
+ const log = createLogger('dev-preview')
6
+
7
+ /**
8
+ * Detects when Claude starts a localhost dev server and creates
9
+ * an ephemeral Cloudflare quick tunnel so the phone can preview it.
10
+ *
11
+ * Listens to tool_result events from sessions, scans output for
12
+ * localhost server patterns, spawns a secondary tunnel, and emits
13
+ * a dev_preview event for the WS layer to broadcast.
14
+ *
15
+ * Lifecycle:
16
+ * - One tunnel per (sessionId, port) pair
17
+ * - Auto-cleanup when session is destroyed
18
+ * - Manual close via closePreview()
19
+ *
20
+ * Events emitted:
21
+ * dev_preview_started { sessionId, port, url }
22
+ * dev_preview_stopped { sessionId, port }
23
+ * dev_preview_error { sessionId, port, error } — tunnel START failure
24
+ * dev_preview_stop_failed { sessionId, port, error } — tunnel STOP failure (#5731)
25
+ */
26
+
27
+ // Patterns that indicate a dev server started on localhost
28
+ const SERVER_PATTERNS = [
29
+ // "listening on port 3000", "listening at port 8080"
30
+ /listening\s+(?:on|at)\s+(?:port\s+)?(\d{2,5})/i,
31
+ // "http://localhost:3000", "http://127.0.0.1:5173"
32
+ /https?:\/\/(?:localhost|127\.0\.0\.1):(\d{2,5})/i,
33
+ // "Local: http://localhost:5173" (Vite)
34
+ /Local:\s+https?:\/\/(?:localhost|127\.0\.0\.1):(\d{2,5})/i,
35
+ // "ready on 0.0.0.0:3000", "started on port 8080"
36
+ /(?:ready|started|running|serving)\s+(?:on|at)\s+(?:(?:0\.0\.0\.0|localhost|127\.0\.0\.1):)?(?:port\s+)?(\d{2,5})/i,
37
+ // "Server is running on port 3000"
38
+ /server\s+is\s+running\s+on\s+port\s+(\d{2,5})/i,
39
+ ]
40
+
41
+ // Ports to ignore (common non-dev-server ports)
42
+ const IGNORED_PORTS = new Set([22, 80, 443, 5432, 3306, 6379, 27017])
43
+
44
+ // Reasonable dev server port range
45
+ const MIN_PORT = 1024
46
+ const MAX_PORT = 65535
47
+
48
+ export class DevPreviewManager extends EventEmitter {
49
+ constructor() {
50
+ super()
51
+ // Map<string, Map<number, CloudflareTunnelAdapter>> sessionId -> port -> tunnel
52
+ this._tunnels = new Map()
53
+ // Set<string> of "sessionId:port" keys currently being started (prevent duplicates)
54
+ this._starting = new Set()
55
+ }
56
+
57
+ /**
58
+ * Detect localhost server port from tool result text.
59
+ * Returns the port number if found, null otherwise.
60
+ */
61
+ detectPort(text) {
62
+ if (!text || typeof text !== 'string') return null
63
+ for (const pattern of SERVER_PATTERNS) {
64
+ const match = text.match(pattern)
65
+ if (match) {
66
+ const port = parseInt(match[1], 10)
67
+ if (port >= MIN_PORT && port <= MAX_PORT && !IGNORED_PORTS.has(port)) {
68
+ return port
69
+ }
70
+ }
71
+ }
72
+ return null
73
+ }
74
+
75
+ /**
76
+ * Handle a tool_result event from a session.
77
+ * If it contains a server start pattern, creates a preview tunnel.
78
+ */
79
+ async handleToolResult(sessionId, result) {
80
+ const port = this.detectPort(result)
81
+ if (!port) return
82
+
83
+ // Already have a tunnel for this session+port
84
+ if (this._getTunnel(sessionId, port)) return
85
+
86
+ // Already starting one
87
+ const key = `${sessionId}:${port}`
88
+ if (this._starting.has(key)) return
89
+ this._starting.add(key)
90
+
91
+ try {
92
+ await this._createPreviewTunnel(sessionId, port)
93
+ } finally {
94
+ this._starting.delete(key)
95
+ }
96
+ }
97
+
98
+ /**
99
+ * Create a preview tunnel for the given session and port.
100
+ *
101
+ * The tunnel object is registered in _tunnels BEFORE start() is called so
102
+ * that closeSession() can find and stop it even if destruction races the
103
+ * 30-second startup window (preventing zombie cloudflared processes).
104
+ */
105
+ async _createPreviewTunnel(sessionId, port) {
106
+ const tunnel = new CloudflareTunnelAdapter({ port, mode: 'quick' })
107
+
108
+ // Register before starting so closeSession() can reach it during startup
109
+ if (!this._tunnels.has(sessionId)) {
110
+ this._tunnels.set(sessionId, new Map())
111
+ }
112
+ this._tunnels.get(sessionId).set(port, tunnel)
113
+
114
+ try {
115
+ const { httpUrl } = await tunnel.start()
116
+ log.info(`Tunnel started for session ${sessionId} port ${port}: ${httpUrl}`)
117
+
118
+ // Check whether the session was destroyed while we were waiting for start()
119
+ if (this._getTunnel(sessionId, port) !== tunnel) {
120
+ // Session was closed during startup — stop the tunnel immediately
121
+ log.info(`Session ${sessionId} destroyed during tunnel startup, stopping port ${port}`)
122
+ try { await tunnel.stop() } catch { /* ignore */ }
123
+ return
124
+ }
125
+
126
+ log.info(`Tunnel started for session ${sessionId} port ${port}: ${httpUrl}`)
127
+ this.emit('dev_preview_started', { sessionId, port, url: httpUrl })
128
+ } catch (err) {
129
+ log.error(`Failed to create tunnel for port ${port}: ${err.message}`)
130
+ this.emit('dev_preview_error', { sessionId, port, error: err.message })
131
+ // Remove the placeholder entry left by pre-registration
132
+ const sessionTunnels = this._tunnels.get(sessionId)
133
+ if (sessionTunnels) {
134
+ sessionTunnels.delete(port)
135
+ if (sessionTunnels.size === 0) this._tunnels.delete(sessionId)
136
+ }
137
+ // Clean up failed tunnel
138
+ try { await tunnel.stop() } catch { /* ignore */ }
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Close a specific preview tunnel.
144
+ */
145
+ async closePreview(sessionId, port) {
146
+ const tunnel = this._getTunnel(sessionId, port)
147
+ if (!tunnel) return
148
+
149
+ // #5731: capture (don't swallow) a stop() failure. The previous code
150
+ // signalled a clean stop unconditionally — if tunnel.stop() threw, the
151
+ // public tunnel (and thus the exposed local port) could still be live while
152
+ // the user was told it was shut down.
153
+ let stopError = null
154
+ try {
155
+ await tunnel.stop()
156
+ } catch (err) {
157
+ stopError = err
158
+ }
159
+
160
+ // Drop our tracking entry regardless: the tunnel handle is unusable for a
161
+ // retry whether or not stop() succeeded, so keeping it would only wedge the
162
+ // port slot. The UI still gets dev_preview_stopped so it doesn't show a
163
+ // phantom live preview.
164
+ const sessionTunnels = this._tunnels.get(sessionId)
165
+ if (sessionTunnels) {
166
+ sessionTunnels.delete(port)
167
+ if (sessionTunnels.size === 0) this._tunnels.delete(sessionId)
168
+ }
169
+
170
+ if (stopError) {
171
+ // Surface it so the user can verify / kill cloudflared manually instead of
172
+ // assuming the port is no longer exposed. Normalize the message — a promise
173
+ // rejection isn't guaranteed to be an Error (could be a string/null), so
174
+ // `.message` alone can drop the actual detail.
175
+ const stopMsg = stopError?.message || String(stopError)
176
+ log.error(`Failed to stop tunnel for session ${sessionId} port ${port}: ${stopMsg}${stopError?.stack ? '\n' + stopError.stack : ''}`)
177
+ this.emit('dev_preview_stop_failed', { sessionId, port, error: stopMsg })
178
+ } else {
179
+ log.info(`Tunnel stopped for session ${sessionId} port ${port}`)
180
+ }
181
+ this.emit('dev_preview_stopped', { sessionId, port })
182
+ }
183
+
184
+ /**
185
+ * Close all preview tunnels for a session.
186
+ */
187
+ async closeSession(sessionId) {
188
+ const sessionTunnels = this._tunnels.get(sessionId)
189
+ if (!sessionTunnels) return
190
+
191
+ const ports = [...sessionTunnels.keys()]
192
+ for (const port of ports) {
193
+ await this.closePreview(sessionId, port)
194
+ }
195
+ }
196
+
197
+ /**
198
+ * Close all preview tunnels.
199
+ */
200
+ async closeAll() {
201
+ const sessionIds = [...this._tunnels.keys()]
202
+ for (const sessionId of sessionIds) {
203
+ await this.closeSession(sessionId)
204
+ }
205
+ }
206
+
207
+ /**
208
+ * Get active previews for a session.
209
+ * Returns [{ port, url }] for client display.
210
+ */
211
+ getActivePreviews(sessionId) {
212
+ const sessionTunnels = this._tunnels.get(sessionId)
213
+ if (!sessionTunnels) return []
214
+
215
+ const previews = []
216
+ for (const [port, tunnel] of sessionTunnels) {
217
+ if (tunnel.url) {
218
+ previews.push({ port, url: tunnel.url })
219
+ }
220
+ }
221
+ return previews
222
+ }
223
+
224
+ _getTunnel(sessionId, port) {
225
+ return this._tunnels.get(sessionId)?.get(port) ?? null
226
+ }
227
+ }