@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
@@ -16,6 +16,7 @@
16
16
  import { createHmac, timingSafeEqual } from 'node:crypto'
17
17
  import { RateLimiter, getRateLimitKey } from './rate-limiter.js'
18
18
  import { sendOversizeResponse } from './http-oversize.js'
19
+ import { readStoredField } from './credential-store.js'
19
20
  import { createLogger } from './logger.js'
20
21
 
21
22
  const log = createLogger('github-webhook')
@@ -25,6 +26,22 @@ export const MAX_WEBHOOK_BYTES = 2 * 1024 * 1024 // 2 MiB
25
26
  /** Bounded repo-event ring capacity. */
26
27
  export const REPO_EVENT_STORE_CAP = 200
27
28
 
29
+ /**
30
+ * #6540 — the credentials-store field name the webhook secret is persisted under
31
+ * (encrypted at rest, mode 0600 — see credential-store.js). A NON-provider-key
32
+ * field like `discordWebhookUrl`; it is NOT injected into any spawned child.
33
+ */
34
+ export const WEBHOOK_SECRET_FIELD = 'githubWebhookSecret'
35
+
36
+ /**
37
+ * #6540 — the GitHub event types the Control Room surfaces, offered as the
38
+ * recommended webhook subscription for copy-paste into GitHub's webhook form.
39
+ */
40
+ export const RECOMMENDED_WEBHOOK_EVENTS = Object.freeze(['pull_request', 'issues', 'push', 'release'])
41
+
42
+ /** #6540 — bounded in-memory recent-delivery ring capacity. */
43
+ export const WEBHOOK_DELIVERY_RING_CAP = 50
44
+
28
45
  const WEBHOOK_WINDOW_MS = 60_000
29
46
  const WEBHOOK_MAX_PER_WINDOW = 120
30
47
  const WEBHOOK_BURST = 30
@@ -134,6 +151,147 @@ export class RepoEventStore {
134
151
  }
135
152
  }
136
153
 
