@chroxy/server 0.10.0 → 0.11.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 (160) hide show
  1. package/CONFIG.md +411 -14
  2. package/hooks/permission-hook.sh +253 -3
  3. package/package.json +8 -15
  4. package/sidecar/node_modules/.package-lock.json +29 -0
  5. package/sidecar/node_modules/ws/LICENSE +20 -0
  6. package/sidecar/node_modules/ws/README.md +548 -0
  7. package/sidecar/node_modules/ws/browser.js +8 -0
  8. package/sidecar/node_modules/ws/index.js +22 -0
  9. package/sidecar/node_modules/ws/lib/buffer-util.js +131 -0
  10. package/sidecar/node_modules/ws/lib/constants.js +19 -0
  11. package/sidecar/node_modules/ws/lib/event-target.js +292 -0
  12. package/sidecar/node_modules/ws/lib/extension.js +203 -0
  13. package/sidecar/node_modules/ws/lib/limiter.js +55 -0
  14. package/sidecar/node_modules/ws/lib/permessage-deflate.js +528 -0
  15. package/sidecar/node_modules/ws/lib/receiver.js +706 -0
  16. package/sidecar/node_modules/ws/lib/sender.js +602 -0
  17. package/sidecar/node_modules/ws/lib/stream.js +161 -0
  18. package/sidecar/node_modules/ws/lib/subprotocol.js +62 -0
  19. package/sidecar/node_modules/ws/lib/validation.js +152 -0
  20. package/sidecar/node_modules/ws/lib/websocket-server.js +554 -0
  21. package/sidecar/node_modules/ws/lib/websocket.js +1393 -0
  22. package/sidecar/node_modules/ws/package.json +70 -0
  23. package/sidecar/node_modules/ws/wrapper.mjs +21 -0
  24. package/src/base-session.js +151 -6
  25. package/src/billing-budget.js +5 -1
  26. package/src/binary-provenance-trust.js +95 -0
  27. package/src/built-in-tools/file-ops.js +5 -4
  28. package/src/byok-mcp-client.js +1061 -13
  29. package/src/byok-mcp-config.js +1201 -4
  30. package/src/byok-mcp-fleet.js +374 -29
  31. package/src/byok-mcp-oauth-store.js +327 -0
  32. package/src/byok-mcp-oauth.js +635 -0
  33. package/src/byok-mcp-trust.js +254 -37
  34. package/src/byok-session.js +789 -13
  35. package/src/byok-tool-executor.js +20 -13
  36. package/src/checkpoint-manager.js +33 -6
  37. package/src/chroxy-host-metadata.js +122 -0
  38. package/src/claude-stream-parser.js +56 -0
  39. package/src/claude-tui/pty-driver.js +54 -14
  40. package/src/claude-tui-session.js +106 -7
  41. package/src/cli/config-cmd.js +2 -2
  42. package/src/cli/deploy-cmd.js +1 -1
  43. package/src/cli/init-cmd.js +1 -1
  44. package/src/cli/providers-cmd.js +3 -3
  45. package/src/cli/schedule-cmd.js +775 -0
  46. package/src/cli/server-cmd.js +16 -1
  47. package/src/cli/service-cmd.js +39 -19
  48. package/src/cli/shared.js +7 -4
  49. package/src/cli/tokens-cmd.js +213 -0
  50. package/src/cli/tunnel-cmd.js +1 -1
  51. package/src/cli-session.js +66 -10
  52. package/src/cli.js +4 -0
  53. package/src/codex-app-server-session.js +671 -39
  54. package/src/codex-session.js +121 -18
  55. package/src/config.js +453 -27
  56. package/src/control-room/integrations.js +16 -10
  57. package/src/control-room/skills-inventory.js +6 -1
  58. package/src/control-room/survey.js +32 -0
  59. package/src/credential-store.js +256 -10
  60. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
  61. package/src/diagnostics.js +3 -0
  62. package/src/docker-sdk-session.js +16 -1
  63. package/src/docker-session.js +9 -0
  64. package/src/doctor.js +19 -8
  65. package/src/environments/backends/docker.js +8 -0
  66. package/src/environments/backends/k8s.js +9 -0
  67. package/src/event-ingest.js +19 -1
  68. package/src/event-normalizer.js +354 -19
  69. package/src/external-session-registry.js +0 -0
  70. package/src/gemini-session.js +19 -2
  71. package/src/github-webhook.js +188 -4
  72. package/src/handler-utils.js +42 -8
  73. package/src/handlers/checkpoint-handlers.js +126 -19
  74. package/src/handlers/control-room-handlers.js +48 -18
  75. package/src/handlers/conversation-handlers.js +127 -2
  76. package/src/handlers/credential-handlers.js +43 -2
  77. package/src/handlers/file-handlers.js +47 -3
  78. package/src/handlers/github-webhook-handlers.js +204 -0
  79. package/src/handlers/input-handlers.js +4 -0
  80. package/src/handlers/orchestration-handlers.js +238 -0
  81. package/src/handlers/scheduler-handlers.js +510 -0
  82. package/src/handlers/session-handlers.js +10 -2
  83. package/src/handlers/settings-handlers.js +510 -11
  84. package/src/handlers/token-handlers.js +11 -2
  85. package/src/http-routes.js +159 -0
  86. package/src/jsonl-reader.js +60 -6
  87. package/src/jsonl-subprocess-session.js +35 -6
  88. package/src/keychain.js +159 -12
  89. package/src/logger.js +182 -19
  90. package/src/notification-prefs.js +88 -6
  91. package/src/notifications/discord-webhook-sink.js +30 -1
  92. package/src/orchestration/build-manager.js +56 -0
  93. package/src/orchestration/decision-contract.js +245 -0
  94. package/src/orchestration/git-ops.js +347 -0
  95. package/src/orchestration/orchestration-manager.js +1295 -0
  96. package/src/orchestration/permission-gate.js +109 -0
  97. package/src/orchestration/role-prompts.js +136 -0
  98. package/src/orchestration/run-budget.js +81 -0
  99. package/src/orchestration/run-ledger.js +487 -0
  100. package/src/orchestration/run-model.js +205 -0
  101. package/src/orchestration/run-record.js +336 -0
  102. package/src/orchestration/run-report.js +194 -0
  103. package/src/orchestration/to-wire.js +201 -0
  104. package/src/orchestration/turn-driver.js +398 -0
  105. package/src/pairing.js +146 -1
  106. package/src/permission-audit.js +79 -3
  107. package/src/permission-floor.js +455 -0
  108. package/src/permission-manager.js +492 -40
  109. package/src/permission-resolver.js +55 -7
  110. package/src/permission-rule-store.js +411 -0
  111. package/src/platform.js +367 -23
  112. package/src/providers.js +21 -2
  113. package/src/schedule-parser.js +311 -0
  114. package/src/scheduled-task-store.js +653 -0
  115. package/src/scheduler.js +1029 -0
  116. package/src/sdk-session.js +338 -5
  117. package/src/server-cli/server-orchestrator.js +23 -0
  118. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  119. package/src/server-cli.js +238 -26
  120. package/src/server-identity.js +28 -4
  121. package/src/service.js +291 -33
  122. package/src/session-manager.js +417 -25
  123. package/src/session-message-history.js +27 -21
  124. package/src/session-title.js +168 -0
  125. package/src/session-token-store.js +60 -35
  126. package/src/skills-usage.js +20 -2
  127. package/src/statusline.js +584 -0
  128. package/src/subagent-counter.js +9 -1
  129. package/src/supervisor.js +77 -27
  130. package/src/token-manager.js +39 -9
  131. package/src/transcript-tasks.js +41 -6
  132. package/src/tunnel/cloudflare.js +115 -8
  133. package/src/tunnel/index.js +4 -1
  134. package/src/tunnel-check.js +1 -1
  135. package/src/turn-tracker.js +0 -0
  136. package/src/usage-normalize.js +118 -0
  137. package/src/user-shell-session.js +98 -32
  138. package/src/utils/componentwise-resolver.js +205 -0
  139. package/src/utils/composite-key.js +45 -0
  140. package/src/utils/iso-datetime.js +51 -0
  141. package/src/utils/preflight.js +140 -28
  142. package/src/utils/spawn-env.js +8 -2
  143. package/src/utils/verify-binary.js +276 -0
  144. package/src/utils/verify-provenance.js +241 -0
  145. package/src/utils/wire-counters.js +48 -0
  146. package/src/worktree-gc.js +4 -1
  147. package/src/ws-file-ops/browser.js +42 -11
  148. package/src/ws-file-ops/common.js +68 -1
  149. package/src/ws-file-ops/git.js +221 -3
  150. package/src/ws-file-ops/index.js +5 -0
  151. package/src/ws-file-ops/memory.js +358 -0
  152. package/src/ws-file-ops/reader.js +124 -0
  153. package/src/ws-forwarding.js +44 -16
  154. package/src/ws-handler-context.js +19 -0
  155. package/src/ws-history.js +84 -11
  156. package/src/ws-message-handlers.js +6 -0
  157. package/src/ws-outbound-schemas.js +207 -0
  158. package/src/ws-permissions.js +285 -4
  159. package/src/ws-schemas.js +1 -0
  160. package/src/ws-server.js +301 -17
