@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
@@ -401,6 +401,129 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
401
401
  }
402
402
  }
403
403
 
404
+ /**
405
+ * Append a single note line to the session cwd's project CLAUDE.md, creating
406
+ * the file if it doesn't exist (#6861, epic #6760).
407
+ *
408
+ * The TARGET is chosen SERVER-side (`<cwd>/CLAUDE.md`) — the client sends only
409
+ * the note text, never a path — so the write is path-confined BY CONSTRUCTION.
410
+ * validatePathWithinCwd is still run for symlink-escape defence (a CLAUDE.md
411
+ * symlinked out of the workspace is rejected), and the open uses O_NOFOLLOW to
412
+ * close the post-validation TOCTOU window, matching writeFileContent above.
413
+ *
414
+ * The write uses O_APPEND (+ O_CREAT): each append lands atomically at EOF, so
415
+ * concurrent appends can't lose a line and a crash can't truncate the file —
416
+ * the correct primitive for appending, unlike a read-modify-write O_TRUNC. The
417
+ * only read is a cheap 1-byte tail check to decide whether a separating newline
418
+ * is needed; a race there is benign (a stray/missing separator at worst — the
419
+ * note line itself is always written atomically and in full).
420
+ */
421
+ async function appendMemory(ws, note, sessionCwd) {
422
+ if (!sessionCwd) {
423
+ sendFn(ws, { type: 'append_memory_result', path: null, created: false, error: 'Memory is not available in this mode' })
424
+ return
425
+ }
426
+ if (typeof note !== 'string' || !note.trim()) {
427
+ sendFn(ws, { type: 'append_memory_result', path: null, created: false, error: 'No note provided' })
428
+ return
429
+ }
430
+ const MAX_NOTE = 10_000
431
+ if (note.length > MAX_NOTE) {
432
+ sendFn(ws, { type: 'append_memory_result', path: null, created: false, error: `Note too long (max ${MAX_NOTE} characters)` })
433
+ return
434
+ }
435
+ // Collapse to a single line — quick-append is a one-line note by definition.
436
+ const line = note.trim().replace(/\r?\n/g, ' ')
437
+
438
+ let absPath = null
439
+ try {
440
+ const cwdReal = await resolveSessionCwd(sessionCwd)
441
+ const target = normalize(resolve(cwdReal, 'CLAUDE.md'))
442
+
443
+ // Resolve symlinks: if CLAUDE.md already exists, validate its real path;
444
+ // if not, validate the lexical target (still inside cwd by construction).
445
+ let resolvedTarget
446
+ let fileExists = false
447
+ try {
448
+ resolvedTarget = await realpath(target)
449
+ fileExists = true
450
+ } catch (err) {
451
+ if (err.code === 'ENOENT') resolvedTarget = target
452
+ else throw err
453
+ }
454
+
455
+ const { valid } = await validatePathWithinCwd(fileExists ? resolvedTarget : target, sessionCwd)
456
+ if (!valid) {
457
+ sendFn(ws, {
458
+ type: 'append_memory_result',
459
+ path: null,
460
+ created: false,
461
+ error: 'Access denied: memory is restricted to the project directory',
462
+ })
463
+ return
464
+ }
465
+ absPath = fileExists ? resolvedTarget : target
466
+
467
+ // Cheap tail check: does the existing file already end with a newline? If
468
+ // not, prepend one so the note lands on its own line. Best-effort (a race
469
+ // only affects the separator, never the note itself).
470
+ let needsLeadingNewline = false
471
+ if (fileExists) {
472
+ try {
473
+ const st = await stat(absPath)
474
+ if (st.size > 0) {
475
+ let rfh
476
+ try {
477
+ rfh = await open(absPath, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW)
478
+ const tail = Buffer.alloc(1)
479
+ await rfh.read(tail, 0, 1, st.size - 1)
480
+ needsLeadingNewline = tail[0] !== 0x0a
481
+ } finally {
482
+ await rfh?.close()
483
+ }
484
+ }
485
+ } catch {
486
+ // Tail read is advisory only — fall back to no separator.
487
+ }
488
+ }
489
+
490
+ const data = Buffer.from((needsLeadingNewline ? '\n' : '') + line + '\n', 'utf-8')
491
+
492
+ // O_APPEND: atomic append at EOF (no lost-update / truncation window).
493
+ // O_CREAT (WITHOUT O_EXCL) opens-or-creates, so there is no EEXIST race to
494
+ // retry — a concurrent creator just means we append instead. O_NOFOLLOW
495
+ // keeps the symlink-escape defence on the final component.
496
+ {
497
+ let fh
498
+ try {
499
+ const flags = fsConstants.O_WRONLY | fsConstants.O_APPEND | fsConstants.O_CREAT | fsConstants.O_NOFOLLOW
500
+ fh = await open(absPath, flags, 0o666)
501
+ await fh.writeFile(data)
502
+ } catch (openErr) {
503
+ if (openErr.code === 'ELOOP') {
504
+ sendFn(ws, {
505
+ type: 'append_memory_result',
506
+ path: null,
507
+ created: false,
508
+ error: 'Access denied: memory is restricted to the project directory',
509
+ })
510
+ return
511
+ }
512
+ throw openErr
513
+ } finally {
514
+ await fh?.close()
515
+ }
516
+ }
517
+
518
+ sendFn(ws, { type: 'append_memory_result', path: absPath, created: !fileExists, error: null })
519
+ } catch (err) {
520
+ let errorMessage
521
+ if (err.code === 'EACCES') errorMessage = 'Permission denied'
522
+ else errorMessage = err.message || 'Unknown error'
523
+ sendFn(ws, { type: 'append_memory_result', path: absPath, created: false, error: errorMessage })
524
+ }
525
+ }
526
+
404
527
  /** Get git diff for uncommitted changes in the session CWD */
