@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
@@ -0,0 +1,510 @@
1
+ /**
2
+ * Scheduled-tasks WS handlers (#6871, epic #6784) — the server half of the
3
+ * dashboard scheduled-tasks panel, and the GUI counterpart to the
4
+ * `chroxy schedule` CLI (#6868).
5
+ *
6
+ * Handles: scheduled_tasks_request (read), scheduled_task_action (CRUD),
7
+ * set_scheduler_enabled (the global gate).
8
+ *
9
+ * ── Authority (the crux) ──────────────────────────────────────────────────────
10
+ * A scheduled task is a standing arrangement for this machine to run an agent
11
+ * session WITH NOBODY WATCHING. Creating one is therefore in the same
12
+ * escalation class as adding an MCP server ("a configured MCP server is a
13
+ * command this machine will run", #6974/#7001) or creating a `user-shell`
14
+ * session: it causes future host-side execution the requester will not be
15
+ * present to supervise. Every MUTATION here is consequently gated on the STRICT
16
+ * PRIMARY token class AND on being unbound (`client.isPrimaryToken === true &&
17
+ * !client.boundSessionId`) — a superset of, not an alternative to, the weaker
18
+ * "any unbound client" host-authority bar, because an ordinary paired phone
19
+ * holds an unbound linking-mode pairing token and must not be able to schedule
20
+ * unattended execution. See docs/security/bearer-token-authority.md.
21
+ *
22
+ * Per the #6998 house pattern there is NO shared cross-surface reject helper:
23
+ * each surface defines its own local one so the error CODE names the surface
24
+ * that refused (`rejectMutationIfBound` in file-handlers.js,
25
+ * `rejectCredentialWriteIfBound` in credential-handlers.js,
26
+ * `rejectMcpConfigWriteUnlessPrimary` in settings-handlers.js, `guardAction` in
27
+ * orchestration-handlers.js). Ours is `rejectSchedulerWriteUnlessPrimary` with
28
+ * `SCHEDULER_FORBIDDEN_NON_PRIMARY_CLIENT`.
29
+ *
30
+ * The READ (`scheduled_tasks_request`) is deliberately NOT primary-gated: it is
31
+ * host-level but non-mutating, and it is the read that lets the panel warn an
32
+ * operator that the gate is closed or that a task will never fire. It follows
33
+ * the Control Room surveys' bar — host-level authority, i.e. an UNBOUND client
34
+ * (`client.boundSessionId` unset) — because the registry spans every repo/session
35
+ * on the host and a pairing-BOUND (share-one-session) client must not receive it.
36
+ *
37
+ * ── Honest status ─────────────────────────────────────────────────────────────
38
+ * This handler never computes a health verdict of its own. It ships the raw
39
+ * record plus the ANSWERS from the engine's own exported helpers —
40
+ * `scheduledProviderRefusalReason()`, `resolveScheduledPermissionMode()`,
41
+ * `listSchedulableProviders()` and `SchedulerEngine.quarantinedTaskIds` — so the
42
+ * panel renders the engine's real verdict instead of a second guess at it. The
43
+ * health TAG is derived from the shared `@chroxy/protocol` helper that the CLI
44
+ * uses, so the two surfaces cannot drift.
45
+ */
46
+
47
+ import { createLogger, sessionLogger } from '../logger.js'
48
+ import { isSchedulerEnabled, writeSchedulerEnabledToConfig } from '../config.js'
49
+ import { DEFAULT_PROVIDER } from '../providers.js'
50
+ import {
51
+ listSchedulableProviders,
52
+ resolveScheduledPermissionMode,
53
+ scheduledProviderRefusalReason,
54
+ } from '../scheduler.js'
55
+ import { ScheduledTaskValidationError } from '../scheduled-task-store.js'
56
+ import { getErrorMessage } from '../utils/error-message.js'
57
+
58
+ const log = createLogger('ws')
59
+
60
+ /** Actions that only need a taskId (no `task` payload). */
61
+ const ID_ONLY_ACTIONS = new Set(['pause', 'resume', 'delete'])
62
+
63
+ /**
64
+ * Send a scheduled-task failure envelope.
65
+ *
66
+ * Deliberately `session_error` (with `code` + `message` + the echoed
67
+ * `requestId`) rather than `sendError`'s `{ type: 'error' }` frame: the
68
+ * dashboard correlates this panel's in-flight mutations by requestId inside its
69
+ * `session_error` handler, exactly as the orchestration Runs surface does
70
+ * (`makeActionError` in control-room/handler-factory.js emits this same shape).
71
+ * Using one envelope for BOTH the authority rejections and the action failures
72
+ * means every rejection releases the panel's pending state — a button that spins
73
+ * forever because a refusal arrived on a frame the panel wasn't watching is its
74
+ * own kind of dishonest status.
75
+ */
76
+ function schedulerError(ws, ctx, msg, code, message) {
77
+ ctx.transport.send(ws, {
78
+ type: 'session_error',
79
+ code,
80
+ message,
81
+ requestId: msg?.requestId ?? null,
82
+ })
83
+ }
84
+
85
+ /**
86
+ * MUTATION gate — require the STRICT PRIMARY token class before any validation,
87
+ * store read, or config write.
88
+ *
89
+ * Rationale for strict-primary rather than the unbound-client bar used by the
90
+ * credential-write / permission-rule / file-git gates: those reject only
91
+ * `client.boundSessionId`, which leaves an ordinary paired phone (an unbound
92
+ * linking-mode pairing token) with full authority. Scheduling unattended agent
93
+ * execution on the host is the escalation class that checks
94
+ * `client.isPrimaryToken === true` — the same tier as `user-shell` creation,
95
+ * `terminal_input`, `revoke_token`, `orchestration_run_start` and MCP config
96
+ * writes.
97
+ *
98
+ * The `boundSessionId` term keeps this gate strictly STRONGER than the read gate
99
+ * below (#7025). Without it the two were asymmetric in the unsafe direction: a
100
+ * bound + primary client was refused the harmless registry READ yet permitted
101
+ * every MUTATION. That combination is not reachable over the wire today —
102
+ * `ws-auth.js` derives `isPrimaryToken` as `!authRequired ||
103
+ * !pairingManager?.isSessionTokenValid(token)`, so a session-bound token always
104
+ * yields `false` — so this is defence in depth against a future auth change,
105
+ * not a live hole. It costs one conjunct and removes the trap.
106
+ *
107
+ * Both refusals share `SCHEDULER_FORBIDDEN_NON_PRIMARY_CLIENT`: it is the code
108
+ * the dashboard correlates a failed mutation on, and a second code for a state
109
+ * no wire client can reach would be untestable surface for no gain. The message
110
+ * text therefore states the WHOLE bar (an unbound primary token) rather than only
111
+ * the reachable half, so one envelope describes both refusals honestly instead of
112
+ * telling a bound primary that its problem is being "pairing-issued".
113
+ *
114
+ * Logging uses `sessionLogger` (never `loggerForSession`, which throws on an
115
+ * absent sessionId) because a rejected client is frequently unbound.
116
+ *
117
+ * @returns {boolean} true if the caller was rejected (handler must return).
118
+ */
119
+ function rejectSchedulerWriteUnlessPrimary(ws, client, msg, ctx, op) {
120
+ if (client?.isPrimaryToken === true && !client?.boundSessionId) return false
121
+ sessionLogger(client?.boundSessionId).warn(
122
+ `Client ${client?.id}${client?.boundSessionId ? ` (bound to ${client.boundSessionId})` : ' (unbound, non-primary)'} attempted ${op} — rejected (scheduled-task writes require an UNBOUND primary token)`,
123
+ )
124
+ schedulerError(
125
+ ws, ctx, msg,
126
+ 'SCHEDULER_FORBIDDEN_NON_PRIMARY_CLIENT',
127
+ 'Creating, changing, or deleting a scheduled task requires an UNBOUND primary token — neither a pairing-issued token nor a connection bound to a single shared session qualifies, because a scheduled task makes this machine run an agent session unattended. Use the primary API token from a device with physical access to this machine.',
128
+ )
129
+ return true
130
+ }
131
+
132
+ /**
133
+ * READ gate — host-level authority, matching the Control Room surveys. The
134
+ * registry spans every repo and session on the host, so a pairing-BOUND client
135
+ * (scoped to one shared session) must not receive it.
136
+ *
137
+ * @returns {boolean} true if the caller was rejected (handler must return).
138
+ */
139
+ function rejectSchedulerReadIfBound(ws, client, msg, ctx) {
140
+ if (!client?.boundSessionId) return false
141
+ schedulerError(
142
+ ws, ctx, msg,
143
+ 'SCHEDULER_FORBIDDEN_BOUND_CLIENT',
144
+ 'A session-scoped (pairing-bound) client cannot read the host scheduled-task registry.',
145
+ )
146
+ return true
147
+ }
148
+
149
+ /** The registry, or null when no SessionManager is wired. */
150
+ function resolveStore(ctx) {
151
+ return ctx?.sessions?.sessionManager?.scheduledTaskStore ?? null
152
+ }
153
+
154
+ /**
155
+ * The provider a task would ACTUALLY resolve to — the same precedence
156
+ * SchedulerEngine._resolveProviderName uses (task target → manager default →
157
+ * DEFAULT_PROVIDER), so the refusal verdict judges the real target rather than
158
+ * the stored field.
159
+ */
160
+ function effectiveProvider(task, ctx) {
161
+ const explicit = task?.target?.provider
162
+ if (typeof explicit === 'string' && explicit.length > 0) return explicit
163
+ const managerDefault = ctx?.sessions?.sessionManager?.providerType
164
+ if (typeof managerDefault === 'string' && managerDefault.length > 0) return managerDefault
165
+ return DEFAULT_PROVIDER
166
+ }
167
+
168
+ /**
169
+ * Clamp a string to the wire schema's cap for its field.
170
+ *
171
+ * The store deliberately enforces NO length caps (its validation authority is
172
+ * about shape, not size), but `ScheduledTaskSchema` does — `name`/`id` 256,
173
+ * `provider` 128, `model` 256, `cwd` 4096, `lastRun.error` 2048. That asymmetry
174
+ * was a live brick: a store-legal task (a 300-char `name` from the CLI, or a
175
+ * long engine error in `lastRun.error`) made the WHOLE snapshot fail the
176
+ * dashboard's `safeParse`, so every task vanished and the tab hung on
177
+ * "Loading…". A snapshot the contract cannot represent is worse than a
178
+ * shortened display string.
179
+ *
180
+ * ── The clamp is display-only, but ONLY if every writer cooperates (#7049) ────
181
+ * This block used to end "and the store keeps the full value either way", which
182
+ * was true of the READ and false of the write-back. A surface that seeds an EDIT
183
+ * FORM from this projection and sends the fields back on save persists the
184
+ * SHORTENED value, permanently — and nothing here can prevent it, because
185
+ * `ScheduledTaskInputSchema`'s caps are the SAME numbers, so an over-cap value
186
+ * cannot be sent back even deliberately. The only thing that keeps it is not
187
+ * sending the field.
188
+ *
189
+ * So the dashboard's task form sends PATCH semantics on `update` — only the
190
+ * fields the operator actually changed (ScheduledTasksSection.tsx `submit()`) —
191
+ * and any NEW writer of `scheduled_task_action:update` must do the same. The
192
+ * store's `update()` also replaces `target` WHOLESALE, so the same rule is what
193
+ * keeps a `target.permissionMode` (which no form field owns) from being erased
194
+ * by an unrelated save.
195
+ */
196
+ function clampWire(value, max) {
197
+ if (typeof value !== 'string') return value
198
+ return value.length > max ? value.slice(0, max) : value
199
+ }
200
+
201
+ /** Clamp the target's string fields to their wire caps. */
202
+ function projectTarget(target) {
203
+ if (!target || typeof target !== 'object') return {}
204
+ const out = { ...target }
205
+ if (typeof out.provider === 'string') out.provider = clampWire(out.provider, 128)
206
+ if (typeof out.model === 'string') out.model = clampWire(out.model, 256)
207
+ if (typeof out.cwd === 'string') out.cwd = clampWire(out.cwd, 4096)
208
+ if (typeof out.permissionMode === 'string') out.permissionMode = clampWire(out.permissionMode, 64)
209
+ return out
210
+ }
211
+
212
+ /**
213
+ * Clamp the last-run block's string fields. `error` is the realistic offender —
214
+ * an engine failure message (or a stack) easily exceeds the wire's 2048.
215
+ */
216
+ function projectLastRun(lastRun) {
217
+ if (!lastRun || typeof lastRun !== 'object') return null
218
+ const out = { ...lastRun }
219
+ // A clamped status is still an unrecognized status, which the shared health
220
+ // helper maps to ERROR — the pessimistic direction, so this cannot invent health.
221
+ if (typeof out.status === 'string') out.status = clampWire(out.status, 64)
222
+ if (typeof out.sessionId === 'string') out.sessionId = clampWire(out.sessionId, 256)
223
+ if (typeof out.error === 'string') out.error = clampWire(out.error, 2048)
224
+ return out
225
+ }
226
+
227
+ /**
228
+ * Project one stored task onto the wire shape, attaching the engine's own
229
+ * verdicts. NOTHING here is re-derived: the refusal string is verbatim
230
+ * `scheduledProviderRefusalReason()` output and the permission mode is verbatim
231
+ * `resolveScheduledPermissionMode()` output, so the panel cannot disagree with
232
+ * what the engine will actually do.
233
+ *
234
+ * String fields are clamped to the wire caps (see `clampWire`). `id` is
235
+ * deliberately NOT clamped: it is the mutation key, so a truncated id would let
236
+ * pause/delete address the wrong record (or nothing) — far worse than a rejected
237
+ * snapshot. Store ids are generated, so an over-cap id means a hand-edited
238
+ * registry, and the panel now surfaces that as a readable snapshot error rather
239
+ * than hanging.
240
+ */
241
+ function projectTask(task, ctx, quarantinedIds) {
242
+ const provider = effectiveProvider(task, ctx)
243
+ const requestedMode = task?.target?.permissionMode
244
+ const effectiveMode = resolveScheduledPermissionMode(requestedMode)
245
+ return {
246
+ id: task.id,
247
+ name: clampWire(task.name ?? null, 256),
248
+ enabled: task.enabled === true,
249
+ prompt: typeof task.prompt === 'string' ? task.prompt : '',
250
+ target: projectTarget(task.target),
251
+ cadence: task.cadence,
252
+ nextRun: Number.isFinite(task.nextRun) ? task.nextRun : null,
253
+ lastRun: projectLastRun(task.lastRun),
254
+ createdAt: Number.isFinite(task.createdAt) ? task.createdAt : 0,
255
+ updatedAt: Number.isFinite(task.updatedAt) ? task.updatedAt : 0,
256
+ providerRefusal: clampWire(scheduledProviderRefusalReason(provider), 2048),
257
+ effectiveProvider: clampWire(provider, 128),
258
+ effectivePermissionMode: clampWire(effectiveMode, 64),
259
+ // True only when the task ASKED for something and got clamped — an absent
260
+ // mode is a default, not a downgrade the operator needs warning about.
261
+ permissionModeClamped: typeof requestedMode === 'string'
262
+ && requestedMode.length > 0
263
+ && requestedMode !== effectiveMode,
264
+ quarantined: quarantinedIds.has(task.id),
265
+ }
266
+ }
267
+
268
+ /**
269
+ * Where the gate's value came from. Surfaced so the panel can explain that a
270
+ * config toggle cannot override `CHROXY_ENABLE_SCHEDULER=1`.
271
+ */
272
+ function gateSource(ctx) {
273
+ if (process.env.CHROXY_ENABLE_SCHEDULER === '1') return 'env'
274
+ if (ctx?.services?.config?.features?.scheduler === true) return 'config'
275
+ return 'default'
276
+ }
277
+
278
+ /**
279
+ * Build the full snapshot. `engineArmed` is the RUNTIME truth (a live, armed
280
+ * engine) which can disagree with the persisted gate, because the engine is
281
+ * built once at daemon boot — `restartRequired` names that disagreement rather
282
+ * than letting `enabled` imply something is firing.
283
+ */
284
+ function buildSnapshot(ctx, requestId, { error = null } = {}) {
285
+ const store = resolveStore(ctx)
286
+ const engine = ctx?.services?.schedulerEngine ?? null
287
+ const quarantinedIds = engine?.quarantinedTaskIds instanceof Set
288
+ ? engine.quarantinedTaskIds
289
+ : new Set()
290
+ const enabled = isSchedulerEnabled(ctx?.services?.config)
291
+ const engineArmed = engine?.armed === true
292
+ let tasks = []
293
+ if (store && !error) {
294
+ try {
295
+ tasks = store.list().map((t) => projectTask(t, ctx, quarantinedIds))
296
+ } catch (err) {
297
+ // Degrade to a structurally valid empty snapshot + error, the same posture
298
+ // the Control Room surveys use — never a dead/unparseable reply.
299
+ log.warn(`Failed to list scheduled tasks: ${getErrorMessage(err)}`)
300
+ return buildSnapshot(ctx, requestId, {
301
+ error: { code: 'SCHEDULER_REGISTRY_UNAVAILABLE', message: getErrorMessage(err) },
302
+ })
303
+ }
304
+ }
305
+ const defaultProvider = effectiveProvider(null, ctx)
306
+ return {
307
+ type: 'scheduled_tasks',
308
+ requestId: requestId ?? null,
309
+ generatedAt: new Date().toISOString(),
310
+ scheduler: {
311
+ enabled,
312
+ engineArmed,
313
+ restartRequired: enabled !== engineArmed,
314
+ source: gateSource(ctx),
315
+ },
316
+ schedulableProviders: listSchedulableProviders(),
317
+ defaultProvider,
318
+ defaultProviderRefusal: scheduledProviderRefusalReason(defaultProvider),
319
+ tasks,
320
+ ...(error ? { error } : {}),
321
+ }
322
+ }
323
+
324
+ /** Send the snapshot to the requesting client only. */
325
+ function replySnapshot(ws, ctx, requestId, opts) {
326
+ ctx.transport.send(ws, buildSnapshot(ctx, requestId, opts))
327
+ }
328
+
329
+ /**
330
+ * Read the registry + gate state. Reply is a `scheduled_tasks` snapshot to the
331
+ * requesting client. Host-level (unbound) authority; see the file header.
332
+ */
333
+ function handleScheduledTasksRequest(ws, client, msg, ctx) {
334
+ if (rejectSchedulerReadIfBound(ws, client, msg, ctx)) return
335
+ const requestId = msg?.requestId ?? null
336
+ if (!resolveStore(ctx)) {
337
+ replySnapshot(ws, ctx, requestId, {
338
+ error: {
339
+ code: 'SCHEDULER_REGISTRY_UNAVAILABLE',
340
+ message: 'No scheduled-task registry is available on this server.',
341
+ },
342
+ })
343
+ return
344
+ }
345
+ replySnapshot(ws, ctx, requestId)
346
+ }
347
+
348
+ /**
349
+ * Create / update / pause / resume / delete a scheduled task.
350
+ *
351
+ * STRICT-PRIMARY gated (first statement, before any validation or store touch).
352
+ * On success the reply is the re-emitted snapshot echoing `requestId` — that IS
353
+ * the ack, mirroring #6998's `mcp_servers` re-broadcast. Every failure is a
354
+ * `SCHEDULED_TASK_ACTION_FAILED` session_error echoing the same `requestId`, so
355
+ * the panel can clear its pending entry either way and never shows a mutation
356
+ * as applied when it was not.
357
+ *
358
+ * Validation authority is the store: its `ScheduledTaskValidationError` carries
359
+ * the offending field, which is surfaced verbatim rather than re-implemented
360
+ * here (a second validator would be free to accept what the store rejects).
361
+ */
362
+ function handleScheduledTaskAction(ws, client, msg, ctx) {
363
+ if (rejectSchedulerWriteUnlessPrimary(ws, client, msg, ctx, `scheduled_task_action:${msg?.action}`)) return
364
+ const requestId = msg?.requestId ?? null
365
+ const action = msg?.action
366
+ const fail = (message, code = 'SCHEDULED_TASK_ACTION_FAILED') => {
367
+ schedulerError(ws, ctx, msg, code, message)
368
+ }
369
+
370
+ const store = resolveStore(ctx)
371
+ if (!store) {
372
+ fail('No scheduled-task registry is available on this server.', 'SCHEDULER_REGISTRY_UNAVAILABLE')
373
+ return
374
+ }
375
+
376
+ const taskId = typeof msg?.taskId === 'string' ? msg.taskId.trim() : ''
377
+ if ((ID_ONLY_ACTIONS.has(action) || action === 'update') && !taskId) {
378
+ fail(`scheduled_task_action '${action}' requires a taskId`)
379
+ return
380
+ }
381
+ if (action === 'create' && (!msg?.task || typeof msg.task !== 'object')) {
382
+ fail("scheduled_task_action 'create' requires a task payload")
383
+ return
384
+ }
385
+ if (action === 'update' && (!msg?.task || typeof msg.task !== 'object')) {
386
+ fail("scheduled_task_action 'update' requires a task payload")
387
+ return
388
+ }
389
+
390
+ try {
391
+ switch (action) {
392
+ case 'create': {
393
+ const created = store.add(msg.task)
394
+ // Log the id + cadence kind only — a prompt is user content.
395
+ log.info(`Scheduled task created: ${created.id} (cadence ${created.cadence?.kind})`)
396
+ break
397
+ }
398
+ case 'update': {
399
+ if (!store.update(taskId, msg.task)) {
400
+ fail(`No scheduled task with id ${taskId}`, 'SCHEDULED_TASK_NOT_FOUND')
401
+ return
402
+ }
403
+ log.info(`Scheduled task updated: ${taskId}`)
404
+ break
405
+ }
406
+ case 'pause':
407
+ case 'resume': {
408
+ if (!store.update(taskId, { enabled: action === 'resume' })) {
409
+ fail(`No scheduled task with id ${taskId}`, 'SCHEDULED_TASK_NOT_FOUND')
410
+ return
411
+ }
412
+ log.info(`Scheduled task ${action}d: ${taskId}`)
413
+ break
414
+ }
415
+ case 'delete': {
416
+ if (!store.remove(taskId)) {
417
+ fail(`No scheduled task with id ${taskId}`, 'SCHEDULED_TASK_NOT_FOUND')
418
+ return
419
+ }
420
+ log.info(`Scheduled task deleted: ${taskId}`)
421
+ break
422
+ }
423
+ default:
424
+ fail(`Unsupported scheduled_task_action '${action}'`)
425
+ return
426
+ }
427
+ } catch (err) {
428
+ if (err instanceof ScheduledTaskValidationError) {
429
+ // The store is the validation authority — pass its field-precise reason
430
+ // straight through so the panel can point at the offending input.
431
+ fail(`${err.field ? `${err.field}: ` : ''}${err.message}`, 'SCHEDULED_TASK_INVALID')
432
+ return
433
+ }
434
+ log.error(`scheduled_task_action '${action}' failed: ${getErrorMessage(err)}`)
435
+ fail(getErrorMessage(err))
436
+ return
437
+ }
438
+
439
+ // The registry changed — let a running engine re-evaluate immediately instead
440
+ // of waiting out its max-sleep tick. Best-effort: a refresh failure must not
441
+ // turn an applied mutation into a reported failure.
442
+ const engine = ctx?.services?.schedulerEngine ?? null
443
+ try {
444
+ engine?.refresh?.()
445
+ } catch (err) {
446
+ log.warn(`Scheduler refresh after ${action} failed: ${getErrorMessage(err)}`)
447
+ }
448
+
449
+ replySnapshot(ws, ctx, requestId)
450
+ }
451
+
452
+ /**
453
+ * Flip the PERSISTED global enable gate (`features.scheduler` in config.json).
454
+ *
455
+ * STRICT-PRIMARY gated — this is the switch that decides whether the daemon runs
456
+ * agent sessions with nobody watching at all.
457
+ *
458
+ * HONESTY CONTRACT: this writes the persisted flag and updates the in-memory
459
+ * config so the reported gate state is accurate, but it does NOT arm or disarm a
460
+ * running daemon — the engine is constructed once at boot (buildSchedulerEngine
461
+ * returns null when the gate is closed) and `destroy()` is terminal. So the reply
462
+ * snapshot reports `scheduler.restartRequired` whenever the gate and the live
463
+ * engine disagree, and the panel says so. Pretending a toggle took effect would
464
+ * be exactly the lie this panel exists to prevent.
465
+ *
466
+ * A gate forced by `CHROXY_ENABLE_SCHEDULER=1` cannot be turned off by a config
467
+ * write, so that case is refused explicitly instead of writing a flag that has
468
+ * no effect.
469
+ */
470
+ function handleSetSchedulerEnabled(ws, client, msg, ctx) {
471
+ if (rejectSchedulerWriteUnlessPrimary(ws, client, msg, ctx, 'set_scheduler_enabled')) return
472
+ const requestId = msg?.requestId ?? null
473
+ const enabled = msg?.enabled
474
+ if (typeof enabled !== 'boolean') {
475
+ schedulerError(ws, ctx, msg, 'SCHEDULER_GATE_FAILED', 'set_scheduler_enabled requires a boolean `enabled`')
476
+ return
477
+ }
478
+ if (enabled === false && process.env.CHROXY_ENABLE_SCHEDULER === '1') {
479
+ schedulerError(
480
+ ws, ctx, msg, 'SCHEDULER_GATE_ENV_FORCED',
481
+ 'Scheduled execution is forced ON by the CHROXY_ENABLE_SCHEDULER=1 environment variable, which overrides config.json. Unset it in the daemon environment and restart to disable.',
482
+ )
483
+ return
484
+ }
485
+
486
+ try {
487
+ writeSchedulerEnabledToConfig(enabled)
488
+ } catch (err) {
489
+ log.error(`Failed to persist features.scheduler=${enabled}: ${getErrorMessage(err)}`)
490
+ schedulerError(ws, ctx, msg, 'SCHEDULER_GATE_FAILED', `Could not persist the scheduler gate: ${getErrorMessage(err)}`)
491
+ return
492
+ }
493
+
494
+ // Keep the in-memory config in step so the snapshot reports the new gate value
495
+ // (and `restartRequired`) rather than the stale boot-time one.
496
+ const config = ctx?.services?.config
497
+ if (config && typeof config === 'object') {
498
+ if (!config.features || typeof config.features !== 'object') config.features = {}
499
+ config.features.scheduler = enabled
500
+ }
501
+ log.warn(`Scheduled execution gate set to ${enabled} by the primary client — a daemon restart is required for it to take effect`)
502
+
503
+ replySnapshot(ws, ctx, requestId)
504
+ }
505
+
506
+ export const schedulerHandlers = {
507
+ scheduled_tasks_request: handleScheduledTasksRequest,
508
+ scheduled_task_action: handleScheduledTaskAction,
509
+ set_scheduler_enabled: handleSetSchedulerEnabled,
510
+ }
@@ -6,8 +6,9 @@
6
6
  */
