@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/server-cli.js CHANGED
@@ -13,6 +13,7 @@ import { createTunnel, parseTunnelArg } from './tunnel/index.js'
13
13
  import { waitForTunnel } from './tunnel-check.js'
14
14
  import { PushManager, settlePush } from './push.js'
15
15
  import { ensureIngestSecret } from './event-ingest.js'
16
+ import { getChroxyHostEnv } from './chroxy-host-metadata.js'
16
17
  import { PushNotificationHandler } from './server-cli/push-notification-handler.js'
17
18
  import { StartupDisplay } from './server-cli/startup-display.js'
18
19
  import { TunnelLifecycleHandler } from './server-cli/tunnel-lifecycle-handler.js'
@@ -21,7 +22,7 @@ import { hostname, homedir } from 'os'
21
22
  import { readFileSync, existsSync } from 'fs'
22
23
  import { fileURLToPath } from 'url'
23
24
  import { dirname, join, relative, sep } from 'path'
24
- import { createLogger, setJsonMode, initFileLogging } from './logger.js'
25
+ import { createLogger, setJsonMode, initFileLogging, setConsoleQuiet } from './logger.js'
25
26
 
26
27
  const log = createLogger('cli')
27
28
  // #5368 slice (b): QRCode + writeConnectionInfo moved to startup-display.js with
@@ -46,9 +47,12 @@ import { getRegistryForProvider, watchModelsOverlay } from './models.js'
46
47
  // environment-manager.js itself remains behind the dynamic import below
47
48
  // (`if (config?.environments?.enabled)`).
48
49
  import { UNREACHABLE_STATUSES } from './environment-statuses.js'
49
- import { resolveSkipPermissions, buildEnvironmentBackend, isUserShellEnabled, getAllowAnyModelProviders } from './config.js'
50
+ import { resolveSkipPermissions, buildEnvironmentBackend, isUserShellEnabled, getAllowAnyModelProviders, isSemanticTitlesEnabled, resolveSemanticTitleModel, resolveSemanticTitleTimeoutMs, resolveBinaryProvenanceMode, isBinarySignatureGateEnabled } from './config.js'
51
+ import { buildOrchestrationManager } from './orchestration/build-manager.js'
52
+ import { buildSchedulerEngine } from './scheduler.js'
50
53
  import { parseDuration } from './duration.js'
51
54
  import { createSessionTokenStore } from './session-token-store.js'
55
+ import { StatusLineManager } from './statusline.js'
52
56
 
53
57
  const __filename = fileURLToPath(import.meta.url)
54
58
  const __dirname = dirname(__filename)
@@ -71,6 +75,103 @@ const SERVER_VERSION = packageJson.version
71
75
  * @param {{ tunnelMode: string, tunnelUrl: string, attempt?: number, maxAttempts?: number }} args
72
76
  * @returns {object} WS message envelope
73
77
  */