405
528
  async function getDiff(ws, base, sessionCwd) {
406
529
  if (!sessionCwd) {
@@ -590,6 +713,7 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
590
713
  return {
591
714
  readFile: readFileContent,
592
715
  writeFile: writeFileContent,
716
+ appendMemory,
593
717
  getDiff,
594
718
  }
595
719
  }
@@ -78,6 +78,22 @@ function safeForward(label, fn) {
78
78
  * @param {Function} ctx.broadcast - (message, filter?) => void
79
79
  * @param {Function} ctx.broadcastToSession - (sessionId, message, filter?) => void
80
80
  */
81
+ /**
82
+ * Events the LEGACY single-CLI path forwards through the normalizer.
83
+ *
84
+ * Exported so tests can iterate the real list rather than a copy — a hand-maintained
85
+ * duplicate in a test cannot fail when this list grows, which is exactly the false
86
+ * assurance #7096's first attempt shipped.
87
+ */
88
+ export const FORWARDED_CLI_EVENTS = Object.freeze([
89
+ 'ready', 'stream_start', 'stream_delta', 'stream_end',
90
+ 'message', 'tool_start', 'tool_result', 'result', 'error',
91
+ 'user_question', 'agent_spawned', 'agent_completed',
92
+ 'plan_started', 'plan_ready', 'mcp_servers',
93
+ 'permission_expired', 'skill_changed', 'skill_trust_request', 'skill_trust_granted',
94
+ 'stopped',
95
+ ])
96
+
81
97
  export function setupForwarding(ctx) {
82
98
  const {
83
99
  normalizer,
@@ -89,12 +105,17 @@ export function setupForwarding(ctx) {
89
105
 
90
106
  // Wire the normalizer's timer-based delta flush to broadcast
91
107
  normalizer.onFlush = (entries) => {
92
- for (const { sessionId, messageId, delta, emitMonoMs } of entries) {
108
+ for (const { sessionId, messageId, delta, emitMonoMs, thinking } of entries) {
93
109
  recordEmitToBroadcast(emitMonoMs)
110
+ // #6818: stamp `thinking: true` back on so a coalesced reasoning frame
111
+ // routes to the thinking bubble, not the response slot. Absent for
112
+ // response text (byte-identical to pre-#6818).
113
+ const msg = { type: 'stream_delta', messageId, delta }
114
+ if (thinking) msg.thinking = true
94
115
  if (sessionId) {
95
- broadcastToSession(sessionId, withServerTs({ type: 'stream_delta', messageId, delta }))
116
+ broadcastToSession(sessionId, withServerTs(msg))
96
117
  } else {
97
- broadcast(withServerTs({ type: 'stream_delta', messageId, delta }))
118
+ broadcast(withServerTs(msg))
98
119
  }
99
120
  }
100
121
  }
@@ -207,7 +228,9 @@ function setupSessionForwarding(normalizer, ctx) {
207
228
 
208
229
  // Handle delta buffering
209
230
  if (result.buffer) {
210
- normalizer.bufferDelta(sessionId, data.messageId, data.delta, data._emitMonoMs)
231
+ // #6818: forward the thinking flag so the coalesced frame reconstructs as
232
+ // a thinking stream_delta on flush.
233
+ normalizer.bufferDelta(sessionId, data.messageId, data.delta, data._emitMonoMs, result.thinking === true)
211
234
  return
212
235
  }
213
236
 
@@ -339,14 +362,14 @@ function setupCliForwarding(normalizer, ctx) {
339
362
  // session-manager.js `_wireSessionEvents` builtinTransient) so the legacy
340
363
  // single-CLI path also surfaces the user-initiated Stop confirmation via
341
364
  // the normalizer's `session_stopped` wire message.
342
- const FORWARDED_EVENTS = [
343
- 'ready', 'stream_start', 'stream_delta', 'stream_end',
344
- 'message', 'tool_start', 'tool_result', 'result', 'error',
345
- 'user_question', 'agent_spawned', 'agent_completed',
346
- 'plan_started', 'plan_ready', 'mcp_servers',
347
- 'permission_expired', 'skill_changed', 'skill_trust_request', 'skill_trust_granted',
348
- 'stopped',
349
- ]
365
+ // #7096 HAZARD: this path normalises with `sessionId: null` (see normCtx below), and
366
+ // several server schemas declare `sessionId: z.string().optional()` — so `undefined`
367
+ // is legal but `null` is NOT. Before adding an event here, check that its normalizer
368
+ // mapping either omits `sessionId` when absent (the `mcp_servers` / `permission_expired`
369
+ // pattern) or that its schema accepts null (`result`, `skill_changed`,
370
+ // `skill_trust_request` do). An unguarded `sessionId: ctx.sessionId` stamp on a
371
+ // null-rejecting schema makes every frame on this path wire-illegal.
372
+ const FORWARDED_EVENTS = FORWARDED_CLI_EVENTS
350
373
  for (const event of FORWARDED_EVENTS) {
351
374
  cliSession.on(event, (data) => {
352
375
  // #5313 (WP-1.3): same crash shape as the multi-session listener — a
@@ -365,7 +388,9 @@ function setupCliForwarding(normalizer, ctx) {
365
388
  if (!result) return
366
389
 
367
390
  if (result.buffer) {
368
- normalizer.bufferDelta(null, data.messageId, data.delta, data._emitMonoMs)
391
+ // #6818: forward the thinking flag (legacy-CLI path) so a coalesced
392
+ // reasoning frame reconstructs as a thinking stream_delta on flush.
393
+ normalizer.bufferDelta(null, data.messageId, data.delta, data._emitMonoMs, result.thinking === true)
369
394
  return
370
395
  }
371
396
 
@@ -467,12 +492,15 @@ function executeSideEffects(sideEffects, sessionId, ctx) {
467
492
  case 'flush_deltas': {
468
493
  const sid = effect.sessionId ?? sessionId
469
494
  const entries = normalizer.flushSession(sid)
470
- for (const { sessionId: eSid, messageId, delta, emitMonoMs } of entries) {
495
+ for (const { sessionId: eSid, messageId, delta, emitMonoMs, thinking } of entries) {
471
496
  recordEmitToBroadcast(emitMonoMs)
497
+ // #6818: preserve the thinking flag through the pre-stream_end flush.
498
+ const msg = { type: 'stream_delta', messageId, delta }
499
+ if (thinking) msg.thinking = true
472
500
  if (eSid) {
473
- broadcastToSession(eSid, withServerTs({ type: 'stream_delta', messageId, delta }))
501
+ broadcastToSession(eSid, withServerTs(msg))
474
502
  } else {
475
- broadcast(withServerTs({ type: 'stream_delta', messageId, delta }))
503
+ broadcast(withServerTs(msg))
476
504
  }
477
505
  }
478
506
  break
@@ -142,6 +142,25 @@ export const CTX_NAMESPACES = {
142
142
  // #5966: bounded RepoEventStore drained by the Control Room repo-events
143
143
  // survey. Null until the first GitHub-webhook delivery lazily creates it.
144
144
  'repoEventStore',
145
+ // #6540: repo-events webhook-secret config surface. `webhookPayloadUrl`
146
+ // derives the GitHub payload URL from the live origin; `repoWebhookDeliveries`
147
+ // is the in-memory recent-delivery ring (null until the first delivery);
148
+ // `setWebhookSecretCache` refreshes the in-process secret cache on a
149
+ // set/rotate/clear.
150
+ 'webhookPayloadUrl',
151
+ 'repoWebhookDeliveries',
152
+ 'setWebhookSecretCache',
153
+ // #6691: the OrchestrationManager (delegation harness). Present only when
154
+ // the orchestration feature is enabled and the engine is wired (E-4); the
155
+ // handlers (S-2) treat an absent manager as "engine not running".
156
+ 'orchestrationManager',
157
+ // #6871: the SchedulerEngine. NULL whenever the scheduled-execution gate is
158
+ // closed (buildSchedulerEngine returns null), which is the DEFAULT — so the
159
+ // scheduled-tasks handlers must treat absence as "nothing is armed" and
160
+ // report it, never as "fine". The registry itself lives on the
161
+ // SessionManager and exists either way, so tasks are still readable and
162
+ // editable with no engine present.
163
+ 'schedulerEngine',
145
164
  ],
146
165
  runtime: [
147
166
  'draining',
package/src/ws-history.js CHANGED
@@ -5,7 +5,7 @@
5
5
  * handshake and history replay concerns from core server orchestration.
6
6
  */
7
7
  import { toShortModelId, getRegistryForProvider } from './models.js'
8
- import { PERMISSION_MODES } from './handler-utils.js'
8
+ import { getPermissionModes } from './handler-utils.js'
9
9
  import { listProviders, getProvider } from './providers.js'
10
10
  import { createLogger } from './logger.js'
11
11
  import { createKeyPair, deriveSharedKey, deriveConnectionKey, signExchangeKey } from '@chroxy/store-core/crypto'
@@ -186,6 +186,10 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
186
186
  // so clients reveal IDE navigation/editing UI. Optional — absent → false
187
187
  // (fail-closed) for old servers / callers.
188
188
  ideEnabled,
189
+ // #6691: whether the orchestration harness is enabled on this server,
190
+ // surfaced as the `orchestration` capability so the dashboard reveals the
191
+ // Runs surface. Optional — absent → false (fail-closed) for old servers.
192
+ orchestrationEnabled,
189
193
  // #6006: whether the server has a rotating TokenManager (i.e. auth is on),
190
194
  // so the operator panic button (`revoke_token`) can fire. Surfaced as the
191
195
  // `tokenRevoke` capability, gated to primary-token clients below. Optional —
@@ -213,9 +217,33 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
213
217
 
214
218
  // Get initial session info for auth_ok payload
215
219
  let sessionInfo = {}
220
+ // #6638: the active session's provider, captured for the auth_ok permission-mode
221
+ // copy (Codex gets codex-tuned descriptions). `entry` below is block-scoped, so
222
+ // hoist the provider to function scope.
223
+ let authOkProvider = null
216
224
  if (sessionManager) {
217
- let activeId = defaultSessionId
218
- let entry = activeId ? sessionManager.getSession(activeId) : null
225
+ // #6687: resolve the active session with the SAME precedence block 2 uses to
226
+ // restore the client — the per-device persisted active session (#4835) first,
227
+ // then defaultSessionId → firstSessionId, then the bound-session override — so
228
+ // auth_ok's cwd + permission-mode copy describe the session the client is
229
+ // actually switched to, not the server default.
230
+ let activeId = null
231
+ let entry = null
232
+ const persistedDeviceId = client.deviceInfo?.deviceId
233
+ if (devicePreferences && persistedDeviceId) {
234
+ const persistedId = devicePreferences.getActiveSessionId(persistedDeviceId)
235
+ if (persistedId) {
236
+ const persistedEntry = sessionManager.getSession(persistedId)
237
+ if (persistedEntry) {
238
+ activeId = persistedId
239
+ entry = persistedEntry
240
+ }
241
+ }
242
+ }
243
+ if (!entry) {
244
+ activeId = defaultSessionId
245
+ entry = activeId ? sessionManager.getSession(activeId) : null
246
+ }
219
247
  if (!entry) {
220
248
  activeId = sessionManager.firstSessionId
221
249
  entry = activeId ? sessionManager.getSession(activeId) : null
@@ -232,6 +260,7 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
232
260
  }
233
261
  if (entry) {
234
262
  sessionInfo.cwd = entry.cwd
263
+ authOkProvider = entry.provider || null
235
264
  }
236
265
  } else if (cliSession) {
237
266
  sessionInfo.cwd = cliSession.cwd
@@ -383,6 +412,19 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
383
412
  // (fail-closed). A server-wide feature gate, not token-scoped — available to
384
413
  // every client when the operator opts in.
385
414
  ide: ideEnabled === true,
415
+ // #6691: the opt-in orchestration/delegation harness ("committee") is
416
+ // enabled on THIS server (features.orchestration / CHROXY_ENABLE_ORCHESTRATION).
417
+ // Clients gate the Runs surface on this flag; absent/false (default, or older
418
+ // servers) → no orchestration chrome (fail-closed).
419
+ orchestration: orchestrationEnabled === true,
420
+ // #6871 (epic #6784): this server has the scheduled-tasks WS surface
421
+ // (scheduled_tasks_request / scheduled_task_action / set_scheduler_enabled +
422
+ // the `scheduled_tasks` snapshot). CONSTANT true — deliberately NOT tied to
423
+ // whether scheduled EXECUTION is enabled. The enable gate is off by default
424
+ // and the registry exists either way, so gating the panel on the gate would
425
+ // hide exactly the banner that tells an operator their saved tasks will never
426
+ // fire. Clients read the real gate state off the snapshot's `scheduler` block.
427
+ scheduledTasks: true,
386
428
  // #5986 (epic #5982) — the embedded user-shell terminal is available to THIS
387
429
  // client: the server has it enabled (userShell.enabled) AND this connection
388
430
  // holds the primary token. Both conditions of the create gate are reflected
@@ -467,7 +509,7 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
467
509
  // client never has to wait for (or react to) the discrete
468
510
  // `available_permission_modes` burst frame. The discrete frame is still
469
511
  // sent below for older clients that read the enum only from it.
470
- availablePermissionModes: PERMISSION_MODES,
512
+ availablePermissionModes: getPermissionModes(authOkProvider),
471
513
  resultTimeoutMs: effectiveResultTimeoutMs,
472
514
  hardTimeoutMs: effectiveHardTimeoutMs,
473
515
  streamStallTimeoutMs: effectiveStreamStallTimeoutMs,
@@ -691,13 +733,18 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
691
733
  // schedule. With no active session activeProvider is null and there is nothing
692
734
  // to refresh (scheduleProviderModelsRefresh no-ops on a null provider).
693
735
  scheduleProviderModelsRefresh(ctx, ws, activeProvider)
694
- send(ws, { type: 'available_permission_modes', modes: PERMISSION_MODES })
736
+ send(ws, { type: 'available_permission_modes', modes: getPermissionModes(activeProvider) })
695
737
  permissions.resendPendingPermissions(ws, client)
696
738
  // #5555: fire the connect-time bootstrap burst (providers + slash commands
697
739
  // + agents) so a new client never sends its 3-request list_* round trip.
698
740
  // Fire-and-forget — the slash/agent compute is async (disk scans) and the
699
741
  // synchronous post-auth burst above must not block on it.
700
- sendAuthBootstrap(ctx, ws, { cwd: entry?.cwd || null, provider: activeProvider, sessionId: activeId })
742
+ // #6823: include the active BYOK session's MCP prompts so the connect-time
743
+ // burst's slash_commands match the on-demand list_slash_commands response.
744
+ const bootMcpPrompts = typeof entry?.session?.getMcpPromptCommands === 'function'
745
+ ? entry.session.getMcpPromptCommands()
746
+ : []
747
+ sendAuthBootstrap(ctx, ws, { cwd: entry?.cwd || null, provider: activeProvider, sessionId: activeId, mcpPrompts: bootMcpPrompts })
701
748
  return
702
749
  }
703
750
 
@@ -730,7 +777,7 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
730
777
  type: 'permission_mode_changed',
731
778
  mode: cliSession.permissionMode || 'approve',
732
779
  })
733
- send(ws, { type: 'available_permission_modes', modes: PERMISSION_MODES })
780
+ send(ws, { type: 'available_permission_modes', modes: getPermissionModes(legacyProvider) })
734
781
  }
735
782
 
736
783
  permissions.resendPendingPermissions(ws)
@@ -771,6 +818,9 @@ function sendAuthBootstrap(ctx, ws, info = {}) {
771
818
  const fileOps = ctx.fileOps || services?.fileOps || null
772
819
  const cwd = info.cwd || null
773
820
  const provider = info.provider || null
821
+ // #6823: MCP prompts to fold into the bootstrap slash-command list (empty for
822
+ // non-BYOK / legacy sessions).
823
+ const mcpPrompts = Array.isArray(info.mcpPrompts) ? info.mcpPrompts : []
774
824
 
775
825
  // providers is a cheap synchronous read off the registry — same source as
776
826
  // the list_providers handler.
@@ -785,7 +835,7 @@ function sendAuthBootstrap(ctx, ws, info = {}) {
785
835
  // slash commands + agents are async disk scans; compute in parallel and
786
836
  // tolerate either failing on its own.
787
837
  const slashP = fileOps && typeof fileOps.computeSlashCommands === 'function'
788
- ? fileOps.computeSlashCommands(cwd, provider).catch(err => {
838
+ ? fileOps.computeSlashCommands(cwd, provider, mcpPrompts).catch(err => {
789
839
  log.warn(`auth_bootstrap: computeSlashCommands failed: ${err.message}`)
790
840
  return []
791
841
  })
@@ -937,11 +987,34 @@ export function sendSessionInfo(ctx, ws, sessionId, opts = {}) {
937
987
  sessionId,
938
988
  })
939
989
  }
940
- // Replay permission rules so reconnecting clients have current whitelist
990
+ // Replay permission rules so reconnecting clients have current whitelist.
991
+ // #6771 — also replay durable per-project rules (persistentRules) so the
992
+ // rules surfaces show standing "always allow" grants on session load, not
993
+ // only after a fresh allowAlways in the current session.
941
994
  if (typeof session.getPermissionRules === 'function') {
942
995
  const rules = session.getPermissionRules()
943
- if (rules.length > 0) {
944
- send(ws, { type: 'permission_rules_updated', rules, sessionId })
996
+ const persistentRules = typeof session.getPersistentPermissionRules === 'function'
997
+ ? session.getPersistentPermissionRules()
998
+ : []
999
+ if (rules.length > 0 || persistentRules.length > 0) {
1000
+ send(ws, { type: 'permission_rules_updated', rules, persistentRules, sessionId })
1001
+ }
1002
+ }
1003
+
1004
+ // #6832: replay the last-known `mcp_servers` list so a client subscribing
1005
+ // to an already-warmed session (dashboard reconnect, second client joining
1006
+ // a shared session) sees the current server list without waiting on the
1007
+ // next emission. `mcp_servers` is a transient event (not recorded in
1008
+ // history) — sdk/cli sessions emit it once at the stream-json `system/init`
1009
+ // and claude-tui re-derives it on warmup/respawn (#6820/#6831), so a late
1010
+ // joiner previously saw "No MCP servers" until the next respawn. The
1011
+ // session caches the last payload (BaseSession `getMcpServersSnapshot()`,
1012
+ // set via a self-listener on `mcp_servers`); null means this session has
1013
+ // never emitted one, so there is nothing to replay.
1014
+ if (typeof session.getMcpServersSnapshot === 'function') {
1015
+ const mcpSnapshot = session.getMcpServersSnapshot()
1016
+ if (mcpSnapshot) {
1017
+ send(ws, { ...mcpSnapshot, sessionId })
945
1018
  }
946
1019
  }
947
1020
 
@@ -19,9 +19,12 @@ import { repoHandlers } from './handlers/repo-handlers.js'
19
19
  import { featureHandlers } from './handlers/feature-handlers.js'
20
20
  import { evaluatorHandlers } from './handlers/evaluator-handlers.js'
21
21
  import { controlRoomHandlers } from './handlers/control-room-handlers.js'
22
+ import { githubWebhookHandlers } from './handlers/github-webhook-handlers.js'
22
23
  import { summarizeHandlers } from './handlers/summarize-handlers.js'
23
24
  import { pairingHandlers } from './handlers/pairing-handlers.js'
24
25
  import { tokenHandlers } from './handlers/token-handlers.js'
26
+ import { orchestrationHandlers } from './handlers/orchestration-handlers.js'
27
+ import { schedulerHandlers } from './handlers/scheduler-handlers.js'
25
28
 
26
29
  const log = createLogger('ws')
27
30
 
@@ -38,9 +41,12 @@ const handlerRegistry = new Map([
38
41
  ...Object.entries(featureHandlers),
39
42
  ...Object.entries(evaluatorHandlers),
40
43
  ...Object.entries(controlRoomHandlers),
44
+ ...Object.entries(githubWebhookHandlers),
41
45
  ...Object.entries(summarizeHandlers),
42
46
  ...Object.entries(pairingHandlers),
43
47
  ...Object.entries(tokenHandlers),
48
+ ...Object.entries(orchestrationHandlers),
49
+ ...Object.entries(schedulerHandlers),
44
50
  ])
45
51
 
46
52
  /**