@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
@@ -42,6 +42,9 @@ export function createClientSender(log, opts = {}) {
42
42
  const warnThreshold = opts.warnThreshold ?? WARN_THRESHOLD
43
43
  const evictThreshold = opts.evictThreshold ?? EVICT_THRESHOLD
44
44
  const warnThrottleMs = opts.warnThrottleMs ?? WARN_THROTTLE_MS
45
+ // Optional delivery gate: (client, message) => boolean. A false answer drops the
46
+ // frame (a connection whose credential is no longer valid receives no replies).
47
+ const mayDeliver = typeof opts.mayDeliver === 'function' ? opts.mayDeliver : null
45
48
 
46
49
  return function send(ws, client, message) {
47
50
  // #4834: short-circuit if this client has already been evicted. ws.close()
@@ -51,6 +54,10 @@ export function createClientSender(log, opts = {}) {
51
54
  if (client?._evicted) {
52
55
  return false
53
56
  }
57
+ if (client && mayDeliver && !mayDeliver(client, message)) {
58
+ log.debug?.(`Dropped ${message?.type || 'unknown'} for client ${client.id}: credential no longer valid`)
59
+ return false
60
+ }
54
61
  // Queue messages while key exchange is pending
55
62
  if (client?.encryptionPending && client.postAuthQueue) {
56
63
  client.postAuthQueue.push(message)
@@ -1,59 +1,206 @@
1
- import { readdir, readFile, stat, realpath } from 'fs/promises'
1
+ import { readdir, stat, lstat, realpath } from 'fs/promises'
2
+ import { readContainedTextFile } from '../utils/regular-file.js'
2
3
  import { homedir } from 'os'
3
- import { join, resolve, normalize, relative } from 'path'
4
+ import { claudeConfigDir } from '../utils/claude-config-dir.js'
5
+ import { join, resolve, normalize, relative, sep, isAbsolute, dirname, basename } from 'path'
4
6
  import { createLogger } from '../logger.js'
5
7
  import { getBuiltinCommands } from '../builtin-commands.js'
6
8
  import { getProvider } from '../providers.js'
9
+ import { isPathWithin } from '../utils/path-containment.js'
10
+ import { realpathOfDeepestAncestor, unresolvablePathError, fileOpErrorMessage } from './common.js'
11
+ import { truncateForLog } from './reader.js'
12
+ import { isGitRepo } from '../utils/git-repo.js'
13
+ import { validateCwdAllowed } from '../handler-utils.js'
14
+ import { DIRECTORY_LISTING_DENIED_PREFIX } from '@chroxy/protocol'
7
15
 
8
16
  const log = createLogger('ws')
9
17
 
18
+ // #8972 — max distinct check_git_repo probes in flight per socket.
19
+ const MAX_GIT_CHECKS_PER_CLIENT = 4
20
+
21
+ // #8012 — the message list_directory / browse_files send when `realpath()`
22
+ // failed with one of these codes for a path INSIDE their boundary. Any other
23
+ // code, or any path outside it, gets the handler's generic denial instead
24
+ // (see unresolvablePathError).
25
+ const LISTING_UNRESOLVABLE_REASONS = {
26
+ EACCES: 'Permission denied',
27
+ EPERM: 'Permission denied',
28
+ ENOTDIR: 'Not a directory',
29
+ }
30
+
31
+ const HOME_ONLY_DENIAL = `${DIRECTORY_LISTING_DENIED_PREFIX}: directory listing is restricted to the home directory`
32
+ const HOME_AND_ROOTS_DENIAL =
33
+ `${DIRECTORY_LISTING_DENIED_PREFIX}: directory listing is restricted to the home directory and any usable workspace roots`
34
+
35
+ function hasWorkspaceRoots(config) {
36
+ return Array.isArray(config?.workspaceRoots) &&
37
+ config.workspaceRoots.some((r) => typeof r === 'string' && r.length > 0)
38
+ }
39
+
40
+ /**
41
+ * The requested path in the form New Session hands to `validateCwdAllowed`: the
42
+ * trimmed input with `~` expanded and NOT lexically normalised, so the kernel
43
+ * resolves any `..` through the links before it (`/tmp/..` is `/private` where
44
+ * `/tmp` links to `/private/tmp`). `normalize`/`resolve` would collapse it
45
+ * textually and make Browse and Create answer differently for one input (#8303).
46
+ * The containment decision is made on the realpath of this form.
47
+ */
48
+ function kernelForm(trimmed, home) {
49
+ if (trimmed.startsWith('~')) {
50
+ // ONE tilde rule for every Browse path: drop every separator after the `~`,
51
+ // so `~//x` is `<home>/x` for list_directory and check_git_repo alike.
52
+ const rest = trimmed.slice(1).replace(/^[\\/]+/, '')
53
+ return rest ? home + sep + rest : home
54
+ }
55
+ return isAbsolute(trimmed) ? trimmed : process.cwd() + sep + trimmed
56
+ }
57
+
58
+ function hasDotDot(p) {
59
+ return p.split(/[\\/]+/).includes('..')
60
+ }
61
+
62
+ const MAX_ANCESTOR_STEPS = 256
63
+
64
+ /**
65
+ * Resolve `raw` the way the kernel does, and for a target that does not exist
66
+ * find its deepest EXISTING ancestor (a `..` is applied to the prefix before it,
67
+ * through links, never textually). Returns `{ real, missing, code }`: `real` is
68
+ * the resolved target (or ancestor), `missing` whether the target itself is
69
+ * absent, `code` the first failure (ENOENT or ENOTDIR). A dangling symlink on
70
+ * the way is followed with realpathOfDeepestAncestor (#8013). Any other error,
71
+ * or a walk that cannot finish, throws with `walked` set when it happened after
72
+ * the target was already known to be missing, so the caller can answer with the
73
+ * uniform denial instead of an error that differs by what exists out there.
74
+ */
75
+ async function deepestExistingAncestor(raw) {
76
+ let cur = raw
77
+ let firstCode = null
78
+ for (let i = 0; i < MAX_ANCESTOR_STEPS; i++) {
79
+ try {
80
+ return { real: await realpath(cur), missing: firstCode !== null, code: firstCode }
81
+ } catch (err) {
82
+ if (firstCode === null && err.code !== 'ENOENT' && err.code !== 'ENOTDIR') throw err
83
+ try {
84
+ if (err.code !== 'ENOENT' && err.code !== 'ENOTDIR') throw err
85
+ firstCode ??= err.code
86
+ const parent = dirname(cur)
87
+ if (parent === cur) throw err
88
+ const leaf = basename(cur)
89
+ if (leaf !== '..' && leaf !== '.') {
90
+ let isLink = false
91
+ try { isLink = (await lstat(cur)).isSymbolicLink() } catch { /* absent */ }
92
+ if (isLink) {
93
+ const realParent = await realpath(parent)
94
+ return { real: await realpathOfDeepestAncestor(join(realParent, leaf)), missing: true, code: firstCode }
95
+ }
96
+ }
97
+ cur = parent
98
+ } catch (inner) {
99
+ inner.walked = true
100
+ throw inner
101
+ }
102
+ }
103
+ }
104
+ throw Object.assign(new Error('ancestor walk too deep'), { walked: true })
105
+ }
106
+
107
+ /** The directory to judge for a (possibly missing) target: its nearest existing directory. */
108
+ async function judgedDirectory(real) {
109
+ let cur = real
110
+ for (let i = 0; i < MAX_ANCESTOR_STEPS; i++) {
111
+ try {
112
+ const st = await stat(cur)
113
+ return st.isDirectory() ? cur : dirname(cur)
114
+ } catch {
115
+ const parent = dirname(cur)
116
+ if (parent === cur) return null
117
+ cur = parent
118
+ }
119
+ }
120
+ return null
121
+ }
122
+
123
+ /**
124
+ * The one containment rule for Browse (`list_directory`, `check_git_repo`): $HOME
125
+ * as before, plus whatever New Session's cwd check (`validateCwdAllowed`, the
126
+ * credential-directory deny-list then `workspaceRoots`) accepts. Asking the same
127
+ * function keeps the two from drifting. A session-bound client is denied these
128
+ * message types before dispatch (bound-client-policy.js), so this is a second
129
+ * layer: should one ever reach here it keeps the $HOME-only boundary, since it
130
+ * cannot create sessions and gets nothing from the create allowlist
131
+ * (docs/security/bearer-token-authority.md section 4).
132
+ * @param {string} realPath canonical (realpath) target
133
+ * @param {string} homeReal canonical home
134
+ * @param {{ config?: object|null, bound?: boolean }} [opts]
135
+ */
136
+ function isBrowsable(realPath, homeReal, opts = {}) {
137
+ if (isPathWithin(realPath, homeReal)) return true
138
+ if (opts.bound !== false || !opts.config) return false
139
+ return validateCwdAllowed(realPath, opts.config) === null
140
+ }
141
+
10
142
  /**
11
143
  * Directory browsing, file listing, slash commands, and agent listing.
12
144
  *
13
145
  * @param {Function} sendFn - (ws, message) => void
14
146
  * @param {Function} resolveSessionCwd - shared CWD resolver
15
147
  * @param {Function} validatePathWithinCwd - shared path validator
148
+ * @param {{ realpath?: Function, readdir?: Function }} [deps] test seam for the catalog directory scans
16
149
  * @returns {Object} browser operation methods
17
150
  */
18
- export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCwd) {
151
+ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCwd, deps = {}) {
152
+ const catalogRealpath = deps.realpath ?? realpath
153
+ const catalogReaddir = deps.readdir ?? readdir
19
154
 
20
155
  /** List directories at a given path, sending a directory_listing response */
21
- async function listDirectory(ws, requestedPath) {
156
+ async function listDirectory(ws, requestedPath, opts = {}) {
22
157
  let absPath = null
158
+ // #8303 — echo the caller's correlation id on every reply, to this socket
159
+ // only (sendFn is per-socket). A malformed id is dropped, never echoed; the
160
+ // schema already refuses one before dispatch.
161
+ const requestId = typeof opts.requestId === 'string' && opts.requestId.length > 0 && opts.requestId.length <= 128
162
+ ? opts.requestId
163
+ : null
164
+ const send = (message) => sendFn(ws, requestId ? { ...message, requestId } : message)
23
165
  try {
24
166
  const home = homedir()
25
- if (!requestedPath || typeof requestedPath !== 'string' || !requestedPath.trim()) {
26
- absPath = home
27
- } else {
28
- const trimmed = requestedPath.trim()
29
- absPath = trimmed.startsWith('~')
30
- ? resolve(home, trimmed.slice(1).replace(/^\//, ''))
31
- : resolve(trimmed)
32
- }
33
- absPath = normalize(absPath)
167
+ const trimmed = typeof requestedPath === 'string' ? requestedPath.trim() : ''
168
+ // Create's form (kernelForm); the lexical `absPath` is only the echo.
169
+ const rawPath = trimmed ? kernelForm(trimmed, home) : home
170
+ absPath = normalize(resolve(rawPath))
171
+ const denial = hasWorkspaceRoots(opts.config) && opts.bound === false ? HOME_AND_ROOTS_DENIAL : HOME_ONLY_DENIAL
172
+ const deny = (message = denial) => send({
173
+ type: 'directory_listing',
174
+ path: absPath,
175
+ parentPath: null,
176
+ entries: [],
177
+ error: message,
178
+ })
34
179
 
35
- let realAbsPath
180
+ let walk
36
181
  try {
37
- realAbsPath = await realpath(absPath)
182
+ walk = await deepestExistingAncestor(rawPath)
38
183
  } catch (err) {
39
- if (err.code === 'ENOENT') {
40
- realAbsPath = absPath
41
- } else {
42
- throw err
43
- }
184
+ if (err.walked) return deny() // cannot establish containment: the uniform denial
185
+ // #8012 — a first-step failure other than "missing" (EACCES, EPERM,
186
+ // ELOOP, …) keeps a specific message only for a path inside home.
187
+ const homeReal = await realpath(home).catch(() => null)
188
+ deny(await unresolvablePathError(err, absPath, homeReal, LISTING_UNRESOLVABLE_REASONS, denial))
189
+ return
44
190
  }
45
191
  const homeReal = await realpath(home)
46
192
 
47
- if (!realAbsPath.startsWith(homeReal + '/') && realAbsPath !== homeReal) {
48
- sendFn(ws, {
49
- type: 'directory_listing',
50
- path: absPath,
51
- parentPath: null,
52
- entries: [],
53
- error: 'Access denied: directory listing is restricted to the home directory',
54
- })
55
- return
56
- }
193
+ // #8011/#8303 — a MISSING target is judged by its deepest existing
194
+ // ancestor, resolved as the kernel resolves it, with the SAME rule an
195
+ // existing one gets. Outside the browsable area the answer is the same
196
+ // denial whether or not anything exists out there; inside it nothing is
197
+ // hidden, so the answer is a plain "not found".
198
+ // (A file is judged by the directory holding it, so a file or a path below
199
+ // one inside a root is not mistaken for a path outside it.)
200
+ const judged = await judgedDirectory(walk.real)
201
+ if (judged === null || !isBrowsable(judged, homeReal, opts)) return deny()
202
+ if (walk.missing) throw Object.assign(new Error('missing'), { code: walk.code })
203
+ const realAbsPath = walk.real
57
204
 
58
205
  const dirents = await readdir(realAbsPath, { withFileTypes: true })
59
206
  const entries = dirents
@@ -61,23 +208,25 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
61
208
  .sort((a, b) => a.name.localeCompare(b.name))
62
209
  .map(d => ({ name: d.name, isDirectory: true }))
63
210
 
64
- const parentPath = absPath === '/' ? null : resolve(absPath, '..')
211
+ // Report the directory actually listed. Without a `..` in the input the
212
+ // lexical form IS that directory (and is what the client asked for); with
213
+ // one, the lexical collapse can name a different directory, so report the
214
+ // resolved one.
215
+ const listedPath = hasDotDot(rawPath) ? realAbsPath : absPath
216
+ const parentPath = dirname(listedPath) === listedPath ? null : dirname(listedPath)
65
217
 
66
- sendFn(ws, {
218
+ send({
67
219
  type: 'directory_listing',
68
- path: absPath,
220
+ path: listedPath,
69
221
  parentPath,
70
222
  entries,
71
223
  error: null,
72
224
  })
73
225
  } catch (err) {
74
- let errorMessage
75
- if (err.code === 'ENOENT') errorMessage = 'Directory not found'
76
- else if (err.code === 'EACCES') errorMessage = 'Permission denied'
77
- else if (err.code === 'ENOTDIR') errorMessage = 'Not a directory'
78
- else errorMessage = err.message || 'Unknown error'
226
+ log.error(`list_directory failed: ${truncateForLog(err.message)}`)
227
+ const errorMessage = fileOpErrorMessage(err, 'Operation failed', { ENOENT: 'Directory not found' })
79
228
 
80
- sendFn(ws, {
229
+ send({
81
230
  type: 'directory_listing',
82
231
  path: absPath || requestedPath || null,
83
232
  parentPath: null,
@@ -109,7 +258,26 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
109
258
  }
110
259
  absPath = normalize(absPath)
111
260
 
112
- const { valid, realPath: realAbsPath, cwdReal } = await validatePathWithinCwd(absPath, sessionCwd)
261
+ // A session cwd that cannot be resolved keeps the outer catch's answer.
262
+ const sessionCwdReal = await resolveSessionCwd(sessionCwd)
263
+ let validation
264
+ try {
265
+ validation = await validatePathWithinCwd(absPath, sessionCwd)
266
+ } catch (err) {
267
+ // #8012 — same residual as list_directory above: a non-ENOENT
268
+ // failure resolving the target skipped containment and reached the
269
+ // outer catch. Outside the project, or a cycle, is the denial.
270
+ sendFn(ws, {
271
+ type: 'file_listing',
272
+ path: absPath,
273
+ parentPath: null,
274
+ entries: [],
275
+ error: await unresolvablePathError(err, absPath, sessionCwdReal, LISTING_UNRESOLVABLE_REASONS,
276
+ 'Access denied: browsing is restricted to the project directory'),
277
+ })
278
+ return
279
+ }
280
+ const { valid, realPath: realAbsPath, cwdReal } = validation
113
281
  if (!valid) {
114
282
  sendFn(ws, {
115
283
  type: 'file_listing',
@@ -151,11 +319,8 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
151
319
  error: null,
152
320
  })
153
321
  } catch (err) {
154
- let errorMessage
155
- if (err.code === 'ENOENT') errorMessage = 'Directory not found'
156
- else if (err.code === 'EACCES') errorMessage = 'Permission denied'
157
- else if (err.code === 'ENOTDIR') errorMessage = 'Not a directory'
158
- else errorMessage = err.message || 'Unknown error'
322
+ log.error(`browse_files failed: ${truncateForLog(err.message)}`)
323
+ const errorMessage = fileOpErrorMessage(err, 'Operation failed', { ENOENT: 'Directory not found' })
159
324
 
160
325
  sendFn(ws, {
161
326
  type: 'file_listing',
@@ -281,7 +446,9 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
281
446
  // Load .gitignore if it exists
282
447
  let gitignoreRules = []
283
448
  try {
284
- const content = await readFile(join(cwdReal, '.gitignore'), 'utf-8')
449
+ // One pinned, contained, size-capped read (utils/regular-file.js).
450
+ const content = await readContainedTextFile(join(cwdReal, '.gitignore'), cwdReal, 1024 * 1024)
451
+ if (content === null) throw new Error('unreadable')
285
452
  gitignoreRules = parseGitignore(content)
286
453
  } catch {
287
454
  // No .gitignore or unreadable — proceed without
@@ -318,7 +485,14 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
318
485
  if (d.name === 'node_modules') continue
319
486
 
320
487
  const absPath = join(dir, d.name)
321
- const relPath = relative(cwdReal, absPath)
488
+ // POSIX separators, always (#7282). This string goes onto the wire
489
+ // as `file_list.files[].path`, and a client must not have to know
490
+ // which OS the daemon runs on — on Windows `relative()` yields
491
+ // `src\app.js`. It also feeds `isIgnored` below, whose matcher
492
+ // splits on '/' and builds `[^/]` classes: fed a backslash path it
493
+ // saw one segment, so directory-scoped .gitignore rules silently
494
+ // stopped hiding files on Windows. Same idiom as ide/search.js.
495
+ const relPath = relative(cwdReal, absPath).split(sep).join('/')
322
496
 
323
497
  // Validate symlinks stay within CWD boundary
324
498
  if (d.isSymbolicLink()) {
@@ -418,7 +592,16 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
418
592
  * path (`listSlashCommands`) and the connect-time `auth_bootstrap` burst
419
593
  * (#5555) so both produce an identical `commands` array.
420
594
  */
421
- async function computeSlashCommands(cwd, providerName = null, mcpPrompts = []) {
595
+ // True when `dirReal` (already a real path) lies within the real path of `cwd`.
596
+ async function isInsideProject(cwd, dirReal) {
597
+ try {
598
+ return isPathWithin(dirReal, await realpath(cwd))
599
+ } catch {
600
+ return false
601
+ }
602
+ }
603
+
604
+ async function computeSlashCommands(cwd, providerName = null, mcpPrompts = [], { projectOnly = false } = {}) {
422
605
  const commands = []
423
606
  const seen = new Set()
424
607
 
@@ -443,7 +626,18 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
443
626
 
444
627
  const scanDir = async (dir, source) => {
445
628
  try {
446
- const entries = await readdir(dir, { withFileTypes: true })
629
+ const dirReal = await catalogRealpath(dir)
630
+ // A project-confined caller: the catalog directory must really be inside
631
+ // the project (a link out to the user-level catalog is not the project's).
632
+ if (projectOnly && source === 'project' && !(await isInsideProject(cwd, dirReal))) return
633
+ const entries = await catalogReaddir(dirReal, { withFileTypes: true })
634
+ // The listing was read from the path as it was a moment ago: check that the
635
+ // directory still resolves there, so names read through a link swapped in
636
+ // between are not returned. This narrows a race, it does not close one
637
+ // (the directory can still change right after this check); what is at
638
+ // stake is file NAMES only, since the descriptions are read through the
639
+ // pinned, contained reader.
640
+ if (projectOnly && source === 'project' && (await catalogRealpath(dir)) !== dirReal) return
447
641
  for (const entry of entries) {
448
642
  if (!entry.isFile() || !entry.name.endsWith('.md')) continue
449
643
  if (entry.name.includes('/') || entry.name.includes('\\')) continue
@@ -453,7 +647,9 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
453
647
 
454
648
  let description = ''
455
649
  try {
456
- const content = await readFile(join(dir, entry.name), 'utf-8')
650
+ // Pinned, contained in the directory, head-capped.
651
+ const content = await readContainedTextFile(join(dirReal, entry.name), dirReal, 64 * 1024, { head: true })
652
+ if (content === null) throw new Error('unreadable')
457
653
  const lines = content.split('\n')
458
654
  for (const line of lines) {
459
655
  const trimmed = line.trim()
@@ -475,7 +671,9 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
475
671
  if (cwd) {
476
672
  await scanDir(join(cwd, '.claude', 'commands'), 'project')
477
673
  }
478
- await scanDir(join(homedir(), '.claude', 'commands'), 'user')
674
+ // A project-confined caller (a session-scoped connection) is shown the
675
+ // project's commands only, not the user-level catalog.
676
+ if (!projectOnly) await scanDir(join(claudeConfigDir(), 'commands'), 'user')
479
677
 
480
678
  // #6823: MCP-server prompts merged as `source: 'mcp'` slash commands
481
679
  // (`/mcp__<server>__<prompt>`). Added last so a same-named built-in / .md
@@ -507,8 +705,8 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
507
705
  return commands
508
706
  }
509
707
 
510
- async function listSlashCommands(ws, cwd, sessionId, providerName = null, mcpPrompts = []) {
511
- const commands = await computeSlashCommands(cwd, providerName, mcpPrompts)
708
+ async function listSlashCommands(ws, cwd, sessionId, providerName = null, mcpPrompts = [], opts = {}) {
709
+ const commands = await computeSlashCommands(cwd, providerName, mcpPrompts, opts)
512
710
  const response = { type: 'slash_commands', commands }
513
711
  if (sessionId) response.sessionId = sessionId
514
712
  sendFn(ws, response)
@@ -537,8 +735,17 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
537
735
  * the others (#3024).
538
736
  */
539
737
  const listDir = async (dir, source) => {
738
+ const dirArg = dir
540
739
  try {
541
- const entries = await readdir(dir, { withFileTypes: true })
740
+ dir = await catalogRealpath(dir)
741
+ if (opts.projectOnly && source === 'project' && !(await isInsideProject(cwd, dir))) {
742
+ return { dir, source, filenames: [] }
743
+ }
744
+ const entries = await catalogReaddir(dir, { withFileTypes: true })
745
+ // Same narrowed (not closed) re-check as the commands scan; names only.
746
+ if (opts.projectOnly && source === 'project' && (await catalogRealpath(dirArg)) !== dir) {
747
+ return { dir, source, filenames: [] }
748
+ }
542
749
  const filenames = entries
543
750
  .filter(e => e.isFile() && e.name.endsWith('.md'))
544
751
  .filter(e => !e.name.includes('/') && !e.name.includes('\\'))
@@ -554,7 +761,7 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
554
761
  // the caller-supplied list when multiple providers are active (#2965).
555
762
  const userAgentsDirs = (Array.isArray(opts.userAgentsDirs) && opts.userAgentsDirs.length > 0)
556
763
  ? opts.userAgentsDirs
557
- : [join(homedir(), '.claude', 'agents')]
764
+ : [join(claudeConfigDir(), 'agents')]
558
765
 
559
766
  // Phase 1: readdir project + all user dirs in parallel (#3024). Promise.all
560
767
  // preserves input order in the resolved array, so first-wins dedup below
@@ -564,8 +771,11 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
564
771
  if (cwd) {
565
772
  dirScans.push(listDir(join(cwd, '.claude', 'agents'), 'project'))
566
773
  }
567
- for (const dir of userAgentsDirs) {
568
- dirScans.push(listDir(dir, 'user'))
774
+ // A project-confined caller is shown the project's agents only.
775
+ if (!opts.projectOnly) {
776
+ for (const dir of userAgentsDirs) {
777
+ dirScans.push(listDir(dir, 'user'))
778
+ }
569
779
  }
570
780
  const dirResults = await Promise.all(dirScans)
571
781
 
@@ -587,7 +797,8 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
587
797
  const agents = await Promise.all(winners.map(async ({ name, dir, source, filename }) => {
588
798
  let description = ''
589
799
  try {
590
- const content = await readFile(join(dir, filename), 'utf-8')
800
+ const content = await readContainedTextFile(join(dir, filename), dir, 64 * 1024, { head: true })
801
+ if (content === null) throw new Error('unreadable')
591
802
  const lines = content.split('\n')
592
803
  for (const line of lines) {
593
804
  const trimmed = line.trim()
@@ -613,8 +824,70 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
613
824
  sendFn(ws, response)
614
825
  }
615
826
 
827
+
828
+ /**
829
+ * #8972 — `check_git_repo`: is the directory the New Session dialog is
830
+ * pointing at a git repository? Lets the dialog refuse the worktree switch
831
+ * up front instead of after Create (the server still refuses on create).
832
+ *
833
+ * Answers `isGitRepo: true | false | null`. `null` means "cannot tell" and
834
+ * the client must leave the switch enabled: the path is outside the home
835
+ * directory, unresolvable, not a directory, refused (bound client) or over
836
+ * the per-client probe budget. Those cases share one answer on purpose, so
837
+ * the PAYLOAD is uniform for paths outside home (same containment as
838
+ * `list_directory`); reply timing is not guaranteed uniform.
839
+ *
840
+ * Spawn budget: identical in-flight paths from one socket share one probe,
841
+ * and a socket may have at most MAX_GIT_CHECKS_PER_CLIENT distinct probes in
842
+ * flight; beyond that the reply is `null` without touching the filesystem.
843
+ */
844
+ const inFlightChecks = new WeakMap() // ws -> Map<trimmed path, Promise<boolean|null>>
845
+
846
+ function replyGitRepoCheck(ws, requestedPath, requestId, isGitRepoValue) {
847
+ const msg = { type: 'git_repo_check_result', path: typeof requestedPath === 'string' ? requestedPath : '', isGitRepo: isGitRepoValue }
848
+ if (requestId) msg.requestId = requestId
849
+ sendFn(ws, msg)
850
+ }
851
+
852
+ async function probeGitRepo(trimmed, opts) {
853
+ try {
854
+ const home = homedir()
855
+ // Same form New Session validates (kernel-resolved `..`), see kernelForm.
856
+ const [realAbs, homeReal] = await Promise.all([realpath(kernelForm(trimmed, home)), realpath(home)])
857
+ if (!isBrowsable(realAbs, homeReal, opts)) return null
858
+ if (!(await stat(realAbs)).isDirectory()) return null
859
+ return await isGitRepo(realAbs)
860
+ } catch {
861
+ return null
862
+ }
863
+ }
864
+
865
+ /** Refuse without any path resolution or filesystem access (bound clients). */
866
+ function refuseGitRepoCheck(ws, requestedPath, requestId) {
867
+ replyGitRepoCheck(ws, requestedPath, requestId, null)
868
+ }
869
+
870
+ async function checkGitRepo(ws, requestedPath, requestId, opts = {}) {
871
+ const trimmed = typeof requestedPath === 'string' ? requestedPath.trim() : ''
872
+ if (!trimmed) return replyGitRepoCheck(ws, requestedPath, requestId, null)
873
+ let pending = ws && typeof ws === 'object' ? inFlightChecks.get(ws) : undefined
874
+ if (!pending) {
875
+ pending = new Map()
876
+ if (ws && typeof ws === 'object') inFlightChecks.set(ws, pending)
877
+ }
878
+ let probe = pending.get(trimmed)
879
+ if (!probe) {
880
+ if (pending.size >= MAX_GIT_CHECKS_PER_CLIENT) return replyGitRepoCheck(ws, requestedPath, requestId, null)
881
+ probe = probeGitRepo(trimmed, opts).finally(() => { pending.delete(trimmed) })
882
+ pending.set(trimmed, probe)
883
+ }
884
+ return replyGitRepoCheck(ws, requestedPath, requestId, await probe)
885
+ }
886
+
616
887
  return {
617
888
  listDirectory,
889
+ checkGitRepo,
890
+ refuseGitRepoCheck,
618
891
  browseFiles,
619
892
  listFiles,
620
893
  listSlashCommands,