@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
@@ -0,0 +1,241 @@
1
+ /**
2
+ * Opt-in provenance verification for spawned provider binaries (#6858).
3
+ *
4
+ * P1 (#6708, `verify-binary.js`) detects a binary that is missing, not
5
+ * executable, or macOS-Gatekeeper-quarantined. It does NOT protect against a
6
+ * binary being SWAPPED in place, or against running an un-notarized build when
7
+ * the operator wants only notarized ones. Those are the residual supply-chain
8
+ * surfaces that matter once the orchestration harness (#6691) auto-spawns worker
9
+ * sessions headless with the operator's credentials.
10
+ *
11
+ * This module adds two OPT-IN gates, both OFF by default so P1 behaviour is
12
+ * byte-identical unless an operator opts in:
13
+ *
14
+ * 1. **SHA-256 pin ledger (cross-platform).** The binary's content hash is
15
+ * pinned on first sight (trust-on-first-use). A later change to the pinned
16
+ * hash re-gates the binary — `warn` surfaces the change and allows the
17
+ * spawn; `block` refuses the spawn until an operator re-approves. This
18
+ * catches an in-place binary swap regardless of signature or quarantine
19
+ * state. The ledger is `binary-provenance-trust.js` — the same path-keyed,
20
+ * atomic-0600, fail-open `PathHashTrustLedger` that backs skills/preset
21
+ * trust.
22
+ * 2. **macOS signature gate (opt-in, hard block).** When enabled, a binary
23
+ * that fails `spctl --assess` (Gatekeeper / notarization) is refused. This
24
+ * is for operators who run ONLY notarized provider builds — chroxy's own
25
+ * bundled providers are ad-hoc/linker-signed and `spctl` rejects them, so
26
+ * this can only ever be opt-in. It is macOS-only: on other platforms the
27
+ * gate is a documented no-op (skipped) — the pin ledger still applies
28
+ * cross-platform. Windows Authenticode is a tracked follow-up.
29
+ *
30
+ * FAIL-SAFE: when a gate is ON, a verification failure blocks (`block` mode) or
31
+ * loudly surfaces (`warn` mode) — it never silently spawns an unverified binary.
32
+ * A binary we cannot even hash is treated as unverifiable: blocked in `block`
33
+ * mode, surfaced-but-allowed in `warn` mode.
34
+ *
35
+ * Every filesystem / subprocess touchpoint is an injectable seam so the whole
36
+ * module is unit-testable with no real binary, ledger file, or `spctl`.
37
+ */
38
+
39
+ import { createHash } from 'crypto'
40
+ import { readFileSync as fsReadFileSync } from 'fs'
41
+ import { execFileSync } from 'child_process'
42
+
43
+ /**
44
+ * Classification of a provenance verification.
45
+ * @enum {string}
46
+ */
47
+ export const PROVENANCE_STATUS = Object.freeze({
48
+ /** Verified: pinned hash matches (and signature gate, if on, passed). */
49
+ OK: 'ok',
50
+ /** First sight: hash recorded (trust-on-first-use) and allowed. */
51
+ PINNED: 'pinned',
52
+ /** Pinned hash differs from the current binary — an in-place swap. */
53
+ HASH_MISMATCH: 'hash_mismatch',
54
+ /** macOS signature gate on and the binary failed `spctl` assessment. */
55
+ SIGNATURE_INVALID: 'signature_invalid',
56
+ /** The binary could not be read to hash it. */
57
+ UNREADABLE: 'unreadable',
58
+ /** No gate applied (both off, or nothing to check). */
59
+ SKIPPED: 'skipped',
60
+ })
61
+
62
+ // Absolute path to the system `spctl`. Like `verify-binary.js`'s use of the
63
+ // absolute `/usr/bin/xattr`, this is deliberately NOT a bare-name PATH lookup: a
64
+ // shadowed `spctl` planted earlier on PATH could lie about the assessment and
65
+ // defeat the gate. `/usr/sbin/spctl` is a fixed, SIP-protected macOS binary.
66
+ export const MACOS_SPCTL = '/usr/sbin/spctl'
67
+
68
+ /**
69
+ * Compute the SHA-256 hex digest of a file's raw bytes.
70
+ *
71
+ * @param {string} path
72
+ * @param {object} [opts]
73
+ * @param {(p:string)=>Buffer} [opts.readFileSync=fsReadFileSync]
74
+ * @returns {string} 64-char lower-case hex digest
75
+ */
76
+ export function sha256File(path, { readFileSync = fsReadFileSync } = {}) {
77
+ const buf = readFileSync(path)
78
+ return createHash('sha256').update(buf).digest('hex')
79
+ }
80
+
81
+ /**
82
+ * Assess a binary's code signature / notarization with `spctl --assess`.
83
+ *
84
+ * macOS-only. On any other platform this is a no-op that returns
85
+ * `{ ok: true, skipped: true }` — there is no equivalent Gatekeeper assessment,
86
+ * and the pin ledger carries the cross-platform integrity story on its own.
87
+ *
88
+ * `spctl --assess --type execute` exits 0 for an accepted (notarized / approved)
89
+ * binary and non-zero otherwise; `execFileSync` throws on a non-zero exit, which
90
+ * we treat as "not accepted" (fail-safe — the gate is opt-in and its whole point
91
+ * is to refuse un-notarized builds).
92
+ *
93
+ * @param {string} path - absolute path to the binary
94
+ * @param {object} [opts]
95
+ * @param {string} [opts.platform=process.platform]
96
+ * @param {Function} [opts.execFile=execFileSync]
97
+ * @returns {{ ok: boolean, skipped: boolean, detail?: string }}
98
+ */
99
+ export function assessMacSignature(path, { platform = process.platform, execFile = execFileSync } = {}) {
100
+ if (platform !== 'darwin') {
101
+ return { ok: true, skipped: true, detail: 'signature assessment is macOS-only' }
102
+ }
103
+ try {
104
+ const out = execFile(MACOS_SPCTL, ['--assess', '--type', 'execute', '--verbose', path], {
105
+ encoding: 'utf-8',
106
+ stdio: ['ignore', 'pipe', 'pipe'],
107
+ timeout: 5000,
108
+ })
109
+ return { ok: true, skipped: false, detail: (typeof out === 'string' ? out.trim() : '') || 'accepted' }
110
+ } catch (err) {
111
+ // Non-zero exit (rejected / error) OR spctl itself unavailable. Both mean
112
+ // "could not confirm this binary is notarized" → not ok. spctl writes its
113
+ // verdict to stderr ("rejected\nsource=Unnotarized Developer ID").
114
+ const stderr = err && typeof err.stderr === 'string' ? err.stderr.trim() : ''
115
+ const detail = stderr || (err && err.message) || 'spctl assessment failed'
116
+ return { ok: false, skipped: false, detail }
117
+ }
118
+ }
119
+
120
+ /**
121
+ * @typedef {Object} ProvenanceVerdict
122
+ * @property {boolean} ok True when the spawn is allowed (not blocked, no fatal issue).
123
+ * @property {string} status One of {@link PROVENANCE_STATUS}.
124
+ * @property {boolean} blocked True when the spawn MUST be refused.
125
+ * @property {string} path The path that was checked.
126
+ * @property {string|null} hash The computed hash (null when not hashed).
127
+ * @property {string} [pinnedHash] The previously-pinned hash on a mismatch.
128
+ * @property {string} [message] Human-facing description of a non-OK verdict.
129
+ * @property {string} [remediation] How to resolve a non-OK verdict.
130
+ */
131
+
132
+ /**
133
+ * Verify a resolved binary's provenance against the opt-in gates.
134
+ *
135
+ * Runs AFTER the P1 `verifyBinary()` existence/quarantine check — the caller
136
+ * only invokes this on an otherwise-healthy, absolute, resolved path.
137
+ *
138
+ * Order: the signature gate runs FIRST (so a signature-rejected binary is never
139
+ * pinned), then the pin ledger.
140
+ *
141
+ * @param {object} opts
142
+ * @param {string} opts.resolvedPath - absolute path the spawn will exec
143
+ * @param {'off'|'warn'|'block'} [opts.mode='off'] - pin-ledger mode
144
+ * @param {boolean} [opts.signatureGate=false] - macOS spctl gate (hard block when on)
145
+ * @param {{ getRecord:Function, approve:Function }|null} [opts.ledger=null] - pin ledger
146
+ * @param {string} [opts.platform=process.platform]
147
+ * @param {Function} [opts.sha256File=sha256File] - injectable hasher
148
+ * @param {Function} [opts.assessSignature=assessMacSignature] - injectable signature assessor
149
+ * @returns {ProvenanceVerdict}
150
+ */
151
+ export function verifyProvenance({
152
+ resolvedPath,
153
+ mode = 'off',
154
+ signatureGate = false,
155
+ ledger = null,
156
+ platform = process.platform,
157
+ sha256File: hashFn = sha256File,
158
+ assessSignature = assessMacSignature,
159
+ } = {}) {
160
+ const path = typeof resolvedPath === 'string' ? resolvedPath : ''
161
+ const pinning = mode === 'warn' || mode === 'block'
162
+
163
+ // Nothing to do — behaviour identical to the pre-#6858 spawn path.
164
+ if ((!pinning && !signatureGate) || !path) {
165
+ return { ok: true, status: PROVENANCE_STATUS.SKIPPED, blocked: false, path, hash: null }
166
+ }
167
+
168
+ // 1. macOS signature gate — a hard block when enabled. Checked first so a
169
+ // signature-rejected binary is never pinned into the trust ledger.
170
+ if (signatureGate) {
171
+ const sig = assessSignature(path, { platform })
172
+ if (!sig.skipped && !sig.ok) {
173
+ return {
174
+ ok: false,
175
+ status: PROVENANCE_STATUS.SIGNATURE_INVALID,
176
+ blocked: true,
177
+ path,
178
+ hash: null,
179
+ message: `code signature / notarization check failed (${sig.detail || 'spctl rejected the binary'})`,
180
+ remediation: 'install a notarized build of this provider, or disable the signature gate (binaryProvenance.signatureGate=false / CHROXY_BINARY_SIGNATURE_GATE=0)',
181
+ }
182
+ }
183
+ }
184
+
185
+ // 2. SHA-256 pin ledger.
186
+ if (pinning) {
187
+ let hash
188
+ try {
189
+ hash = hashFn(path)
190
+ } catch (err) {
191
+ // Cannot read the binary to hash it → unverifiable. Fail-safe: block in
192
+ // `block` mode, surface-but-allow in `warn` mode.
193
+ const blocked = mode === 'block'
194
+ return {
195
+ ok: !blocked,
196
+ status: PROVENANCE_STATUS.UNREADABLE,
197
+ blocked,
198
+ path,
199
+ hash: null,
200
+ message: `could not read binary to verify its hash (${(err && err.code) || (err && err.message) || 'read failed'})`,
201
+ remediation: 'ensure the binary is readable, or disable provenance pinning (binaryProvenance.mode=off)',
202
+ }
203
+ }
204
+
205
+ if (!ledger) {
206
+ // Pinning requested but no ledger wired — treat as skipped rather than
207
+ // guessing. (Production always wires a ledger when mode is on.)
208
+ return { ok: true, status: PROVENANCE_STATUS.SKIPPED, blocked: false, path, hash }
209
+ }
210
+
211
+ const record = ledger.getRecord(path)
212
+ if (!record) {
213
+ // First sight — trust-on-first-use: pin the hash and allow.
214
+ ledger.approve(path, hash)
215
+ return { ok: true, status: PROVENANCE_STATUS.PINNED, blocked: false, path, hash }
216
+ }
217
+ if (record.sha256 === hash) {
218
+ return { ok: true, status: PROVENANCE_STATUS.OK, blocked: false, path, hash }
219
+ }
220
+
221
+ // Mismatch — the binary changed in place since it was pinned. Do NOT re-pin
222
+ // here: the mismatch must stay visible until an operator explicitly approves
223
+ // (matches the skills/preset trust ledgers).
224
+ const blocked = mode === 'block'
225
+ return {
226
+ ok: !blocked,
227
+ status: PROVENANCE_STATUS.HASH_MISMATCH,
228
+ blocked,
229
+ path,
230
+ hash,
231
+ pinnedHash: record.sha256,
232
+ message: `binary hash changed since it was pinned (pinned ${record.sha256.slice(0, 8)}…, now ${hash.slice(0, 8)}…)`,
233
+ remediation: blocked
234
+ ? `if this change is expected, re-approve it by removing this path's entry from the binary trust ledger and re-spawning; otherwise investigate the unexpected binary swap`
235
+ : 'if this change is unexpected, investigate the binary swap',
236
+ }
237
+ }
238
+
239
+ // Signature gate on, pinning off, signature OK → nothing left to check.
240
+ return { ok: true, status: PROVENANCE_STATUS.OK, blocked: false, path, hash: null }
241
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * #7082 — coerce a counter to what its wire schema accepts.
3
+ *
4
+ * Several counters are `z.number().int().nonnegative()` on the wire —
5
+ * `CumulativeUsageSchema`'s four token counts and `turnsBilled`, and
6
+ * `monthly_budget.turnsBilled` — while the server guarded them only for finiteness
7
+ * and sign. Measured against the built schemas, three shapes are refused:
8
+ *
9
+ * 1234.5 -> invalid_type (fractional)
10
+ * 2**53 -> too_big (`.int()` enforces the SAFE-integer range, not just
11
+ * integrality — the #7095 lesson)
12
+ * -1 -> too_small
13
+ *
14
+ * Both server sites carried comments claiming to mirror the schema; they mirrored the
15
+ * `.nonnegative()` half and not the `.int()` half.
16
+ *
17
+ * CLAMPS rather than nulls, because unlike `result.duration` or a skills `lastUsed`
18
+ * these fields are NOT nullable — there is no "unknown" to fall back to, so the
19
+ * representable extreme is the only option left. A count past 2^53 is ~9 quadrillion
20
+ * tokens, i.e. already garbage; pinning it at MAX_SAFE_INTEGER keeps the snapshot
21
+ * parseable instead of blanking the whole session list.
22
+ *
23
+ * `Math.trunc`, matching #7083's choice for counts: these are quantities, not measured
24
+ * elapsed times, and truncation cannot round a value up across a boundary.
25
+ *
26
+ * DELIBERATELY NOT for money. `costUsd` (`z.number().finite()`) and `spentUsd`
27
+ * (`.finite().nonnegative()`) carry no `.int()`, are legitimately fractional, and
28
+ * `costUsd` is legitimately NEGATIVE — a refund / credit-adjustment turn subtracts
29
+ * (#4099). Coercing either would silently corrupt a billing figure, which is the same
30
+ * trap `costBudget` presented in #7083.
31
+ */
32
+
33
+ /** Largest value the `.int()` wire constraint accepts. */
34
+ export const MAX_WIRE_COUNT = Number.MAX_SAFE_INTEGER
35
+
36
+ /**
37
+ * Coerce a value to a non-negative safe integer suitable for an `.int().nonnegative()`
38
+ * wire field.
39
+ *
40
+ * @param {unknown} value
41
+ * @returns {number} a non-negative safe integer; 0 for anything non-numeric or non-finite
42
+ */
43
+ export function toWireCount(value) {
44
+ const n = Number(value)
45
+ if (!Number.isFinite(n) || n <= 0) return 0
46
+ if (n >= MAX_WIRE_COUNT) return MAX_WIRE_COUNT
47
+ return Math.trunc(n)
48
+ }
@@ -162,7 +162,10 @@ export function planRepoGc(repoPath, deps = {}) {
162
162
  exists = existsSync,
163
163
  readLockReason = (wtPath) => readLockReasonFromAdmin(wtPath),
164
164
  // #5706: age-fallback seams. `now`/`mtimeMs` are injectable for tests.
165
- // `maxLockAgeMs` defaults to 30d; 0 (or negative) disables the fallback.
165
+ // `maxLockAgeMs` defaults to 0 — i.e. OFF; any value <= 0 disables the
166
+ // fallback. When on, it fires only STRICTLY past the threshold: an age of
167
+ // exactly `maxLockAgeMs` is still skipped. See DEFAULT_MAX_LOCK_AGE_MS
168
+ // above for why it's opt-in.
166
169
  now = () => Date.now(),
167
170
  mtimeMs = (p) => { try { return statSync(p).mtimeMs } catch { return null } },
168
171
  maxLockAgeMs = DEFAULT_MAX_LOCK_AGE_MS,
@@ -250,9 +250,23 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
250
250
  * List files recursively from session CWD with gitignore filtering.
251
251
  * Max depth defaults to 3. Optional query for substring filtering.
252
252
  */
253
- async function listFiles(ws, sessionCwd, query, sessionId) {
253
+ async function listFiles(ws, sessionCwd, query, sessionId, mcpResources = []) {
254
+ // #6823: MCP resources ride alongside the project file listing so the
255
+ // dashboard `@`-picker can surface them. They are cwd-independent (a BYOK
256
+ // session with no project cwd can still expose resources), applied the same
257
+ // substring `query` filter as files, and included in EVERY response branch.
258
+ const filterResources = (list, q) => {
259
+ const arr = Array.isArray(list) ? list.filter((r) => r && typeof r.uri === 'string' && r.uri) : []
260
+ if (!q || typeof q !== 'string' || !q.trim()) return arr
261
+ const lower = q.toLowerCase()
262
+ return arr.filter((r) =>
263
+ r.uri.toLowerCase().includes(lower) ||
264
+ (typeof r.name === 'string' && r.name.toLowerCase().includes(lower)))
265
+ }
266
+ const resources = filterResources(mcpResources, query)
267
+
254
268
  if (!sessionCwd) {
255
- const response = { type: 'file_list', files: [], error: 'File listing is not available in this mode' }
269
+ const response = { type: 'file_list', files: [], resources, error: 'File listing is not available in this mode' }
256
270
  if (sessionId) response.sessionId = sessionId
257
271
  sendFn(ws, response)
258
272
  return
@@ -357,7 +371,7 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
357
371
  result = files.filter(f => f.path.toLowerCase().includes(lower))
358
372
  }
359
373
 
360
- const response = { type: 'file_list', files: result, error: null }
374
+ const response = { type: 'file_list', files: result, resources, error: null }
361
375
  if (sessionId) response.sessionId = sessionId
362
376
  sendFn(ws, response)
363
377
  } catch (err) {
@@ -367,7 +381,7 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
367
381
  } else if (err && typeof err === 'object' && err.code === 'EACCES') {
368
382
  message = 'Permission denied'
369
383
  }
370
- const response = { type: 'file_list', files: [], error: message }
384
+ const response = { type: 'file_list', files: [], resources, error: message }
371
385
  if (sessionId) response.sessionId = sessionId
372
386
  sendFn(ws, response)
373
387
  }
@@ -404,7 +418,7 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
404
418
  * path (`listSlashCommands`) and the connect-time `auth_bootstrap` burst
405
419
  * (#5555) so both produce an identical `commands` array.
406
420
  */
407
- async function computeSlashCommands(cwd, providerName = null) {
421
+ async function computeSlashCommands(cwd, providerName = null, mcpPrompts = []) {
408
422
  const commands = []
409
423
  const seen = new Set()
410
424
 
@@ -463,10 +477,27 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
463
477
  }
464
478
  await scanDir(join(homedir(), '.claude', 'commands'), 'user')
465
479
 
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)
480
+ // #6823: MCP-server prompts merged as `source: 'mcp'` slash commands
481
+ // (`/mcp__<server>__<prompt>`). Added last so a same-named built-in / .md
482
+ // skill still wins the collision (built-in > project > user > mcp), and the
483
+ // namespaced `mcp__` names practically never collide anyway. Element shape
484
+ // matches the others (`{ name, description, source }`).
485
+ if (Array.isArray(mcpPrompts)) {
486
+ for (const p of mcpPrompts) {
487
+ if (!p || typeof p.name !== 'string' || !p.name) continue
488
+ if (seen.has(p.name)) continue
489
+ seen.add(p.name)
490
+ commands.push({
491
+ name: p.name,
492
+ description: typeof p.description === 'string' ? p.description : '',
493
+ source: 'mcp',
494
+ })
495
+ }
496
+ }
497
+
498
+ // Stable order: built-ins (alphabetical) first, then project/user, then
499
+ // MCP prompts (each alphabetical) — using `source` as the primary key.
500
+ const sourceRank = (s) => (s === 'builtin' ? 0 : s === 'project' ? 1 : s === 'user' ? 2 : 3)
470
501
  commands.sort((a, b) => {
471
502
  const rankDiff = sourceRank(a.source) - sourceRank(b.source)
472
503
  if (rankDiff !== 0) return rankDiff
@@ -476,8 +507,8 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
476
507
  return commands
477
508
  }
478
509
 
479
- async function listSlashCommands(ws, cwd, sessionId, providerName = null) {
480
- const commands = await computeSlashCommands(cwd, providerName)
510
+ async function listSlashCommands(ws, cwd, sessionId, providerName = null, mcpPrompts = []) {
511
+ const commands = await computeSlashCommands(cwd, providerName, mcpPrompts)
481
512
  const response = { type: 'slash_commands', commands }
482
513
  if (sessionId) response.sessionId = sessionId
483
514
  sendFn(ws, response)
@@ -1,5 +1,6 @@
1
1
  import { realpath } from 'fs/promises'
2
- import { resolve, dirname, basename, join, isAbsolute } from 'path'
2
+ import { resolve, dirname, basename, join, isAbsolute, sep } from 'path'
3
+ import { resolveTargetComponentwiseAsync } from '../utils/componentwise-resolver.js'
3
4
 
4
5
  /**
5
6
  * Shared utilities for file operations: CWD resolution, path validation, exec helpers.
@@ -42,6 +43,24 @@ export async function resolveSessionCwd(sessionCwd, cwdRealCache, cwdCacheTtl) {
42
43
  * defeats the otherwise-correct 04a2fbbb1 realpath-TOCTOU fix on the
43
44
  * new-file code path.
44
45
  *
46
+ * #6921/#6923 — RESIDUAL LIMITATION (shared with the pre-#6921 protected-path
47
+ * floor): this resolves the deepest EXISTING ancestor via `realpath()`, then
48
+ * re-appends the unresolved tail LEXICALLY. It therefore cannot honour a `..`
49
+ * that FOLLOWS a symlinked component the way `open(2)` does — both this helper's
50
+ * `realpath` step AND its callers (which pre-compute `absPath = resolve(...)`,
51
+ * collapsing `..` textually before calling in) discard the ordering the kernel
52
+ * uses (follow symlink, THEN apply `..`). The floor closed the same gap by
53
+ * switching to a COMPONENT-BY-COMPONENT walk (`permission-manager.js`
54
+ * `resolveTargetComponentwiseSync`, #6921); the BYOK confinement path was brought
55
+ * to parity in #6923 via the async {@link resolveTargetComponentwiseAsync} +
56
+ * {@link validateRawPathWithinCwd} (raw target, walked componentwise), which the
57
+ * BYOK executor now uses instead of this helper. This helper is retained for the
58
+ * ws-file-ops (dashboard) callers, which hand in paths they have already
59
+ * `resolve()`d / `normalize()`d (no surviving `..`), so the evasion cannot reach
60
+ * it there. Impact of the limitation is narrower than the floor's — the
61
+ * containment check only asks "does it escape the workspace?", and the common
62
+ * chroxy topology (`.claude`/`.git` under the workspace) stays inside it.
63
+ *
45
64
  * @param {string} absPath - Absolute path to resolve (may not exist)
46
65
  * @returns {Promise<string>} Real path with all symlink ancestors resolved
47
66
  */
@@ -101,6 +120,45 @@ export async function realpathOfDeepestAncestor(absPath) {
101
120
  )
102
121
  }
103
122
 
123
+ // #6923/#6928 — the async component-wise resolver (and its separator-agnostic
124
+ // split + MAXSYMLINKS cap) moved to `utils/componentwise-resolver.js`, the SINGLE
125
+ // SOURCE shared with the sync protected-path floor (`permission-manager.js`), so
126
+ // the two open(2)-faithful walks can no longer drift (#6928 was a bug present in
127
+ // BOTH copies). Re-exported here so existing importers of the async resolver from
128
+ // this module keep working.
129
+ export { resolveTargetComponentwiseAsync }
130
+
131
+ /**
132
+ * #6923 — validate that a RAW (un-`resolve`d) target stays within the session
133
+ * CWD, resolving it `open(2)`-faithfully via {@link resolveTargetComponentwiseAsync}.
134
+ *
135
+ * The async sibling / hardened replacement of {@link validatePathWithinCwd} for
136
+ * the BYOK file-ops confinement path. The old path had the caller pre-compute
137
+ * `absPath = resolve(cwd, filePath)` and then ran {@link realpathOfDeepestAncestor}
138
+ * over it — but `resolve()` collapses `..` LEXICALLY, so a `..` that follows a
139
+ * symlinked component was cancelled before any symlink was followed (the #6921
140
+ * evasion, on the sync floor). Handing the RAW target (its `..` intact) to a
141
+ * component-by-component walk closes it: a symlink-out-of-workspace followed by
142
+ * `..` that lexically looks in-bounds now RESOLVES to its true (escaping)
143
+ * destination and is rejected.
144
+ *
145
+ * FAIL-CLOSED: any error resolving the real target (EACCES on a directory, ELOOP
146
+ * on a symlink cycle / depth bomb) propagates to the caller, whose own catch
147
+ * turns it into a rejected tool call — never a silent allow.
148
+ *
149
+ * @param {string} rawTarget - The RAW tool-supplied path (relative or absolute; `..` intact)
150
+ * @param {string} sessionCwd - Session working directory
151
+ * @param {Map} cwdRealCache - Shared cache
152
+ * @param {number} cwdCacheTtl - Cache TTL
153
+ * @returns {Promise<{ valid: boolean, realPath: string, cwdReal: string }>}
154
+ */
155
+ export async function validateRawPathWithinCwd(rawTarget, sessionCwd, cwdRealCache, cwdCacheTtl) {
156
+ const cwdReal = await resolveSessionCwd(sessionCwd, cwdRealCache, cwdCacheTtl)
157
+ const realPath = await resolveTargetComponentwiseAsync(cwdReal, rawTarget)
158
+ const valid = realPath.startsWith(cwdReal + sep) || realPath === cwdReal
159
+ return { valid, realPath, cwdReal }
160
+ }
161
+
104
162
  /**
105
163
  * Validate that a resolved path is within the session CWD.
106
164
  * Follows symlinks to prevent symlink escape.
@@ -110,6 +168,15 @@ export async function realpathOfDeepestAncestor(absPath) {
110
168
  * resolved — see realpathOfDeepestAncestor above for the failure mode
111
169
  * this closes.
112
170
  *
171
+ * NOTE (#6923): this variant takes an already-ABSOLUTE path and resolves via the
172
+ * deepest-existing-ancestor + lexical-tail helper, so a `..` that follows a
173
+ * symlinked component is collapsed lexically before the symlink is followed. The
174
+ * BYOK file-ops path now uses {@link validateRawPathWithinCwd} (raw target +
175
+ * component-wise walk) to close that evasion; the ws-file-ops (dashboard) callers
176
+ * still route here with paths they have already `resolve()`d/`normalize()`d (no
177
+ * surviving `..`), so this function's contract — and its ENAMETOOLONG
178
+ * depth-ceiling fail-closed — is preserved for them unchanged.
179
+ *
113
180
  * @param {string} absPath - Absolute path to validate
114
181
  * @param {string} sessionCwd - Session working directory
115
182
  * @param {Map} cwdRealCache - Shared cache