@chroxy/server 0.11.0 → 0.11.10

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 (317) hide show
  1. package/CONFIG.md +204 -18
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +166 -11
  5. package/package.json +16 -12
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1203 -36
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +19 -0
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +11 -5
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +69 -5
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +92 -7
  37. package/src/byok-mcp-config.js +628 -121
  38. package/src/byok-mcp-fleet.js +49 -7
  39. package/src/byok-mcp-oauth-store.js +18 -16
  40. package/src/byok-mcp-trust.js +3 -3
  41. package/src/byok-session.js +650 -175
  42. package/src/byok-tool-executor.js +2662 -26
  43. package/src/byok-tools.js +9 -2
  44. package/src/channels/chroxy-channel-server.js +2 -3
  45. package/src/checkpoint-manager.js +64 -46
  46. package/src/claude-channel-session.js +16 -10
  47. package/src/claude-model-catalog.js +131 -16
  48. package/src/claude-model-refresh.js +385 -0
  49. package/src/claude-model-request.js +103 -0
  50. package/src/claude-stream-parser.js +53 -3
  51. package/src/claude-tui/diagnostic-tail.js +83 -0
  52. package/src/claude-tui/form-driver.js +44 -7
  53. package/src/claude-tui/model-error.js +41 -0
  54. package/src/claude-tui/pty-driver.js +211 -88
  55. package/src/claude-tui/sanitize-question-payload.js +109 -0
  56. package/src/claude-tui/usage-limit.js +239 -0
  57. package/src/claude-tui-session.js +3513 -287
  58. package/src/claude-tui-tool-response.js +300 -0
  59. package/src/cli/agent-control-cmd.js +65 -0
  60. package/src/cli/config-cmd.js +4 -4
  61. package/src/cli/config-dir-cmd.js +234 -0
  62. package/src/cli/deploy-cmd.js +45 -10
  63. package/src/cli/doctor-cmd.js +7 -3
  64. package/src/cli/init-cmd.js +15 -16
  65. package/src/cli/providers-cmd.js +3 -3
  66. package/src/cli/schedule-cmd.js +68 -39
  67. package/src/cli/server-cmd.js +48 -1
  68. package/src/cli/service-cmd.js +33 -10
  69. package/src/cli/session-cmd.js +227 -74
  70. package/src/cli/shared.js +162 -11
  71. package/src/cli/tokens-cmd.js +4 -5
  72. package/src/cli/tunnel-cmd.js +255 -24
  73. package/src/cli/worktree-gc-cmd.js +2 -2
  74. package/src/cli-session.js +1066 -121
  75. package/src/cli.js +4 -0
  76. package/src/codex-app-server-client.js +36 -3
  77. package/src/codex-app-server-session.js +1454 -79
  78. package/src/codex-bundled-client.js +66 -0
  79. package/src/codex-model-catalog.js +548 -0
  80. package/src/codex-model-rejections.js +87 -0
  81. package/src/codex-native-resume.js +104 -0
  82. package/src/codex-protocol-capabilities.js +188 -0
  83. package/src/codex-session.js +450 -27
  84. package/src/config-dir-migration.js +444 -0
  85. package/src/config-dir.js +108 -0
  86. package/src/config.js +286 -26
  87. package/src/connection-authority.js +48 -0
  88. package/src/connection-info.js +5 -9
  89. package/src/connection-locality.js +60 -0
  90. package/src/container-liveness-monitor.js +189 -0
  91. package/src/continuation-metadata-worker.js +17 -0
  92. package/src/continuations.js +114 -0
  93. package/src/control-room/host-prune.js +5 -0
  94. package/src/control-room/integrations.js +7 -20
  95. package/src/control-room/skills-inventory.js +2 -2
  96. package/src/conversation-scanner.js +40 -18
  97. package/src/conversation-scope.js +59 -39
  98. package/src/conversation-search.js +24 -22
  99. package/src/credential-store.js +23 -19
  100. package/src/daemon-commit.js +92 -0
  101. package/src/daemon-idle-state.js +171 -0
  102. package/src/daemon-update-status.js +314 -0
  103. package/src/dashboard-build.js +70 -0
  104. package/src/declared-status.js +90 -0
  105. package/src/deepseek-credentials.js +2 -3
  106. package/src/dev-preview.js +169 -182
  107. package/src/device-preferences.js +2 -2
  108. package/src/diff-parser.js +87 -0
  109. package/src/discord-credentials.js +2 -3
  110. package/src/docker-byok-pool.js +3 -1
  111. package/src/docker-byok-session.js +678 -78
  112. package/src/docker-image-allowlist.js +23 -1
  113. package/src/docker-sdk-session.js +172 -3
  114. package/src/docker-session.js +284 -10
  115. package/src/doctor.js +767 -61
  116. package/src/edited-input.js +264 -0
  117. package/src/environment-manager.js +175 -36
  118. package/src/environments/authority.js +95 -0
  119. package/src/environments/backends/container-claude-spawn.js +94 -0
  120. package/src/environments/backends/docker.js +31 -10
  121. package/src/environments/backends/k8s.js +49 -24
  122. package/src/environments/destroy-with-sessions.js +142 -0
  123. package/src/event-ingest.js +118 -13
  124. package/src/event-normalizer.js +151 -233
  125. package/src/gemini-session.js +81 -5
  126. package/src/handler-utils.js +535 -68
  127. package/src/handlers/checkpoint-handlers.js +39 -4
  128. package/src/handlers/control-room-handlers.js +51 -11
  129. package/src/handlers/conversation-handlers.js +469 -56
  130. package/src/handlers/daemon-update-handlers.js +81 -0
  131. package/src/handlers/evaluator-handlers.js +14 -1
  132. package/src/handlers/feature-handlers.js +186 -69
  133. package/src/handlers/file-handlers.js +57 -13
  134. package/src/handlers/input-handlers.js +685 -48
  135. package/src/handlers/orchestration-handlers.js +3 -3
  136. package/src/handlers/scheduler-handlers.js +88 -14
  137. package/src/handlers/session-handlers.js +542 -20
  138. package/src/handlers/session-pr-status-handlers.js +283 -0
  139. package/src/handlers/session-pr-threads-handlers.js +247 -0
  140. package/src/handlers/settings-handlers.js +330 -42
  141. package/src/handlers/skills-handlers.js +13 -4
  142. package/src/handlers/summarize-handlers.js +32 -1
  143. package/src/handlers/survey-throttle.js +380 -0
  144. package/src/health-proof.js +40 -0
  145. package/src/history-page.js +104 -0
  146. package/src/http-routes.js +127 -8
  147. package/src/ide/search.js +24 -6
  148. package/src/ide/symbols.js +20 -6
  149. package/src/input-context.js +117 -0
  150. package/src/instruction-policy-compiler.js +229 -0
  151. package/src/instruction-policy.js +250 -0
  152. package/src/jsonl-reader.js +289 -82
  153. package/src/jsonl-subprocess-session.js +92 -8
  154. package/src/keychain.js +1 -1
  155. package/src/logger.js +63 -17
  156. package/src/mailbox-route.js +11 -22
  157. package/src/message-wire.js +386 -0
  158. package/src/model-discovery.js +43 -3
  159. package/src/models.js +1276 -174
  160. package/src/notification-prefs.js +12 -4
  161. package/src/notifications/discord-billing-sink.js +22 -5
  162. package/src/notifications/discord-ci-sink.js +243 -0
  163. package/src/notifications/discord-webhook-client.js +71 -0
  164. package/src/notifications/discord-webhook-sink.js +64 -23
  165. package/src/notifications/expo-push-sink.js +85 -6
  166. package/src/notifications/ready-body.js +16 -5
  167. package/src/ollama-session.js +34 -2
  168. package/src/orchestration/build-manager.js +9 -2
  169. package/src/orchestration/git-ops.js +41 -7
  170. package/src/orchestration/orchestration-manager.js +80 -33
  171. package/src/orchestration/permission-gate.js +13 -1
  172. package/src/orchestration/run-model.js +2 -1
  173. package/src/orchestration/turn-driver.js +44 -20
  174. package/src/orphan-reaper.js +413 -0
  175. package/src/outgoing-policy.js +183 -0
  176. package/src/pairing.js +92 -13
  177. package/src/path-hash-trust-ledger.js +642 -25
  178. package/src/permission-deadlines.js +82 -0
  179. package/src/permission-floor.js +1357 -42
  180. package/src/permission-hook.js +180 -69
  181. package/src/permission-manager.js +712 -83
  182. package/src/permission-mode-support.js +35 -0
  183. package/src/permission-resolver.js +122 -8
  184. package/src/permission-scope.js +43 -0
  185. package/src/platform.js +159 -43
  186. package/src/preview-ingress.js +54 -0
  187. package/src/preview-target.js +213 -0
  188. package/src/prompt-evaluator.js +34 -4
  189. package/src/provider-customization.js +180 -0
  190. package/src/providers.js +207 -4
  191. package/src/push.js +30 -4
  192. package/src/question-route-map.js +130 -0
  193. package/src/redaction.js +360 -8
  194. package/src/roster-broadcast.js +186 -0
  195. package/src/scheduled-task-store.js +318 -26
  196. package/src/scheduler.js +73 -3
  197. package/src/sdk-session.js +2060 -187
  198. package/src/server-cli/preview-shutdown.js +22 -0
  199. package/src/server-cli/push-notification-handler.js +11 -2
  200. package/src/server-cli/server-orchestrator.js +28 -5
  201. package/src/server-cli-child.js +33 -18
  202. package/src/server-cli.js +524 -38
  203. package/src/server-identity.js +15 -11
  204. package/src/service.js +396 -25
  205. package/src/session-archive-limits.js +15 -0
  206. package/src/session-archive.js +1029 -0
  207. package/src/session-busy-state.js +72 -0
  208. package/src/session-ci-watcher.js +926 -0
  209. package/src/session-context.js +7 -2
  210. package/src/session-manager.js +3491 -312
  211. package/src/session-message-history.js +722 -16
  212. package/src/session-pr-status.js +654 -0
  213. package/src/session-pr-threads.js +271 -0
  214. package/src/session-preset-trust.js +3 -3
  215. package/src/session-preset.js +10 -5
  216. package/src/session-state-persistence.js +94 -17
  217. package/src/session-timeout-manager.js +20 -0
  218. package/src/session-token-store.js +17 -8
  219. package/src/session-wake.js +240 -0
  220. package/src/shell-approval-info.js +2 -2
  221. package/src/shell-approval-store.js +3 -1
  222. package/src/skills-loader.js +7 -4
  223. package/src/skills-manager.js +2 -2
  224. package/src/skills-trust.js +95 -13
  225. package/src/skills-usage.js +2 -3
  226. package/src/snapshots-store.js +2 -3
  227. package/src/statusline.js +23 -11
  228. package/src/summarize-session.js +51 -4
  229. package/src/supervisor.js +22 -11
  230. package/src/sweep-stale-provider-dirs.js +95 -0
  231. package/src/thinking-level-wire.js +39 -0
  232. package/src/thinking-stream.js +179 -0
  233. package/src/tool-result.js +61 -0
  234. package/src/transcript-sources.js +109 -0
  235. package/src/transcript-tasks.js +372 -25
  236. package/src/trusted-file-read.js +302 -0
  237. package/src/tunnel/base.js +0 -8
  238. package/src/tunnel/cloudflare.js +34 -31
  239. package/src/tunnel/index.js +9 -0
  240. package/src/tunnel/preview.js +64 -0
  241. package/src/turn-outcome.js +137 -0
  242. package/src/usage-normalize.js +9 -5
  243. package/src/user-shell-session.js +59 -5
  244. package/src/utils/agent-sdk-version.js +107 -0
  245. package/src/utils/argv-safety.js +741 -0
  246. package/src/utils/auth-cause.js +60 -0
  247. package/src/utils/binary-package-manifest.js +597 -0
  248. package/src/utils/binary-version.js +224 -0
  249. package/src/utils/bounded-regex-worker.js +25 -0
  250. package/src/utils/bounded-regex.js +153 -0
  251. package/src/utils/claude-binary.js +43 -0
  252. package/src/utils/claude-config-dir.js +245 -0
  253. package/src/utils/claude-login-command.js +16 -0
  254. package/src/utils/claude-native-route.js +81 -0
  255. package/src/utils/componentwise-resolver.js +133 -37
  256. package/src/utils/deploy-control-files.js +87 -0
  257. package/src/utils/exec-failure-reason.js +21 -0
  258. package/src/utils/git-repo.js +42 -0
  259. package/src/utils/is-entry-point.js +137 -0
  260. package/src/utils/node-pty-probe.js +95 -0
  261. package/src/utils/node-pty-support.js +118 -0
  262. package/src/utils/opened-file-path.js +167 -0
  263. package/src/utils/path-containment.js +165 -0
  264. package/src/utils/permission-mode-sidecar.js +51 -0
  265. package/src/utils/preflight.js +360 -16
  266. package/src/utils/read-limiter.js +217 -0
  267. package/src/utils/regular-file.js +375 -0
  268. package/src/utils/safe-regex.js +113 -0
  269. package/src/utils/small-file.js +129 -0
  270. package/src/utils/spawn-env.js +189 -4
  271. package/src/utils/stale-session-dirs.js +182 -0
  272. package/src/utils/stat-identity.js +43 -0
  273. package/src/utils/verify-provenance.js +406 -13
  274. package/src/web-task-manager.js +256 -16
  275. package/src/worktree-gc.js +7 -2
  276. package/src/ws-auth.js +69 -21
  277. package/src/ws-broadcaster.js +14 -2
  278. package/src/ws-client-manager.js +16 -1
  279. package/src/ws-client-sender.js +7 -0
  280. package/src/ws-file-ops/browser.js +331 -58
  281. package/src/ws-file-ops/common.js +320 -14
  282. package/src/ws-file-ops/git.js +395 -42
  283. package/src/ws-file-ops/index.js +2 -0
  284. package/src/ws-file-ops/memory.js +137 -35
  285. package/src/ws-file-ops/open-nofollow.js +354 -0
  286. package/src/ws-file-ops/reader.js +571 -113
  287. package/src/ws-forwarding.js +329 -39
  288. package/src/ws-handler-context.js +70 -2
  289. package/src/ws-history.js +940 -172
  290. package/src/ws-message-handlers.js +17 -1
  291. package/src/ws-permissions.js +307 -37
  292. package/src/ws-schemas.js +5 -0
  293. package/src/ws-server.js +643 -96
  294. package/sidecar/node_modules/.package-lock.json +0 -29
  295. package/sidecar/node_modules/ws/LICENSE +0 -20
  296. package/sidecar/node_modules/ws/README.md +0 -548
  297. package/sidecar/node_modules/ws/browser.js +0 -8
  298. package/sidecar/node_modules/ws/index.js +0 -22
  299. package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
  300. package/sidecar/node_modules/ws/lib/constants.js +0 -19
  301. package/sidecar/node_modules/ws/lib/event-target.js +0 -292
  302. package/sidecar/node_modules/ws/lib/extension.js +0 -203
  303. package/sidecar/node_modules/ws/lib/limiter.js +0 -55
  304. package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
  305. package/sidecar/node_modules/ws/lib/receiver.js +0 -706
  306. package/sidecar/node_modules/ws/lib/sender.js +0 -602
  307. package/sidecar/node_modules/ws/lib/stream.js +0 -161
  308. package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
  309. package/sidecar/node_modules/ws/lib/validation.js +0 -152
  310. package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
  311. package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
  312. package/sidecar/node_modules/ws/package.json +0 -70
  313. package/sidecar/node_modules/ws/wrapper.mjs +0 -21
  314. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  315. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  316. package/src/dashboard-next/dist/index.html +0 -13
  317. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
