@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
@@ -47,11 +47,26 @@ export function registerServerCommands(program) {
47
47
  for (const f of failures) {
48
48
  console.error(` ✗ ${f.name}: ${f.message}`)
49
49
  }
50
- console.error('\nRun `npx chroxy doctor` for details, or `--skip-checks` to bypass.\n')
50
+ console.error('\nRun `chroxy doctor` for details, or `--skip-checks` to bypass.\n')
51
51
  process.exitCode = 1
52
52
  return
53
53
  }
54
54
  }
55
+ // #7162: bound the service-manager capture files exactly once per
56
+ // service boot — here, in the process the service manager spawned,
57
+ // BEFORE any supervisor fork. This is the only point where the capture
58
+ // fd offset is guaranteed ~0 on the non-append platform (systemd
59
+ // `file:`); a supervised child restart must never re-truncate under
60
+ // the supervisor's live fd (capStdioCaptureLogs itself excludes
61
+ // win32 — the .cmd wrapper rotates before the redirect opens). The
62
+ // notice lands at the top of the freshly truncated capture.
63
+ if (process.env.CHROXY_DAEMON === '1' && process.env.CHROXY_SUPERVISED !== '1') {
64
+ const { capStdioCaptureLogs } = await import('../logger.js')
65
+ for (const { file, archive, preservedBytes } of capStdioCaptureLogs()) {
66
+ console.log(`[chroxy] capped oversized capture log ${file} (last ${preservedBytes} bytes preserved to ${archive})`)
67
+ }
68
+ }
69
+
55
70
  const useSupervisor = !!parsedTunnel
56
71
  && !config.noAuth
57
72
  && !config.externalUrl