154
+ /**
155
+ * #6540 — bounded in-memory ring of recent webhook-delivery outcomes. Powers the
156
+ * config surface's "recent delivery status" readout (count / last / verify
157
+ * result). Deliberately in-memory (the plan's recommended default): it is
158
+ * observability, not durable state, and resets on daemon restart. Only deliveries
159
+ * that reached the HMAC-verify step are recorded — rate-limited (429), oversize
160
+ * (413), and no-secret (503) responses never touch the ring.
161
+ */
162
+ export class WebhookDeliveryRing {
163
+ constructor({ cap = WEBHOOK_DELIVERY_RING_CAP } = {}) {
164
+ this._cap = cap > 0 ? cap : WEBHOOK_DELIVERY_RING_CAP
165
+ this._items = []
166
+ this._total = 0
167
+ }
168
+
169
+ /** Record one delivery outcome. `verified` is the HMAC result; `kind` the X-GitHub-Event. */
170
+ record({ verified, kind = null, at = new Date().toISOString() } = {}) {
171
+ const entry = { at, verified: !!verified, kind: kind || null }
172
+ this._items.push(entry)
173
+ const overflow = this._items.length - this._cap
174
+ if (overflow > 0) this._items.splice(0, overflow)
175
+ this._total++
176
+ return entry
177
+ }
178
+
179
+ get total() {
180
+ return this._total
181
+ }
182
+
183
+ get size() {
184
+ return this._items.length
185
+ }
186
+
187
+ list() {
188
+ return this._items.slice()
189
+ }
190
+
191
+ /** Value-free summary for the `github_webhook_config` reply. */
192
+ summary() {
193
+ const last = this._items.length > 0 ? this._items[this._items.length - 1] : null
194
+ let verified = 0
195
+ let rejected = 0
196
+ for (const it of this._items) {
197
+ if (it.verified) verified++
198
+ else rejected++
199
+ }
200
+ return {
201
+ total: this._total,
202
+ verified,
203
+ rejected,
204
+ lastAt: last ? last.at : null,
205
+ lastResult: last ? (last.verified ? 'verified' : 'rejected') : null,
206
+ lastKind: last ? last.kind : null,
207
+ }
208
+ }
209
+ }
210
+
211
+ /**
212
+ * #6540 — lazily record a delivery outcome onto the server's delivery ring,
213
+ * creating it on first use. Guarded — a bare/stubbed server (tests) still works.
214
+ */
215
+ export function recordWebhookDelivery(server, entry) {
216
+ if (!server) return
217
+ if (!server._repoWebhookDeliveries) server._repoWebhookDeliveries = new WebhookDeliveryRing()
218
+ server._repoWebhookDeliveries.record(entry)
219
+ }
220
+
221
+ /**
222
+ * #6540 — derive the public `…/api/github/webhook` payload URL an operator pastes
223
+ * into GitHub, from the server's live origin. Pure + inputs-only so it is unit
224
+ * testable without a running server. Precedence:
225
+ * 1. tunnel URL (a `wss://`/`ws://` endpoint) → `https://host/api/github/webhook`
226
+ * 2. operator-supplied external URL (SKIP_TUNNEL mode) → normalized the same way
227
+ * 3. LAN / loopback fallback → `http://<lanIp-or-host>:<port>/api/github/webhook`,
228
+ * flagged `lanOnly` with a note (GitHub.com cannot reach it — e.g. `--tunnel none`)
229
+ *
230
+ * @param {{ tunnelUrl?: string|null, externalUrl?: string|null, boundHost?: string, port?: number, lanIp?: string|null, isLoopbackHost?: (h: string) => boolean }} inputs
231
+ * @returns {{ url: string|null, lanOnly: boolean, note: string|null }}
232
+ */
233
+ export function deriveWebhookPayloadUrl(inputs = {}) {
234
+ const { tunnelUrl, externalUrl, boundHost, port, lanIp, isLoopbackHost } = inputs
235
+ const PATH = '/api/github/webhook'
236
+
237
+ const fromEndpoint = (endpoint) => {
238
+ try {
239
+ const u = new URL(endpoint)
240
+ const scheme = u.protocol === 'wss:' || u.protocol === 'https:'
241
+ ? 'https:'
242
+ : (u.protocol === 'ws:' || u.protocol === 'http:' ? 'http:' : 'https:')
243
+ return `${scheme}//${u.host}${PATH}`
244
+ } catch {
245
+ return null
246
+ }
247
+ }
248
+
249
+ // 1. Public tunnel URL (the QR-shared wss:// endpoint).
250
+ if (typeof tunnelUrl === 'string' && tunnelUrl.length > 0) {
251
+ const url = fromEndpoint(tunnelUrl)
252
+ if (url) return { url, lanOnly: false, note: null }
253
+ }
254
+
255
+ // 2. Operator-supplied external URL (SKIP_TUNNEL: the operator fronts the daemon).
256
+ if (typeof externalUrl === 'string' && externalUrl.length > 0) {
257
+ const url = fromEndpoint(externalUrl)
258
+ if (url) return { url, lanOnly: false, note: null }
259
+ }
260
+
261
+ // 3. LAN / loopback fallback — GitHub.com cannot deliver to this.
262
+ const isLoopback = typeof isLoopbackHost === 'function' ? isLoopbackHost : () => false
263
+ const p = typeof port === 'number' && port > 0 ? port : null
264
+ if (boundHost !== undefined && isLoopback(boundHost)) {
265
+ return {
266
+ url: p ? `http://127.0.0.1:${p}${PATH}` : null,
267
+ lanOnly: true,
268
+ note: 'Loopback bind — GitHub cannot reach this address. Start a tunnel (chroxy tunnel) or bind to your LAN to receive public webhook deliveries.',
269
+ }
270
+ }
271
+ const host = typeof lanIp === 'string' && lanIp.length > 0 ? lanIp : 'YOUR_LAN_IP'
272
+ return {
273
+ url: p ? `http://${host}:${p}${PATH}` : null,
274
+ lanOnly: true,
275
+ note: 'No tunnel active — this LAN address is only reachable from your local network. GitHub.com cannot deliver to it; start a tunnel (chroxy tunnel) for public webhooks.',
276
+ }
277
+ }
278
+
279
+ /**
280
+ * #6540 — determine whether a webhook secret is configured and from which source,
281
+ * WITHOUT reading the value. `store` (the encrypted credentials file) wins over
282
+ * `env` (`GITHUB_WEBHOOK_SECRET`) for the "manageable from the dashboard" signal,
283
+ * matching `resolveWebhookSecret`'s precedence. Pure/injectable for tests.
284
+ *
285
+ * @param {{ readField?: (field: string) => { value: string|null }, env?: string|undefined }} [deps]
286
+ * @returns {'store'|'env'|'none'}
287
+ */
288
+ export function webhookSecretSource({ readField = readStoredField, env = process.env.GITHUB_WEBHOOK_SECRET } = {}) {
289
+ const stored = readField(WEBHOOK_SECRET_FIELD)
290
+ if (stored && typeof stored.value === 'string' && stored.value.length > 0) return 'store'
291
+ if (typeof env === 'string' && env.length > 0) return 'env'
292
+ return 'none'
293
+ }
294
+
137
295
  function sendJson(res, status, body, extraHeaders = {}) {
138
296
  const payload = JSON.stringify(body)
139
297
  res.writeHead(status, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(payload), ...extraHeaders })