7
7
  import { USER_SHELL_PROVIDER } from '@chroxy/protocol'
8
8
  import { auditShellCreate } from '../shell-audit.js'
9
- import { validateCwdAllowed, broadcastFocusChanged, autoSubscribeOtherClients, buildSessionTokenMismatchPayload, sendSessionError, isSessionViewer, isUserShellSession, ALLOWED_PERMISSION_MODE_IDS } from '../handler-utils.js'
9
+ import { validateCwdAllowed, broadcastFocusChanged, autoSubscribeOtherClients, buildSessionTokenMismatchPayload, sendSessionError, isSessionViewer, isUserShellSession, ALLOWED_PERMISSION_MODE_IDS, getPermissionModes } from '../handler-utils.js'
10
10
  import { getRegistryForProvider } from '../models.js'
11
+ import { CODEX_SANDBOX_MODES } from '../codex-session.js'
11
12
  import { isUserShellEnabled, isUserShellApprovalRequired } from '../config.js'
12
13
  import { createLogger, loggerForSession } from '../logger.js'
13
14
 
@@ -81,6 +82,9 @@ function handleSwitchSession(ws, client, msg, ctx) {
81
82
  const switchProvider = entry.provider || null
82
83
  const switchRegistry = getRegistryForProvider(switchProvider)
83
84
  ctx.transport.send(ws, { type: 'available_models', models: switchRegistry.getModels(), defaultModel: switchRegistry.getDefaultModelId(), provider: switchProvider })
85
+ // #6638: also re-send the permission-mode copy so switching to/from a Codex
86
+ // session updates the mode descriptions (Codex has different tools + no plan mode).
87
+ ctx.transport.send(ws, { type: 'available_permission_modes', modes: getPermissionModes(switchProvider) })
84
88
  broadcastFocusChanged(client, targetId, ctx)
85
89
  }