@@ -12,7 +12,7 @@ export function registerServiceCommand(program) {
12
12
 
13
13
  serviceCmd
14
14
  .command('install')
15
- .description('Register Chroxy as a system daemon (launchd/systemd)')
15
+ .description('Register Chroxy as a system daemon (launchd / systemd / Windows Task Scheduler)')
16
16
  .option('--cwd <path>', 'Working directory for Claude sessions')
17
17
  .option('--start-at-login', 'Start automatically on login')
18
18
  .action(async (options) => {
@@ -25,12 +25,6 @@ export function registerServiceCommand(program) {
25
25
  installService,
26
26
  } = await import('../service.js')
27
27
 
28
- if (isWindows) {
29
- console.error('Error: Service install is not supported on Windows.')
30
- console.error('Only macOS (launchd) and Linux (systemd) are supported.')
31
- process.exit(1)
32
- }
33
-
34
28
  const existing = loadServiceState()
35
29
  if (existing) {
36
30
  console.error('Chroxy service is already installed.')
@@ -76,7 +70,7 @@ export function registerServiceCommand(program) {
76
70
  const startAtLogin = options.startAtLogin || false
77
71
 
78
72
  try {
79
- installService({
73
+ const result = installService({
80
74
  nodePath,
81
75
  chroxyBin,
82
76
  claudeBin,
@@ -85,22 +79,37 @@ export function registerServiceCommand(program) {
85
79
  })
86
80
 
87
81
  const paths = getServicePaths()
88
- const servicePath = paths.type === 'launchd' ? paths.plistPath : paths.unitPath
89
82
 
90
83
  console.log('\n\u2705 Chroxy service installed successfully!\n')
91
84
  console.log(` Node: ${nodePath}`)
92
85
  console.log(` Chroxy CLI: ${chroxyBin}`)
93
86
  console.log(` Claude CLI: ${claudeBin}`)
94
- console.log(` Service file: ${servicePath}`)
95
- console.log(` Log dir: ${paths.logDir}`)
96
- console.log(` Working dir: ${cwd}`)
97
- console.log(` Start on login: ${startAtLogin}`)
98
- if (paths.type === 'launchd') {
99
- console.log('\nThe service is installed but not running. To start it now:')
100
- console.log(' launchctl start com.chroxy.server')
87
+
88
+ if (paths.type === 'windows') {
89
+ console.log(` Task: ${result?.taskName || 'Chroxy'} (Windows Task Scheduler)`)
90
+ console.log(` Wrapper: ${result?.wrapperPath}`)
91
+ console.log(` Log dir: ${paths.logDir}`)
92
+ console.log(` Working dir: ${cwd}`)
93
+ console.log(' Start on login: true (ONLOGON)')
94
+ console.log('\nThe scheduled task is registered and will start Chroxy at your next logon.')
95
+ console.log('To start it now: chroxy service start')
96
+ console.log('To check it: chroxy service status')
97
+ console.log('\nNote: the task runs at LOGON as your user (schtasks /SC ONLOGON /IT), not at')
98
+ console.log('boot. A boot-time daemon would run as SYSTEM with no access to your credential')
99
+ console.log('store or session \u2014 the wrong model for a per-user dev daemon.')
101
100
  } else {
102
- console.log('\nThe service is enabled and running. To restart it:')
103
- console.log(' systemctl --user restart chroxy.service')
101
+ const servicePath = paths.type === 'launchd' ? paths.plistPath : paths.unitPath
102
+ console.log(` Service file: ${servicePath}`)
103
+ console.log(` Log dir: ${paths.logDir}`)
104
+ console.log(` Working dir: ${cwd}`)
105
+ console.log(` Start on login: ${startAtLogin}`)
106
+ if (paths.type === 'launchd') {
107
+ console.log('\nThe service is installed but not running. To start it now:')
108
+ console.log(' launchctl start com.chroxy.server')
109
+ } else {
110
+ console.log('\nThe service is enabled and running. To restart it:')
111
+ console.log(' systemctl --user restart chroxy.service')
112
+ }
104
113
  }
105
114
  } catch (err) {
106
115
  console.error(`Error installing service: ${err.message}`)
@@ -126,6 +135,8 @@ export function registerServiceCommand(program) {
126
135
  console.log(' Service file and state have been removed.')
127
136
  if (state.platform === 'darwin') {
128
137
  console.log(' The launchd job has been unloaded.')
138
+ } else if (state.platform === 'win32') {
139
+ console.log(' The Windows scheduled task has been deleted.')
129
140
  } else {
130
141
  console.log(' The systemd unit has been disabled and stopped.')
131
142
  }
@@ -190,7 +201,7 @@ export function registerServiceCommand(program) {
190
201
  .command('status')
191
202
  .description('Show daemon status')
192
203
  .action(async () => {
193
- const { getFullServiceStatus } = await import('../service.js')
204
+ const { getFullServiceStatus, getWindowsTaskStatus } = await import('../service.js')
194
205
  const status = await getFullServiceStatus()
195
206
 
196
207
  console.log('\nChroxy Service Status\n')
@@ -203,6 +214,15 @@ export function registerServiceCommand(program) {
203
214
 
204
215
  console.log(' Installed: Yes')
205
216
 
217
+ // On Windows, surface the scheduled task's registration/run state
218
+ // (schtasks /Query /V) alongside the daemon-liveness (PID) check (#6647).
219
+ if (isWindows) {
220
+ const task = getWindowsTaskStatus()
221
+ console.log(' Task: ' + (task.registered
222
+ ? `registered${task.status ? ` (${task.status})` : ''}`
223
+ : 'not registered'))
224
+ }
225
+
206
226
  if (!status.running) {
207
227
  if (status.stale) {
208
228
  console.log(' Running: No (stale PID file)')
package/src/cli/shared.js CHANGED
@@ -8,7 +8,7 @@ import { existsSync, readFileSync } from 'fs'
8
8
  import { join } from 'path'
9
9
  import { homedir } from 'os'
10
10
  import readline from 'readline'
11
- import { validateConfig, mergeConfig, isFatalConfigWarning } from '../config.js'
11
+ import { validateConfig, mergeConfig, isFatalConfigWarning, DEFAULT_MAX_PAYLOAD_BYTES } from '../config.js'
12
12
 
13
13
  export const CONFIG_DIR = join(homedir(), '.chroxy')
14
14
  export const CONFIG_FILE = join(CONFIG_DIR, 'config.json')
@@ -47,7 +47,10 @@ export function addServerOptions(cmd) {
47
47
  .option('--legacy-cli', 'Use legacy CLI process mode instead of Agent SDK')
48
48
  .option('--provider <name>', 'Session provider to use (e.g. claude-sdk, claude-cli)')
49
49
  .option('--max-messages <count>', 'Max messages retained per session (FIFO eviction, default: 1000)')
50
- .option('--max-payload <bytes>', 'WebSocket max message size in bytes (default: 1048576)')
50
+ // #7011 — interpolated, never hand-copied: Commander gets no defaultValue for
51
+ // this option, so --help is the only place the default is advertised, and a
52
+ // literal here drifted 10x from the WsServer fallback.
53
+ .option('--max-payload <bytes>', `WebSocket max message size in bytes (default: ${DEFAULT_MAX_PAYLOAD_BYTES})`)
51
54
  .option('--max-tool-input <bytes>', 'Maximum tool input size in bytes (default: 262144)')
52
55
  .option('--session-timeout <duration>', 'Idle session timeout (e.g. 2h, 30m). Disabled by default')
53
56
  .option('--cost-budget <dollars>', 'Per-session cost budget in dollars (e.g., 5.00)')
@@ -99,7 +102,7 @@ export function loadAndMergeConfig(options, extraOverrides = {}) {
99
102
  if (err instanceof SyntaxError) {
100
103
  console.error(`❌ Config file contains invalid JSON: ${options.config}`)
101
104
  console.error(` ${err.message}`)
102
- console.error(` Fix the file or delete it and run 'npx chroxy init' to recreate.`)
105
+ console.error(` Fix the file or delete it and run 'chroxy init' to recreate.`)
103
106
  process.exit(1)
104
107
  }
105
108
  throw err
@@ -108,7 +111,7 @@ export function loadAndMergeConfig(options, extraOverrides = {}) {
108
111
  console.error(`❌ Config file not found: ${options.config}`)
109
112
  process.exit(1)
110
113
  } else {
111
- console.error('❌ No config found. Run \'npx chroxy init\' first.')
114
+ console.error('❌ No config found. Run \'chroxy init\' first.')
112
115
  process.exit(1)
113
116
  }
114
117
 
@@ -0,0 +1,213 @@
1
+ // `chroxy tokens` — list and revoke persisted paired-device session tokens
2
+ // (#6599, part of epic #6597). Operates on the on-disk session-token store
3
+ // (`~/.chroxy/session-tokens.json`, #6598) — the same encrypted store the daemon
4
+ // loads at boot.
5
+ //
6
+ // Like `chroxy identity rotate`, this edits the PERSISTED store and takes effect
7
+ // on the daemon's next start: a running daemon keeps its already-issued tokens in
8
+ // memory (and would re-persist them on the next change), so restart the daemon to
9
+ // enforce a revoke. Live revocation against a running daemon is a follow-up.
10
+ //
11
+ // Revoke targets a token by a unique handle PREFIX (from `tokens list`); the full
12
+ // token is never printed. `--all` is the panic button and requires `--yes`.
13
+
14
+ import { homedir } from 'os'
15
+ import { join } from 'path'
16
+ import { createSessionTokenStore } from '../session-token-store.js'
17
+
18
+ /** Resolve the chroxy config dir the same way server-cli does. */
19
+ function resolveChroxyDir(env = process.env) {
20
+ return env.CHROXY_CONFIG_DIR || join(homedir(), '.chroxy')
21
+ }
22
+
23
+ /** Human-readable age string; 'unknown' when the caller passes a non-finite age. */
24
+ function formatAge(ms) {
25
+ if (typeof ms !== 'number' || !Number.isFinite(ms) || ms < 0) return 'unknown'
26
+ const sec = Math.floor(ms / 1000)
27
+ if (sec < 60) return `${sec}s`
28
+ const min = Math.floor(sec / 60)
29
+ if (min < 60) return `${min}m`
30
+ const hr = Math.floor(min / 60)
31
+ if (hr < 24) return `${hr}h`
32
+ return `${Math.floor(hr / 24)}d`
33
+ }
34
+
35
+ const ENFORCE_NOTE =
36
+ 'Restart the daemon to enforce — a running daemon keeps already-issued tokens in memory ' +
37
+ 'and will re-persist (effectively restoring this token) if it writes before you restart.'
38
+
39
+ const UNREADABLE_NOTE =
40
+ 'The session-token store exists but could not be read (keychain unavailable, wrong file ' +
41
+ 'permissions, or corrupt). Refusing to touch it so a readable store is never lost. Fix the ' +
42
+ 'store access (or stop the daemon and inspect ~/.chroxy/session-tokens.json) and retry.'
43
+
44
+ // A decoded store SHOULD be `[token, meta]` tuples, but a hand-edited / partially
45
+ // corrupt store could carry a non-tuple element. These accessors never throw on
46
+ // one, so a single bad row can't crash `list`/`revoke` — the bad row shows as
47
+ // malformed and is preserved (not silently dropped) across a targeted revoke.
48
+ function tokenOf(entry) {
49
+ return Array.isArray(entry) && typeof entry[0] === 'string' ? entry[0] : ''
50
+ }
51
+ function metaOf(entry) {
52
+ return Array.isArray(entry) && entry[1] && typeof entry[1] === 'object' ? entry[1] : {}
53
+ }
54
+
55
+ /**
56
+ * List persisted session tokens. Pure aside from the injected store/writer/clock,
57
+ * so a test drives it with an in-memory store.
58
+ *
59
+ * @param {object} [deps] - { store, write, now }
60
+ * @returns {{ count: number, tokens: Array<{ handle: string, sessionId: string, ageMs: number|null }> }}
61
+ */
62
+ export function runTokensList(deps = {}) {
63
+ const out = deps.write || console.log
64
+ const store = deps.store || createSessionTokenStore({ dir: resolveChroxyDir() })
65
+ const now = typeof deps.now === 'number' ? deps.now : Date.now()
66
+
67
+ const { status, entries } = store.loadResult()
68
+ if (status === 'unreadable') {
69
+ out(UNREADABLE_NOTE)
70
+ return { count: 0, tokens: [], error: 'unreadable' }
71
+ }
72
+ if (!Array.isArray(entries) || entries.length === 0) {
73
+ out('No paired session tokens. Devices pair via the dashboard QR / pairing code.')
74
+ return { count: 0, tokens: [] }
75
+ }
76
+
77
+ const rows = entries.map((entry) => {
78
+ const token = tokenOf(entry)
79
+ const meta = metaOf(entry)
80
+ return {
81
+ handle: token ? token.slice(0, 12) : '(malformed)',
82
+ sessionId: (typeof meta.sessionId === 'string' && meta.sessionId) || '(none)',
83
+ ageMs: typeof meta.createdAt === 'number' ? now - meta.createdAt : null,
84
+ }
85
+ })
86
+
87
+ out(`${rows.length} paired session token(s):`)
88
+ for (const r of rows) {
89
+ out(` ${r.handle}… session=${r.sessionId} age=${formatAge(r.ageMs)}`)
90
+ }
91
+ out('')
92
+ out('Revoke one: chroxy tokens revoke <handle-prefix>')
93
+ out('Revoke all: chroxy tokens revoke --all --yes')
94
+ return { count: rows.length, tokens: rows }
95
+ }
96
+
97
+ /**
98
+ * Revoke a session token by handle prefix, or every token with `--all`.
99
+ *
100
+ * @param {string|undefined} target - handle prefix (ignored when `options.all`)
101
+ * @param {{ all?: boolean, yes?: boolean }} [options]
102
+ * @param {object} [deps] - { store, write }
103
+ * @returns {{ revoked: number, mode: 'all'|'one', confirmed?: boolean, error?: string, matches?: number }}
104
+ */
105
+ export function runTokensRevoke(target, options = {}, deps = {}) {
106
+ const out = deps.write || console.log
107
+ const store = deps.store || createSessionTokenStore({ dir: resolveChroxyDir() })
108
+
109
+ // #6599 — never operate on a store we couldn't read: an 'unreadable' result
110
+ // (present file, bad perms / no keychain key / corrupt) must NOT be mistaken for
111
+ // an empty store, or `revoke --all` would silently overwrite real tokens with []
112
+ // and report "0". Refuse and exit non-zero instead.
113
+ const { status, entries } = store.loadResult()
114
+ if (status === 'unreadable') {
115
+ out(UNREADABLE_NOTE)
116
+ return { revoked: 0, mode: options.all ? 'all' : 'one', error: 'unreadable' }
117
+ }
118
+ const list = Array.isArray(entries) ? entries : []
119
+
120
+ if (options.all) {
121
+ if (!options.yes) {
122
+ out(
123
+ [
124
+ `chroxy tokens revoke --all — the panic button: revoke ALL ${list.length} paired device token(s).`,
125
+ '',
126
+ 'Every paired device must re-pair (dashboard QR / pairing code) after this.',
127
+ `${ENFORCE_NOTE}`,
128
+ '',
129
+ 'This is consequential — re-run with --yes to proceed:',
130
+ ' chroxy tokens revoke --all --yes',
131
+ ].join('\n'),
132
+ )
133
+ return { revoked: 0, mode: 'all', confirmed: false }
134
+ }
135
+ // #6927 — DURABLE revoke: fsync the emptied store before reporting success,
136
+ // mirroring the daemon's live revoke (`_persistSessionTokensSnapshot`, #6914).
137
+ // Without it a power loss within the OS writeback window rolls the file back
138
+ // and every "revoked" token RESURRECTS on the next daemon start — after the
139
+ // operator was told the panic-button revoke landed.
140
+ if (!store.save([], { durable: true })) {
141
+ out(`Failed to write the session-token store — nothing revoked. ${UNREADABLE_NOTE}`)
142
+ return { revoked: 0, mode: 'all', error: 'persist-failed' }
143
+ }
144
+ out(`Revoked all ${list.length} session token(s). ${ENFORCE_NOTE}`)
145
+ return { revoked: list.length, mode: 'all', confirmed: true }
146
+ }
147
+
148
+ if (!target) {
149
+ out('Specify a token handle prefix (see: chroxy tokens list), or --all to revoke every token.')
150
+ return { revoked: 0, mode: 'one', error: 'no-target' }
151
+ }
152
+
153
+ // target is non-empty here (guarded above), so a malformed row (tokenOf === '')
154
+ // never matches and is preserved in `remaining`.
155
+ const matches = list.filter((e) => tokenOf(e).startsWith(target))
156
+ if (matches.length === 0) {
157
+ out(`No session token matches "${target}". Run: chroxy tokens list`)
158
+ return { revoked: 0, mode: 'one', error: 'no-match' }
159
+ }
160
+ if (matches.length > 1) {
161
+ // Never guess which token to drop — demand a longer, unambiguous prefix.
162
+ out(`"${target}" matches ${matches.length} tokens — use a longer handle prefix to disambiguate.`)
163
+ return { revoked: 0, mode: 'one', error: 'ambiguous', matches: matches.length }
164
+ }
165
+
166
+ const remaining = list.filter((e) => !tokenOf(e).startsWith(target))
167
+ // #6927 — DURABLE revoke (see the --all branch above): fsync the post-removal
168
+ // snapshot before reporting success so a power loss can't resurrect the revoked
169
+ // token on the next start.
170
+ if (!store.save(remaining, { durable: true })) {
171
+ out(`Failed to write the session-token store — nothing revoked. ${UNREADABLE_NOTE}`)
172
+ return { revoked: 0, mode: 'one', error: 'persist-failed' }
173
+ }
174
+ out(`Revoked 1 session token (${target}…). ${ENFORCE_NOTE}`)
175
+ return { revoked: 1, mode: 'one', confirmed: true }
176
+ }
177
+
178
+ export function registerTokensCommand(program) {
179
+ const tokens = program
180
+ .command('tokens')
181
+ .description('List and revoke persisted paired-device session tokens (#6599)')
182
+
183
+ tokens
184
+ .command('list')
185
+ .description('List paired-device session tokens (handle, session, age)')
186
+ .action(() => {
187
+ try {
188
+ const res = runTokensList()
189
+ if (res.error) process.exitCode = 1
190
+ } catch (err) {
191
+ console.error(`tokens list failed: ${err.message}`)
192
+ process.exitCode = 1
193
+ }
194
+ })
195
+
196
+ tokens
197
+ .command('revoke [handle]')
198
+ .description('Revoke a session token by handle prefix, or --all to revoke every token')
199
+ .option('--all', 'Revoke EVERY paired-device token (panic button — all devices re-pair)')
200
+ .option('--yes', 'Confirm --all (without it, the command only explains what it would do)')
201
+ .action((handle, options) => {
202
+ try {
203
+ const res = runTokensRevoke(handle, options)
204
+ // Exit non-zero on genuine operational failures (a store we couldn't read
205
+ // or write) so scripts/operators know the revoke did NOT happen. User-input
206
+ // guidance (no-match / ambiguous / no-target / unconfirmed --all) exits 0.
207
+ if (res.error === 'unreadable' || res.error === 'persist-failed') process.exitCode = 1
208
+ } catch (err) {
209
+ console.error(`tokens revoke failed: ${err.message}`)
210
+ process.exitCode = 1
211
+ }
212
+ })
213
+ }
@@ -96,6 +96,6 @@ async function setupCloudflare() {
96
96
  console.log(` HTTP: https://${hostname}`)
97
97
  console.log(` WebSocket: wss://${hostname}`)
98
98
  console.log('')
99
- console.log('Run \'npx chroxy start\' to launch with your Named Tunnel.')
99
+ console.log('Run \'chroxy start\' to launch with your Named Tunnel.')
100
100
  console.log('The QR code will always be the same — scan it once, connect forever.\n')
101
101
  }
@@ -1,6 +1,7 @@
1
1
  import { spawn } from 'child_process'
2
2
  import { createInterface } from 'readline'
3
3
  import { randomBytes } from 'crypto'
4
+ import { normalizeSdkModelUsage } from './usage-normalize.js'
4
5
  import { homedir } from 'os'
5
6
  import { join } from 'path'
6
7
  import { createPermissionHookManager } from './permission-hook.js'
@@ -9,11 +10,12 @@ import { BaseSession, buildBaseSessionOpts } from './base-session.js'
9
10
  import { buildContentBlocks } from './content-blocks.js'
10
11
  import { ALLOWED_MODEL_IDS } from './models.js'
11
12
  import { CLAUDE_FALLBACK_MODELS, claudeModelMetadata } from './claude-model-catalog.js'
12
- import { forceKill } from './platform.js'
13
+ import { forceKill, killProcessTree } from './platform.js'
13
14
  import { MessageTransformPipeline } from './message-transform.js'
14
15
  import { emitToolResults } from './tool-result.js'
15
- import { buildToolStartData, extractToolInputSemantics } from './claude-stream-parser.js'
16
+ import { buildToolStartData, extractToolInputSemantics, parseCompactBoundaryMeta, formatCompactBoundaryContent } from './claude-stream-parser.js'
16
17
  import { resolveBinary } from './utils/resolve-binary.js'
18
+ import { labelBinarySpawnFailure } from './utils/verify-binary.js'
17
19
  import { prepareSpawn } from './utils/win-spawn.js'
18
20
  import { buildSpawnEnv } from './utils/spawn-env.js'
19
21
  import { RespawnRateLimiter } from './utils/respawn-rate-limiter.js'
@@ -23,16 +25,23 @@ import { BILLING_CLASSES, isProgrammaticCreditEra } from './billing-class.js'
23
25
 
24
26
  const log = createLogger('cli-session')
25
27
 
26
- // Resolve the claude binary once at module load. Under a GUI launch
27
- // (e.g. Tauri on macOS) PATH is minimal and may exclude the user's
28
- // install dir — fall through to known locations so `spawn()` succeeds.
29
- const CLAUDE = resolveBinary('claude', [
28
+ // Well-known fallback locations. Under a GUI launch (e.g. Tauri on macOS) PATH
29
+ // is minimal and may exclude the user's install dir — fall through to these so
30
+ // `spawn()` succeeds.
31
+ const CLAUDE_BINARY_CANDIDATES = [
30
32
  join(homedir(), '.local/bin/claude'),
31
33
  '/opt/homebrew/bin/claude',
32
34
  '/usr/local/bin/claude',
33
35
  join(homedir(), '.claude/local/node_modules/.bin/claude'),
34
36
  join(homedir(), '.npm-global/bin/claude'),
35
- ])
37
+ ]
38
+
39
+ // Re-resolve fresh on every spawn (NOT a frozen module-load const) so a binary
40
+ // quarantined / moved / reinstalled after daemon start is spawned from its
41
+ // CURRENT path — and matches what preflight verified (#6708 defect #3).
42
+ function resolveClaudeBinary() {
43
+ return resolveBinary('claude', CLAUDE_BINARY_CANDIDATES)
44
+ }
36
45
 
37
46
  // Default max accumulated size for tool_use input_json_delta chunks (~256KB)
38
47
  const DEFAULT_MAX_TOOL_INPUT_LENGTH = 262144
@@ -259,6 +268,14 @@ export class CliSession extends BaseSession {
259
268
  }
260
269
  }
261
270
 
271
+ /**
272
+ * The exact path the CLI subprocess will spawn, re-resolved fresh so
273
+ * preflight verifies the SAME path the spawn uses (no stale const). (#6708)
274
+ */
275
+ static get resolvedBinary() {
276
+ return resolveClaudeBinary()
277
+ }
278
+
262
279
  /**
263
280
  * Preflight dependency spec used by `chroxy doctor`.
264
281
  * Declares the binary and credential requirements for this provider so
@@ -518,7 +535,10 @@ export class CliSession extends BaseSession {
518
535
  // with no native `claude.exe`); spawning a `.cmd` via child_process throws
519
536
  // EINVAL on Node 24, so route it through cmd.exe with proper escaping. No-op
520
537
  // for a directly-runnable `.exe` and on POSIX. See utils/win-spawn.js.
521
- const spawnSpec = prepareSpawn(CLAUDE, args)
538
+ // Captured so the spawn-time backstop (#6708) verifies the EXACT binary this
539
+ // attempt used, not a fresh re-resolve that could land on a different path.
540
+ const attemptedBinary = resolveClaudeBinary()
541
+ const spawnSpec = prepareSpawn(attemptedBinary, args)
522
542
  const child = spawn(spawnSpec.command, spawnSpec.args, {
523
543
  cwd: this.cwd,
524
544
  stdio: ['pipe', 'pipe', 'pipe'],
@@ -576,7 +596,12 @@ export class CliSession extends BaseSession {
576
596
  this._cleanupReadlines()
577
597
  this._processReady = false
578
598
  this._child = null
579
- this.emit('error', { message: `Failed to spawn claude: ${err.message}` })
599
+ // #6708 — a spawn error (ENOENT/EACCES) can mean the binary was quarantined
600
+ // /moved/removed out from under the running daemon (this is the respawn
601
+ // path too, so it fires mid-session). Verify the ATTEMPTED path and label
602
+ // the cause + fix instead of surfacing a bare ENOENT. Falls back to raw.
603
+ const labeled = labelBinarySpawnFailure({ attemptedPath: err?.path || attemptedBinary, binary: 'claude' })
604
+ this.emit('error', { message: labeled || `Failed to spawn claude: ${err.message}` })
580
605
  this._scheduleRespawn()
581
606
  })
582
607
 
@@ -994,6 +1019,25 @@ export class CliSession extends BaseSession {
994
1019
  }
995
1020
  this.emit('mcp_servers', { servers: data.mcp_servers })
996
1021
  }
1022
+ } else if (data.subtype === 'compact_boundary') {
1023
+ // #6768: `claude -p --output-format stream-json` mirrors the SDK's
1024
+ // `SDKCompactBoundaryMessage` shape, so this is the CLI equivalent
1025
+ // of SdkSession's compact_boundary branch — parse the structured
1026
+ // `compact_metadata` into a distinct marker instead of the generic
1027
+ // fallback below, which would forward the literal string
1028
+ // `compact_boundary` with no human-readable text.
1029
+ const meta = parseCompactBoundaryMeta(data.compact_metadata)
1030
+ ;(this._log || log).info(
1031
+ `Context compacted (${meta.trigger}): ${meta.preTokens ?? '?'} -> ${meta.postTokens ?? '?'} tokens` +
1032
+ (meta.durationMs != null ? ` in ${meta.durationMs}ms` : '')
1033
+ )
1034
+ this.emit('message', {
1035
+ type: 'system',
1036
+ subtype: 'compact_boundary',
1037
+ content: formatCompactBoundaryContent(meta),
1038
+ compactMetadata: meta,
1039
+ timestamp: Date.now(),
1040
+ })
997
1041
  } else {
998
1042
  // Forward non-init system events (e.g. usage limits, sub-agent
999
1043
  // notifications) as system messages to the client
@@ -1212,6 +1256,13 @@ export class CliSession extends BaseSession {
1212
1256
  cost: data.total_cost_usd,
1213
1257
  duration: data.duration_ms,
1214
1258
  usage: data.usage,
1259
+ // #6692: the CLI's stream-json result is produced by the same
1260
+ // runtime as the SDK's; when it carries modelUsage/num_turns/
1261
+ // duration_api_ms, forward them — all three degrade to null on
1262
+ // older CLI builds that omit them.
1263
+ numTurns: Number.isFinite(data.num_turns) ? data.num_turns : null,
1264
+ apiDurationMs: Number.isFinite(data.duration_api_ms) ? data.duration_api_ms : null,
1265
+ modelUsage: normalizeSdkModelUsage(data.modelUsage),
1215
1266
  })
1216
1267
 
1217
1268
  // Message complete — ready for next message
@@ -1478,7 +1529,12 @@ export class CliSession extends BaseSession {
1478
1529
  // tests with a mock child that never emits 'close').
1479
1530
  if (typeof forceKillTimer.unref === 'function') forceKillTimer.unref()
1480
1531
 
1481
- oldChild.kill('SIGTERM')
1532
+ // #6643 — on Windows a plain SIGTERM only TerminateProcess-es the cmd.exe
1533
+ // shim wrapping a `.cmd` provider (claude/codex/…); the real node
1534
+ // grandchild is orphaned and the wrapper's `close` above then cancels the
1535
+ // forceKill escalation before it can fire. killProcessTree reaps the whole
1536
+ // tree (POSIX behaviour is an identical graceful SIGTERM).
1537
+ killProcessTree(oldChild)
1482
1538
  } else {
1483
1539
  this._respawning = false
1484
1540
  this._respawnCount = 0
package/src/cli.js CHANGED
@@ -27,6 +27,8 @@ import { registerProvidersCommand } from './cli/providers-cmd.js'
27
27
  import { registerPagesCommands } from './cli/pages-cmd.js'
28
28
  import { registerShellApprovalCommand } from './cli/shell-cmd.js'
29
29
  import { registerIdentityCommand } from './cli/identity-cmd.js'
30
+ import { registerTokensCommand } from './cli/tokens-cmd.js'
31
+ import { registerScheduleCommands } from './cli/schedule-cmd.js'
30
32
 
31
33
  const require = createRequire(import.meta.url)
32
34
  const { version } = require('../package.json')
@@ -56,5 +58,7 @@ registerProvidersCommand(program)
56
58
  registerPagesCommands(program)
57
59
  registerShellApprovalCommand(program)
58
60
  registerIdentityCommand(program)
61
+ registerTokensCommand(program)
62
+ registerScheduleCommands(program)
59
63
 
60
64
  program.parse()