78
+ /**
79
+ * #6927/#7067 — write the (possibly rotated) primary token into config.json.
80
+ *
81
+ * Exported and `_write`-injectable so the DURABILITY limb is testable: #7067
82
+ * made `writeFileRestricted` REPORT a post-rename directory-fsync failure rather
83
+ * than throw, which is right for callers where a landed write must not be
84
+ * reported as failed. This caller is the deliberate exception — #6965 built an
85
+ * operator-visible `REVOKE_NOT_DURABLE` frame for exactly this outcome and the
86
+ * revoke ack is gated on this callback, so swallowing the caveat would trade the
87
+ * old false-FAILURE for a false SUCCESS on the panic button. Re-raise it and let
88
+ * #6965's existing path surface it.
89
+ *
90
+ * @param {string} configFile
91
+ * @param {string} newToken
92
+ * @param {{ durable?: boolean, _write?: Function }} [opts]
93
+ */
94
+ export function persistTokenToConfigFile(configFile, newToken, { durable = false, _write = writeFileRestricted } = {}) {
95
+ const raw = existsSync(configFile) ? readFileSync(configFile, 'utf-8') : '{}'
96
+ const cfg = JSON.parse(raw)
97
+ cfg.apiToken = newToken
98
+ const outcome = _write(configFile, JSON.stringify(cfg, null, 2), { durable })
99
+ if (durable && outcome?.durabilityUnconfirmed) {
100
+ throw new Error(
101
+ `token written but its directory entry could not be fsynced (${outcome.durabilityUnconfirmed})`,
102
+ )
103
+ }
104
+ }
105
+
106
+ /**
107
+ * #7055 — build the `TokenManager({ onPersist })` callback.
108
+ *
109
+ * Extracted from `startServer`'s inline closure so BOTH limbs are drivable by a
110
+ * test. It is load-bearing for a security guarantee (#6965 gates the revoke ack
111
+ * on it settling; #7045 made it rethrow so a failed write cannot masquerade as a
112
+ * durable revoke) yet nothing executed it: the gate tests supply a synthetic
113
+ * `onPersist`, and every local/CI run disables the keychain.
114
+ *
115
+ * The keychain seam matters more than it looks. `setToken()` re-checks
116
+ * availability itself and RETURNS SILENTLY when the keychain is unavailable — no
117
+ * throw, no boolean. The outer `_isKeychainAvailable()` guard is the only thing
118
+ * stopping that from becoming a persist that writes nothing anywhere and still
119
+ * reports success, i.e. a revoke acked for a write that never happened.
120
+ *
121
+ * @param {object} opts
122
+ * @param {string} opts.configFile - path to `~/.chroxy/config.json`
123
+ * @param {{ error: Function }} [opts.logger]
124
+ * @param {Function} [opts._isKeychainAvailable] - test seam
125
+ * @param {Function} [opts._setToken] - test seam
126
+ * @param {Function} [opts._write] - test seam, forwarded to persistTokenToConfigFile
127
+ * @returns {(newToken: string, ctx?: { reason?: string }) => void}
128
+ */
129
+ export function buildTokenPersistCallback({
130
+ configFile,
131
+ logger = log,
132
+ _isKeychainAvailable = isKeychainAvailable,
133
+ _setToken = setToken,
134
+ _write = writeFileRestricted,
135
+ } = {}) {
136
+ return (newToken, { reason } = {}) => {
137
+ // #6927 — a 'revoke' is the operator panic button (a compromised primary
138
+ // token killed NOW). Persist it DURABLY so a power loss within the OS
139
+ // writeback window can't roll config.json back to the compromised token and
140
+ // resurrect it on the next daemon start. A routine 'scheduled' rotation is
141
+ // fail-safe (the old token keeps working through its grace window), so it
142
+ // stays non-durable. Only the file fallback is fsync-controllable here; the
143
+ // keychain path's durability is the OS keychain's responsibility.
144
+ const durable = reason === 'revoke'
145
+ const persistToFile = () => persistTokenToConfigFile(configFile, newToken, { durable, _write })
146
+ try {
147
+ if (_isKeychainAvailable()) {
148
+ try {
149
+ _setToken(newToken)
150
+ } catch {
151
+ // Keychain write failed — fall back to config file
152
+ persistToFile()
153
+ }
154
+ } else {
155
+ persistToFile()
156
+ }
157
+ } catch (err) {
158
+ // `err?.message || String(err)` (the platform.js idiom), not `err.message`:
159
+ // a thrown `null`/`undefined` would make the LOG LINE throw a TypeError,
160
+ // which then replaces the original failure on its way to the ack gate —
161
+ // the operator would be told the persist failed for the wrong reason and
162
+ // never see a `Failed to persist token` line at all.
163
+ logger.error(`Failed to persist token: ${err?.message || String(err)}`)
164
+ // #6965 — RETHROW. The revoke ack is now gated on this callback resolving,
165
+ // so swallowing the error here would report a durable revoke that never
166
+ // reached the disk (the exact false-safety this closes). TokenManager logs
167
+ // the rejection too, and for a revoke WsServer sends an explicit
168
+ // REVOKE_NOT_DURABLE error FIRST and then the token-less revoke transition
169
+ // anyway — the client must still re-authenticate.
170
+ throw err
171
+ }
172
+ }
173
+ }
174
+
74
175
  export function buildTunnelWarmingStatus({ tunnelMode, tunnelUrl, attempt, maxAttempts }) {
75
176
  const base = {
76
177
  type: 'server_status',
@@ -446,7 +547,28 @@ export async function startCliServer(config) {
446
547
  setJsonMode(true)
447
548
  }
448
549
 
449
- initFileLoggingFromConfig(config)
550
+ const fileLogging = initFileLoggingFromConfig(config)
551
+
552
+ // #7162: under a service manager (CHROXY_DAEMON=1) the console streams are
553
+ // captured to files nothing rotates (launchd StandardOutPath et al); the
554
+ // logger's console mirror is how the stdout capture reached 32MB in a
555
+ // month. With the file log live it is authoritative, so quiet the
556
+ // info/debug/audit mirror — warn/error keep flowing to chroxy-stderr.log,
557
+ // and write() falls back to the console for any line whose file append
558
+ // fails. Only when file logging actually initialized: with no file log,
559
+ // the capture is the only record and must stay verbose. Capture BOUNDING
560
+ // deliberately does NOT happen here — startCliServer re-runs in every
561
+ // supervised child restart, and the cap is safe exactly once per service
562
+ // boot (see the `start` action in cli/server-cmd.js).
563
+ if (process.env.CHROXY_DAEMON === '1' && fileLogging.enabled) {
564
+ setConsoleQuiet(true)
565
+ }
566
+
567
+ // #6633: publish Chroxy's host identity into this process's environment so the
568
+ // in-process SDK provider's Bash tools inherit it (subprocess providers get it
569
+ // via buildSpawnEnv). Computed + authoritative — a session can read
570
+ // $CHROXY_HOST_VERSION / _GIT_SHA / _CHANNEL to confirm the exact running build.
571
+ Object.assign(process.env, getChroxyHostEnv())
450
572
 
451
573
  const PORT = config.port || parseInt(process.env.PORT || '8765', 10)
452
574
  const NO_AUTH = !!config.noAuth
@@ -479,7 +601,7 @@ export async function startCliServer(config) {
479
601
  }
480
602
 
481
603
  if (!NO_AUTH && !API_TOKEN) {
482
- console.error('[!] No API token configured. Run \'npx chroxy init\' first.') // intentional user-facing output
604
+ console.error('[!] No API token configured. Run \'chroxy init\' first.') // intentional user-facing output
483
605
  process.exit(1)
484
606
  }
485
607
 
@@ -658,6 +780,12 @@ export async function startCliServer(config) {
658
780
  // API-valid model id without a release). Empty Set unless the operator set
659
781
  // config.providers.allowAnyModel.
660
782
  allowAnyModelProviders: getAllowAnyModelProviders(config),
783
+ // #6858: opt-in provenance verification for spawned provider binaries. Both
784
+ // OFF by default (behaviour identical to #6708). `mode` drives the SHA-256
785
+ // pin ledger (warn surfaces a swap + allows; block refuses the spawn);
786
+ // `signatureGate` toggles the macOS `spctl` notarization gate.
787
+ binaryProvenanceMode: resolveBinaryProvenanceMode(config),
788
+ binarySignatureGate: isBinarySignatureGateEnabled(config),
661
789
  providerType,
662
790
  maxToolInput: config.maxToolInput || null,
663
791
  transforms: config.transforms || [],
@@ -667,6 +795,18 @@ export async function startCliServer(config) {
667
795
  // #5665: monthly programmatic-credit budget meter config.
668
796
  billing: config.billing || null,
669
797
  maxMessages: config.maxMessages || config.maxHistory || null,
798
+ // #6764: opt-in semantic session titles. Off unless the operator set
799
+ // features.semanticTitles:true (or CHROXY_SEMANTIC_TITLES=1). The title model
800
+ // defaults to a cheap Haiku alias; summarize.model / CHROXY_SEMANTIC_TITLES_MODEL
801
+ // override it (resolveSemanticTitleModel). When off, the historical truncation
802
+ // label is used unchanged.
803
+ semanticTitlesEnabled: isSemanticTitlesEnabled(config),
804
+ semanticTitleModel: resolveSemanticTitleModel(config),
805
+ // #6764: hard timeout (ms) for the fire-and-forget one-shot title call so a
806
+ // stalled provider aborts the subprocess and falls open to the truncation
807
+ // label instead of leaking a never-settling promise. Env / summarize.titleTimeoutMs
808
+ // override; default ~15s (resolveSemanticTitleTimeoutMs).
809
+ semanticTitleTimeoutMs: resolveSemanticTitleTimeoutMs(config),
670
810
  // #3749 / #3884 / #3899: SOFT-warning inactivity timeout (ms). null = BaseSession default (30 min).
671
811
  // #3899: HARD-cap inactivity timeout (ms). null = BaseSession default (2h).
672
812
  // #4467: stream-stall recovery (ms). null = BaseSession default (5min).
@@ -758,6 +898,57 @@ export async function startCliServer(config) {
758
898
  }
759
899
  })
760
900
 
901
+ // #6791: read + execute the user's OWN Claude Code statusLine script and
902
+ // surface its stdout. The command is ONLY ever the one in the user's own
903
+ // settings.json (~/.claude / the project's .claude) — never client-supplied —
904
+ // and every execution is bounded by a timeout + stdout cap + secret-stripped
905
+ // env (see statusline.js). Inactive (silent no-op) when no statusLine is
906
+ // configured. Session-scoped broadcast so one session's status never fans out
907
+ // to clients viewing another.
908
+ const statusLineManager = new StatusLineManager()
909
+ const buildStatuslineContext = (sessionId) => {
910
+ const entry = sessionManager.getSession(sessionId)
911
+ if (!entry) return null
912
+ const usage = entry.cumulativeUsage || {}
913
+ const cost = {}
914
+ if (Number.isFinite(usage.costUsd)) cost.totalCostUsd = usage.costUsd
915
+ return {
916
+ sessionId,
917
+ sessionName: entry.name || null,
918
+ cwd: entry.cwd,
919
+ projectDir: entry.worktreeRepoDir || entry.cwd,
920
+ model: { id: entry.session?.model || entry.session?.bootedModel || null },
921
+ cost,
922
+ }
923
+ }
924
+ statusLineManager.on('output', ({ sessionId, text, active, truncated }) => {
925
+ // wsServer is assigned further down; a periodic tick can fire first.
926
+ if (!wsServer) return
927
+ wsServer._broadcastToSession(sessionId, { type: 'statusline_output', text, active, truncated })
928
+ })
929
+ sessionManager.on('session_created', ({ sessionId }) => {
930
+ statusLineManager.startSession(sessionId, () => buildStatuslineContext(sessionId))
931
+ })
932
+ sessionManager.on('session_destroyed', ({ sessionId }) => {
933
+ // Clears the session's periodic timer. On graceful shutdown, destroyAll()
934
+ // cascades a session_destroyed per session, so every timer is cleared here
935
+ // (and all timers are .unref()'d, so they never block process exit anyway).
936
+ statusLineManager.stopSession(sessionId)
937
+ })
938
+ // Turn-boundary refresh for immediacy (mirrors Claude Code's "new assistant
939
+ // message" trigger); the periodic loop in StatusLineManager covers the rest.
940
+ sessionManager.on('session_event', ({ sessionId, event }) => {
941
+ if (event !== 'result') return
942
+ const ctx = buildStatuslineContext(sessionId)
943
+ if (ctx) statusLineManager.refresh(sessionId, ctx)
944
+ })
945
+ // NOTE: session_created above fires only for FUTURE sessions; the default
946
+ // session (and any restored ones) were created before these listeners
947
+ // registered, so their loops are started AFTER wsServer is constructed (see
948
+ // below) — starting them here would let the first tick's `output` fire while
949
+ // `wsServer` is still null, and the manager's dedupe would then swallow the
950
+ // (dropped) broadcast until the script's text next changed.
951
+
761
952
  // 3. Create push notification manager, token manager, and WebSocket server
762
953
  const pushManager = new PushManager({
763
954
  storagePath: join(homedir(), '.chroxy', 'push-tokens.json'),
@@ -803,28 +994,9 @@ export async function startCliServer(config) {
803
994
  const tokenManager = NO_AUTH ? null : new TokenManager({
804
995
  token: API_TOKEN,
805
996
  tokenExpiry: config.tokenExpiry || null,
806
- onPersist: (newToken) => {
807
- const persistToFile = () => {
808
- const raw = existsSync(configFile) ? readFileSync(configFile, 'utf-8') : '{}'
809
- const cfg = JSON.parse(raw)
810
- cfg.apiToken = newToken
811
- writeFileRestricted(configFile, JSON.stringify(cfg, null, 2))
812
- }
813
- try {
814
- if (isKeychainAvailable()) {
815
- try {
816
- setToken(newToken)
817
- } catch {
818
- // Keychain write failed — fall back to config file
819
- persistToFile()
820
- }
821
- } else {
822
- persistToFile()
823
- }
824
- } catch (err) {
825
- log.error(`Failed to persist token: ${err.message}`)
826
- }
827
- },
997
+ // #7055 — the callback body lives in `buildTokenPersistCallback` (above) so
998
+ // both its limbs are testable; as an inline closure nothing could drive it.
999
+ onPersist: buildTokenPersistCallback({ configFile }),
828
1000
  })
829
1001
  if (tokenManager) tokenManager.start()
830
1002
 
@@ -927,10 +1099,24 @@ export async function startCliServer(config) {
927
1099
  sessionTokenStore: createSessionTokenStore({ dir: chroxyDir }),
928
1100
  })
929
1101
 
1102
+ // #6691 (E-4): the orchestration engine (null when the feature is off or if
1103
+ // construction fails — never a throw, so it can't break daemon boot).
1104
+ const orchestrationManager = buildOrchestrationManager({ sessionManager, config, chroxyDir, log })
1105
+
1106
+ // #6865: the headless scheduler engine — fires due scheduled tasks (#6862)
1107
+ // into a session with no client connected. null unless the operator opted in
1108
+ // (`features.scheduler` / CHROXY_ENABLE_SCHEDULER=1), so a default daemon arms
1109
+ // no timers and spawns nothing.
1110
+ const schedulerEngine = buildSchedulerEngine({ sessionManager, config, logger: log })
1111
+
930
1112
  wsServer = new WsServer({
931
1113
  port: PORT,
932
1114
  apiToken: API_TOKEN,
933
1115
  sessionManager,
1116
+ orchestrationManager,
1117
+ // #6871: nullable — null whenever the scheduled-execution gate is closed (the
1118
+ // default). The scheduled-tasks handlers report that as "not armed".
1119
+ schedulerEngine,
934
1120
  defaultSessionId,
935
1121
  authRequired: !NO_AUTH,
936
1122
  pushManager,
@@ -952,9 +1138,24 @@ export async function startCliServer(config) {
952
1138
  // enforce the 2026-04-11 audit blocker 1 workspace allowlist.
953
1139
  config,
954
1140
  })
1141
+ // #6791: now that wsServer exists, start statusLine loops for the sessions
1142
+ // that already existed at boot (the default + any restored). session_created
1143
+ // covers every FUTURE session; startSession is idempotent so no double-start.
1144
+ for (const s of sessionManager.listSessions()) {
1145
+ if (s?.sessionId) statusLineManager.startSession(s.sessionId, () => buildStatuslineContext(s.sessionId))
1146
+ }
955
1147
  // Resolve the bind address. --no-auth forces loopback; otherwise an explicit
956
1148
  // config.host (e.g. --host 127.0.0.1) binds that interface with auth still
957
1149
  // on, and the default (undefined) binds 0.0.0.0 as before.
1150
+ // #6691 (E-4): forward engine run deltas to host-level (unbound) dashboard
1151
+ // clients. The manager already projects each delta to the wire shape; the
1152
+ // WsServer only routes it. Guarded so a broadcast error never bubbles.
1153
+ if (orchestrationManager) {
1154
+ orchestrationManager.on('run_delta', (delta) => {
1155
+ try { wsServer._broadcastOrchestrationDelta(delta) } catch (err) { log.warn(`orchestration delta broadcast failed: ${err?.message || err}`) }
1156
+ })
1157
+ }
1158
+
958
1159
  const bindHost = resolveBindHost({ noAuth: NO_AUTH, host: config.host })
959
1160
  // #5356 (visibility layer): one warning when binding non-loopback (the
960
1161
  // default 0.0.0.0 included) — LAN peers can reach the unauthenticated
@@ -1115,6 +1316,15 @@ export async function startCliServer(config) {
1115
1316
  tunnelConfig: config.tunnelConfig,
1116
1317
  tunnelName: config.tunnelName || null,
1117
1318
  tunnelHostname: config.tunnelHostname || null,
1319
+ // #6858: fold cloudflared into the SAME opt-in provenance gate + pin
1320
+ // ledger as the provider binaries. Reuse the SessionManager's ledger
1321
+ // instance so pins are unified across every spawned binary. Off by
1322
+ // default (mode 'off' + gate false) ⇒ the tunnel gate is a no-op.
1323
+ binaryProvenance: {
1324
+ mode: resolveBinaryProvenanceMode(config),
1325
+ signatureGate: isBinarySignatureGateEnabled(config),
1326
+ ledger: sessionManager.binaryProvenanceLedger,
1327
+ },
1118
1328
  },
1119
1329
  wsServer,
1120
1330
  startupDisplay,
@@ -1208,6 +1418,8 @@ export async function startCliServer(config) {
1208
1418
  pairingManager,
1209
1419
  pushManager,
1210
1420
  billingCanaryMonitor,
1421
+ orchestrationManager,
1422
+ schedulerEngine,
1211
1423
  modelsOverlayWatcher,
1212
1424
  getWorktreeReapTimer: () => worktreeReapTimer,
1213
1425
  emergencyCleanupSync,
@@ -192,9 +192,20 @@ function readIdentityFromKeychain(keychain) {
192
192
  * @param {object} [opts]
193
193
  * @param {object} [opts.keychain]
194
194
  * @param {string} [opts.filePath]
195
+ * @param {boolean} [opts.durable] - #6927: fsync the fallback-file write before
196
+ * returning (temp before rename + dir after). Set ONLY by `rotateServerIdentity`
197
+ * (the compromise-response path); first-run mint leaves it off (fail-safe — a
198
+ * lost mint just re-mints). Applies only to the FILE fallback; the keychain
199
+ * path's durability is the OS keychain's responsibility, not ours.
200
+ * @param {Function} [opts._write] - test seam for the atomic writer.
195
201
  * @returns {'keychain'|'file'}
196
202
  */
197
- export function persistServerIdentity(keyPair, { keychain = realKeychain, filePath = DEFAULT_IDENTITY_FILE } = {}) {
203
+ export function persistServerIdentity(keyPair, {
204
+ keychain = realKeychain,
205
+ filePath = DEFAULT_IDENTITY_FILE,
206
+ durable = false,
207
+ _write = writeFileRestricted,
208
+ } = {}) {
198
209
  const secretB64 = Buffer.from(keyPair.secretKey).toString('base64')
199
210
  if (keychain.isKeychainAvailable()) {
200
211
  try {
@@ -211,7 +222,7 @@ export function persistServerIdentity(keyPair, { keychain = realKeychain, filePa
211
222
  // on CREATION — a pre-existing file at a looser mode would keep that mode.
212
223
  // writeFileRestricted chmods the final file to 0600 unconditionally.
213
224
  mkdirSync(dirname(filePath), { recursive: true })
214
- writeFileRestricted(filePath, JSON.stringify({ v: 1, secretKey: secretB64 }))
225
+ _write(filePath, JSON.stringify({ v: 1, secretKey: secretB64 }), { durable })
215
226
  return 'file'
216
227
  }
217
228
 
@@ -338,6 +349,7 @@ export function rotateServerIdentity({
338
349
  keychain = realKeychain,
339
350
  filePath = DEFAULT_IDENTITY_FILE,
340
351
  rotationFilePath = DEFAULT_IDENTITY_ROTATION_FILE,
352
+ _write = writeFileRestricted,
341
353
  } = {}) {
342
354
  const current = loadServerIdentity({ keychain, filePath })
343
355
  if (!current) {
@@ -366,8 +378,15 @@ export function rotateServerIdentity({
366
378
  // reuse writeFileRestricted for its ATOMIC temp+rename write so a crash can't
367
379
  // leave a half-written cert — the 0600 mode it also sets is incidental here
368
380
  // (nothing secret), not a requirement.
381
+ //
382
+ // #6927 — the sidecar is left NON-durable on purpose: its rollback is a
383
+ // CONTINUITY concern, not a security one. If a power loss drops the sidecar
384
+ // (while the durable secret persist below survives), the daemon serves the NEW
385
+ // identity and pinned clients fall back to a manual re-pair — an availability
386
+ // regression, never a resurrection of the retired key. Only the secret persist
387
+ // (whose rollback WOULD resurrect the retired/compromised key) is made durable.
369
388
  mkdirSync(dirname(rotationFilePath), { recursive: true })
370
- writeFileRestricted(
389
+ _write(
371
390
  rotationFilePath,
372
391
  JSON.stringify({
373
392
  v: 1,
@@ -377,7 +396,12 @@ export function rotateServerIdentity({
377
396
  }),
378
397
  )
379
398
  // Persist the new secret in place of the old (keychain or fallback file).
380
- const backend = persistServerIdentity(next, { keychain, filePath })
399
+ // #6927 — DURABLE: `chroxy identity rotate` is the compromise-response path, so
400
+ // a power-loss rollback resurrecting the RETIRED secret is the same acute class
401
+ // as a token revoke. fsync the fallback-file write before reporting success
402
+ // (the keychain path's durability is the OS's job). First-run mint stays
403
+ // non-durable (fail-safe — a lost mint just re-mints).
404
+ const backend = persistServerIdentity(next, { keychain, filePath, durable: true, _write })
381
405
  log.info(`Rotated server identity (backend: ${backend}); continuity cert written for previous pin`)
382
406
  return { previousPublicKey: current.publicKey, newPublicKey: next.publicKey, backend }
383
407
  }