@@ -37,10 +37,8 @@
37
37
  */
38
38
 
39
39
  import { readCredentialJsonField } from './credentials-file.js'
40
- import { join } from 'path'
41
- import { homedir } from 'os'
42
40
  import Anthropic from '@anthropic-ai/sdk'
43
- import { ClaudeByokSession } from './byok-session.js'
41
+ import { ClaudeByokSession, buildByokSessionOpts } from './byok-session.js'
44
42
  import { validateAnthropicCompatibleProviders } from './anthropic-compatible-config.js'
45
43
  import { registerProvider, getRegisteredProviderNames } from './providers.js'
46
44
  import { getRegistryForProvider } from './models.js'
@@ -48,6 +46,8 @@ import { refreshDiscoveredModels } from './model-discovery.js'
48
46
  import { cachedResolveCredentialFile } from './auth-probes.js'
49
47
  import { createLogger } from './logger.js'
50
48
  import { BILLING_CLASSES } from './billing-class.js'
49
+ import { configPath } from './config-dir.js'
50
+ import { BYOK_CUSTOMIZATION, customizationWithEgress } from './provider-customization.js'
51
51
 
52
52
  const log = createLogger('anthropic-compatible')
53
53
 
@@ -65,7 +65,7 @@ const ZERO_PRICING = Object.freeze({ input: 0, output: 0, cacheRead: 0, cacheWri
65
65
  // Lazy-resolved per call so tests that mutate process.env.HOME between
66
66
  // cases pick up the new home (same rationale as deepseek-credentials.js).
67
67
  function credentialsFilePath() {
68
- return join(homedir(), '.chroxy', 'credentials.json')
68
+ return configPath('credentials.json')
69
69
  }
70
70
 
71
71
  /**
@@ -290,6 +290,12 @@ export function createAnthropicCompatibleSessionClass(rawEntry, { blockLabel = '
290
290
  // soft-fall-back to claude).
291
291
  static claudeFamily = false
292
292
 
293
+ static get customizationDescriptor() {
294
+ // A configured compatible endpoint may be a local runtime, a cloud API,
295
+ // or a proxy. The adapter cannot infer egress from the URL spelling.
296
+ return customizationWithEgress(BYOK_CUSTOMIZATION, 'unknown')
297
+ }
298
+
293
299
  /** The validated config entry this class was built from (introspection/tests). */
294
300
  static get compatEntry() {
295
301
  return entry
@@ -463,8 +469,11 @@ export function createAnthropicCompatibleSessionClass(rawEntry, { blockLabel = '
463
469
  constructor(opts = {}) {
464
470
  // Force the registry name so the provider id on this session is
465
471
  // always the config entry's id — independent of whatever the
466
- // embedder passed (mirrors DeepSeekSession / OllamaSession).
467
- super({ ...opts, provider: entry.id })
472
+ // embedder passed (mirrors DeepSeekSession / OllamaSession). Keep a
473
+ // named intermediate so the session-opt lint can verify the complete
474
+ // object is spread while buildByokSessionOpts preserves BYOK-local opts.
475
+ const forwardedOpts = buildByokSessionOpts(opts)
476
+ super({ ...forwardedOpts, provider: entry.id })
468
477
  }
469
478
 
470
479
  /**
@@ -100,7 +100,6 @@ function createShimStream(client, params, opts) {
100
100
  if (finalMessage === null) {
101
101
  // Drain remaining events so the generator runs finish() and assembles
102
102
  // the message (the events themselves are discarded on this path).
103
- // eslint-disable-next-line no-unused-vars
104
103
  for await (const _event of iterable) { /* drain */ }
105
104
  }
106
105
  return finalMessage
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Context seed for "continue an archived session as a NEW thread" (#8866).
3
+ *
4
+ * A provider that cannot resume natively (no locator, or a Codex app-server
5
+ * session in auto mode: docs/providers.md "Native restart continuity") gets a
6
+ * brand-new conversation. So the model is not left blind, the archived history
7
+ * is reduced to a bounded plain-text transcript that rides along with the
8
+ * FIRST message the user sends, as a one_turn text context item (the
9
+ * input-context.js v1 contract). Nothing is sent until the user types: the new
10
+ * session is created idle.
11
+ *
12
+ * BUDGET. `CONTINUATION_SEED_MAX_BYTES` is 32 KiB. The default provider
13
+ * (claude-tui) delivers a prompt through a PTY, and the seed makes every first
14
+ * prompt multi-line, which takes the single bracketed-paste write path in
15
+ * claude-tui/pty-driver.js (`_writePtyTextThrottled`): one atomic write with no
16
+ * per-character throttle and no length cap of its own. The only limit is what
17
+ * claude's composer and the terminal buffer take in one paste, and the file
18
+ * documents a silent ~4 KB truncation for the attachment-path suffix, so a
19
+ * prompt well under a few tens of KiB is the conservative size. 32 KiB is about
20
+ * 8k tokens of context, enough for the recent turns that matter, and far below
21
+ * the 100k-character context-item cap. Older turns are dropped first and the
22
+ * counts are stated, both in the seed and in the new session's first system
23
+ * line, so the omission is never silent.
24
+ */
25
+
26
+ export const CONTINUATION_SEED_MAX_BYTES = 32 * 1024
27
+ /** One message is shortened to this many characters (head kept) so a single huge reply cannot use the whole budget. */
28
+ export const CONTINUATION_ENTRY_MAX_CHARS = 4000
29
+ /** Persisted/restored seeds are re-bounded to this, a little above the build budget (the header lines). */
30
+ export const CONTINUATION_SEED_HARD_MAX_BYTES = CONTINUATION_SEED_MAX_BYTES + 4 * 1024
31
+ export const CONTINUATION_SEED_ITEM_ID = 'chroxy-archive-seed'
32
+ export const CONTINUATION_SEED_SOURCE = 'archived_session'
33
+
34
+ // C0 controls other than \t and \n, DEL, and C1 controls. The seed is typed
35
+ // into a terminal by claude-tui; an escape sequence inside archived output must
36
+ // never reach it as one.
37
+ // eslint-disable-next-line no-control-regex
38
+ const CONTROL_CHARS = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g
39
+
40
+ /**
41
+ * The ONE sanitizer for seed text: applied when the transcript is built and again
42
+ * when a seed is read back from the (untrusted) state file, so neither path can
43
+ * deliver a control sequence or a premature `[/context]` marker.
44
+ */
45
+ export function sanitizeSeedText(text) {
46
+ return String(text)
47
+ .replace(/\r\n?/g, '\n')
48
+ .replace(CONTROL_CHARS, '')
49
+ // The envelope closes a section with this exact marker; keep archived text
50
+ // from ending it early.
51
+ .replace(/\[\/context\]/gi, '[/ context]')
52
+ }
53
+ const clean = sanitizeSeedText
54
+
55
+ function shorten(text, max) {
56
+ const chars = [...text]
57
+ if (chars.length <= max) return text
58
+ return `${chars.slice(0, max).join('')}\n[... ${chars.length - max} more characters of this message omitted]`
59
+ }
60
+
61
+ /** @returns {{ role: 'User'|'Assistant', text: string } | null} */
62
+ function conversationEntry(entry) {
63
+ if (!entry || entry.type !== 'message' || typeof entry.content !== 'string') return null
64
+ if (entry.messageType === 'user_input') {
65
+ const text = entry.content.trim()
66
+ return text ? { role: 'User', text } : null
67
+ }
68
+ // A reasoning stream is recorded as a response with kind 'thinking'; it is not
69
+ // something the assistant said.
70
+ if (entry.messageType === 'response' && entry.kind !== 'thinking') {
71
+ const text = entry.content.trim()
72
+ return text ? { role: 'Assistant', text } : null
73
+ }
74
+ return null
75
+ }
76
+
77
+ /**
78
+ * Build the transcript seed from an archived session's history.
79
+ *
80
+ * Only user inputs and assistant responses are kept (no tool traffic, thinking
81
+ * or system lines). The NEWEST messages that fit the budget are kept.
82
+ *
83
+ * @param {object[]} history - the archived `saved.history`
84
+ * @param {{ omittedOldest?: number, maxBytes?: number }} [opts] `omittedOldest`
85
+ * is how many of the oldest history entries the archive itself had to drop
86
+ * for size, so the header can say the transcript is not the whole session.
87
+ * @returns {{ text: string, messagesIncluded: number, messagesTotal: number, bytes: number } | null}
88
+ * null when the history has no conversation to carry
89
+ */
90
+ export function buildContinuationSeed(history, { omittedOldest = 0, maxBytes = CONTINUATION_SEED_MAX_BYTES } = {}) {
91
+ const messages = (Array.isArray(history) ? history : []).map(conversationEntry).filter(Boolean)
92
+ if (messages.length === 0) return null
93
+
94
+ const blocks = messages.map((m) => `${m.role}: ${shorten(clean(m.text), CONTINUATION_ENTRY_MAX_CHARS)}`)
95
+ const sizes = blocks.map((b) => Buffer.byteLength(b) + 2)
96
+ // Reserve room for the header, which names the counts and so depends on them.
97
+ const headerReserve = 512
98
+ let used = headerReserve
99
+ let first = blocks.length
100
+ while (first > 0 && used + sizes[first - 1] <= maxBytes) {
101
+ first--
102
+ used += sizes[first]
103
+ }
104
+ // The newest message alone is over budget: keep its head rather than nothing.
105
+ let kept = blocks.slice(first)
106
+ if (kept.length === 0) {
107
+ const room = Math.max(256, maxBytes - headerReserve)
108
+ kept = [Buffer.from(blocks[blocks.length - 1]).subarray(0, room).toString('utf8').replace(/�+$/, '')]
109
+ first = blocks.length - 1
110
+ }
111
+
112
+ const header = [
113
+ `Transcript of an archived Chroxy session, continued here as a NEW thread: ${kept.length} of ${messages.length} messages are included` +
114
+ (first > 0 ? ` (the ${first} oldest were left out to fit)` : '') +
115
+ (omittedOldest > 0 ? `; the archive had already dropped ${omittedOldest} older history entries` : '') +
116
+ '.',
117
+ 'You did not take part in this conversation natively: tool calls, file contents and any approvals from it are not available to you. Use it for context only.',
118
+ ].join('\n')
119
+ const text = `${header}\n\n${kept.join('\n\n')}`
120
+ return { text, messagesIncluded: kept.length, messagesTotal: messages.length, bytes: Buffer.byteLength(text) }
121
+ }
122
+
123
+ /**
124
+ * Coerce a seed read back from the persisted session state (an untrusted file).
125
+ * @returns {{ text: string, messagesIncluded: number, messagesTotal: number, bytes: number, name: string|null, archivedAt: number|null } | null}
126
+ */
127
+ export function coerceContinuationSeed(raw) {
128
+ if (!raw || typeof raw !== 'object' || typeof raw.text !== 'string' || raw.text.length === 0) return null
129
+ // A seed recorded as in-flight (claimed) may or may not have reached the
130
+ // provider before a crash; re-sending it risks injecting the transcript twice,
131
+ // so only a never-claimed seed is re-armed.
132
+ if (raw.claimed === true) return null
133
+ // Sanitize first and measure after: normalization can change the size.
134
+ const text = sanitizeSeedText(raw.text)
135
+ if (text.length === 0) return null
136
+ const bytes = Buffer.byteLength(text)
137
+ if (bytes > CONTINUATION_SEED_HARD_MAX_BYTES) return null
138
+ const count = (v) => (Number.isInteger(v) && v >= 0 && v <= 1_000_000 ? v : 0)
139
+ return {
140
+ text,
141
+ messagesIncluded: count(raw.messagesIncluded),
142
+ messagesTotal: count(raw.messagesTotal),
143
+ bytes,
144
+ name: typeof raw.name === 'string' ? (sanitizeSeedText(raw.name).slice(0, 256) || null) : null,
145
+ archivedAt: typeof raw.archivedAt === 'number' && Number.isFinite(raw.archivedAt) ? raw.archivedAt : null,
146
+ }
147
+ }
148
+
149
+ /** The one_turn text context item that carries a seed through `prepareInputContext`. */
150
+ export function continuationSeedItem(seed) {
151
+ return {
152
+ id: CONTINUATION_SEED_ITEM_ID,
153
+ kind: 'text',
154
+ mediaType: 'text/plain',
155
+ sizeBytes: seed.bytes,
156
+ lifetime: 'one_turn',
157
+ provenance: {
158
+ source: CONTINUATION_SEED_SOURCE,
159
+ ...(seed.name ? { label: seed.name } : {}),
160
+ ...(typeof seed.archivedAt === 'number' ? { capturedAt: seed.archivedAt } : {}),
161
+ },
162
+ content: { type: 'text', text: seed.text },
163
+ }
164
+ }
@@ -0,0 +1,24 @@
1
+ import { MAX_DECLARATION_MESSAGE_CHARS } from './declared-status.js'
2
+ import { outcomeFromSdkResult } from './turn-outcome.js'
3
+
4
+ /** Preserve complete message identity without retaining a second raw buffer. */
5
+ export function assistantResponseText(content) {
6
+ if (typeof content === 'string') return content.length <= MAX_DECLARATION_MESSAGE_CHARS ? content : null
7
+ if (!Array.isArray(content)) return null
8
+ const parts = []
9
+ let length = 0
10
+ for (const block of content) {
11
+ if (block?.type !== 'text' || typeof block.text !== 'string') continue
12
+ length += block.text.length
13
+ if (length > MAX_DECLARATION_MESSAGE_CHARS) return null
14
+ parts.push(block.text)
15
+ }
16
+ return parts.join('')
17
+ }
18
+
19
+ /** Declaration eligibility is distinct from user-visible turn outcomes. */
20
+ export function sdkDeclarationEligible(result) {
21
+ const outcome = outcomeFromSdkResult(result)
22
+ return result?.is_error !== true && result?.subtype === 'success'
23
+ && (!outcome || outcome === 'completed')
24
+ }
@@ -28,8 +28,11 @@
28
28
  * file-by-file rationale.
29
29
  */
30
30
  import { existsSync, readFileSync, statSync } from 'fs'
31
+ import { spawnSync } from 'child_process'
31
32
  import { join } from 'path'
32
33
  import { homedir } from 'os'
34
+ import { claudeConfigDir, claudeGlobalConfigPath, parseClaudeConfigText } from './utils/claude-config-dir.js'
35
+ import { configPath } from './config-dir.js'
33
36
 
34
37
  /**
35
38
  * Best-effort probe for `claude login` OAuth state on disk (#3674).
@@ -41,42 +44,142 @@ import { homedir } from 'os'
41
44
  * 1. `~/.claude/auth.json` — current SDK auth file
42
45
  * 2. `~/.claude/.credentials.json` — older Claude Code CLI keystore
43
46
  * 3. `~/.claude.json` — global config; contains a
44
- * `claudeAiOauth` block when the
45
- * user has logged in via subscription
47
+ * `claudeAiOauth` block (older) or an
48
+ * `oauthAccount` block (current) when
49
+ * the user has logged in
50
+ * 4. macOS Keychain — the generic-password item
51
+ * `Claude Code-credentials`, which is
52
+ * where current Claude Code actually
53
+ * stores the credential on darwin
54
+ *
55
+ * #7331: checks 1-3 were file-only and keyed on `claudeAiOauth`, so on a
56
+ * FULLY AUTHENTICATED current macOS install the probe returned false — both
57
+ * files absent, `~/.claude.json` carrying `oauthAccount` instead, and the real
58
+ * credential sitting in the Keychain the probe never looked at. That is not a
59
+ * cosmetic label: `CreateSessionModal` disables the Create button on
60
+ * `auth.ready === false`, so a correctly-logged-in user could not start an SDK
61
+ * session at all, and was silently pushed onto `claude-tui` — the provider that
62
+ * can neither report nor switch models (#7327).
63
+ *
64
+ * The Keychain check tests EXISTENCE ONLY. It never passes `-w`, so the secret
65
+ * is never printed, and stdout/stderr are discarded rather than captured: the
66
+ * daemon has no reason to hold the user's credential in its own memory, and
67
+ * the question being asked is only "is there one".
46
68
  *
47
69
  * Override paths for tests / atypical installs:
48
- * - `CHROXY_CLAUDE_HOME` — overrides the directory for the first two
49
- * file checks AND the default location of
50
- * `.claude.json` (one level up from this dir).
51
- * - `CHROXY_CLAUDE_CONFIG` — overrides the global `.claude.json` path
52
- * directly. Wins over the `CHROXY_CLAUDE_HOME`-
53
- * derived default when both are set.
70
+ * - `CHROXY_CLAUDE_HOME` — overrides the directory for the first two
71
+ * file checks AND the default location of
72
+ * `.claude.json` (one level up from this dir).
73
+ * - `CHROXY_CLAUDE_CONFIG` — overrides the global `.claude.json` path
74
+ * directly. Wins over the `CHROXY_CLAUDE_HOME`-
75
+ * derived default when both are set.
76
+ * - `CHROXY_CLAUDE_KEYCHAIN` — `0` forces the Keychain probe to report
77
+ * absent, `1` forces present. A test cannot
78
+ * delete the developer's real Keychain item, so
79
+ * without this the logged-OUT direction could
80
+ * not be proven on a developer machine — and a
81
+ * probe only ever proven in the `true`
82
+ * direction is exactly as broken as the one
83
+ * this replaces (docs/false-safety-guards.md).
54
84
  */
55
85
  function probeClaudeOAuthCreds() {
56
86
  try {
57
- const claudeHome = process.env.CHROXY_CLAUDE_HOME || join(homedir(), '.claude')
87
+ const claudeHome = process.env.CHROXY_CLAUDE_HOME || claudeConfigDir()
58
88
  if (existsSync(join(claudeHome, 'auth.json'))) return true
59
89
  if (existsSync(join(claudeHome, '.credentials.json'))) return true
60
90
  const globalConfig = process.env.CHROXY_CLAUDE_CONFIG
61
91
  || (process.env.CHROXY_CLAUDE_HOME
62
92
  ? join(process.env.CHROXY_CLAUDE_HOME, '..', '.claude.json')
63
- : join(homedir(), '.claude.json'))
93
+ : claudeGlobalConfigPath())
64
94
  if (existsSync(globalConfig)) {
65
95
  try {
66
- const parsed = JSON.parse(readFileSync(globalConfig, 'utf-8'))
67
- if (parsed && typeof parsed === 'object' && parsed.claudeAiOauth) {
96
+ const parsed = parseClaudeConfigText(readFileSync(globalConfig, 'utf-8'))
97
+ // `claudeAiOauth` is the older shape; current Claude Code writes
98
+ // `oauthAccount` here instead (#7331). Accept either.
99
+ if (parsed && typeof parsed === 'object' && (parsed.claudeAiOauth || parsed.oauthAccount)) {
68
100
  return true
69
101
  }
70
102
  } catch {
71
103
  // Malformed JSON — treat as absent.
72
104
  }
73
105
  }
106
+ if (probeClaudeKeychainCreds()) return true
74
107
  } catch {
75
108
  // Any unexpected fs error → behave as if no creds.
76
109
  }
77
110
  return false
78
111
  }
79
112
 
113
+ /** The macOS Keychain generic-password service Claude Code stores its creds under. */
114
+ const CLAUDE_KEYCHAIN_SERVICE = 'Claude Code-credentials'
115
+
116
+ /**
117
+ * Does the macOS Keychain hold a Claude Code credential? EXISTENCE ONLY.
118
+ *
119
+ * Deliberately never passes `-w` (which would print the secret) and discards
120
+ * all output — the daemon has no reason to hold the user's credential, and the
121
+ * exit code alone answers the question. Non-darwin returns false without
122
+ * spawning anything.
123
+ *
124
+ * A spawn failure (no `security` binary, sandbox denial, a locked Keychain)
125
+ * counts as ABSENT. That is the honest reading: we could not observe a
126
+ * credential, so we must not claim one. It also keeps the failure mode the
127
+ * same as it was before this probe existed.
128
+ */
129
+ function probeClaudeKeychainCreds() {
130
+ const override = process.env.CHROXY_CLAUDE_KEYCHAIN
131
+ if (override === '0') return false
132
+ if (override === '1') return true
133
+ return keychainItemExists(CLAUDE_KEYCHAIN_SERVICE)
134
+ }
135
+
136
+ /**
137
+ * The argv for the existence check, exported so a test can assert what this
138
+ * module is about to hand to `security`.
139
+ *
140
+ * The absent flag is the point: `-w` makes `security` PRINT the password to
141
+ * stdout. Nothing in a readiness probe should be able to do that, and a
142
+ * source-level guard is the only thing standing between "we ask whether a
143
+ * credential exists" and "we pipe the user's credential into the daemon". The
144
+ * override that keeps the unit tests hermetic also means the spawn itself is
145
+ * rarely executed under test, so this shape is pinned directly rather than
146
+ * inferred from behaviour.
147
+ */
148
+ export function claudeKeychainProbeArgv() {
149
+ return ['find-generic-password', '-s', CLAUDE_KEYCHAIN_SERVICE]
150
+ }
151
+
152
+ /**
153
+ * Does a macOS Keychain generic-password item exist for `service`?
154
+ * EXISTENCE ONLY — output is discarded, the secret is never requested.
155
+ *
156
+ * Non-darwin returns false without spawning — an optimisation, not a
157
+ * correctness guard: on a host with no `security` binary the spawn below
158
+ * reports absent anyway.
159
+ *
160
+ * Every failure counts as ABSENT — we could not observe a credential, so we
161
+ * must not claim one. Note WHERE that is enforced, because the obvious reading
162
+ * is wrong: `spawnSync` does NOT throw for a missing binary. MEASURED, it
163
+ * returns `{ status: null, error: ENOENT }`, so it is the `status === 0`
164
+ * comparison that rejects it, not the `catch`. The `catch` is an unreachable
165
+ * backstop kept for a genuinely thrown error; it has no test because nothing
166
+ * observable reaches it, and claiming otherwise would be the exact
167
+ * comment-stronger-than-code shape catalogued in docs/false-safety-guards.md.
168
+ */
169
+ export function keychainItemExists(service) {
170
+ if (process.platform !== 'darwin') return false
171
+ try {
172
+ const result = spawnSync(
173
+ 'security',
174
+ ['find-generic-password', '-s', service],
175
+ { stdio: 'ignore', timeout: 5_000 },
176
+ )
177
+ return result.status === 0
178
+ } catch {
179
+ return false
180
+ }
181
+ }
182
+
80
183
  /**
81
184
  * Best-effort probe for `codex login` OAuth state on disk (#4301).
82
185
  *
@@ -153,7 +256,11 @@ function _cachedProbe(slot, key, probe) {
153
256
  }
154
257
 
155
258
  export function hasClaudeOAuthCreds() {
259
+ // The Keychain override is part of the key: without it a test that flips
260
+ // CHROXY_CLAUDE_KEYCHAIN inside the 5s TTL would silently read the previous
261
+ // verdict, and the logged-out assertion would pass for the wrong reason.
156
262
  const key = `${process.env.CHROXY_CLAUDE_HOME ?? ''}|${process.env.CHROXY_CLAUDE_CONFIG ?? ''}`
263
+ + `|${process.env.CHROXY_CLAUDE_KEYCHAIN ?? ''}`
157
264
  return _cachedProbe('claude', key, probeClaudeOAuthCreds)
158
265
  }
159
266
 
@@ -218,7 +325,7 @@ const _SLOT_ENV_VAR = {
218
325
  */
219
326
  export function cachedResolveCredentialFile(slot, envValue, resolve, envVarName) {
220
327
  const entry = _credFileCache[slot] || _EMPTY_CRED_FILE_SLOT
221
- const credPath = join(homedir(), '.chroxy', 'credentials.json')
328
+ const credPath = configPath('credentials.json')
222
329
 
223
330
  if (typeof envValue === 'string' && envValue.length > 0) {
224
331
  if (entry.envValue === envValue && entry.path === null && entry.result) {
@@ -306,6 +306,33 @@ export class BackgroundShellTracker {
306
306
  }
307
307
  }
308
308
 
309
+ /**
310
+ * #7611: forget EVERY pending shell, but leave the tracker usable.
311
+ *
312
+ * For the moment the process that owned the shells is gone while the session
313
+ * lives on (a respawn that signalled its whole process tree, #7608). Nothing
314
+ * can ever poll those shells or hear their completion again, and the entries
315
+ * would otherwise pin `size` — and with it the session's `isRunning` — above
316
+ * zero until the hard-quiesce reap, four hours later (`BACKGROUND_SHELL_HARD_
317
+ * QUIESCE_MS`), keeping the session immune to the idle timeout.
318
+ *
319
+ * Not `destroy()`: that is the end-of-session teardown. This is the same
320
+ * state as if each shell had been cleared one by one — the sweep is stopped
321
+ * (it re-arms on the next `trackBackgroundShell`) and the dashboard banner is
322
+ * told, once, with the empty snapshot. A tracker with nothing pending is a
323
+ * no-op, so no `background_work_changed` is emitted for an idle respawn.
324
+ *
325
+ * @returns {number} how many pending shells were forgotten
326
+ */
327
+ clearAll() {
328
+ const forgotten = this._pendingBackgroundShells.size
329
+ if (forgotten === 0) return 0
330
+ this._pendingBackgroundShells.clear()
331
+ this._stopBackgroundShellSweep()
332
+ this._emitBackgroundWorkChanged()
333
+ return forgotten
334
+ }
335
+
309
336
  /**
310
337
  * #4307: stop the sweep and clear the pending map on session destroy. The
311
338
  * session-level companions (`_pendingBackgroundCommands`, the activity