@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
package/src/platform.js CHANGED
@@ -1,4 +1,6 @@
1
- import { writeFileSync, chmodSync, renameSync, unlinkSync } from 'fs'
1
+ import { writeFileSync, chmodSync, renameSync, unlinkSync, openSync, closeSync, fsyncSync } from 'fs'
2
+ import { dirname } from 'path'
3
+ import { execFileSync } from 'child_process'
2
4
  import { createLogger } from './logger.js'
3
5
 
4
6
  const log = createLogger('platform')
@@ -7,9 +9,194 @@ export const isWindows = process.platform === 'win32'
7
9
  export const isMac = process.platform === 'darwin'
8
10
  export const isLinux = process.platform === 'linux'
9
11
 
10
- export function defaultShell() {
11
- if (isWindows) return process.env.COMSPEC || 'cmd.exe'
12
- return process.env.SHELL || '/bin/zsh'
12
+ // Windows rename failures worth one retry: an open handle held by antivirus or
13
+ // Windows Search briefly locks the destination (#6644 / #4927).
14
+ const WIN_RENAME_RETRY_CODES = new Set(['EPERM', 'EACCES', 'EBUSY', 'EEXIST'])
15
+ // fsync error codes that mean "this filesystem cannot provide durability here"
16
+ // and are therefore BENIGN for the `{ durable: true }` path: the data already
17
+ // reached the OS page cache and the atomic rename still happened, we just can't
18
+ // force it further — exactly the guarantee of the non-durable default path. A
19
+ // GENUINE I/O failure (EIO / ENOSPC) is NOT in this set and propagates, so a
20
+ // durability-critical caller (the session-token revoke snapshot) reports the
21
+ // failure instead of a false success. EINVAL is the common member: a *directory*
22
+ // fsync on some virtual / network filesystems, or a regular-file fsync on a FS
23
+ // with no writeback to sync, surfaces EINVAL / ENOTSUP rather than succeeding.
24
+ const BENIGN_FSYNC_CODES = new Set(['EINVAL', 'ENOTSUP', 'EPERM', 'EISDIR', 'EBADF', 'ENOSYS'])
25
+ // Well-known SYSTEM SID — locale-independent (the NAME "SYSTEM" is localized, so
26
+ // icacls grants must use the SID form to work on non-English Windows).
27
+ const SID_SYSTEM = 'S-1-5-18'
28
+ // Absolute System32 dir so `whoami`/`icacls` resolve to the real Windows tools
29
+ // regardless of PATH order (a shell like Git Bash puts its own `whoami` first).
30
+ const WIN_SYSTEM32 = `${process.env.SystemRoot || process.env.windir || 'C:\\Windows'}\\System32`
31
+
32
+ let _cachedUserSid
33
+ /**
34
+ * The current user's SID (e.g. `S-1-5-21-…`), resolved once via `whoami /user`
35
+ * and cached for the process. SIDs (not account names) are used for icacls so
36
+ * the grant is correct regardless of domain membership or OS display language.
37
+ * Returns null if it can't be resolved (caller then leaves inherited ACLs).
38
+ */
39
+ function currentUserSid() {
40
+ if (_cachedUserSid !== undefined) return _cachedUserSid
41
+ _cachedUserSid = null
42
+ try {
43
+ const out = execFileSync(`${WIN_SYSTEM32}\\whoami.exe`, ['/user', '/fo', 'csv', '/nh'], {
44
+ encoding: 'utf-8',
45
+ windowsHide: true,
46
+ timeout: 5000,
47
+ })
48
+ const m = out.match(/S-1-[0-9-]+/)
49
+ if (m) _cachedUserSid = m[0]
50
+ } catch {
51
+ // whoami unavailable / failed — leave null; the file keeps inherited ACLs.
52
+ }
53
+ return _cachedUserSid
54
+ }
55
+
56
+ /**
57
+ * Stamp an owner-only DACL on a Windows file (#6644): strip inherited ACEs and
58
+ * grant Full control to ONLY the current user + SYSTEM. This is the NTFS
59
+ * analogue of POSIX 0o600 — without it, files under `%LOCALAPPDATA%` /
60
+ * `~/.chroxy` inherit the parent directory's ACL, which the audit found could
61
+ * include a secondary group able to read the secrets. Best-effort: an icacls
62
+ * failure is logged, not thrown — the file is still written (just at inherited
63
+ * perms), and the caller's write must not fail over a hardening step.
64
+ */
65
+ function stampWindowsAcl(filePath) {
66
+ // Real-Windows only: icacls/whoami don't exist elsewhere. The `_isWindowsOverride`
67
+ // seam drives the write/rename path on POSIX CI runners, but must NOT shell out
68
+ // to Windows tools there — those tests inject `_stampAcl` to assert this call.
69
+ if (!isWindows) return
70
+ const sid = currentUserSid()
71
+ if (!sid) {
72
+ log.warn(`could not resolve current-user SID — leaving inherited ACL on ${filePath}`)
73
+ return
74
+ }
75
+ try {
76
+ execFileSync(`${WIN_SYSTEM32}\\icacls.exe`, [
77
+ filePath,
78
+ '/inheritance:r',
79
+ '/grant:r', `*${sid}:F`,
80
+ '/grant:r', `*${SID_SYSTEM}:F`,
81
+ ], { stdio: 'ignore', windowsHide: true, timeout: 5000 })
82
+ } catch (err) {
83
+ log.warn(`icacls could not stamp owner-only ACL on ${filePath}: ${err.message}`)
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Per-platform "how to install cloudflared" hint for user-facing errors:
89
+ * Windows → winget, macOS → Homebrew, Linux → the Cloudflare package repo.
90
+ * The tunnel adapter and doctor share this single source of truth; the desktop
91
+ * app mirrors the same logic in Rust (`cloudflared_install_hint` in lib.rs), as
92
+ * it can't call across the JS/Rust boundary (#6649).
93
+ */
94
+ export function cloudflaredInstallHint() {
95
+ if (isMac) return 'brew install cloudflared'
96
+ if (isWindows) return 'winget install Cloudflare.cloudflared'
97
+ return 'see https://pkg.cloudflare.com/ for installation'
98
+ }
99
+
100
+ /**
101
+ * The OS default shell: Windows → `COMSPEC` (cmd.exe), POSIX → `$SHELL`
102
+ * (falling back to zsh). `platform`/`env` are injectable so callers that resolve
103
+ * a shell for a spawn (e.g. the embedded user-shell, #6646) can unit-test both
104
+ * platform branches on any CI host; production calls pass no args.
105
+ */
106
+ export function defaultShell({ platform = process.platform, env = process.env } = {}) {
107
+ if (platform === 'win32') return env.COMSPEC || 'cmd.exe'
108
+ return env.SHELL || '/bin/zsh'
109
+ }
110
+
111
+ /**
112
+ * fsync `target` so its buffered bytes — or, for a directory (`isDir`), the
113
+ * rename that just changed its entries — are physically on disk before we
114
+ * return (#6914). The fd is opened solely to drive the fsync and is ALWAYS
115
+ * closed in the `finally`, so this leaks no descriptor even when fsync throws.
116
+ *
117
+ * A BENIGN fsync failure (`BENIGN_FSYNC_CODES` — e.g. EINVAL on a filesystem
118
+ * that cannot sync a directory entry) is logged and swallowed: the write already
119
+ * landed in the page cache and the rename happened, so we are no worse off than
120
+ * the non-durable path. Any OTHER error (EIO / ENOSPC — a genuine durability
121
+ * failure) propagates so the caller's durability contract fails loudly.
122
+ *
123
+ * `_fsync` is a test seam (default `fsyncSync`) so the durable + benign-error
124
+ * paths are exercisable without a real disk fault.
125
+ */
126
+ export function fsyncForDurability(target, { isDir = false, _fsync = fsyncSync } = {}) {
127
+ let fd
128
+ try {
129
+ // Directories open read-only; regular files open `r+` so the handle is
130
+ // writable — a strictly read-only fd is rejected by fsync on a few
131
+ // platforms. The file/dir already exists (we just wrote/renamed it), so no
132
+ // O_CREAT and no mode is needed.
133
+ fd = openSync(target, isDir ? 'r' : 'r+')
134
+ _fsync(fd)
135
+ } catch (err) {
136
+ if (err && BENIGN_FSYNC_CODES.has(err.code)) {
137
+ log.warn(`durable-write: fsync of ${isDir ? 'directory' : 'file'} ${target} unsupported (${err.code}); continuing best-effort`)
138
+ return
139
+ }
140
+ throw err
141
+ } finally {
142
+ if (fd !== undefined) {
143
+ try { closeSync(fd) } catch { /* fd already invalid — nothing to reclaim */ }
144
+ }
145
+ }
146
+ }
147
+
148
+ /**
149
+ * #7054 — the ONE implementation of "confirm a rename is durable, and REPORT
150
+ * rather than throw when it is not".
151
+ *
152
+ * This policy lived in three places (`writeFileRestricted`,
153
+ * `credential-store.writeStoreAtomically`, `byok-mcp-config.writeClaudeConfigAtomic`)
154
+ * and drifted exactly as #7054 predicted: two of the three threw on a post-rename
155
+ * directory-fsync failure, reporting a write that had ALREADY landed as failed
156
+ * (#7067). Rename STRATEGY stays with each caller — they genuinely differ, and
157
+ * credential-store's snapshot-and-restore retry is strictly more protective than a
158
+ * plain rename — but the durability VERDICT is now shared.
159
+ *
160
+ * Never throws. By the time this runs the rename has published the file, so the
161
+ * write succeeded; only the durability of its directory ENTRY is unproven.
162
+ * Callers for whom that caveat must be operator-visible re-raise it themselves
163
+ * (see server-cli's revoke persist, which feeds #6965's REVOKE_NOT_DURABLE frame).
164
+ *
165
+ * @param {string} filePath — the path whose DIRECTORY ENTRY changed; its dirname
166
+ * is fsynced. The entry may have been created (rename) or removed (unlink) —
167
+ * both are directory-metadata changes with the same durability requirement.
168
+ * @param {{ durable?: boolean, fsync?: Function, onWindows?: boolean, change?: string }} [opts]
169
+ * `change` describes what happened to the entry, for the log only ('rename' by
170
+ * default, 'removal' for an unlink). The generic wording matters: this helper
171
+ * serves both, and telling an operator a REMOVED file is "written and live"
172
+ * would send them looking for the wrong thing.
173
+ * `fsync` is injected at the `fsyncForDurability(target, { isDir })` level so a
174
+ * test can pin ORDERING (which target, file-or-dir, whether the final file
175
+ * existed yet) rather than merely that a syscall happened.
176
+ * @returns {{ durabilityUnconfirmed: string | null }}
177
+ */
178
+ export function confirmRenameDurable(
179
+ filePath,
180
+ { durable = false, fsync = fsyncForDurability, onWindows = isWindows, change = 'rename' } = {},
181
+ ) {
182
+ // Windows has no directory fsync, and renameSync already passes
183
+ // MOVEFILE_WRITE_THROUGH (a durable rename), so the temp-file fsync plus the
184
+ // write-through rename cover the same guarantee.
185
+ if (!durable || onWindows) return { durabilityUnconfirmed: null }
186
+ try {
187
+ fsync(dirname(filePath), { isDir: true })
188
+ return { durabilityUnconfirmed: null }
189
+ } catch (err) {
190
+ const durabilityUnconfirmed = err?.message || String(err)
191
+ // The only surviving artifact: nothing is thrown and callers that ignore the
192
+ // return value see a plain success, so this must be `error`.
193
+ log.error(
194
+ `durable-write: the ${change} of ${filePath} IS in effect, but its directory entry could not be ` +
195
+ `fsynced (${durabilityUnconfirmed}) — a power loss could roll that ${change} back. ` +
196
+ `Treat its durability as unconfirmed.`,
197
+ )
198
+ return { durabilityUnconfirmed }
199
+ }
13
200
  }
14
201
 
15
202
  /**
@@ -53,6 +240,31 @@ export function defaultShell() {
53
240
  * should pass a per-process suffix such as `.tmp-${process.pid}`
54
241
  * so the intermediate files never overwrite each other. Honoured
55
242
  * on POSIX since #4874, and on Windows since #4913.
243
+ * - `durable` (default `false`): when `true`, `fsync` the temp file
244
+ * BEFORE the rename (so its bytes are physically on disk) and, on
245
+ * POSIX, `fsync` the containing DIRECTORY AFTER the rename (so the
246
+ * rename itself is durable) — the standard atomic-durable-write recipe
247
+ * (#6914). The default is OFF: the ordinary config / state callers are
248
+ * fail-SAFE (a lost page-cache write on power loss merely reverts to a
249
+ * harmless earlier state, or re-pairs), and an fsync per write would add
250
+ * blocking disk I/O to hot state-persistence paths for no security gain.
251
+ * Only durability-CRITICAL callers opt in — specifically the session-token
252
+ * REVOKE snapshot (`_persistSessionTokensSnapshot` in `pairing.js`), where
253
+ * a power loss / kernel panic within the OS writeback window could
254
+ * otherwise resurrect a revoked token AFTER the operator was told the
255
+ * revoke succeeded. A genuine PRE-rename fsync failure (EIO / ENOSPC) is
256
+ * re-thrown so that caller reports the failure — nothing was published, so
257
+ * "the write failed" is true. A POST-rename DIRECTORY-fsync failure is NOT
258
+ * thrown (#7067): the rename already published the file, so the write
259
+ * SUCCEEDED and only its directory entry's durability is unproven; it is
260
+ * returned as `durabilityUnconfirmed` and logged at error. Callers for whom
261
+ * that caveat must be operator-visible re-raise it themselves — see
262
+ * server-cli's revoke persist, which feeds #6965's REVOKE_NOT_DURABLE frame.
263
+ * A benign fsync failure (EINVAL / ENOTSUP on a FS that cannot sync — see
264
+ * `BENIGN_FSYNC_CODES`) is logged and the write still succeeds. On Windows the directory fsync is skipped: there is no
265
+ * directory-fsync, and `renameSync` already passes `MOVEFILE_WRITE_THROUGH`
266
+ * (a durable rename), so the temp-file fsync plus the write-through rename
267
+ * cover the same guarantee.
56
268
  * - `_isWindowsOverride` (test-only): force the Windows branch
57
269
  * regardless of host platform. Mirrors the same hook in
58
270
  * `SessionStatePersistence` and lets the cross-platform atomicity
@@ -67,24 +279,40 @@ export function defaultShell() {
67
279
  * cleanup wrappers in environment-manager.js / session-state-persistence.js
68
280
  * had this warn before the hoist in #4874).
69
281
  *
70
- * AV-held-handle retry decision (#4927). On Windows, an open handle held
71
- * by antivirus / Windows Search can cause `renameSync` to fail with
72
- * EPERM / EACCES / EBUSY / EEXIST. `session-state-persistence.js._rotateToBak`
73
- * handles this with a one-shot retry, but `writeFileRestricted` does NOT
74
- * replicate that pattern — every existing caller already has its own
75
- * retry / fallback path (session manager debounce loop, models cache TTL
76
- * refresh, env manager next-tick re-persist), so an inner retry would
77
- * mask the error from the caller without changing the outcome.
78
- * `_rotateToBak`'s retry is special because rotation has no caller-level
79
- * retry — a missed rotation silently loses the prior-generation `.bak`
80
- * until the next write. If a future site without its own retry adopts
81
- * `writeFileRestricted`, revisit this decision. See `platform-windows.test.js`
82
- * for the full rationale.
282
+ * AV-held-handle retry (#4927 / #6644). On Windows, an open handle held by
283
+ * antivirus / Windows Search can cause `renameSync` to fail with EPERM /
284
+ * EACCES / EBUSY / EEXIST. This helper now does a ONE-SHOT retry on those codes
285
+ * (Windows only) before giving up — matching `session-state-persistence.js.
286
+ * _rotateToBak`. The original #4927 decision was to NOT retry here, on the
287
+ * grounds that every caller then had its own retry/fallback; that reasoning was
288
+ * flagged for revisit "if a future site without its own retry adopts
289
+ * `writeFileRestricted`", and #6644's DPAPI `_winSetToken` is exactly that site
290
+ * (a keychain write with no outer retry). The retry is bounded to a single extra
291
+ * attempt and to the transient-lock error codes, so a genuine failure (e.g.
292
+ * ENOSPC, a bad path) still surfaces immediately. See `platform-windows.test.js`.
293
+ */
294
+ /**
295
+ * @returns {{ durabilityUnconfirmed: string | null }} `durabilityUnconfirmed` is
296
+ * the post-rename directory-fsync error message when the file is live but its
297
+ * directory entry's durability could not be confirmed; `null` otherwise —
298
+ * including every non-durable write, which makes no durability claim at all.
299
+ * Mirrors `credential-store.writeStoreAtomically`'s contract (#7067).
83
300
  */
84
301
  export function writeFileRestricted(
85
302
  filePath,
86
303
  data,
87
- { tmpSuffix = '.tmp', _isWindowsOverride } = {},
304
+ {
305
+ tmpSuffix = '.tmp',
306
+ durable = false,
307
+ _isWindowsOverride,
308
+ // Test seams (#6644): inject the ACL stamper / rename so the Windows ACL +
309
+ // one-shot-retry paths are exercisable on a POSIX CI runner.
310
+ _stampAcl = stampWindowsAcl,
311
+ _rename = renameSync,
312
+ // Test seam (#6914): inject the fsync used by the `durable` path so the
313
+ // durable + benign-fsync-error branches are exercisable without a disk fault.
314
+ _fsync = fsyncSync,
315
+ } = {},
88
316
  ) {
89
317
  const onWindows = _isWindowsOverride ?? isWindows
90
318
  const tmpPath = `${filePath}${tmpSuffix}`
@@ -111,14 +339,56 @@ export function writeFileRestricted(
111
339
  // `writeFileSync`'s `mode` is mostly a no-op on Win32. The temp+rename
112
340
  // pattern still applies for atomicity (#4913).
113
341
  if (onWindows) {
342
+ // Create/truncate the temp file EMPTY, stamp the owner-only DACL, THEN write
343
+ // the data — so the secret bytes only ever exist while the file is already
344
+ // owner-only. Writing first would leave a window where the freshly-written
345
+ // bytes carry the parent's (possibly group-readable) inherited ACL, and this
346
+ // also re-restricts a stale, permissively-ACL'd temp left by a prior crash.
347
+ // The DACL survives the same-directory rename (NTFS preserves explicit DACLs
348
+ // across MoveFileEx), so the final file lands owner-only (#6644).
349
+ writeFileSync(tmpPath, '')
350
+ _stampAcl(tmpPath)
114
351
  writeFileSync(tmpPath, data)
115
352
  } else {
116
353
  writeFileSync(tmpPath, data, { mode: 0o600 })
117
354
  chmodSync(tmpPath, 0o600)
118
355
  }
356
+ // #6914: durability-critical callers force the temp file's bytes to disk BEFORE
357
+ // the rename, so a power loss / kernel panic within the OS writeback window can
358
+ // never roll a reported-successful write back to its pre-write state. A genuine
359
+ // fsync failure means we cannot promise durability — clean up the orphaned temp
360
+ // and surface it, mirroring the rename-failure path below. (`fsyncForDurability`
361
+ // has already swallowed the benign, filesystem-cannot-sync codes.)
362
+ if (durable) {
363
+ try {
364
+ fsyncForDurability(tmpPath, { _fsync })
365
+ } catch (err) {
366
+ try {
367
+ unlinkSync(tmpPath)
368
+ } catch (cleanupErr) {
369
+ if (cleanupErr && cleanupErr.code !== 'ENOENT') {
370
+ log.warn(`Failed to remove orphaned ${tmpPath}: ${cleanupErr.message}`)
371
+ }
372
+ }
373
+ throw err
374
+ }
375
+ }
119
376
  try {
120
- renameSync(tmpPath, filePath)
377
+ _rename(tmpPath, filePath)
121
378
  } catch (err) {
379
+ // Windows: an AV / Windows Search handle can briefly lock the destination
380
+ // (EPERM/EACCES/EBUSY/EEXIST). Retry once before giving up (#6644 / #4927).
381
+ if (onWindows && err && WIN_RENAME_RETRY_CODES.has(err.code)) {
382
+ try {
383
+ _rename(tmpPath, filePath)
384
+ // Windows-only branch: no directory fsync (Windows has none; the durable
385
+ // rename comes from MOVEFILE_WRITE_THROUGH). The temp file was already
386
+ // fsynced above when `durable`.
387
+ return { durabilityUnconfirmed: null }
388
+ } catch {
389
+ // fall through to cleanup + rethrow the original error below
390
+ }
391
+ }
122
392
  try {
123
393
  unlinkSync(tmpPath)
124
394
  } catch (cleanupErr) {
@@ -128,12 +398,86 @@ export function writeFileRestricted(
128
398
  }
129
399
  throw err
130
400
  }
401
+ // #6914: after a successful rename, fsync the CONTAINING DIRECTORY so the rename
402
+ // itself (a directory-metadata change) is durable — otherwise a crash could
403
+ // leave the new file's data on disk but the directory entry still pointing at
404
+ // the old inode. POSIX-only: Windows has no directory fsync, and its renameSync
405
+ // already passes MOVEFILE_WRITE_THROUGH (a durable rename), so the temp-file
406
+ // fsync above plus the write-through rename cover the same guarantee.
407
+ //
408
+ // #7067: this failure does NOT throw, unlike the PRE-rename fsync above. The
409
+ // asymmetry is the point. Before the rename nothing is published, so "the write
410
+ // failed" is TRUE and throwing is right. After it, the file is already live and
411
+ // only the durability of its directory ENTRY is unproven — throwing there told
412
+ // the caller a landed write had failed, and `pairing.js` turned that into "the
413
+ // session-token revoke failed" for a revoke already on disk, sending the
414
+ // operator to retry or to assume a revoked token was still live. Report the
415
+ // caveat instead, matching `credential-store.writeStoreAtomically` (#6964/#7061),
416
+ // which resolved this exact moment the same way.
417
+ return confirmRenameDurable(filePath, {
418
+ durable,
419
+ onWindows,
420
+ // Bind this call's `_fsync` seam into the shared helper's higher-level one.
421
+ fsync: (target, opts) => fsyncForDurability(target, { ...opts, _fsync }),
422
+ })
131
423
  }
132
424
 
133
- export function forceKill(child) {
425
+ /**
426
+ * Terminate `child` — its whole descendant TREE on Windows (taskkill /T), or
427
+ * just the DIRECT process on POSIX (see the per-platform notes below; callers
428
+ * that need the whole POSIX group spawn `detached` and signal the negative pid).
429
+ *
430
+ * POSIX: `child.kill(force ? 'SIGKILL' : 'SIGTERM')` on the direct process —
431
+ * the long-standing behaviour (callers that need the whole group spawn
432
+ * `detached` and signal the negative pid themselves). `force:false` stays a
433
+ * graceful SIGTERM so a caller's existing SIGTERM→SIGKILL escalation is
434
+ * unchanged.
435
+ *
436
+ * Windows: there is no process-group signal and no graceful console-tree
437
+ * termination — Node maps BOTH `SIGTERM` and `SIGKILL` to `TerminateProcess`
438
+ * on the DIRECT pid, so descendants are orphaned. This is acute for Chroxy:
439
+ * `.cmd`/`.bat` provider shims (claude, codex, gemini, …) run under
440
+ * `cmd.exe /d /s /c`, so the real agent/node process is a GRANDCHILD of the
441
+ * tracked pid. `cmd /c` waits for its child, so actively killing the wrapper
442
+ * (respawn / model-switch / destroy) leaves node running — still editing files
443
+ * and burning tokens — after Stop/teardown (#6643). Reap the whole tree with
444
+ * `taskkill /PID <pid> /T /F`. The `force` flag is POSIX-only; on Windows the
445
+ * kill is always forced (matching Node's existing TerminateProcess semantics,
446
+ * where SIGTERM was never graceful anyway). Best-effort: an already-exited pid
447
+ * or a taskkill failure falls back to a direct `child.kill()` — this never
448
+ * throws, so it is safe to call from a teardown path.
449
+ */
450
+ export function killProcessTree(child, { force = false } = {}) {
451
+ if (!child) return
134
452
  if (isWindows) {
135
- child.kill('SIGKILL')
136
- } else {
137
- child.kill('SIGKILL')
453
+ const pid = child.pid
454
+ if (pid) {
455
+ try {
456
+ execFileSync('taskkill', ['/PID', String(pid), '/T', '/F'], {
457
+ stdio: 'ignore',
458
+ windowsHide: true,
459
+ // Bound the teardown path: a wedged taskkill must not hang stop /
460
+ // respawn. On timeout execFileSync throws and we fall back to the
461
+ // direct child.kill() below (#6657 review).
462
+ timeout: 5000,
463
+ })
464
+ return
465
+ } catch {
466
+ // pid already gone, or taskkill unavailable/failed — fall through to a
467
+ // direct kill so teardown still makes progress.
468
+ }
469
+ }
470
+ try { child.kill('SIGKILL') } catch { /* already gone */ }
471
+ return
138
472
  }
473
+ try { child.kill(force ? 'SIGKILL' : 'SIGTERM') } catch { /* already gone */ }
474
+ }
475
+
476
+ /**
477
+ * Force-kill `child` and its whole descendant tree (#6643). POSIX sends
478
+ * SIGKILL to the process; Windows reaps the tree via taskkill. See
479
+ * {@link killProcessTree}.
480
+ */
481
+ export function forceKill(child) {
482
+ killProcessTree(child, { force: true })
139
483
  }
package/src/providers.js CHANGED
@@ -202,12 +202,23 @@ export function getProvider(name) {
202
202
  * the server still boots with a readable banner even if someone registers a
203
203
  * custom provider without a label, and returns `'unknown'` for empty input.
204
204
  *
205
+ * #6676 — resolves through `getProvider(name)` (not the static `PROVIDERS[name]`),
206
+ * so codex reports the label of its RUNTIME driver (app-server by default →
207
+ * "OpenAI Codex (app-server)", exec on `CHROXY_CODEX_APPSERVER=0` → "OpenAI
208
+ * Codex"), matching what a live session's `constructor.displayLabel` reports.
209
+ * `getProvider` throws for an unknown name, so those fall back to the raw name.
210
+ *
205
211
  * @param {string | undefined | null} name - Provider identifier
206
212
  * @returns {string} Human-readable label
207
213
  */
208
214
  export function resolveProviderLabel(name) {
209
215
  if (!name || typeof name !== 'string') return 'unknown'
210
- const ProviderClass = PROVIDERS[name]
216
+ let ProviderClass
217
+ try {
218
+ ProviderClass = getProvider(name)
219
+ } catch {
220
+ ProviderClass = PROVIDERS[name]
221
+ }
211
222
  if (ProviderClass && typeof ProviderClass.displayLabel === 'string' && ProviderClass.displayLabel.length > 0) {
212
223
  return ProviderClass.displayLabel
213
224
  }
@@ -256,8 +267,16 @@ export function getProviderDataDirs() {
256
267
  */
257
268
  export function listProviders() {
258
269
  const list = []
259
- for (const [name, ProviderClass] of Object.entries(PROVIDERS)) {
270
+ for (const name of Object.keys(PROVIDERS)) {
260
271
  if (HIDDEN.has(name)) continue
272
+ // #6618 — resolve to the class that will ACTUALLY be instantiated for this
273
+ // provider id. getProvider honors CHROXY_CODEX_APPSERVER for codex (app-server
274
+ // by default, exec on opt-out), so the picker's advertised capabilities match
275
+ // what a live session reports in session_info. For every other provider
276
+ // getProvider is just PROVIDERS[name], so this is a no-op. codex's app-server
277
+ // class delegates dataDir/resolveAuth/preflight to the exec class, so `auth` is
278
+ // unchanged — only the capability shape follows the runtime driver.
279
+ const ProviderClass = getProvider(name)
261
280
  list.push({
262
281
  name,
263
282
  capabilities: {