@chroxy/server 0.10.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 (326) hide show
  1. package/CONFIG.md +602 -19
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +416 -11
  5. package/package.json +20 -23
  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 +1353 -41
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +24 -1
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +101 -0
  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 +74 -9
  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 +1153 -20
  37. package/src/byok-mcp-config.js +1712 -8
  38. package/src/byok-mcp-fleet.js +416 -29
  39. package/src/byok-mcp-oauth-store.js +329 -0
  40. package/src/byok-mcp-oauth.js +635 -0
  41. package/src/byok-mcp-trust.js +257 -40
  42. package/src/byok-session.js +1400 -149
  43. package/src/byok-tool-executor.js +2681 -38
  44. package/src/byok-tools.js +9 -2
  45. package/src/channels/chroxy-channel-server.js +2 -3
  46. package/src/checkpoint-manager.js +96 -51
  47. package/src/chroxy-host-metadata.js +122 -0
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-stream-parser.js +109 -3
  53. package/src/claude-tui/diagnostic-tail.js +83 -0
  54. package/src/claude-tui/form-driver.js +44 -7
  55. package/src/claude-tui/model-error.js +41 -0
  56. package/src/claude-tui/pty-driver.js +223 -60
  57. package/src/claude-tui/sanitize-question-payload.js +109 -0
  58. package/src/claude-tui/usage-limit.js +239 -0
  59. package/src/claude-tui-session.js +3611 -286
  60. package/src/claude-tui-tool-response.js +300 -0
  61. package/src/cli/agent-control-cmd.js +65 -0
  62. package/src/cli/config-cmd.js +6 -6
  63. package/src/cli/config-dir-cmd.js +234 -0
  64. package/src/cli/deploy-cmd.js +46 -11
  65. package/src/cli/doctor-cmd.js +7 -3
  66. package/src/cli/init-cmd.js +16 -17
  67. package/src/cli/providers-cmd.js +6 -6
  68. package/src/cli/schedule-cmd.js +804 -0
  69. package/src/cli/server-cmd.js +64 -2
  70. package/src/cli/service-cmd.js +70 -27
  71. package/src/cli/session-cmd.js +227 -74
  72. package/src/cli/shared.js +168 -14
  73. package/src/cli/tokens-cmd.js +212 -0
  74. package/src/cli/tunnel-cmd.js +256 -25
  75. package/src/cli/worktree-gc-cmd.js +2 -2
  76. package/src/cli-session.js +1117 -116
  77. package/src/cli.js +8 -0
  78. package/src/codex-app-server-client.js +36 -3
  79. package/src/codex-app-server-session.js +2108 -101
  80. package/src/codex-bundled-client.js +66 -0
  81. package/src/codex-model-catalog.js +548 -0
  82. package/src/codex-model-rejections.js +87 -0
  83. package/src/codex-native-resume.js +104 -0
  84. package/src/codex-protocol-capabilities.js +188 -0
  85. package/src/codex-session.js +571 -45
  86. package/src/config-dir-migration.js +444 -0
  87. package/src/config-dir.js +108 -0
  88. package/src/config.js +738 -52
  89. package/src/connection-authority.js +48 -0
  90. package/src/connection-info.js +5 -9
  91. package/src/connection-locality.js +60 -0
  92. package/src/container-liveness-monitor.js +189 -0
  93. package/src/continuation-metadata-worker.js +17 -0
  94. package/src/continuations.js +114 -0
  95. package/src/control-room/host-prune.js +5 -0
  96. package/src/control-room/integrations.js +23 -30
  97. package/src/control-room/skills-inventory.js +8 -3
  98. package/src/control-room/survey.js +32 -0
  99. package/src/conversation-scanner.js +40 -18
  100. package/src/conversation-scope.js +59 -39
  101. package/src/conversation-search.js +24 -22
  102. package/src/credential-store.js +279 -29
  103. package/src/daemon-commit.js +92 -0
  104. package/src/daemon-idle-state.js +171 -0
  105. package/src/daemon-update-status.js +314 -0
  106. package/src/dashboard-build.js +70 -0
  107. package/src/declared-status.js +90 -0
  108. package/src/deepseek-credentials.js +2 -3
  109. package/src/dev-preview.js +169 -182
  110. package/src/device-preferences.js +2 -2
  111. package/src/diagnostics.js +3 -0
  112. package/src/diff-parser.js +87 -0
  113. package/src/discord-credentials.js +2 -3
  114. package/src/docker-byok-pool.js +3 -1
  115. package/src/docker-byok-session.js +678 -78
  116. package/src/docker-image-allowlist.js +23 -1
  117. package/src/docker-sdk-session.js +188 -4
  118. package/src/docker-session.js +293 -10
  119. package/src/doctor.js +783 -66
  120. package/src/edited-input.js +264 -0
  121. package/src/environment-manager.js +175 -36
  122. package/src/environments/authority.js +95 -0
  123. package/src/environments/backends/container-claude-spawn.js +94 -0
  124. package/src/environments/backends/docker.js +39 -10
  125. package/src/environments/backends/k8s.js +58 -24
  126. package/src/environments/destroy-with-sessions.js +142 -0
  127. package/src/event-ingest.js +137 -14
  128. package/src/event-normalizer.js +363 -110
  129. package/src/external-session-registry.js +0 -0
  130. package/src/gemini-session.js +100 -7
  131. package/src/github-webhook.js +188 -4
  132. package/src/handler-utils.js +563 -62
  133. package/src/handlers/checkpoint-handlers.js +162 -20
  134. package/src/handlers/control-room-handlers.js +99 -29
  135. package/src/handlers/conversation-handlers.js +563 -25
  136. package/src/handlers/credential-handlers.js +43 -2
  137. package/src/handlers/daemon-update-handlers.js +81 -0
  138. package/src/handlers/evaluator-handlers.js +14 -1
  139. package/src/handlers/feature-handlers.js +186 -69
  140. package/src/handlers/file-handlers.js +101 -13
  141. package/src/handlers/github-webhook-handlers.js +204 -0
  142. package/src/handlers/input-handlers.js +689 -48
  143. package/src/handlers/orchestration-handlers.js +238 -0
  144. package/src/handlers/scheduler-handlers.js +584 -0
  145. package/src/handlers/session-handlers.js +546 -16
  146. package/src/handlers/session-pr-status-handlers.js +283 -0
  147. package/src/handlers/session-pr-threads-handlers.js +247 -0
  148. package/src/handlers/settings-handlers.js +822 -35
  149. package/src/handlers/skills-handlers.js +13 -4
  150. package/src/handlers/summarize-handlers.js +32 -1
  151. package/src/handlers/survey-throttle.js +380 -0
  152. package/src/handlers/token-handlers.js +11 -2
  153. package/src/health-proof.js +40 -0
  154. package/src/history-page.js +104 -0
  155. package/src/http-routes.js +286 -8
  156. package/src/ide/search.js +24 -6
  157. package/src/ide/symbols.js +20 -6
  158. package/src/input-context.js +117 -0
  159. package/src/instruction-policy-compiler.js +229 -0
  160. package/src/instruction-policy.js +250 -0
  161. package/src/jsonl-reader.js +309 -48
  162. package/src/jsonl-subprocess-session.js +122 -9
  163. package/src/keychain.js +160 -13
  164. package/src/logger.js +240 -31
  165. package/src/mailbox-route.js +11 -22
  166. package/src/message-wire.js +386 -0
  167. package/src/model-discovery.js +43 -3
  168. package/src/models.js +1276 -174
  169. package/src/notification-prefs.js +100 -10
  170. package/src/notifications/discord-billing-sink.js +22 -5
  171. package/src/notifications/discord-ci-sink.js +243 -0
  172. package/src/notifications/discord-webhook-client.js +71 -0
  173. package/src/notifications/discord-webhook-sink.js +82 -12
  174. package/src/notifications/expo-push-sink.js +85 -6
  175. package/src/notifications/ready-body.js +16 -5
  176. package/src/ollama-session.js +34 -2
  177. package/src/orchestration/build-manager.js +63 -0
  178. package/src/orchestration/decision-contract.js +245 -0
  179. package/src/orchestration/git-ops.js +381 -0
  180. package/src/orchestration/orchestration-manager.js +1342 -0
  181. package/src/orchestration/permission-gate.js +121 -0
  182. package/src/orchestration/role-prompts.js +136 -0
  183. package/src/orchestration/run-budget.js +81 -0
  184. package/src/orchestration/run-ledger.js +487 -0
  185. package/src/orchestration/run-model.js +206 -0
  186. package/src/orchestration/run-record.js +336 -0
  187. package/src/orchestration/run-report.js +194 -0
  188. package/src/orchestration/to-wire.js +201 -0
  189. package/src/orchestration/turn-driver.js +422 -0
  190. package/src/orphan-reaper.js +413 -0
  191. package/src/outgoing-policy.js +183 -0
  192. package/src/pairing.js +236 -12
  193. package/src/path-hash-trust-ledger.js +642 -25
  194. package/src/permission-audit.js +79 -3
  195. package/src/permission-deadlines.js +82 -0
  196. package/src/permission-floor.js +1770 -0
  197. package/src/permission-hook.js +180 -69
  198. package/src/permission-manager.js +1175 -94
  199. package/src/permission-mode-support.js +35 -0
  200. package/src/permission-resolver.js +174 -12
  201. package/src/permission-rule-store.js +411 -0
  202. package/src/permission-scope.js +43 -0
  203. package/src/platform.js +483 -23
  204. package/src/preview-ingress.js +54 -0
  205. package/src/preview-target.js +213 -0
  206. package/src/prompt-evaluator.js +34 -4
  207. package/src/provider-customization.js +180 -0
  208. package/src/providers.js +228 -6
  209. package/src/push.js +30 -4
  210. package/src/question-route-map.js +130 -0
  211. package/src/redaction.js +360 -8
  212. package/src/roster-broadcast.js +186 -0
  213. package/src/schedule-parser.js +311 -0
  214. package/src/scheduled-task-store.js +945 -0
  215. package/src/scheduler.js +1099 -0
  216. package/src/sdk-session.js +2374 -168
  217. package/src/server-cli/preview-shutdown.js +22 -0
  218. package/src/server-cli/push-notification-handler.js +11 -2
  219. package/src/server-cli/server-orchestrator.js +50 -4
  220. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  221. package/src/server-cli-child.js +33 -18
  222. package/src/server-cli.js +760 -62
  223. package/src/server-identity.js +42 -14
  224. package/src/service.js +682 -53
  225. package/src/session-archive-limits.js +15 -0
  226. package/src/session-archive.js +1029 -0
  227. package/src/session-busy-state.js +72 -0
  228. package/src/session-ci-watcher.js +926 -0
  229. package/src/session-context.js +7 -2
  230. package/src/session-manager.js +3879 -308
  231. package/src/session-message-history.js +749 -37
  232. package/src/session-pr-status.js +654 -0
  233. package/src/session-pr-threads.js +271 -0
  234. package/src/session-preset-trust.js +3 -3
  235. package/src/session-preset.js +10 -5
  236. package/src/session-state-persistence.js +94 -17
  237. package/src/session-timeout-manager.js +20 -0
  238. package/src/session-title.js +168 -0
  239. package/src/session-token-store.js +70 -36
  240. package/src/session-wake.js +240 -0
  241. package/src/shell-approval-info.js +2 -2
  242. package/src/shell-approval-store.js +3 -1
  243. package/src/skills-loader.js +7 -4
  244. package/src/skills-manager.js +2 -2
  245. package/src/skills-trust.js +95 -13
  246. package/src/skills-usage.js +22 -5
  247. package/src/snapshots-store.js +2 -3
  248. package/src/statusline.js +596 -0
  249. package/src/subagent-counter.js +9 -1
  250. package/src/summarize-session.js +51 -4
  251. package/src/supervisor.js +99 -38
  252. package/src/sweep-stale-provider-dirs.js +95 -0
  253. package/src/thinking-level-wire.js +39 -0
  254. package/src/thinking-stream.js +179 -0
  255. package/src/token-manager.js +39 -9
  256. package/src/tool-result.js +61 -0
  257. package/src/transcript-sources.js +109 -0
  258. package/src/transcript-tasks.js +413 -31
  259. package/src/trusted-file-read.js +302 -0
  260. package/src/tunnel/base.js +0 -8
  261. package/src/tunnel/cloudflare.js +145 -35
  262. package/src/tunnel/index.js +13 -1
  263. package/src/tunnel/preview.js +64 -0
  264. package/src/tunnel-check.js +1 -1
  265. package/src/turn-outcome.js +137 -0
  266. package/src/turn-tracker.js +0 -0
  267. package/src/usage-normalize.js +122 -0
  268. package/src/user-shell-session.js +157 -37
  269. package/src/utils/agent-sdk-version.js +107 -0
  270. package/src/utils/argv-safety.js +741 -0
  271. package/src/utils/auth-cause.js +60 -0
  272. package/src/utils/binary-package-manifest.js +597 -0
  273. package/src/utils/binary-version.js +224 -0
  274. package/src/utils/bounded-regex-worker.js +25 -0
  275. package/src/utils/bounded-regex.js +153 -0
  276. package/src/utils/claude-binary.js +43 -0
  277. package/src/utils/claude-config-dir.js +245 -0
  278. package/src/utils/claude-login-command.js +16 -0
  279. package/src/utils/claude-native-route.js +81 -0
  280. package/src/utils/componentwise-resolver.js +301 -0
  281. package/src/utils/composite-key.js +45 -0
  282. package/src/utils/deploy-control-files.js +87 -0
  283. package/src/utils/exec-failure-reason.js +21 -0
  284. package/src/utils/git-repo.js +42 -0
  285. package/src/utils/is-entry-point.js +137 -0
  286. package/src/utils/iso-datetime.js +51 -0
  287. package/src/utils/node-pty-probe.js +95 -0
  288. package/src/utils/node-pty-support.js +118 -0
  289. package/src/utils/opened-file-path.js +167 -0
  290. package/src/utils/path-containment.js +165 -0
  291. package/src/utils/permission-mode-sidecar.js +51 -0
  292. package/src/utils/preflight.js +485 -29
  293. package/src/utils/read-limiter.js +217 -0
  294. package/src/utils/regular-file.js +375 -0
  295. package/src/utils/safe-regex.js +113 -0
  296. package/src/utils/small-file.js +129 -0
  297. package/src/utils/spawn-env.js +196 -5
  298. package/src/utils/stale-session-dirs.js +182 -0
  299. package/src/utils/stat-identity.js +43 -0
  300. package/src/utils/verify-binary.js +276 -0
  301. package/src/utils/verify-provenance.js +634 -0
  302. package/src/utils/wire-counters.js +48 -0
  303. package/src/web-task-manager.js +256 -16
  304. package/src/worktree-gc.js +11 -3
  305. package/src/ws-auth.js +69 -21
  306. package/src/ws-broadcaster.js +14 -2
  307. package/src/ws-client-manager.js +16 -1
  308. package/src/ws-client-sender.js +7 -0
  309. package/src/ws-file-ops/browser.js +370 -66
  310. package/src/ws-file-ops/common.js +384 -11
  311. package/src/ws-file-ops/git.js +615 -44
  312. package/src/ws-file-ops/index.js +7 -0
  313. package/src/ws-file-ops/memory.js +460 -0
  314. package/src/ws-file-ops/open-nofollow.js +354 -0
  315. package/src/ws-file-ops/reader.js +676 -94
  316. package/src/ws-forwarding.js +373 -55
  317. package/src/ws-handler-context.js +89 -2
  318. package/src/ws-history.js +1018 -177
  319. package/src/ws-message-handlers.js +23 -1
  320. package/src/ws-outbound-schemas.js +207 -0
  321. package/src/ws-permissions.js +589 -38
  322. package/src/ws-schemas.js +6 -0
  323. package/src/ws-server.js +936 -105
  324. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  325. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  326. package/src/dashboard-next/dist/index.html +0 -13