@@ -141,13 +299,32 @@ function sendJson(res, status, body, extraHeaders = {}) {
141
299
  }
142
300
 
143
301
  /**
144
- * Resolve the webhook secret. Prefers an explicit `server._githubWebhookSecret`
145
- * (set from config at startup), falling back to `$GITHUB_WEBHOOK_SECRET`.
302
+ * Resolve the webhook secret. Precedence (#6540):
303
+ * 1. an explicit in-process override / hot cache (`server._githubWebhookSecret`)
304
+ * — the config handler sets it on a set/rotate so live deliveries pick up the
305
+ * new secret without a keychain re-read, and it is also the test seam;
306
+ * 2. the encrypted credentials store (`githubWebhookSecret` field). On a hit we
307
+ * lazily cache it into `server._githubWebhookSecret` so subsequent deliveries
308
+ * skip the keychain decrypt (the config handler resets this cache on
309
+ * set/rotate/clear, so it can never go stale);
310
+ * 3. `$GITHUB_WEBHOOK_SECRET` (back-compat for env-configured deployments).
311
+ *
312
+ * @param {object} server
313
+ * @param {{ readField?: (field: string) => { value: string|null } }} [deps]
314
+ * @returns {string}
146
315
  */
147
- function resolveWebhookSecret(server) {
316
+ export function resolveWebhookSecret(server, { readField = readStoredField } = {}) {
148
317
  if (typeof server?._githubWebhookSecret === 'string' && server._githubWebhookSecret.length > 0) {
149
318
  return server._githubWebhookSecret
150
319
  }
320
+ const stored = readField(WEBHOOK_SECRET_FIELD)
321
+ if (stored && typeof stored.value === 'string' && stored.value.length > 0) {
322
+ // Lazy hot-cache: skip the keychain decrypt on later deliveries. Kept
323
+ // consistent with the store by the config handler (it overwrites/clears
324
+ // `_githubWebhookSecret` on every set/rotate/clear).
325
+ if (server) server._githubWebhookSecret = stored.value
326
+ return stored.value
327
+ }
151
328
  const env = process.env.GITHUB_WEBHOOK_SECRET
152
329
  return typeof env === 'string' && env.length > 0 ? env : ''
153
330
  }
@@ -219,10 +396,18 @@ export function handleGithubWebhook(server, req, res) {
219
396
  const raw = Buffer.concat(chunks)
220
397
  const sig = req.headers['x-hub-signature-256']
221
398
  if (!verifyGithubSignature(raw, sig, secret)) {
399
+ // #6540: record the rejected delivery for the config-surface readout.
400
+ recordWebhookDelivery(server, { verified: false })
222
401
  log.warn('Rejected GitHub webhook: invalid or missing X-Hub-Signature-256')
223
402
  sendJson(res, 401, { error: 'invalid signature' })
224
403
  return
225
404
  }
405
+ const eventType = String(req.headers['x-github-event'] || '')
406
+ // #6540: authentic (signature-verified) delivery — record it regardless of
407
+ // whether the event type is one the Control Room surfaces. `eventType` comes
408
+ // from the header (available pre-parse), so a verified-but-malformed body
409
+ // still counts as an authentic delivery.
410
+ recordWebhookDelivery(server, { verified: true, kind: eventType || null })
226
411
  let payload
227
412
  try {
228
413
  payload = JSON.parse(raw.toString('utf8'))
@@ -230,7 +415,6 @@ export function handleGithubWebhook(server, req, res) {
230
415
  sendJson(res, 400, { error: 'invalid JSON' })
231
416
  return
232
417
  }
233
- const eventType = String(req.headers['x-github-event'] || '')
234
418
  const event = normalizeGithubEvent(eventType, payload)
235
419
  if (!event) {
236
420
  // Authentic delivery, but an event type the Control Room doesn't surface.
@@ -16,14 +16,48 @@ const log = createLogger('handler-utils')
16
16
  // `description` is a short, plain-English sentence the dashboard
17
17
  // surfaces as a tooltip / inline hint (#4013). Keep terse — the picker
18
18
  // space is limited and screen readers re-narrate the whole string.
19
- // The auto-mode description deliberately names `--dangerously-skip-permissions`
20
- // so users searching for that Claude CLI flag find the chroxy equivalent.
21
- export const PERMISSION_MODES = [
22
- { id: 'approve', label: 'Approve', description: 'Default. Every tool call gates on your approval in the dashboard or mobile app.' },
23
- { id: 'acceptEdits', label: 'Accept Edits', description: 'Auto-approve Read/Write/Edit/NotebookEdit/Glob/Grep. Bash, MCP, and other tools still gate on approval.' },
24
- { id: 'auto', label: 'Auto (skip all prompts)', description: 'Auto-approve every tool call without prompting. Equivalent to `claude --dangerously-skip-permissions`.' },
25
- { id: 'plan', label: 'Plan', description: 'Plan mode — Claude is asked to plan before acting; each tool call still gates on approval.' },
26
- ]
19
+ // The default (Claude) auto-mode description deliberately names
20
+ // `--dangerously-skip-permissions` so users searching for that Claude CLI flag
21
+ // find the chroxy equivalent.
22
+ //
23
+ // #6638: the mode IDs are provider-independent, but the descriptions are NOT —
24
+ // the default copy is Claude-oriented (Read/Write/Edit tool names, the
25
+ // `--dangerously-skip-permissions` flag, real plan mode). Codex has different
26
+ // tools (apply_patch / shell / connectors) and no plan enforcement, so
27
+ // `getPermissionModes('codex')` returns codex-tuned copy. Callers pass the active
28
+ // session's provider; a switch re-sends `available_permission_modes` (session-handlers).
29
+ const MODE_LABELS = { approve: 'Approve', acceptEdits: 'Accept Edits', auto: 'Auto (skip all prompts)', plan: 'Plan' }
30
+ const MODE_DESCRIPTIONS = {
31
+ default: {
32
+ approve: 'Default. Every tool call gates on your approval in the dashboard or mobile app.',
33
+ acceptEdits: 'Auto-approve Read/Write/Edit/NotebookEdit/Glob/Grep. Bash, MCP, and other tools still gate on approval.',
34
+ auto: 'Auto-approve every tool call without prompting. Equivalent to `claude --dangerously-skip-permissions`.',
35
+ plan: 'Plan mode — Claude is asked to plan before acting; each tool call still gates on approval.',
36
+ },
37
+ codex: {
38
+ approve: 'Default. Every codex command, file edit, and connector action gates on your approval.',
39
+ acceptEdits: 'Auto-approve codex file edits (apply_patch). Shell commands, connector actions, and permission escalations still gate on approval.',
40
+ auto: 'Auto-approve every codex action without prompting (codex runs with approvalPolicy `never`).',
41
+ plan: 'Not a distinct codex mode — behaves like Approve (codex has no plan enforcement).',
42
+ },
43
+ }
44
+ const MODE_IDS = ['approve', 'acceptEdits', 'auto', 'plan']
45
+ const buildModes = (desc) => MODE_IDS.map((id) => ({ id, label: MODE_LABELS[id], description: desc[id] }))
46
+
47
+ // The default (Claude) mode list. Kept as a named export for back-compat.
48
+ export const PERMISSION_MODES = buildModes(MODE_DESCRIPTIONS.default)
49
+
50
+ /**
51
+ * The permission-mode list with descriptions tuned to the given provider (#6638).
52
+ * Codex gets codex-specific copy; everything else gets the default. The mode IDs
53
+ * are identical across providers, so validation (ALLOWED_PERMISSION_MODE_IDS) is
54
+ * provider-independent.
55
+ * @param {string|null|undefined} provider
56
+ */
57
+ export function getPermissionModes(provider) {
58
+ return provider === 'codex' ? buildModes(MODE_DESCRIPTIONS.codex) : PERMISSION_MODES
59
+ }
60
+
27
61
  export const ALLOWED_PERMISSION_MODE_IDS = new Set(PERMISSION_MODES.map((m) => m.id))
28
62
 
29
63
  // -- Attachment validation constants --
@@ -51,6 +51,9 @@ async function handleCreateCheckpoint(ws, client, msg, ctx) {
51
51
  name: typeof msg.name === 'string' ? msg.name.slice(0, 100) : undefined,
52
52
  description: typeof msg.description === 'string' ? msg.description.slice(0, 500) : undefined,
53
53
  messageCount: ctx.sessions.sessionManager.getHistoryCount(sid),
54
+ // #6766: capture the conversation fork boundary so a later restore can
55
+ // truncate the transcript to this point (SDK provider only; others → null).
56
+ boundaryMessageId: entry.session.lastMessageUuid,
54
57
  })
55
58
  ctx.transport.send(ws, {
56
59
  type: 'checkpoint_created',
@@ -89,11 +92,34 @@ async function handleRestoreCheckpoint(ws, client, msg, ctx) {
89
92
  sendSessionError(ws, ctx, 'Missing checkpointId')
90
93
  return
91
94
  }
95
+ // #6767: selective restore mode. 'files' reverts only the working tree and
96
+ // keeps the CURRENT session/conversation (no fork, no new session); 'conversation'
97
+ // branches the conversation at the checkpoint and leaves the working tree
98
+ // untouched (fork-capable providers only); 'both' (the default and the pre-#6767
99
+ // behaviour) does both. Any unknown value falls back to 'both'.
100
+ const mode = msg.mode === 'files' || msg.mode === 'conversation' || msg.mode === 'both' ? msg.mode : 'both'
92
101
  const currentEntry = ctx.sessions.sessionManager.getSession(sid)
93
102
  if (currentEntry?.session?.isRunning) {
94
103
  sendSessionError(ws, ctx, 'Cannot restore checkpoint while session is busy. Wait for the current task to finish or interrupt first.')
95
104
  return
96
105
  }
106
+ // #6767: whether the ORIGINAL session's provider can branch the conversation.
107
+ const origSession = currentEntry?.session
108
+ const forkCapable = !!(
109
+ origSession &&
110
+ origSession.supportsConversationFork === true &&
111
+ typeof origSession.forkConversation === 'function'
112
+ )
113
+ // #6767: 'conversation' mode is meaningless on a provider that can't fork a
114
+ // resumed transcript — reject clearly rather than silently doing nothing (or
115
+ // a misleading full-transcript resume). 'files'/'both' still work everywhere.
116
+ if (mode === 'conversation' && !forkCapable) {
117
+ sendSessionError(ws, ctx, "This session's provider can't restore the conversation only — it can't branch a resumed transcript. Use \"Files\" or \"Both\" instead.")
118
+ return
119
+ }
120
+ // #6767: only 'files'/'both' hard-reset the working tree. 'conversation' leaves
121
+ // it untouched, so it neither needs the shared-cwd guard below nor the git restore.
122
+ const restoreFiles = mode !== 'conversation'
97
123
  // #5731 T8 (confirms deferred #5700): restoring hard-resets the working tree
98
124
  // at the checkpoint's cwd. If ANOTHER non-destroying session shares that cwd
99
125
  // (the default for non-worktree sessions) and is mid-turn, the reset yanks
@@ -107,31 +133,105 @@ async function handleRestoreCheckpoint(ws, client, msg, ctx) {
107
133
  // and the whole scan is wrapped so an unexpected accessor failure (throw or a
108
134
  // non-array return) fails OPEN — the guard is defense-in-depth, so on its own
109
135
  // error we fall through to the normal restore (the pre-#5731 behaviour) rather
110
- // than crashing the WS message handler.
111
- try {
112
- const checkpointMgr = ctx.services.checkpointManager
113
- const sessionMgr = ctx.sessions.sessionManager
114
- if (typeof checkpointMgr.getCheckpoint === 'function' && typeof sessionMgr.listSessions === 'function') {
115
- const cp = checkpointMgr.getCheckpoint(sid, msg.checkpointId)
116
- const liveSessions = sessionMgr.listSessions()
117
- if (cp?.cwd && Array.isArray(liveSessions)) {
118
- const targetCwd = normalizeCwd(cp.cwd)
119
- const busyShare = liveSessions.find(
120
- (s) => s && s.sessionId !== sid && s.isBusy && normalizeCwd(s.cwd) === targetCwd,
121
- )
122
- if (busyShare) {
123
- sendSessionError(ws, ctx, `Cannot restore checkpoint: another session ("${busyShare.name}") is busy in the same working directory and would lose its in-progress changes. Wait for it to finish or interrupt it first.`)
124
- return
136
+ // than crashing the WS message handler. Skipped entirely for 'conversation'
137
+ // mode (#6767), which never touches the working tree.
138
+ if (restoreFiles) {
139
+ try {
140
+ const checkpointMgr = ctx.services.checkpointManager
141
+ const sessionMgr = ctx.sessions.sessionManager
142
+ if (typeof checkpointMgr.getCheckpoint === 'function' && typeof sessionMgr.listSessions === 'function') {
143
+ const cp = checkpointMgr.getCheckpoint(sid, msg.checkpointId)
144
+ const liveSessions = sessionMgr.listSessions()
145
+ if (cp?.cwd && Array.isArray(liveSessions)) {
146
+ const targetCwd = normalizeCwd(cp.cwd)
147
+ const busyShare = liveSessions.find(
148
+ (s) => s && s.sessionId !== sid && s.isBusy && normalizeCwd(s.cwd) === targetCwd,
149
+ )
150
+ if (busyShare) {
151
+ sendSessionError(ws, ctx, `Cannot restore checkpoint: another session ("${busyShare.name}") is busy in the same working directory and would lose its in-progress changes. Wait for it to finish or interrupt it first.`)
152
+ return
153
+ }
125
154
  }
126
155
  }
156
+ } catch (err) {
157
+ log.warn(`Shared-cwd restore guard skipped (accessor error, failing open): ${err?.message || err}`)
127
158
  }
128
- } catch (err) {
129
- log.warn(`Shared-cwd restore guard skipped (accessor error, failing open): ${err?.message || err}`)
130
159
  }
131
160
  try {
132
- const checkpoint = await ctx.services.checkpointManager.restoreCheckpoint(sid, msg.checkpointId)
161
+ // #6767: 'files'/'both' restore the git snapshot; 'conversation' reads the
162
+ // checkpoint WITHOUT touching the working tree.
163
+ let checkpoint
164
+ if (restoreFiles) {
165
+ checkpoint = await ctx.services.checkpointManager.restoreCheckpoint(sid, msg.checkpointId)
166
+ } else {
167
+ checkpoint = ctx.services.checkpointManager.getCheckpoint(sid, msg.checkpointId)
168
+ if (!checkpoint) throw new Error(`Checkpoint not found: ${msg.checkpointId}`)
169
+ }
170
+
171
+ // #6766/#6767: decide whether this rewind branches the conversation. A real
172
+ // branch needs (a) a fork-capable provider on the ORIGINAL session, (b) a
173
+ // captured fork boundary, and (c) a mode that includes the conversation
174
+ // ('conversation'/'both'; 'files' never forks). When they hold, fork the
175
+ // conversation truncated to the boundary so the rewound session resumes AT
176
+ // the checkpoint's point (not the full latest transcript); otherwise resume
177
+ // the checkpoint's conversation id unchanged and report the restore as
178
+ // files-only so the UI never claims a conversation rewind it didn't do.
179
+ const boundaryMessageId = checkpoint.boundaryMessageId
180
+ const hasBoundary = typeof boundaryMessageId === 'string' && boundaryMessageId.length > 0
181
+ // #6767: a 'conversation'-only rewind has no file restore to fall back on, so
182
+ // a checkpoint with no branch point (created before fork support) can't be
183
+ // honored — reject instead of resuming the full latest transcript with no
184
+ // change. 'both' still degrades to files-only in that case (below).
185
+ if (mode === 'conversation' && !hasBoundary) {
186
+ sendSessionError(ws, ctx, 'This checkpoint has no conversation branch point (it predates conversation-fork support). Use "Files" or "Both" instead.')
187
+ return
188
+ }
189
+ const branchConversation = mode !== 'files'
190
+ let resumeSessionId = checkpoint.resumeSessionId
191
+ let filesOnly = true
192
+ if (branchConversation && forkCapable && hasBoundary) {
193
+ try {
194
+ const forkedId = await origSession.forkConversation({
195
+ sessionId: checkpoint.resumeSessionId,
196
+ upToMessageId: boundaryMessageId,
197
+ })
198
+ if (forkedId) {
199
+ resumeSessionId = forkedId
200
+ filesOnly = false
201
+ } else {
202
+ log.warn('Checkpoint conversation fork returned no id — restoring files only')
203
+ }
204
+ } catch (err) {
205
+ log.warn(`Checkpoint conversation fork failed, restoring files only: ${err.message}`)
206
+ }
207
+ }
208
+ // #6767: a 'conversation'-only rewind that failed to branch would create a
209
+ // misleading full-transcript session with no file change — surface the
210
+ // failure instead. (Verified fork-capable + boundary above, so this only
211
+ // fires when forkConversation itself throws or returns no id.)
212
+ if (mode === 'conversation' && filesOnly) {
213
+ sendSessionError(ws, ctx, 'Failed to branch the conversation for this checkpoint. The working tree was left unchanged.')
214
+ return
215
+ }
216
+
217
+ // #6767: 'files' mode reverts only the working tree — the current session and
218
+ // conversation continue, so there is no new session and nothing to re-home.
219
+ if (mode === 'files') {
220
+ ctx.transport.send(ws, {
221
+ type: 'checkpoint_restored',
222
+ checkpointId: checkpoint.id,
223
+ // No newSessionId: the client stays on the current session. `name` here
224
+ // is the CHECKPOINT's name (there is no new session to name) so clients
225
+ // can confirm "Files restored to checkpoint <name>" visibly (#6827).
226
+ name: checkpoint.name,
227
+ filesOnly: true,
228
+ mode,
229
+ })
230
+ return
231
+ }
232
+
133
233
  const newSessionId = await ctx.sessions.sessionManager.createSession({
134
- resumeSessionId: checkpoint.resumeSessionId,
234
+ resumeSessionId,
135
235
  cwd: checkpoint.cwd,
136
236
  name: `Rewind: ${checkpoint.name}`,
137
237
  })
@@ -144,6 +244,13 @@ async function handleRestoreCheckpoint(ws, client, msg, ctx) {
144
244
  checkpointId: checkpoint.id,
145
245
  newSessionId,
146
246
  name: newEntry?.name || `Rewind: ${checkpoint.name}`,
247
+ // #6766: true when only the working tree was restored (conversation NOT
248
+ // branched); false when the conversation was forked/truncated to the
249
+ // checkpoint. Lets clients describe what actually happened truthfully.
250
+ filesOnly,
251
+ // #6767: echo the selective-restore mode ('conversation' | 'both') so the
252
+ // client can word the outcome precisely.
253
+ mode,
147
254
  })
148
255
  // The initiator's active session moved to the rewound session above; announce
149
256
  // it to presence/Control-Room observers (the loop below does the same for the
@@ -32,7 +32,7 @@ import { realpathSync } from 'fs'
32
32
  import { resolve } from 'path'
33
33
  import { createLogger } from '../logger.js'
34
34
  import { resolveRepoSet, DEFAULT_CONTROL_ROOM_ROOT } from '../control-room/repo-set.js'
35
- import { surveyRepos } from '../control-room/survey.js'
35
+ import { surveyRepos, resolveActiveRepos } from '../control-room/survey.js'
36
36
  import { surveyRunners, DEFAULT_RUNNER_ROOT } from '../control-room/runners.js'
37
37
  import { surveyContainers } from '../control-room/containers.js'
38
38
  import { surveyRepoRuntimeConfig, hostRuntimeDefaults } from '../control-room/repo-runtime-config.js'
@@ -74,6 +74,9 @@ const simulatorInFlight = new WeakSet()
74
74
  const emulatorInFlight = new WeakSet()
75
75
  // #6138: same again for the WSL distro survey — independent of all above.
76
76
  const wslInFlight = new WeakSet()
77
+ // #6539: repo-events became an async survey (it now resolves active sessions'
78
+ // git remotes for exact scoping), so it gains an in-flight guard like the rest.
79
+ const repoEventsInFlight = new WeakSet()
77
80
 
78
81
  /**
79
82
  * #5377 — shared builder for the survey error-snapshots. The error reply is a
@@ -1893,30 +1896,57 @@ const handleExternalSessionsRequest = makeSyncHostSurvey({
1893
1896
  },
1894
1897
  })
1895
1898
 
1899
+ /**
1900
+ * #6539 — build a schema-valid `repo_events_snapshot`. `events`/`activeRepos`
1901
+ * default empty (the FORBIDDEN / in-progress / failed replies), overwritten by
1902
+ * the success path. `generatedAt` is stamped fresh per reply.
1903
+ */
1904
+ function repoEventsSnapshot(requestId, fields = {}) {
1905
+ return {
1906
+ type: 'repo_events_snapshot',
1907
+ requestId: requestId ?? null,
1908
+ generatedAt: new Date().toISOString(),
1909
+ events: [],
1910
+ activeRepos: [],
1911
+ ...fields,
1912
+ }
1913
+ }
1914
+
1896
1915
  /**
1897
1916
  * #5966 (epic #5422 phase 5) — reply to a `repo_events_request` with a
1898
1917
  * point-in-time snapshot of the GitHub-webhook repo events the daemon buffered
1899
1918
  * in its bounded RepoEventStore (github-webhook.js, HMAC-verified ingest #6468).
1900
- * Reads the in-memory store only (no git/gh survey), so — like the mailbox /
1901
- * external-session surveys — it is synchronous and has no in-flight guard. The
1902
- * store is lazily created on the first webhook delivery, so a null store is the
1903
- * valid "nothing buffered yet" state and yields an empty (schema-valid) feed.
1904
1919
  *
1905
- * A bounded tail (`limit: 50`) keeps the snapshot small even though the store
1906
- * caps at 200 — the pane shows recent activity, not the whole ring. Host-level
1907
- * survey: a pairing-bound (share-a-session) token is rejected, like
1908
- * `host_status_request`, still with a schema-valid empty snapshot carrying an
1909
- * additive `error` so the pane renders the refusal rather than spinning.
1920
+ * #6539: the reply now also carries `activeRepos` — the EXACT `owner/repo` set
1921
+ * the live sessions are working in, resolved server-side from each active
1922
+ * session's git `origin` remote — so the dashboard scopes events by exact match
1923
+ * rather than guessing from cwd basenames. Resolving remotes is async git I/O, so
1924
+ * this moved from a synchronous store read to the async survey factory (gaining
1925
+ * the shared host-authority gate + in-flight guard). A bounded tail (`limit: 50`)
1926
+ * keeps the events small even though the store caps at 200. `ctx.resolveActiveRepos`
1927
+ * is a test seam; production falls through to the real implementation.
1910
1928
  */
1911
- const handleRepoEventsRequest = makeSyncHostSurvey({
1912
- type: 'repo_events_snapshot',
1913
- emptyFields: { events: [] },
1914
- forbiddenMessage: 'repo_events_request requires host-level authority (a session-bound token cannot survey the host)',
1915
- resolve: (ctx) => {
1929
+ const handleRepoEventsRequest = makeSurveyHandler({
1930
+ inFlight: repoEventsInFlight,
1931
+ logName: 'repo_events_request',
1932
+ forbidden: ({ requestId }) => repoEventsSnapshot(requestId, {
1933
+ error: {
1934
+ code: 'FORBIDDEN',
1935
+ message: 'repo_events_request requires host-level authority (a session-bound token cannot survey the host)',
1936
+ },
1937
+ }),
1938
+ inProgress: ({ requestId }) => repoEventsSnapshot(requestId, {
1939
+ error: { code: 'SURVEY_IN_PROGRESS', message: 'A repo events survey is already in progress for this client' },
1940
+ }),
1941
+ failed: ({ requestId, err }) => repoEventsSnapshot(requestId, {
1942
+ error: { code: 'SURVEY_FAILED', message: getErrorMessage(err, 'repo events survey failed') },
1943
+ }),
1944
+ run: async ({ ctx, requestId }) => {
1916
1945
  const store = ctx?.services?.repoEventStore
1917
- return {
1918
- events: typeof store?.list === 'function' ? store.list({ limit: 50 }) : [],
1919
- }
1946
+ const events = typeof store?.list === 'function' ? store.list({ limit: 50 }) : []
1947
+ const resolveFn = typeof ctx?.resolveActiveRepos === 'function' ? ctx.resolveActiveRepos : resolveActiveRepos
1948
+ const activeRepos = await resolveFn(activeSessionCwds(ctx?.sessions?.sessionManager))
1949
+ return repoEventsSnapshot(requestId, { events, activeRepos })
1920
1950
  },
1921
1951
  })
1922
1952