86
90
 
@@ -112,6 +116,10 @@ function handleCreateSession(ws, client, msg, ctx) {
112
116
  const permissionMode = rawPermMode && ALLOWED_PERMISSION_MODE_IDS.has(rawPermMode) ? rawPermMode : undefined
113
117
  const worktree = msg.worktree === true ? true : undefined
114
118
  const sandbox = (msg.sandbox && typeof msg.sandbox === 'object' && !Array.isArray(msg.sandbox)) ? msg.sandbox : undefined
119
+ // #6638: per-session codex sandbox mode. Schema-gated to the valid enum; the
120
+ // guard keeps an unexpected value from reaching the session (→ env/default).
121
+ const rawCodexSandbox = (typeof msg.codexSandbox === 'string' && msg.codexSandbox.trim()) ? msg.codexSandbox.trim() : undefined
122
+ const codexSandbox = rawCodexSandbox && CODEX_SANDBOX_MODES.includes(rawCodexSandbox) ? rawCodexSandbox : undefined
115
123
  const environmentId = (typeof msg.environmentId === 'string' && msg.environmentId.trim()) ? msg.environmentId.trim() : undefined
116
124
  // #4208: opt-in TUI flag — preserve strict booleans so an explicit `false`
117
125
  // can override a server-wide `defaultSkipPermissions: true` on a per-session
@@ -206,7 +214,7 @@ function handleCreateSession(ws, client, msg, ctx) {
206
214
 
207
215
  // #6277 — build the create options + audit identity ONCE; both the synchronous
208
216
  // path and the host-approval deferred path replay the identical create.
209
- const createOptions = { name, cwd, provider, model, permissionMode, worktree, sandbox, skipPermissions, agentCommId, ...envOpts }
217
+ const createOptions = { name, cwd, provider, model, permissionMode, worktree, sandbox, codexSandbox, skipPermissions, agentCommId, ...envOpts }
210
218
  const isUserShell = provider === USER_SHELL_PROVIDER
211
219
  // Capture the audit identity at REQUEST time: the deferred (approved) path may
212
220
  // run after the requesting socket is gone, so it can't read a live `client`.