@@ -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',
@@ -250,9 +415,23 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
250
415
  * List files recursively from session CWD with gitignore filtering.
251
416
  * Max depth defaults to 3. Optional query for substring filtering.
252
417
  */
253
- async function listFiles(ws, sessionCwd, query, sessionId) {
418
+ async function listFiles(ws, sessionCwd, query, sessionId, mcpResources = []) {
419
+ // #6823: MCP resources ride alongside the project file listing so the
420
+ // dashboard `@`-picker can surface them. They are cwd-independent (a BYOK
421
+ // session with no project cwd can still expose resources), applied the same
422
+ // substring `query` filter as files, and included in EVERY response branch.
423
+ const filterResources = (list, q) => {
424
+ const arr = Array.isArray(list) ? list.filter((r) => r && typeof r.uri === 'string' && r.uri) : []
425
+ if (!q || typeof q !== 'string' || !q.trim()) return arr
426
+ const lower = q.toLowerCase()
427
+ return arr.filter((r) =>
428
+ r.uri.toLowerCase().includes(lower) ||
429
+ (typeof r.name === 'string' && r.name.toLowerCase().includes(lower)))
430
+ }
431
+ const resources = filterResources(mcpResources, query)
432
+
254
433
  if (!sessionCwd) {
255
- const response = { type: 'file_list', files: [], error: 'File listing is not available in this mode' }
434
+ const response = { type: 'file_list', files: [], resources, error: 'File listing is not available in this mode' }
256
435
  if (sessionId) response.sessionId = sessionId
257
436
  sendFn(ws, response)
258
437
  return
@@ -267,7 +446,9 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
267
446
  // Load .gitignore if it exists
268
447
  let gitignoreRules = []
269
448
  try {
270
- 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')
271
452
  gitignoreRules = parseGitignore(content)
272
453
  } catch {
273
454
  // No .gitignore or unreadable — proceed without
@@ -304,7 +485,14 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
304
485
  if (d.name === 'node_modules') continue
305
486
 
306
487
  const absPath = join(dir, d.name)
307
- 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('/')
308
496
 
309
497
  // Validate symlinks stay within CWD boundary
310
498
  if (d.isSymbolicLink()) {
@@ -357,7 +545,7 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
357
545
  result = files.filter(f => f.path.toLowerCase().includes(lower))
358
546
  }
359
547
 
360
- const response = { type: 'file_list', files: result, error: null }
548
+ const response = { type: 'file_list', files: result, resources, error: null }
361
549
  if (sessionId) response.sessionId = sessionId
362
550
  sendFn(ws, response)
363
551
  } catch (err) {
@@ -367,7 +555,7 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
367
555
  } else if (err && typeof err === 'object' && err.code === 'EACCES') {
368
556
  message = 'Permission denied'
369
557
  }
370
- const response = { type: 'file_list', files: [], error: message }
558
+ const response = { type: 'file_list', files: [], resources, error: message }
371
559
  if (sessionId) response.sessionId = sessionId
372
560
  sendFn(ws, response)
373
561
  }
@@ -404,7 +592,16 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
404
592
  * path (`listSlashCommands`) and the connect-time `auth_bootstrap` burst
405
593
  * (#5555) so both produce an identical `commands` array.
406
594
  */
407
- async function computeSlashCommands(cwd, providerName = null) {
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 } = {}) {
408
605
  const commands = []
409
606
  const seen = new Set()
410
607
 
@@ -429,7 +626,18 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
429
626
 
430
627
  const scanDir = async (dir, source) => {
431
628
  try {
432
- 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
433
641
  for (const entry of entries) {
434
642
  if (!entry.isFile() || !entry.name.endsWith('.md')) continue
435
643
  if (entry.name.includes('/') || entry.name.includes('\\')) continue
@@ -439,7 +647,9 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
439
647
 
440
648
  let description = ''
441
649
  try {
442
- 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')
443
653
  const lines = content.split('\n')
444
654
  for (const line of lines) {
445
655
  const trimmed = line.trim()
@@ -461,12 +671,31 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
461
671
  if (cwd) {
462
672
  await scanDir(join(cwd, '.claude', 'commands'), 'project')
463
673
  }
464
- 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')
677
+
678
+ // #6823: MCP-server prompts merged as `source: 'mcp'` slash commands
679
+ // (`/mcp__<server>__<prompt>`). Added last so a same-named built-in / .md
680
+ // skill still wins the collision (built-in > project > user > mcp), and the
681
+ // namespaced `mcp__` names practically never collide anyway. Element shape
682
+ // matches the others (`{ name, description, source }`).
683
+ if (Array.isArray(mcpPrompts)) {
684
+ for (const p of mcpPrompts) {
685
+ if (!p || typeof p.name !== 'string' || !p.name) continue
686
+ if (seen.has(p.name)) continue
687
+ seen.add(p.name)
688
+ commands.push({
689
+ name: p.name,
690
+ description: typeof p.description === 'string' ? p.description : '',
691
+ source: 'mcp',
692
+ })
693
+ }
694
+ }
465
695
 
466
- // Stable order: built-ins (alphabetical) first, then project/user
467
- // (alphabetical) — using `source` as the primary key. `builtin` sorts
468
- // before `project` and `user` lexically.
469
- const sourceRank = (s) => (s === 'builtin' ? 0 : s === 'project' ? 1 : 2)
696
+ // Stable order: built-ins (alphabetical) first, then project/user, then
697
+ // MCP prompts (each alphabetical) — using `source` as the primary key.
698
+ const sourceRank = (s) => (s === 'builtin' ? 0 : s === 'project' ? 1 : s === 'user' ? 2 : 3)
470
699
  commands.sort((a, b) => {
471
700
  const rankDiff = sourceRank(a.source) - sourceRank(b.source)
472
701
  if (rankDiff !== 0) return rankDiff
@@ -476,8 +705,8 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
476
705
  return commands
477
706
  }
478
707
 
479
- async function listSlashCommands(ws, cwd, sessionId, providerName = null) {
480
- const commands = await computeSlashCommands(cwd, providerName)
708
+ async function listSlashCommands(ws, cwd, sessionId, providerName = null, mcpPrompts = [], opts = {}) {
709
+ const commands = await computeSlashCommands(cwd, providerName, mcpPrompts, opts)
481
710
  const response = { type: 'slash_commands', commands }
482
711
  if (sessionId) response.sessionId = sessionId
483
712
  sendFn(ws, response)
@@ -506,8 +735,17 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
506
735
  * the others (#3024).
507
736
  */
508
737
  const listDir = async (dir, source) => {
738
+ const dirArg = dir
509
739
  try {
510
- 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
+ }
511
749
  const filenames = entries
512
750
  .filter(e => e.isFile() && e.name.endsWith('.md'))
513
751
  .filter(e => !e.name.includes('/') && !e.name.includes('\\'))
@@ -523,7 +761,7 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
523
761
  // the caller-supplied list when multiple providers are active (#2965).
524
762
  const userAgentsDirs = (Array.isArray(opts.userAgentsDirs) && opts.userAgentsDirs.length > 0)
525
763
  ? opts.userAgentsDirs
526
- : [join(homedir(), '.claude', 'agents')]
764
+ : [join(claudeConfigDir(), 'agents')]
527
765
 
528
766
  // Phase 1: readdir project + all user dirs in parallel (#3024). Promise.all
529
767
  // preserves input order in the resolved array, so first-wins dedup below
@@ -533,8 +771,11 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
533
771
  if (cwd) {
534
772
  dirScans.push(listDir(join(cwd, '.claude', 'agents'), 'project'))
535
773
  }
536
- for (const dir of userAgentsDirs) {
537
- 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
+ }
538
779
  }
539
780
  const dirResults = await Promise.all(dirScans)
540
781
 
@@ -556,7 +797,8 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
556
797
  const agents = await Promise.all(winners.map(async ({ name, dir, source, filename }) => {
557
798
  let description = ''
558
799
  try {
559
- 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')
560
802
  const lines = content.split('\n')
561
803
  for (const line of lines) {
562
804
  const trimmed = line.trim()
@@ -582,8 +824,70 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
582
824
  sendFn(ws, response)
583
825
  }
584
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
+
585
887
  return {
586
888
  listDirectory,
889
+ checkGitRepo,
890
+ refuseGitRepoCheck,
587
891
  browseFiles,
588
892
  listFiles,
589
893
  listSlashCommands,