@@ -9,17 +9,18 @@
9
9
  * the session is in `auto` mode which auto-approves). We don't do
10
10
  * permission gating in here; this module is execution only.
11
11
  *
12
- * Path safety is enforced for file tools by validatePathWithinCwd from
13
- * ws-file-ops/common.js — every file_path is realpath-ed and confirmed
14
- * to be inside the session cwd before any read/write happens. Symlink
15
- * escapes are blocked by the realpath-of-deepest-ancestor pattern there
16
- * (see common.js + the 2026-04-11 production-readiness audit).
12
+ * Path safety is enforced for file tools by validateRawPathWithinCwd from
13
+ * ws-file-ops/common.js — every file_path is resolved COMPONENT BY COMPONENT
14
+ * (open(2)-faithfully) and confirmed to be inside the session cwd before any
15
+ * read/write happens. Symlink escapes — including a `..` that follows a
16
+ * symlinked component (#6923) — are blocked by walking the RAW path rather than
17
+ * a pre-`resolve()`d one (see common.js + the 2026-04-11 production-readiness
18
+ * audit).
17
19
  */
18
20
 
19
- import { resolve, isAbsolute } from 'node:path'
20
21
  import { isIP } from 'node:net'
21
22
  import { lookup as dnsLookup } from 'node:dns/promises'
22
- import { validatePathWithinCwd } from './ws-file-ops/common.js'
23
+ import { validateRawPathWithinCwd } from './ws-file-ops/common.js'
23
24
  import { executeBash, DEFAULT_BASH_TIMEOUT_MS } from './built-in-tools/bash-exec.js'
24
25
  import { readFileTool, writeFileTool, editFileTool } from './built-in-tools/file-ops.js'
25
26
  import {
@@ -140,9 +141,14 @@ async function safeResolve(filePath, cwd, cwdRealCache, cwdCacheTtl) {
140
141
  if (typeof filePath !== 'string' || filePath.length === 0) {
141
142
  throw Object.assign(new Error('file_path is required'), { code: 'EINVAL' })
142
143
  }
143
- const absolute = isAbsolute(filePath) ? filePath : resolve(cwd, filePath)
144
- const { valid, realPath, cwdReal } = await validatePathWithinCwd(
145
- absolute,
144
+ // #6923 — hand the RAW filePath (its `..` intact) to the component-wise walker.
145
+ // Do NOT pre-`resolve(cwd, filePath)`: `resolve()` collapses a `..` that follows
146
+ // a symlinked component LEXICALLY, so `link/../x` cancelled the symlink before it
147
+ // was followed and an escape via a symlink-out-of-workspace + `..` looked in
148
+ // bounds. validateRawPathWithinCwd walks the raw path open(2)-faithfully so the
149
+ // true (escaping) destination is seen and rejected.
150
+ const { valid, realPath, cwdReal } = await validateRawPathWithinCwd(
151
+ filePath,
146
152
  cwd,
147
153
  cwdRealCache,
148
154
  cwdCacheTtl,
@@ -323,9 +329,10 @@ async function runGrep({ input, cwd, cwdRealCache, cwdCacheTtl, signal }) {
323
329
  */
324
330
  async function safeResolveRoot(p, cwd, cwdRealCache, cwdCacheTtl) {
325
331
  if (typeof p !== 'string' || p.length === 0) return cwd
326
- const absolute = isAbsolute(p) ? p : resolve(cwd, p)
327
- const { valid, realPath, cwdReal } = await validatePathWithinCwd(
328
- absolute,
332
+ // #6923 — pass the RAW path; see safeResolve for why pre-`resolve()` is unsafe
333
+ // (lexical `..` collapse hides a symlink+`..` escape).
334
+ const { valid, realPath, cwdReal } = await validateRawPathWithinCwd(
335
+ p,
329
336
  cwd,
330
337
  cwdRealCache,
331
338
  cwdCacheTtl,
@@ -62,8 +62,21 @@ async function acquireCwdLock(cwd) {
62
62
  * This avoids touching the shared stash stack, making concurrent sessions
63
63
  * in the same repository safe.
64
64
  *
65
- * Rewind creates a new session that resumes from the checkpoint's
66
- * conversation ID, effectively branching the conversation.
65
+ * The manager owns the git snapshot and the checkpoint metadata only. It does
66
+ * NOT branch the conversation itself — that is decided at restore time by the
67
+ * WS handler based on the session's provider (#6766): for a fork-capable
68
+ * provider (the SDK, via `forkSession`/`upToMessageId`) restore forks the
69
+ * conversation truncated to the checkpoint's `boundaryMessageId`, so the
70
+ * rewound session's transcript stops at the checkpoint. For providers that
71
+ * cannot truncate a resumed transcript the restore is files-only. The
72
+ * `boundaryMessageId` captured here is what makes that truncation possible.
73
+ *
74
+ * #6767: selective restore (files / conversation / both) is orchestrated by the
75
+ * WS handler, not this manager. `restoreCheckpoint` always performs the git
76
+ * restore (used for the 'files' and 'both' modes); the 'conversation'-only mode
77
+ * reads the checkpoint via `getCheckpoint` instead so the working tree is left
78
+ * untouched. Either way the returned record carries `resumeSessionId` +
79
+ * `boundaryMessageId` for the handler's fork decision.
67
80
  */
68
81
  export class CheckpointManager extends EventEmitter {
69
82
  /**
@@ -103,9 +116,13 @@ export class CheckpointManager extends EventEmitter {
103
116
  * @param {string} [params.name] - User-provided checkpoint name
104
117
  * @param {string} [params.description] - Auto-generated description (e.g., last message)
105
118
  * @param {number} [params.messageCount] - Number of messages at checkpoint time
119
+ * @param {string} [params.boundaryMessageId] - #6766: the SDK transcript UUID
120
+ * marking this checkpoint's conversation boundary. When present (SDK
121
+ * provider), restore forks the conversation truncated up to and including
122
+ * this message; absent → the restore is files-only for this checkpoint.
106
123
  * @returns {Promise<object>} The created checkpoint
107
124
  */
108
- async createCheckpoint({ sessionId, resumeSessionId, cwd, name, description, messageCount }) {
125
+ async createCheckpoint({ sessionId, resumeSessionId, cwd, name, description, messageCount, boundaryMessageId }) {
109
126
  const checkpoints = this._getCheckpoints(sessionId)
110
127
 
111
128
  // Enforce max checkpoints — remove oldest if at limit
@@ -126,6 +143,10 @@ export class CheckpointManager extends EventEmitter {
126
143
  name: name || `Checkpoint ${(this._counters.get(sessionId) || 0) + 1}`,
127
144
  description: description || '',
128
145
  messageCount: messageCount || 0,
146
+ // #6766: fork boundary for a true conversation rewind at restore. Stored
147
+ // as null when the provider can't supply one (subprocess providers) so a
148
+ // restore of that checkpoint honestly degrades to files-only.
149
+ boundaryMessageId: typeof boundaryMessageId === 'string' && boundaryMessageId ? boundaryMessageId : null,
129
150
  createdAt: Date.now(),
130
151
  gitRef: null,
131
152
  }
@@ -193,11 +214,17 @@ export class CheckpointManager extends EventEmitter {
193
214
 
194
215
  /**
195
216
  * Restore file state from a checkpoint's git snapshot.
196
- * Does NOT restore conversation state — that requires creating a new session
197
- * with the checkpoint's resumeSessionId (handled by session-manager).
217
+ *
218
+ * This restores the working tree only. The conversation side of a rewind is
219
+ * the WS restore handler's responsibility (#6766): it reads the returned
220
+ * `resumeSessionId` + `boundaryMessageId` and, for a fork-capable provider,
221
+ * forks the conversation truncated to the boundary; otherwise it resumes
222
+ * files-only. Kept here so the git snapshot and the conversation decision stay
223
+ * decoupled across providers.
198
224
  * @param {string} sessionId
199
225
  * @param {string} checkpointId
200
- * @returns {Promise<object>} The checkpoint data (including resumeSessionId)
226
+ * @returns {Promise<object>} The checkpoint data (including resumeSessionId
227
+ * and boundaryMessageId)
201
228
  */
202
229
  async restoreCheckpoint(sessionId, checkpointId) {
203
230
  const checkpoint = this.getCheckpoint(sessionId, checkpointId)
@@ -0,0 +1,122 @@
1
+ /**
2
+ * chroxy-host-metadata — the identity of the Chroxy host that launched an agent
3
+ * session (#6633).
4
+ *
5
+ * Agents (Claude, Codex, Gemini, …) previously could not answer "what Chroxy
6
+ * build am I running in?" without guessing from screenshots or the checked-out
7
+ * repo. This module computes a small, non-sensitive identity block and exposes
8
+ * it as `CHROXY_HOST_*` environment variables, which are injected into every
9
+ * agent's process environment (see `buildSpawnEnv` for subprocess providers and
10
+ * the server startup `Object.assign(process.env, …)` for the in-process SDK). A
11
+ * session can then read e.g. `$CHROXY_HOST_VERSION` from a Bash tool call.
12
+ *
13
+ * The values are COMPUTED here (version from this package's package.json, git
14
+ * identity via `git`), never passed through from the operator's shell — so they
15
+ * are authoritative and can't be spoofed by a stray `CHROXY_HOST_*` export.
16
+ */
17
+ import { execFileSync } from 'node:child_process'
18
+ import { readFileSync } from 'node:fs'
19
+ import { dirname, join } from 'node:path'
20
+ import { fileURLToPath } from 'node:url'
21
+
22
+ // A synchronous read is fine: the file is tiny and never changes mid-process,
23
+ // and getChroxyHostEnv memoizes the result so this runs at most once on demand
24
+ // (mirrors byok-mcp-client's readPackageVersion). Never block on a
25
+ // missing/unreadable package.json — fall back to a sentinel.
26
+ function readPackageVersion() {
27
+ try {
28
+ const here = dirname(fileURLToPath(import.meta.url))
29
+ const raw = readFileSync(join(here, '..', 'package.json'), 'utf8')
30
+ const parsed = JSON.parse(raw)
31
+ if (typeof parsed?.version === 'string' && parsed.version.length > 0) {
32
+ return parsed.version
33
+ }
34
+ } catch {
35
+ // Fall through — identity should degrade gracefully, never crash a spawn.
36
+ }
37
+ return '0.0.0'
38
+ }
39
+
40
+ /**
41
+ * Best-effort git identity for dev builds. A released npm/tarball install has no
42
+ * `.git`, so this returns `{}` there. Guarded and time-boxed — computing host
43
+ * identity must never block or fail a session spawn.
44
+ *
45
+ * Only a chroxy SOURCE checkout reports git identity. When chroxy is installed as
46
+ * a dependency (`…/node_modules/chroxy/…`), `git rev-parse` would otherwise walk
47
+ * up to the USER's project `.git` and mislabel the build `dev` while leaking the
48
+ * user's branch/SHA into third-party (codex/gemini) subprocesses. The
49
+ * node_modules guard makes that impossible — an installed chroxy is `release`.
50
+ *
51
+ * @param {typeof execFileSync} [exec] - injectable for tests
52
+ * @param {string} [moduleDir] - injectable module directory (for tests)
53
+ * @returns {{ sha?: string, branch?: string }}
54
+ */
55
+ export function readGitIdentity(exec = execFileSync, moduleDir = dirname(fileURLToPath(import.meta.url))) {
56
+ // Installed-as-a-dependency → never inspect the surrounding repo's git.
57
+ if (moduleDir.split(/[/\\]/).includes('node_modules')) return {}
58
+ const cwd = moduleDir
59
+ const run = (args) => String(exec('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 2000 })).trim()
60
+ try {
61
+ const sha = run(['rev-parse', '--short', 'HEAD'])
62
+ if (!sha) return {}
63
+ const out = { sha }
64
+ try {
65
+ const branch = run(['rev-parse', '--abbrev-ref', 'HEAD'])
66
+ // 'HEAD' means detached — no meaningful branch name to report.
67
+ if (branch && branch !== 'HEAD') out.branch = branch
68
+ } catch {
69
+ // No branch is fine; the SHA alone still identifies the build.
70
+ }
71
+ return out
72
+ } catch {
73
+ return {}
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Build the `CHROXY_HOST_*` identity map. Pure — every source is either read
79
+ * fresh or injected, so tests can pin each field without mocking modules.
80
+ *
81
+ * @param {object} [opts]
82
+ * @param {string} [opts.version] - override the package version
83
+ * @param {{ sha?: string, branch?: string }} [opts.git] - override git identity
84
+ * @param {string} [opts.platform] - override process.platform
85
+ * @param {string} [opts.node] - override the node version
86
+ * @param {number|string} [opts.pid] - override the process id
87
+ * @returns {Record<string, string>} string-valued env map (git keys omitted when absent)
88
+ */
89
+ export function buildChroxyHostEnv({ version, git, platform, node, pid } = {}) {
90
+ const g = git ?? readGitIdentity()
91
+ const env = {
92
+ CHROXY_HOST_APP: 'Chroxy',
93
+ CHROXY_HOST_VERSION: version ?? readPackageVersion(),
94
+ // A git SHA means we're running from a working tree → a dev/local build;
95
+ // its absence means a packaged release.
96
+ CHROXY_HOST_CHANNEL: g.sha ? 'dev' : 'release',
97
+ CHROXY_HOST_PLATFORM: platform ?? process.platform,
98
+ CHROXY_HOST_NODE: node ?? process.versions.node,
99
+ CHROXY_HOST_PID: String(pid ?? process.pid),
100
+ }
101
+ if (g.sha) env.CHROXY_HOST_GIT_SHA = g.sha
102
+ if (g.branch) env.CHROXY_HOST_GIT_BRANCH = g.branch
103
+ return env
104
+ }
105
+
106
+ // Memoized per-process view. Git/version don't change mid-run, so compute once
107
+ // and reuse across every spawn.
108
+ let _cache = null
109
+
110
+ /**
111
+ * The memoized `CHROXY_HOST_*` map for this process.
112
+ * @returns {Record<string, string>}
113
+ */
114
+ export function getChroxyHostEnv() {
115
+ if (!_cache) _cache = buildChroxyHostEnv()
116
+ return _cache
117
+ }
118
+
119
+ /** Test seam: drop the memoized value so a test can re-derive it. */
120
+ export function _resetChroxyHostEnvCacheForTest() {
121
+ _cache = null
122
+ }
@@ -27,6 +27,16 @@
27
27
  * the wire schema (`ServerToolStartSchema.toolUseId: z.string()`)
28
28
  * holds even on the defensive fallback path when `content_block.id`
29
29
  * is absent.
30
+ *
31
+ * parseCompactBoundaryMeta(compactMetadata)
32
+ * -> { trigger, preTokens, postTokens, durationMs }
33
+ * #6768: camelCases a `compact_boundary` system event's
34
+ * `compact_metadata` for the wire `message.compactMetadata` field.
35
+ *
36
+ * formatCompactBoundaryContent(meta)
37
+ * -> string
38
+ * #6768: human-readable fallback `content` text for clients that
39
+ * don't render `compactMetadata` as a dedicated marker.
30
40
  */
31
41
 
32
42
  import { parseMcpToolName } from './mcp-tools.js'
@@ -104,3 +114,49 @@ export function buildToolStartData(messageId, contentBlock) {
104
114
  if (mcp) data.serverName = mcp.serverName
105
115
  return data
106
116
  }
117
+
118
+ /**
119
+ * #6768 — parse a `compact_boundary` system event's `compact_metadata` into
120
+ * the camelCase shape carried on the wire `message` event's
121
+ * `compactMetadata` field. Both providers receive the same
122
+ * `SDKCompactBoundaryMessage.compact_metadata` shape (the CLI's
123
+ * `--output-format stream-json` mirrors the SDK's message types — see
124
+ * `@anthropic-ai/claude-agent-sdk/sdk.d.ts` `SDKCompactBoundaryMessage`), so
125
+ * this is a pure function shared by both session drivers to keep field
126
+ * names / fallback values from drifting between them.
127
+ *
128
+ * Numeric fields fall back to `null` (not `undefined`) when missing or
129
+ * non-finite so the wire payload always has a stable shape; `trigger`
130
+ * defaults to `'auto'` for any value other than the literal `'manual'`
131
+ * (matches the SDK's `'manual' | 'auto'` union — an unrecognized value is
132
+ * more likely a spontaneous auto-compaction than a user-issued `/compact`).
133
+ *
134
+ * @param {{ trigger?: string, pre_tokens?: number, post_tokens?: number, duration_ms?: number }} [compactMetadata]
135
+ * @returns {{ trigger: 'manual'|'auto', preTokens: number|null, postTokens: number|null, durationMs: number|null }}
136
+ */
137
+ export function parseCompactBoundaryMeta(compactMetadata) {
138
+ const meta = compactMetadata || {}
139
+ const asFiniteNumber = (value) => (typeof value === 'number' && Number.isFinite(value) ? value : null)
140
+ return {
141
+ trigger: meta.trigger === 'manual' ? 'manual' : 'auto',
142
+ preTokens: asFiniteNumber(meta.pre_tokens),
143
+ postTokens: asFiniteNumber(meta.post_tokens),
144
+ durationMs: asFiniteNumber(meta.duration_ms),
145
+ }
146
+ }
147
+
148
+ /**
149
+ * #6768 — human-readable fallback text for the `compact_boundary` system
150
+ * `message` envelope's `content` field, used by any client that doesn't yet
151
+ * understand `compactMetadata` (older dashboard/app builds render `content`
152
+ * as a plain muted system bubble).
153
+ *
154
+ * @param {{ trigger: 'manual'|'auto', preTokens: number|null, postTokens: number|null }} meta
155
+ * @returns {string}
156
+ */
157
+ export function formatCompactBoundaryContent(meta) {
158
+ if (meta.preTokens != null && meta.postTokens != null) {
159
+ return `Context compacted (${meta.trigger}): ${meta.preTokens.toLocaleString()} → ${meta.postTokens.toLocaleString()} tokens`
160
+ }
161
+ return `Context compacted (${meta.trigger})`
162
+ }
@@ -8,13 +8,18 @@
8
8
  // methods live on `PtyDriverMixin` and are copied onto ClaudeTuiSession.prototype
9
9
  // via applyMixin() in claude-tui-session.js, so `this` still refers to the
10
10
  // session instance and every `this._*` / static reference resolves as before.
11
- import { existsSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'fs'
11
+ import { existsSync, readFileSync, realpathSync, statSync, writeFileSync } from 'fs'
12
12
  import { homedir } from 'os'
13
13
  import { dirname, join, resolve } from 'path'
14
14
  import { fileURLToPath } from 'url'
15
- import { randomUUID } from 'crypto'
16
15
  import { resolveBinary } from '../utils/resolve-binary.js'
17
16
  import { createLogger } from '../logger.js'
17
+ // #7002/#7046 — the ONE writer for `~/.claude.json`. Deliberately shared with the
18
+ // BYOK MCP add/remove path rather than re-implemented here: a second hand-rolled
19
+ // `writeFileSync(tmp)` → `renameSync(tmp, ~/.claude.json)` is exactly how the
20
+ // symlink-destroying, mode-widening bug survived in two places at once. Any new
21
+ // caller that writes this file MUST come through here too.
22
+ import { writeClaudeConfigAtomic } from '../byok-mcp-config.js'
18
23
  // Imported at call-time only (circular-safe): the writer methods read the
19
24
  // PROMPT_CHAR_DELAY_MS / MAX_THROTTLED_CHARS static getters off the class.
20
25
  import { ClaudeTuiSession } from '../claude-tui-session.js'
@@ -87,13 +92,26 @@ export function formatHexDump(input, maxBytes) {
87
92
  return `${header}\n${lines.join('\n')}`
88
93
  }
89
94
 
90
- export const CLAUDE = resolveBinary('claude', [
95
+ // Well-known fallback locations for the `claude` binary. Under a GUI launch
96
+ // (e.g. Tauri on macOS) PATH is minimal and may exclude the user's install dir.
97
+ export const CLAUDE_BINARY_CANDIDATES = [
91
98
  join(homedir(), '.local/bin/claude'),
92
99
  '/opt/homebrew/bin/claude',
93
100
  '/usr/local/bin/claude',
94
101
  join(homedir(), '.claude/local/node_modules/.bin/claude'),
95
102
  join(homedir(), '.npm-global/bin/claude'),
96
- ])
103
+ ]
104
+
105
+ // Re-resolve fresh on each call (NOT a frozen module-load const) so a binary
106
+ // quarantined / moved / reinstalled after daemon start is spawned from its
107
+ // CURRENT path — and matches what preflight verified (#6708 defect #3).
108
+ export function resolveClaudeBinary() {
109
+ return resolveBinary('claude', CLAUDE_BINARY_CANDIDATES)
110
+ }
111
+
112
+ // Back-compat: kept as a lazy-resolved snapshot for any consumer that still
113
+ // imports the constant. Prefer `resolveClaudeBinary()` at spawn time.
114
+ export const CLAUDE = resolveClaudeBinary()
97
115
 
98
116
  // #5321 (WP-4.1) — subscription-auth failure detection. claude-tui routes via
99
117
  // the OAuth subscription (ANTHROPIC_API_KEY is deleted from the spawn env), so a
@@ -124,13 +142,27 @@ export const AUTH_REQUIRED_MESSAGE = 'Claude is not logged in (or the subscripti
124
142
  // block headless spawn. The dialog is interactive-only — without this, the
125
143
  // PTY would render "Is this a project you trust?" and wait for Enter.
126
144
  // Idempotent: if already trusted, no write.
145
+ //
146
+ // NOTE the path is `homedir()/.claude.json`, NOT `defaultClaudeConfigPath()`:
147
+ // the point of this write is to be read by the `claude` binary we are about to
148
+ // spawn, and it only ever reads `$HOME/.claude.json`. `CHROXY_CLAUDE_CONFIG`
149
+ // redirects chroxy's own MCP-config reads, so honouring it here would silently
150
+ // send the trust flags to a file claude never opens.
127
151
  export function ensureCwdTrusted(cwd) {
128
152
  const realCwd = realpathSync(cwd)
129
153
  const claudeConfig = join(homedir(), '.claude.json')
130
154
  let config = {}
155
+ // #7046: PRESERVE the destination's permissions. This write used to call
156
+ // `writeFileSync(tmp, ...)` with no `mode` and never chmod the sidecar, so the
157
+ // rename left `0666 & ~umask` (0644 under the usual umask) on a file that holds
158
+ // OAuth material — chroxy actively WIDENING a 0600 config on every start() that
159
+ // pre-trusts a cwd. `null` means "we are creating the file", and the shared
160
+ // writer then uses 0600.
161
+ let mode = null
131
162
  if (existsSync(claudeConfig)) {
132
163
  try {
133
164
  config = JSON.parse(readFileSync(claudeConfig, 'utf8'))
165
+ mode = statSync(claudeConfig).mode & 0o777
134
166
  } catch (err) {
135
167
  log.warn(`~/.claude.json unreadable, skipping trust pre-write: ${err.message}`)
136
168
  return
@@ -157,16 +189,24 @@ export function ensureCwdTrusted(cwd) {
157
189
  hasCompletedProjectOnboarding: true,
158
190
  projectOnboardingSeenCount: existing?.projectOnboardingSeenCount ?? 0,
159
191
  }
160
- // Atomic write via temp + rename. Use a per-call random suffix rather
161
- // than process.pid — concurrent ClaudeTuiSessions in the same chroxy
162
- // server share the pid, so two start()s racing for a different cwd
163
- // would clobber each other's temp file (#3922). The realpathSync()
164
- // earlier in this function still means each session writes a
165
- // different *target* path, but the temp file is global and needs to
166
- // be unique per write.
167
- const tmp = `${claudeConfig}.chroxy.${randomUUID()}.tmp`
168
- writeFileSync(tmp, JSON.stringify(config, null, 2))
169
- renameSync(tmp, claudeConfig)
192
+ // #7046: through the SHARED atomic writer, which (a) writes THROUGH a symlinked
193
+ // `~/.claude.json` instead of replacing the user's dotfiles link with a regular
194
+ // file, (b) preserves the mode we captured above rather than widening it, (c)
195
+ // still uses a per-call random sidecar suffix — concurrent ClaudeTuiSessions in
196
+ // one daemon share a pid and would race for the same temp path (#3922) — and
197
+ // (d) unlinks that sidecar if the rename throws, so a failed write cannot leave
198
+ // a full credential-bearing copy of the config lying in $HOME (#4463).
199
+ //
200
+ // Best-effort, like the unreadable-config branch above: a REFUSAL (a link we
201
+ // will not follow — dangling, non-regular, foreign-uid) or an I/O failure warns
202
+ // and skips the pre-write instead of failing session start. The degraded outcome
203
+ // is claude rendering its trust dialog; the alternative — destroying the link —
204
+ // is strictly worse.
205
+ try {
206
+ writeClaudeConfigAtomic(claudeConfig, config, { mode })
207
+ } catch (err) {
208
+ log.warn(`~/.claude.json not written, skipping trust pre-write: ${err.message}`)
209
+ }
170
210
  }
171
211
 
172
212
  // Build a settings.json that registers Stop + tool hooks. Claude pipes the
@@ -14,9 +14,15 @@ import { CLAUDE_TUI_PTY_SIZE } from '@chroxy/protocol'
14
14
  // (RESUME_UNKNOWN_STDERR_PATTERNS, #4929/#4950) via this matcher: the PTY
15
15
  // merges stdout+stderr, so claude's resume rejection lands in _outputTail.
16
16
  import { stderrIndicatesUnknownResume } from './cli-session.js'
17
+ // #6820 — the interactive TUI exposes no runtime MCP status (unlike SDK/CLI
18
+ // stream-json `system/init`), so for MCP visibility parity we emit the
19
+ // CONFIGURED server list discovered from the same ~/.claude.json / .mcp.json
20
+ // sources Claude Code reads, labelled `configured` (not live).
21
+ import { discoverConfiguredMcpServers } from './byok-mcp-config.js'
17
22
  import { ALLOWED_MODEL_IDS } from './models.js'
18
23
  import { CLAUDE_FALLBACK_MODELS, claudeModelMetadata } from './claude-model-catalog.js'
19
24
  import { RespawnRateLimiter } from './utils/respawn-rate-limiter.js'
25
+ import { labelBinarySpawnFailure } from './utils/verify-binary.js'
20
26
  import { CHROXY_SECRET_DENYLIST } from './utils/spawn-env.js'
21
27
  import { createLogger, loggerForSession, redactSensitive, redactSensitivePreservingEscapes } from './logger.js'
22
28
  import { formatIdleDuration } from './session-timeout-manager.js'
@@ -38,7 +44,7 @@ import {
38
44
  import {
39
45
  ANSI_STRIP,
40
46
  formatHexDump,
41
- CLAUDE,
47
+ resolveClaudeBinary,
42
48
  AUTH_FAILURE_PATTERNS,
43
49
  AUTH_REQUIRED_CODE,
44
50
  AUTH_REQUIRED_MESSAGE,
@@ -172,6 +178,14 @@ export class ClaudeTuiSession extends BaseSession {
172
178
  }
173
179
  }
174
180
 
181
+ /**
182
+ * The exact path node-pty will spawn, re-resolved fresh so preflight verifies
183
+ * the SAME path the spawn uses (no stale module-load const). (#6708)
184
+ */
185
+ static get resolvedBinary() {
186
+ return resolveClaudeBinary()
187
+ }
188
+
175
189
  static get preflight() {
176
190
  return {
177
191
  label: 'Claude TUI',
@@ -1223,7 +1237,22 @@ export class ClaudeTuiSession extends BaseSession {
1223
1237
  // redraw sub-second (vs the 5s per-turn ceiling). Comfortably above the observed
1224
1238
  // intra-render gaps (~270ms) so it can't false-trigger mid-render; the
1225
1239
  // warmup/turn ceilings still backstop a genuinely-stuck TUI.
1226
- static get READY_QUIESCENCE_MS() { return 400 }
1240
+ //
1241
+ // Override with CHROXY_TUI_READY_QUIESCENCE_MS (positive integer ms) to widen
1242
+ // the window on a flaky/slow host — a genuine mid-warmup pause (MCP enumeration,
1243
+ // a slow skills-dir read, a loaded host) exceeding 400ms would fire quiescence
1244
+ // early and land the throttled prompt on a not-yet-ready composer. In the
1245
+ // no-session-file case quiescence is the only readiness signal, so if it fires
1246
+ // early the #5794 first-turn nudge (a bare `\r` re-send) is the backstop that
1247
+ // recovers the composer — an early fire is a brief wedge at worst (#6603).
1248
+ static get READY_QUIESCENCE_MS() {
1249
+ // Strict digits-only (after trim) so a partial-numeric value like "1200ms"
1250
+ // is rejected → 400, matching the documented "positive integer" contract
1251
+ // (parseInt alone would silently accept "1200ms" as 1200).
1252
+ const raw = (process.env.CHROXY_TUI_READY_QUIESCENCE_MS || '').trim()
1253
+ const override = /^\d+$/.test(raw) ? parseInt(raw, 10) : NaN
1254
+ return override > 0 ? override : 400
1255
+ }
1227
1256
  // #5317 (WP-2.3) — grace window between destroy()'s SIGTERM and the SIGKILL
1228
1257
  // escalation. Long enough for claude to flush its Stop hook + reap its own
1229
1258
  // tool children on a clean SIGTERM, short enough that a hung claude (or a
@@ -1383,6 +1412,51 @@ export class ClaudeTuiSession extends BaseSession {
1383
1412
 
1384
1413
  this._processReady = true
1385
1414
  this.emit('ready', { sessionId: this._sessionId, model: this.model, tools: [] })
1415
+ this._emitConfiguredMcpServers()
1416
+ }
1417
+
1418
+ /**
1419
+ * #6820 — emit the CONFIGURED MCP server list for MCP visibility parity.
1420
+ *
1421
+ * The interactive claude TUI communicates over a PTY + hook payloads and
1422
+ * exposes NO runtime MCP status (unlike the SDK/CLI stream-json `system/init`
1423
+ * event, which carries live `mcp_servers` with real connection status). The
1424
+ * honest signal we CAN give is what the config DECLARES: the merged
1425
+ * user/global + project + `.mcp.json` server list for this session's cwd,
1426
+ * emitted with status `configured` (never `connected`) so the client renders
1427
+ * a neutral, not-live indicator. Emits even an empty list so a stale list
1428
+ * clears on respawn — mirroring sdk/cli-session's "including empty list to
1429
+ * clear stale state" behaviour. Best-effort: a discovery failure logs a warn,
1430
+ * still emits the EMPTY list (so clients don't keep rendering stale servers),
1431
+ * and never blocks the ready path.
1432
+ */
1433
+ _emitConfiguredMcpServers() {
1434
+ try {
1435
+ const { servers, warnings } = discoverConfiguredMcpServers(this.cwd)
1436
+ for (const warning of warnings) {
1437
+ ;(this._log || log).warn(`MCP config: ${warning}`)
1438
+ }
1439
+ const payload = servers.map((s) => ({ name: s.name, status: 'configured' }))
1440
+ if (payload.length > 0) {
1441
+ ;(this._log || log).info(
1442
+ `MCP servers (configured, not live): ${payload.map((s) => s.name).join(', ')}`,
1443
+ )
1444
+ }
1445
+ this.emit('mcp_servers', { servers: payload })
1446
+ } catch (err) {
1447
+ ;(this._log || log).warn(
1448
+ `MCP configured-server discovery failed: ${err?.message || String(err)}`,
1449
+ )
1450
+ // Documented contract: even on failure, emit the empty list so a client
1451
+ // holding a previous session's servers clears instead of rendering stale
1452
+ // state forever. Guarded — a throwing listener must not escape the ready
1453
+ // path this method is called from.
1454
+ try {
1455
+ this.emit('mcp_servers', { servers: [] })
1456
+ } catch {
1457
+ // Swallow: nothing more to do if even the emit fails.
1458
+ }
1459
+ }
1386
1460
  }
1387
1461
 
1388
1462
  /**
@@ -1716,6 +1790,7 @@ export class ClaudeTuiSession extends BaseSession {
1716
1790
  this._didFallbackFromUnknownResume = false
1717
1791
  this._processReady = true
1718
1792
  this.emit('ready', { sessionId: this._sessionId, model: this.model, tools: [] })
1793
+ this._emitConfiguredMcpServers()
1719
1794
  }
1720
1795
 
1721
1796
  /**
@@ -1861,13 +1936,16 @@ export class ClaudeTuiSession extends BaseSession {
1861
1936
  }
1862
1937
  log.info(`spawn claude TUI (uuid=${this._sessionId.slice(0, 8)} model=${this.model || 'default'} perms=${permissionsEnabled} skills=${skillsPrefix ? skillsPrefix.length + 'b' : 'none'})`)
1863
1938
 
1939
+ // Captured so the spawn-time backstop (#6708) verifies the EXACT binary this
1940
+ // attempt used, not a fresh re-resolve that could land on a different path.
1941
+ const attemptedBinary = resolveClaudeBinary()
1864
1942
  try {
1865
1943
  // node-pty spawns CLAUDE directly — no cmd.exe routing needed even when
1866
1944
  // the Windows resolver lands on a `claude.cmd` shim. node-pty routes
1867
1945
  // through conpty/cmd.exe internally and runs a `.cmd` fine (verified),
1868
1946
  // unlike child_process.spawn which throws EINVAL on a `.cmd` (Node 24) and
1869
1947
  // needs the utils/win-spawn.js escaping the cli-session path uses.
1870
- this._term = ptyMod.spawn(CLAUDE, args, {
1948
+ this._term = ptyMod.spawn(attemptedBinary, args, {
1871
1949
  name: 'xterm-256color',
1872
1950
  // #5839: single-sourced default so the dashboard mirror renders at the
1873
1951
  // same grid. #5835 Phase 2: a prior resize is preserved across respawns
@@ -1878,7 +1956,16 @@ export class ClaudeTuiSession extends BaseSession {
1878
1956
  env,
1879
1957
  })
1880
1958
  } catch (err) {
1881
- this.emit('error', { message: `Failed to spawn claude under PTY: ${err.message}` })
1959
+ // #6708 — node-pty throws synchronously when the binary is missing/
1960
+ // unspawnable. If it was quarantined/moved/removed out from under the
1961
+ // running daemon (also the respawn path), name the cause + fix rather than
1962
+ // a bare error. Falls back to the raw message when the binary looks healthy.
1963
+ const labeled = labelBinarySpawnFailure({
1964
+ attemptedPath: err?.path || attemptedBinary,
1965
+ binary: 'claude',
1966
+ prefix: 'Failed to spawn claude under PTY',
1967
+ })
1968
+ this.emit('error', { message: labeled || `Failed to spawn claude under PTY: ${err.message}` })
1882
1969
  return
1883
1970
  }
1884
1971
 
@@ -1900,9 +1987,8 @@ export class ClaudeTuiSession extends BaseSession {
1900
1987
  this._outputTailRaw = Buffer.alloc(0)
1901
1988
  // #6601: re-evaluate output-quiescence readiness for THIS spawn — require
1902
1989
  // fresh output before trusting a quiet stretch, so a leftover _lastOutputMs
1903
- // from the prior process can't read as "ready" the instant we respawn.
1904
- this._sawFirstOutput = false
1905
- this._lastOutputMs = this._nowMonotonic()
1990
+ // from the prior process can't read as "ready" the instant we respawn (#6604).
1991
+ this._resetQuiescenceForSpawn()
1906
1992
 
1907
1993
  // #5794: a fresh PTY can swallow the first submit again, so re-arm the
1908
1994
  // first-turn submit nudge for the first message on THIS spawn. Reset after
@@ -2133,6 +2219,19 @@ export class ClaudeTuiSession extends BaseSession {
2133
2219
  return finish(ready)
2134
2220
  }
2135
2221
 
2222
+ /**
2223
+ * #6601: reset the output-quiescence readiness state for a fresh (re)spawn —
2224
+ * clear the "saw first output" gate and re-stamp `_lastOutputMs` to now, so a
2225
+ * leftover `_lastOutputMs` from the prior process can't read as "ready" the
2226
+ * instant we respawn. The counterpart to `_appendToOutputTail` (which SETS
2227
+ * these). Extracted from `_spawnPty` so the guard is unit-testable without a
2228
+ * real PTY (#6604).
2229
+ */
2230
+ _resetQuiescenceForSpawn() {
2231
+ this._sawFirstOutput = false
2232
+ this._lastOutputMs = this._nowMonotonic()
2233
+ }
2234
+
2136
2235
  /**
2137
2236
  * Append a PTY onData chunk to the recent-output tails (#3919).
2138
2237
  *
@@ -10,7 +10,7 @@ export function registerConfigCommand(program) {
10
10
  .description('Show current configuration')
11
11
  .action(() => {
12
12
  if (!existsSync(CONFIG_FILE)) {
13
- console.log('No config found. Run \'npx chroxy init\' first.')
13
+ console.log('No config found. Run \'chroxy init\' first.')
14
14
  process.exit(1)
15
15
  }
16
16
 
@@ -29,6 +29,6 @@ export function registerConfigCommand(program) {
29
29
  }
30
30
  console.log(` API token: ${config.apiToken}`)
31
31
  console.log('\nNote: CLI flags and environment variables can override these values.')
32
- console.log('Run \'npx chroxy start --verbose\' to see full config resolution.\n')
32
+ console.log('Run \'chroxy start --verbose\' to see full config resolution.\n')
33
33
  })
34
34
  }
@@ -149,7 +149,7 @@ export function registerDeployCommand(program) {
149
149
 
150
150
  if (isWindows) {
151
151
  console.error('[deploy] Deploy restart via SIGUSR2 is not supported on Windows.')
152
- console.error(' Restart the server manually: npx chroxy start')
152
+ console.error(' Restart the server manually: chroxy start')
153
153
  process.exitCode = 1
154
154
  return
155
155
  }