@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,1029 @@
1
+ // Headless scheduler engine (#6865, keystone slice of epic #6784). Owns the
2
+ // TIMING and the SAFETY of firing a persisted scheduled task (#6862) into a real
3
+ // agent session with NO client connected.
4
+ //
5
+ // Split of responsibility across the epic:
6
+ // - schedule-parser.js — pure cadence parsing + next-run computation
7
+ // - scheduled-task-store.js — persistence/CRUD of the standing registry
8
+ // - scheduler.js (this file) — arms timers, fires due tasks, records outcomes
9
+ // - #6868 CLI / #6871 panel — read the registry + this engine's gate state
10
+ //
11
+ // Deliberately NOT `ScheduleWakeup` (transcript-tasks.js): that stays the
12
+ // intra-session, single-shot, transcript-derived mid-turn self-resume. Nothing
13
+ // here reads or writes it — TranscriptTaskScanner is a passive transcript
14
+ // observer and is untouched by this slice.
15
+ //
16
+ // ── Why the daemon owns the timing ────────────────────────────────────────────
17
+ // The upstream `claude` CLI emits its own `scheduled_task_fire` system-message
18
+ // subtype (epic #6784 notes it in real transcripts; in Chroxy it lands in the
19
+ // generic system-event log at sdk-session.js:920). Investigated and NOT used as
20
+ // the timing source: it is a NOTIFICATION that the CLI's internal scheduler
21
+ // fired, not a programmable API — there is no way to register a standing cadence
22
+ // with it, no wire message to drive it, and it would only ever cover the one
23
+ // `claude` provider, so it cannot serve a multi-provider registry. The engine
24
+ // therefore owns timing in-daemon.
25
+ //
26
+ // ── Security posture (the crux — a turn fires with nobody watching) ───────────
27
+ // 1. ENABLE GATE: off unless explicitly enabled (`features.scheduler` /
28
+ // CHROXY_ENABLE_SCHEDULER=1, via config.js's isSchedulerEnabled). A daemon
29
+ // with the gate closed arms NO timer and spawns NOTHING — start() is a no-op.
30
+ // 2. PERMISSION FLOOR: a scheduled run is pinned to the safest posture and can
31
+ // never select an auto-approve mode. resolveScheduledPermissionMode() clamps a
32
+ // stored `target.permissionMode` DOWN to 'approve', so a task definition can
33
+ // never escalate itself. The run is also created with an EXPLICIT
34
+ // `skipPermissions: false`, which overrides the server-wide
35
+ // `dangerouslySkipPermissions` default (session-manager.js:1473) — a global
36
+ // bypass a human opted into for their own interactive TUI use must not silently
37
+ // extend to unattended runs.
38
+ // 3. NOBODY TO ANSWER: a permission prompt raised by a scheduled turn rides the
39
+ // normal pipeline. Rules in the permission-rule store still short-circuit
40
+ // BEFORE a prompt is emitted, so an operator's explicit, auditable allow-rule
41
+ // remains the ONE way to let a scheduled task act — and the protected-path /
42
+ // secret-read floor still cannot be escaped by such a rule. Anything that
43
+ // actually reaches a prompt has no human to answer it, so this engine answers
44
+ // `deny` through the same door a human clicks (`session.respondToPermission`,
45
+ // mirroring orchestration/permission-gate.js), interrupts the turn, and
46
+ // records the run as a VISIBLE failure. The prompt is answered at once (never
47
+ // left to sit out a permission timeout), the interrupted turn settles at once
48
+ // (TurnDriver treats the provider's `stopped` as terminal → TURN_STOPPED,
49
+ // #7009) so the concurrency slot frees immediately, and nothing is ever
50
+ // auto-approved. See _handleSessionEvent.
51
+ // 4. SUPPORTED PROVIDERS ONLY — the engine REFUSES what it cannot govern. The
52
+ // deny mechanism in (3) rides `session_event: permission_request` +
53
+ // `session.respondToPermission`, which exist ONLY on providers whose
54
+ // `capabilities.inProcessPermissions === true` (today: claude-sdk, claude-byok,
55
+ // codex via its app-server driver, deepseek, ollama — the live list is
56
+ // listSchedulableProviders(), read off the registry rather than hardcoded).
57
+ // Hook-routed providers — INCLUDING the daemon default `claude-tui`, plus
58
+ // claude-cli, claude-channel, gemini, and codex when CHROXY_CODEX_APPSERVER=0
59
+ // downgrades it to the exec driver — route prompts through
60
+ // hooks/permission-hook.sh → POST /permission → ws-permissions.js, which emits
61
+ // NO events this engine can observe and auto-denies after a 300s wait. On such
62
+ // a provider an unattended run would stall five minutes per gated tool call
63
+ // and then report SUCCESS for a turn whose every tool call was silently
64
+ // refused. Rather than pretend to govern it, a task resolving to a hook-routed
65
+ // provider is refused BEFORE any session is created and recorded `refused`
66
+ // with the provider named. Widening this to hook-routed providers needs a
67
+ // programmatic permission-answering surface — tracked in #7003.
68
+ // 5. CWD CONFINEMENT is enforced HERE, on this path. It is NOT inherited: the
69
+ // store only trims the cwd string and SessionManager.createSession only
70
+ // `statSync`s it, so the real check (`validateCwdAllowed` — credential-dir
71
+ // deny-list + workspace allowlist + $HOME fallback) is handler-only. A task
72
+ // definition is a user-writable JSON file, so a hand-edited `target.cwd` of
73
+ // `/`, `~/.ssh`, or `~/.chroxy` would otherwise reach a session the dashboard
74
+ // would have rejected. This engine therefore calls the SAME imported
75
+ // `validateCwdAllowed` the WS handlers call, wired exactly the way the sibling
76
+ // feature does it (orchestration/build-manager.js:38), and refuses the run
77
+ // when it rejects. (Moving the check INTO createSession so no caller can miss
78
+ // it is the right long-term fix — tracked in #7005.)
79
+ // 6. THE CLAMP IS RE-ASSERTED PER FIRE, not just at create. Scheduled sessions
80
+ // are deliberately kept alive and reused, and `set_permission_mode` accepts
81
+ // `auto` on any session (handlers/settings-handlers.js) — even mid-turn
82
+ // (base-session.js:1115-1133). An operator who opens a scheduled session and
83
+ // flips it to Auto once would otherwise make every subsequent unattended fire
84
+ // run in bypass, indefinitely. So before each fire the engine re-asserts the
85
+ // clamped mode on the session and VERIFIES it by read-back. The invariant is
86
+ // absolute: a scheduled fire runs at the clamped mode, or it does not run.
87
+ // 7. Every fire attempt — success, error, timeout, permission-blocked, refused,
88
+ // interrupted, shed — is recorded into the registry so #6868/#6871 can surface
89
+ // it. A run the engine refused is recorded `refused` (never `success`), a run
90
+ // whose tool calls were blocked is recorded `error`, and a run someone
91
+ // deliberately STOPPED is recorded `interrupted` (#7038) rather than being
92
+ // dropped into the same bucket as a provider crash. NOTHING reports `success`
93
+ // unless the turn actually completed with no permission prompt raised.
94
+ //
95
+ // ── Resource posture (#6933 lesson) ──────────────────────────────────────────
96
+ // One self-rescheduling timer (never setInterval), injectable via
97
+ // `setTimer`/`clearTimer` and `.unref()`'d by default so it can never keep the
98
+ // event loop alive or wedge a coverage run. destroy() clears everything and is
99
+ // idempotent. Overlapping fires of one task are refused; a burst of
100
+ // simultaneously-due tasks is serialized under a concurrency cap.
101
+
102
+ import { EventEmitter } from 'events'
103
+ import { createLogger } from './logger.js'
104
+ import { isSchedulerEnabled } from './config.js'
105
+ import { getProvider, listProviders, DEFAULT_PROVIDER } from './providers.js'
106
+ import { validateCwdAllowed } from './handler-utils.js'
107
+ import { TurnDriver, TurnError } from './orchestration/turn-driver.js'
108
+
109
+ const log = createLogger('scheduler')
110
+
111
+ /**
112
+ * Longest a single armed timer may sleep. The engine re-evaluates at least this
113
+ * often even when the next task is days away, so a registry mutated by the CLI
114
+ * (#6868) or the dashboard (#6871) is picked up without those callers having to
115
+ * know to poke us, and a large wall-clock jump (suspend/resume, NTP step) can
116
+ * never park us on a stale multi-day deadline.
117
+ */
118
+ export const MAX_SLEEP_MS = 60 * 1000
119
+
120
+ /**
121
+ * How long a single scheduled run may take before it is abandoned and recorded
122
+ * as `timeout`. Bounds the damage of a wedged provider so it cannot hold the
123
+ * concurrency slot (and thus every other task) forever.
124
+ */
125
+ export const DEFAULT_RUN_TIMEOUT_MS = 15 * 60 * 1000
126
+
127
+ /**
128
+ * How late an overdue task may still be fired. A daemon that was down (laptop
129
+ * closed, crash-restart) comes back to tasks whose slot has passed; firing all of
130
+ * them at once is a surprise burst of unattended agent sessions, so anything
131
+ * staler than this grace window is recorded `skipped` instead of run. Recurring
132
+ * cadences rarely reach it — the store recomputes nextRun FORWARD on load, so a
133
+ * missed slot is simply skipped and there is no backfill — it mainly bounds a
134
+ * one-time task whose `at` passed while the daemon was down.
135
+ */
136
+ export const DEFAULT_OVERDUE_GRACE_MS = 60 * 60 * 1000
137
+
138
+ /**
139
+ * Simultaneous scheduled runs. Default 1: each run drives a whole agent session
140
+ * (real cost, real tokens), and a registry where twenty tasks share one cron slot
141
+ * must not become twenty concurrent providers. Due tasks beyond the cap are shed
142
+ * for this tick and picked up on a later one — the thundering-herd guard.
143
+ */
144
+ export const DEFAULT_MAX_CONCURRENT_RUNS = 1
145
+
146
+ /**
147
+ * The permission mode an unattended run is pinned to. Chroxy's mode ids are
148
+ * `approve` | `acceptEdits` | `auto` | `plan` (handler-utils.js
149
+ * ALLOWED_PERMISSION_MODE_IDS); `approve` is the safest — every consequential
150
+ * tool call gates on a human decision.
151
+ */
152
+ export const SCHEDULED_PERMISSION_MODE = 'approve'
153
+
154
+ /**
155
+ * The only modes a task definition may select for an unattended run. `plan` is
156
+ * permitted because it is strictly MORE restrictive than `approve` (the model
157
+ * plans instead of acting), which is a legitimate thing to schedule.
158
+ *
159
+ * Everything else is clamped down. `auto` is Chroxy's bypass (it maps to the SDK's
160
+ * bypassPermissions and auto-approves every non-floored tool) and `acceptEdits`
161
+ * auto-approves Read/Write/Edit/NotebookEdit without asking — both would let a
162
+ * stored task grant itself approvals no human ever gave, which is exactly the
163
+ * escalation this engine exists to prevent. Clamping (rather than refusing to run)
164
+ * keeps the floor a FLOOR: the task still runs, just never above the ceiling.
165
+ *
166
+ * DO NOT relax the `acceptEdits` clamp. It is load-bearing, not merely strict:
167
+ * `acceptEdits` auto-approves file reads, so an unattended run under it would read
168
+ * every non-floored file with nothing gating it. Both pipelines now apply the
169
+ * protected-path / secret-read floor — the in-process providers via
170
+ * permission-manager's `isFlooredTarget`, and the hook path via the
171
+ * `POST /permission-floor` probe the shell hook consults before its short-circuit
172
+ * (#7004, previously a hook-path gap) — so `.env` / `id_rsa` specifically would
173
+ * prompt rather than be read silently. That does NOT make the clamp redundant: the
174
+ * floor covers protected/secret TARGETS only, and an unattended run has no human to
175
+ * answer the prompt it forces (it auto-denies after 300s), so `acceptEdits` would
176
+ * still hand a stored task blanket approval over every ordinary file.
177
+ */
178
+ const SCHEDULED_ALLOWED_PERMISSION_MODES = new Set([SCHEDULED_PERMISSION_MODE, 'plan'])
179
+
180
+ /**
181
+ * The `lastRun.status` recorded when the engine REFUSED to start a run at all:
182
+ * an unsupported (hook-routed) provider, a disallowed cwd, or a permission mode
183
+ * it could not verify. Deliberately its OWN status rather than `error` (which
184
+ * means "the run happened and went wrong") or `skipped` (which means "the slot
185
+ * passed"), so #6868/#6871 can tell an operator that nothing ran AND why — a
186
+ * refused task is a misconfiguration to fix, not a transient failure to retry.
187
+ *
188
+ * NOTHING coerces to `success`: a refused run never touched a provider.
189
+ */
190
+ export const REFUSED_STATUS = 'refused'
191
+
192
+ /**
193
+ * The `lastRun.status` recorded when a run was DELIBERATELY STOPPED (#7038):
194
+ * someone pressed Stop on the scheduled session, or an orchestration cancel
195
+ * interrupted the turn. TurnDriver surfaces that as `TURN_STOPPED` (#7009), and
196
+ * until now this engine dropped it into the same `error` bucket as a provider
197
+ * crash — same status, differing only by a free-text message nothing keys on —
198
+ * so the registry could not distinguish "I stopped this" from "this blew up".
199
+ *
200
+ * Named `interrupted` rather than `stopped` for two reasons. It is the word the
201
+ * rest of the codebase already uses for this exact event — orchestration's
202
+ * subtask state (`run-model.js` `TERMINAL_NODE_STATUSES`) and the turn-driver's
203
+ * own message ('turn interrupted before completing') — so one concept keeps one
204
+ * name across the daemon. And `STOPPED` sitting next to `PAUSED` in a health
205
+ * chip reads as a statement about the SCHEDULE ("this task is stopped") rather
206
+ * than about the run, which is precisely the kind of honest-status ambiguity
207
+ * this vocabulary exists to avoid.
208
+ *
209
+ * NOT `success` (the work did not complete) and NOT `error` (nothing is broken;
210
+ * a human or a cancel did this on purpose). A permission-BLOCKED run that the
211
+ * engine denied and then interrupted stays `error` — see `_runViaSessionManager`,
212
+ * where the `runState.blocked` check deliberately precedes this one.
213
+ */
214
+ export const INTERRUPTED_STATUS = 'interrupted'
215
+
216
+ /** Statuses `_fire` passes through verbatim; everything else becomes `error`. */
217
+ const PASSTHROUGH_STATUSES = new Set(['success', 'timeout', 'skipped', REFUSED_STATUS, INTERRUPTED_STATUS])
218
+
219
+ /**
220
+ * Thrown internally when a run must be refused after the executor was entered
221
+ * (currently: the per-fire permission-mode re-assertion). Carries no data beyond
222
+ * its message — the caller turns it into a `refused` outcome.
223
+ */
224
+ class ScheduledRunRefusedError extends Error {
225
+ constructor(message) {
226
+ super(message)
227
+ this.name = 'ScheduledRunRefusedError'
228
+ }
229
+ }
230
+
231
+ /**
232
+ * The provider ids a scheduled task MAY currently target: every registered,
233
+ * non-hidden provider that answers permissions in-process. Derived from the
234
+ * registry rather than hardcoded, so it follows both new providers and the
235
+ * runtime driver swap (`codex` resolves to the app-server driver unless
236
+ * CHROXY_CODEX_APPSERVER=0 downgrades it to the unsupported exec driver) instead
237
+ * of going stale in a doc string.
238
+ *
239
+ * @param {() => Array<{name: string, capabilities?: object}>} [list=listProviders] - registry seam
240
+ * @returns {string[]} sorted provider ids
241
+ */
242
+ export function listSchedulableProviders(list = listProviders) {
243
+ try {
244
+ return list()
245
+ .filter((p) => p?.capabilities?.inProcessPermissions === true)
246
+ .map((p) => p.name)
247
+ .sort()
248
+ } catch {
249
+ return []
250
+ }
251
+ }
252
+
253
+ /**
254
+ * Why an unattended run may NOT be fired at this provider, or null when it may.
255
+ *
256
+ * The engine's whole permission story (deny-the-prompt, fail visibly) depends on
257
+ * observing `session_event: permission_request` and answering via
258
+ * `session.respondToPermission`. Both exist only where
259
+ * `capabilities.inProcessPermissions === true`. A hook-routed provider instead
260
+ * shells out to hooks/permission-hook.sh → POST /permission → ws-permissions.js,
261
+ * which emits nothing observable and auto-denies after 300s — so an unattended
262
+ * run there would stall five minutes per gated tool call and then look
263
+ * successful. Refusing is the honest outcome; #7003 tracks giving hook-routed
264
+ * providers a programmatic answering surface so support can widen.
265
+ *
266
+ * @param {string} providerName - the provider the run would actually use
267
+ * @param {(name: string) => Function} [getProviderClass=getProvider] - registry seam
268
+ * @returns {string|null} refusal reason, or null when the provider is supported
269
+ */
270
+ export function scheduledProviderRefusalReason(providerName, getProviderClass = getProvider) {
271
+ if (typeof providerName !== 'string' || providerName.length === 0) {
272
+ return 'no provider could be resolved for this scheduled task — refusing to fire an unattended run at an unknown provider'
273
+ }
274
+ let ProviderClass = null
275
+ try {
276
+ ProviderClass = getProviderClass(providerName)
277
+ } catch (err) {
278
+ return `unknown provider '${providerName}': ${err?.message || err}`
279
+ }
280
+ if (ProviderClass?.capabilities?.inProcessPermissions === true) return null
281
+ // Kept under the 500-char cap _recordRefusal applies, so the #7003 pointer and
282
+ // the supported-provider list survive into the registry rather than being cut.
283
+ const supported = listSchedulableProviders()
284
+ const isDefault = providerName === DEFAULT_PROVIDER
285
+ return `provider '${providerName}' routes permission prompts through the permission hook (POST /permission), which the scheduler cannot answer — an unattended run would stall on every gated tool call until the 300s auto-deny, then report a turn whose tool calls were all silently refused.${isDefault ? ` It is also the daemon DEFAULT, so a task with no target.provider lands here.` : ''} Set target.provider to one of: ${supported.length ? supported.join(', ') : '(none)'}. Hook-routed support: #7003.`
286
+ }
287
+
288
+ /** setTimeout that never keeps the event loop alive (self-exit safety, #6933). */
289
+ function unrefTimer(fn, ms) {
290
+ const t = setTimeout(fn, ms)
291
+ if (typeof t.unref === 'function') t.unref()
292
+ return t
293
+ }
294
+
295
+ /**
296
+ * Clamp a task's requested permission mode down to what an unattended run may
297
+ * use. Returns the floor for anything absent, unrecognized, or more permissive
298
+ * than the floor. Never throws — a stored task must not be able to break the
299
+ * engine, only to be de-escalated.
300
+ *
301
+ * @param {string} [requested] - task.target.permissionMode
302
+ * @returns {string} a permission mode id safe for an unattended run
303
+ */
304
+ export function resolveScheduledPermissionMode(requested) {
305
+ if (typeof requested === 'string' && SCHEDULED_ALLOWED_PERMISSION_MODES.has(requested)) return requested
306
+ return SCHEDULED_PERMISSION_MODE
307
+ }
308
+
309
+ /**
310
+ * Fires due scheduled tasks into headless sessions and records each outcome back
311
+ * into the registry.
312
+ *
313
+ * Emits (server-internal only — this slice adds NO wire message; #6871 can layer
314
+ * one on top of these events):
315
+ * - 'run-start' { taskId, at, sessionId? }
316
+ * - 'run-end' { taskId, at, status, sessionId?, error? }
317
+ * - 'run-skip' { taskId, at, reason }
318
+ * - 'task-quarantined' { taskId, at, reason }
319
+ *
320
+ * A REFUSED task (unsupported provider / disallowed cwd) emits `run-end` with
321
+ * status `refused` and NO `run-start`: nothing was started, so nothing started.
322
+ */
323
+ export class SchedulerEngine extends EventEmitter {
324
+ /**
325
+ * @param {object} options
326
+ * @param {object} [options.sessionManager] - source of the registry (`.scheduledTaskStore`) and of sessions
327
+ * @param {import('./scheduled-task-store.js').ScheduledTaskStore} [options.store] - registry override (defaults to sessionManager.scheduledTaskStore)
328
+ * @param {object} [options.config] - loaded daemon config (read for the enable gate)
329
+ * @param {Function} [options.runTask] - injectable executor `(task, ctx) => Promise<{status, sessionId?, error?}>`;
330
+ * defaults to the SessionManager+TurnDriver headless runner. This seam keeps
331
+ * tests hermetic — no provider is ever spawned under test (#6933).
332
+ * @param {() => number} [options.now=Date.now] - clock seam
333
+ * @param {(cwd: string) => (string|null)} [options.validateCwd] - cwd allowlist seam;
334
+ * defaults to the SAME `validateCwdAllowed` the WS handlers use, wired the way
335
+ * orchestration/build-manager.js:38 wires it. Returns an error STRING (falsy = allowed).
336
+ * @param {(name: string) => Function} [options.getProviderClass=getProvider] - provider-registry seam
337
+ * @param {Function} [options.setTimer] - injectable setTimeout (unref'd by default)
338
+ * @param {Function} [options.clearTimer=clearTimeout] - injectable clearTimeout
339
+ * @param {number} [options.maxConcurrentRuns]
340
+ * @param {number} [options.runTimeoutMs]
341
+ * @param {number} [options.overdueGraceMs]
342
+ * @param {number} [options.maxSleepMs]
343
+ * @param {object} [options.logger]
344
+ */
345
+ constructor({
346
+ sessionManager = null,
347
+ store = null,
348
+ config = null,
349
+ runTask = null,
350
+ now = Date.now,
351
+ validateCwd = null,
352
+ getProviderClass = getProvider,
353
+ setTimer = unrefTimer,
354
+ clearTimer = clearTimeout,
355
+ maxConcurrentRuns = DEFAULT_MAX_CONCURRENT_RUNS,
356
+ runTimeoutMs = DEFAULT_RUN_TIMEOUT_MS,
357
+ overdueGraceMs = DEFAULT_OVERDUE_GRACE_MS,
358
+ maxSleepMs = MAX_SLEEP_MS,
359
+ logger = log,
360
+ } = {}) {
361
+ super()
362
+ const resolvedStore = store || sessionManager?.scheduledTaskStore || null
363
+ if (!resolvedStore) throw new Error('SchedulerEngine requires a store (or a sessionManager owning one)')
364
+ this._store = resolvedStore
365
+ this._sm = sessionManager
366
+ this._config = config
367
+ this._injectedRunTask = typeof runTask === 'function' ? runTask : null
368
+ this._now = now
369
+ // The cwd allowlist. Default wires the SAME exported validateCwdAllowed the WS
370
+ // handlers call, against this daemon's config (workspaceRoots etc.) — mirroring
371
+ // orchestration/build-manager.js:38. Not reimplemented, not approximated.
372
+ this._validateCwd = typeof validateCwd === 'function'
373
+ ? validateCwd
374
+ : (cwd) => validateCwdAllowed(cwd, this._config)
375
+ this._getProviderClass = typeof getProviderClass === 'function' ? getProviderClass : getProvider
376
+ this._setTimer = setTimer
377
+ this._clearTimer = clearTimer
378
+ this._maxConcurrentRuns = Math.max(1, Math.floor(maxConcurrentRuns) || 1)
379
+ this._runTimeoutMs = runTimeoutMs
380
+ this._overdueGraceMs = overdueGraceMs
381
+ this._maxSleepMs = Math.max(1, Math.floor(maxSleepMs) || MAX_SLEEP_MS)
382
+ this._log = logger
383
+
384
+ this._timer = null
385
+ this._started = false
386
+ this._destroyed = false
387
+ /** @type {Set<string>} task ids with a run in flight — the overlap guard. */
388
+ this._running = new Set()
389
+ /** @type {Map<string,string>} taskId -> sessionId, so a recurring task RESUMES its session. */
390
+ this._sessionByTask = new Map()
391
+ /**
392
+ * @type {Set<string>} task ids whose outcome could not be persisted. Recording
393
+ * the run is what advances nextRun, so a task we cannot record would stay
394
+ * permanently due and be re-fired on every tick. Quarantining it (for this
395
+ * process only — a restart re-reads the file) turns a storage fault into one
396
+ * logged error instead of a hot loop of unattended agent sessions.
397
+ */
398
+ this._quarantined = new Set()
399
+ /** @type {Map<string,{taskId:string,blocked:null|{toolName:string}}>} sessionId -> live run, for the permission answerer. */
400
+ this._ownedRuns = new Map()
401
+
402
+ // Lazily built on first real run so a disabled daemon (and every unit test
403
+ // using the runTask seam) never constructs a TurnDriver or attaches its
404
+ // SessionManager listeners.
405
+ this._turnDriver = null
406
+ this._permissionListener = null
407
+ }
408
+
409
+ /** Whether the enable gate is open for this daemon. */
410
+ get enabled() {
411
+ return isSchedulerEnabled(this._config)
412
+ }
413
+
414
+ /** Task ids currently mid-run (test/observability aid). */
415
+ get runningTaskIds() {
416
+ return new Set(this._running)
417
+ }
418
+
419
+ /**
420
+ * Task ids this process has quarantined (their outcome could not be persisted,
421
+ * so they have STOPPED firing until the daemon restarts). Part of the engine's
422
+ * gate state that #6868/#6871 read: a quarantined task's registry entry may
423
+ * still show an old healthy-looking lastRun, so this is the authoritative
424
+ * "why has this task gone quiet?" signal alongside the `task-quarantined` event.
425
+ */
426
+ get quarantinedTaskIds() {
427
+ return new Set(this._quarantined)
428
+ }
429
+
430
+ /** Whether a timer is currently armed (test/observability aid). */
431
+ get armed() {
432
+ return this._timer !== null
433
+ }
434
+
435
+ /**
436
+ * Arm the engine. A NO-OP when the enable gate is closed: no timer is armed, so
437
+ * a daemon with the feature off behaves exactly as it did before this slice
438
+ * existed. Idempotent.
439
+ * @returns {boolean} whether the engine actually started
440
+ */
441
+ start() {
442
+ if (this._destroyed || this._started) return this._started
443
+ if (!this.enabled) {
444
+ this._log.info('Scheduled execution is disabled (features.scheduler / CHROXY_ENABLE_SCHEDULER=1) — no scheduled tasks will fire')
445
+ return false
446
+ }
447
+ this._started = true
448
+ this._log.info('Scheduled execution ENABLED — arming headless scheduler')
449
+ this._armNextTick()
450
+ return true
451
+ }
452
+
453
+ /**
454
+ * Re-evaluate the schedule now (e.g. after the CLI/dashboard mutated the
455
+ * registry). Cheap and safe to call often; a no-op when not started.
456
+ */
457
+ refresh() {
458
+ if (!this._started || this._destroyed) return
459
+ this._armNextTick()
460
+ }
461
+
462
+ /**
463
+ * Clear every timer, detach listeners, and stop firing. Idempotent — the
464
+ * daemon's shutdown path may call it more than once. In-flight runs are left to
465
+ * settle (their recording is guarded on `_destroyed`), so shutdown never blocks
466
+ * on a provider.
467
+ */
468
+ destroy() {
469
+ this._destroyed = true
470
+ this._started = false
471
+ this._clearArmedTimer()
472
+ this._detachPermissionListener()
473
+ if (this._turnDriver) {
474
+ try { this._turnDriver.dispose() } catch (err) {
475
+ this._log.warn(`Scheduler turn-driver dispose failed: ${err?.message || err}`)
476
+ }
477
+ this._turnDriver = null
478
+ }
479
+ this._running.clear()
480
+ this._ownedRuns.clear()
481
+ this._sessionByTask.clear()
482
+ this._quarantined.clear()
483
+ this.removeAllListeners()
484
+ }
485
+
486
+ /** @private */
487
+ _clearArmedTimer() {
488
+ if (this._timer !== null) {
489
+ this._clearTimer(this._timer)
490
+ this._timer = null
491
+ }
492
+ }
493
+
494
+ /**
495
+ * @private — arm ONE timer for the earliest interesting moment, clamped to
496
+ * [0, maxSleepMs]. Replaces any previously armed timer, so repeated calls can
497
+ * never stack timers up.
498
+ */
499
+ _armNextTick() {
500
+ if (this._destroyed || !this._started) return
501
+ this._clearArmedTimer()
502
+ const now = this._now()
503
+ let earliest = null
504
+ // At capacity nothing new can start, and a shed task stays due — computing a
505
+ // 0ms delay off it would spin the CPU until the in-flight run finished. Sleep
506
+ // the full cadence instead; _fire() re-arms the moment a slot frees.
507
+ if (this._running.size < this._maxConcurrentRuns) {
508
+ for (const task of this._store.list()) {
509
+ if (!task.enabled || !Number.isFinite(task.nextRun)) continue
510
+ if (this._running.has(task.id) || this._quarantined.has(task.id)) continue
511
+ if (earliest === null || task.nextRun < earliest) earliest = task.nextRun
512
+ }
513
+ }
514
+ // Even with nothing scheduled we re-check on the max-sleep cadence, so a task
515
+ // added by another surface is noticed without an explicit refresh() call.
516
+ const delay = earliest === null
517
+ ? this._maxSleepMs
518
+ : Math.min(this._maxSleepMs, Math.max(0, earliest - now))
519
+ this._timer = this._setTimer(() => this._tick(), delay)
520
+ }
521
+
522
+ /**
523
+ * @private — one evaluation pass: fire everything due (under the concurrency
524
+ * cap), then re-arm. Never throws; a per-task failure is recorded and the pass
525
+ * continues.
526
+ */
527
+ _tick() {
528
+ if (this._destroyed || !this._started) return
529
+ this._timer = null
530
+ const now = this._now()
531
+ try {
532
+ for (const task of this._dueTasks(now)) {
533
+ if (this._isTooOverdue(task, now)) {
534
+ // Persist a `skipped` result so the schedule ADVANCES (and a one-time
535
+ // task retires) instead of re-evaluating as overdue forever.
536
+ this._recordSkip(task, now, `overdue by ${now - task.nextRun}ms (grace ${this._overdueGraceMs}ms)`, { persist: true })
537
+ continue
538
+ }
539
+ if (this._running.size >= this._maxConcurrentRuns) {
540
+ // Thundering-herd guard: shed the rest of this burst WITHOUT persisting.
541
+ // The task is still genuinely due and fires on a later tick.
542
+ this._recordSkip(task, now, `concurrency cap reached (${this._maxConcurrentRuns})`)
543
+ continue
544
+ }
545
+ // Fire-and-forget: _fire() owns its error handling and records its own
546
+ // outcome, so an in-flight run never blocks the evaluation pass. The
547
+ // trailing catch is the backstop for anything _fire's own try/catch cannot
548
+ // cover (chiefly a listener throwing inside emit) — an unhandled rejection
549
+ // here would take the daemon down.
550
+ void this._fire(task, now).catch((err) => {
551
+ this._running.delete(task.id)
552
+ this._log.error(`Scheduled task ${task.id} fire failed unexpectedly: ${err?.stack || err}`)
553
+ })
554
+ }
555
+ } catch (err) {
556
+ this._log.error(`Scheduler tick failed: ${err?.stack || err}`)
557
+ }
558
+ this._armNextTick()
559
+ }
560
+
561
+ /** @private — enabled tasks whose nextRun has arrived, oldest-due first. */
562
+ _dueTasks(now) {
563
+ return this._store
564
+ .list()
565
+ .filter((t) => t.enabled && Number.isFinite(t.nextRun) && t.nextRun <= now
566
+ && !this._running.has(t.id) && !this._quarantined.has(t.id))
567
+ .sort((a, b) => a.nextRun - b.nextRun)
568
+ }
569
+
570
+ /** @private — whether a due task's slot is staler than the grace window. */
571
+ _isTooOverdue(task, now) {
572
+ if (!Number.isFinite(this._overdueGraceMs) || this._overdueGraceMs < 0) return false
573
+ return now - task.nextRun > this._overdueGraceMs
574
+ }
575
+
576
+ /** @private — record a non-run (shed / too-overdue). */
577
+ _recordSkip(task, at, reason, { persist = false } = {}) {
578
+ this._log.warn(`Scheduled task ${task.id} not fired: ${reason}`)
579
+ if (persist) this._recordRun(task, { at, status: 'skipped', error: reason })
580
+ this.emit('run-skip', { taskId: task.id, at, reason })
581
+ }
582
+
583
+ /**
584
+ * @private — execute one task end-to-end: mark it in-flight (overlap guard),
585
+ * run it, then record the outcome and re-arm. Never rejects.
586
+ */
587
+ async _fire(task, at) {
588
+ const ctx = {
589
+ at,
590
+ permissionMode: resolveScheduledPermissionMode(task.target?.permissionMode),
591
+ runTimeoutMs: this._runTimeoutMs,
592
+ }
593
+
594
+ // ── PREFLIGHT: refuse before firing ──────────────────────────────────────
595
+ // Runs BEFORE the overlap guard, BEFORE `run-start`, and BEFORE any session
596
+ // exists — a refused task never spawns a session and is never reported as a
597
+ // run that started. Placed here (the single chokepoint every run passes
598
+ // through) rather than inside the default executor so a future second
599
+ // executor cannot bypass it: a check that lives on only one path is exactly
600
+ // the class of bug this fixes (validateCwdAllowed was handler-only).
601
+ const refusal = this._preflightRefusal(task)
602
+ if (refusal) {
603
+ this._recordRefusal(task, at, refusal)
604
+ return
605
+ }
606
+
607
+ this._running.add(task.id)
608
+ this.emit('run-start', { taskId: task.id, at })
609
+ this._log.info(`Firing scheduled task ${task.id}${task.name ? ` (${task.name})` : ''}`)
610
+
611
+ let outcome
612
+ try {
613
+ const exec = this._injectedRunTask || ((t, c) => this._runViaSessionManager(t, c))
614
+ outcome = await exec(task, ctx)
615
+ } catch (err) {
616
+ outcome = { status: 'error', error: err?.message || String(err) }
617
+ } finally {
618
+ this._running.delete(task.id)
619
+ }
620
+
621
+ const status = outcome?.status
622
+ const result = {
623
+ at,
624
+ status: PASSTHROUGH_STATUSES.has(status) ? status : 'error',
625
+ ...(outcome?.sessionId ? { sessionId: outcome.sessionId } : {}),
626
+ ...(outcome?.error ? { error: String(outcome.error).slice(0, 500) } : {}),
627
+ }
628
+ this._recordRun(task, result)
629
+ this.emit('run-end', { taskId: task.id, ...result })
630
+ if (result.status === 'success') {
631
+ this._log.info(`Scheduled task ${task.id} completed`)
632
+ } else {
633
+ this._log.warn(`Scheduled task ${task.id} finished status=${result.status}${result.error ? `: ${result.error}` : ''}`)
634
+ }
635
+ // A finished run frees a concurrency slot and changed nextRun — re-evaluate.
636
+ this._armNextTick()
637
+ }
638
+
639
+ /**
640
+ * @private — the pre-fire safety gate: everything that must hold BEFORE an
641
+ * unattended turn is allowed to exist. Returns a refusal reason, or null to
642
+ * proceed. Both checks are things the engine cannot recover from by retrying —
643
+ * they are misconfigurations in the stored task definition.
644
+ */
645
+ _preflightRefusal(task) {
646
+ // (a) Can we actually govern this provider's permission prompts? (#7003)
647
+ const providerRefusal = scheduledProviderRefusalReason(this._resolveProviderName(task), this._getProviderClass)
648
+ if (providerRefusal) return providerRefusal
649
+
650
+ // (b) Is the cwd one a session may be created in at all? The registry is a
651
+ // user-writable JSON file, so `target.cwd` is untrusted input — and neither
652
+ // the store (trims the string) nor createSession (statSync only) applies the
653
+ // real allowlist. Validate the EFFECTIVE cwd: the task's own, else whatever
654
+ // createSession would default to. (#7005 moves this into createSession.)
655
+ const cwd = this._resolveTaskCwd(task)
656
+ if (cwd) {
657
+ let cwdError
658
+ try {
659
+ cwdError = this._validateCwd(cwd)
660
+ } catch (err) {
661
+ // A throwing validator must fail CLOSED, never fall through to allowed.
662
+ return `working directory ${cwd} could not be validated for a scheduled run: ${err?.message || err}`
663
+ }
664
+ if (cwdError) {
665
+ return `working directory ${cwd} is not allowed for a scheduled run: ${cwdError}`
666
+ }
667
+ }
668
+ return null
669
+ }
670
+
671
+ /**
672
+ * @private — the provider a run would ACTUALLY use, resolved the same way
673
+ * SessionManager.createSession resolves it (`provider || this._providerType`),
674
+ * so the capability gate judges the real provider rather than the stored field.
675
+ * Falls back to DEFAULT_PROVIDER when no manager is wired.
676
+ */
677
+ _resolveProviderName(task) {
678
+ const explicit = task.target?.provider
679
+ if (typeof explicit === 'string' && explicit.length > 0) return explicit
680
+ const managerDefault = this._sm?.providerType
681
+ if (typeof managerDefault === 'string' && managerDefault.length > 0) return managerDefault
682
+ return DEFAULT_PROVIDER
683
+ }
684
+
685
+ /**
686
+ * @private — the cwd a run would ACTUALLY use: the task's own, else the
687
+ * manager's default (what createSession falls back to). Null when neither is
688
+ * knowable, in which case there is no manager and the run fails anyway.
689
+ */
690
+ _resolveTaskCwd(task) {
691
+ const explicit = task.target?.cwd
692
+ if (typeof explicit === 'string' && explicit.length > 0) return explicit
693
+ const managerDefault = this._sm?.defaultCwd
694
+ if (typeof managerDefault === 'string' && managerDefault.length > 0) return managerDefault
695
+ return null
696
+ }
697
+
698
+ /**
699
+ * @private — record a run the engine refused to start. A VISIBLE, explicit
700
+ * non-success outcome: never `success`, and distinguishable from both `error`
701
+ * (the run happened and failed) and `skipped` (the slot passed) by its own
702
+ * status, so #6868/#6871 can tell the operator nothing ran and why.
703
+ */
704
+ _recordRefusal(task, at, reason) {
705
+ this._log.error(`Scheduled task ${task.id} REFUSED — nothing was run: ${reason}`)
706
+ const result = { at, status: REFUSED_STATUS, error: String(reason).slice(0, 500) }
707
+ this._recordRun(task, result)
708
+ this.emit('run-end', { taskId: task.id, ...result })
709
+ }
710
+
711
+ /**
712
+ * @private — persist a lastRun result. The store recomputes nextRun off the
713
+ * cadence on update(), which is what retires a one-time task (computeNextRun
714
+ * returns null for a `once` cadence that has a lastRun) and advances a recurring
715
+ * one to its next slot with no backfill of missed slots.
716
+ */
717
+ _recordRun(task, result) {
718
+ try {
719
+ this._store.update(task.id, { lastRun: result })
720
+ } catch (err) {
721
+ // A rejected result value or a storage fault must not take the engine down.
722
+ // It must ALSO not be retried forever: without a recorded run its nextRun
723
+ // never advances, so quarantine it for this process rather than re-firing it
724
+ // every tick.
725
+ this._quarantine(task, result?.at ?? this._now(), `its run outcome could not be recorded: ${err?.message || err}`)
726
+ }
727
+ }
728
+
729
+ /**
730
+ * @private — stop firing a task for the rest of this process, and make that
731
+ * VISIBLE. Quarantine used to be a log line only, so a task that had
732
+ * permanently stopped firing still showed its last healthy `lastRun` to every
733
+ * registry-reading surface — indistinguishable from a task that is fine. Now
734
+ * the engine (a) best-effort writes the quarantine onto the task itself, (b)
735
+ * emits `task-quarantined`, and (c) exposes it on `quarantinedTaskIds`. The
736
+ * write is best-effort ON PURPOSE: the usual reason to quarantine is that the
737
+ * store itself is failing, so (b) and (c) are the fallbacks that always work.
738
+ *
739
+ * Quarantine stays process-scoped (a restart re-reads the file), so the task is
740
+ * NOT disabled in the registry.
741
+ */
742
+ _quarantine(task, at, reason) {
743
+ const firstTime = !this._quarantined.has(task.id)
744
+ this._quarantined.add(task.id)
745
+ this._log.error(`Scheduled task ${task.id} QUARANTINED until daemon restart — it will not fire again: ${reason}`)
746
+ try {
747
+ this._store.update(task.id, {
748
+ lastRun: { at, status: REFUSED_STATUS, error: `quarantined until daemon restart: ${reason}`.slice(0, 500) },
749
+ })
750
+ } catch { /* the store is usually the thing that's broken — the event + getter carry the signal */ }
751
+ if (firstTime) this.emit('task-quarantined', { taskId: task.id, at, reason })
752
+ }
753
+
754
+ // ── the default (production) executor ──────────────────────────────────────
755
+
756
+ /**
757
+ * @private — the real headless run: create (or RESUME) this task's session and
758
+ * drive the task prompt through it with no client connected.
759
+ *
760
+ * Session reuse is deliberate (the issue's "spins up (or resumes) a session"):
761
+ * one session per task id, reused while it is still alive. That bounds a daily
762
+ * task to ONE session instead of one per fire, keeps the recorded `sessionId`
763
+ * meaningful (the operator can open it and read what the run actually did), and
764
+ * gives a recurring task continuity across runs. Sessions are NOT auto-destroyed
765
+ * afterwards — they are ordinary sessions the operator can inspect and close
766
+ * (never reaping them is tracked in #7006).
767
+ *
768
+ * Because they are ordinary sessions, the operator can also change their
769
+ * permission mode. That makes reuse an escalation vector, so the clamped mode is
770
+ * re-asserted and verified on EVERY fire — see _assertPermissionMode. The
771
+ * interactive mode switch is deliberately left working (an operator inspecting a
772
+ * scheduled session may legitimately want to drive it by hand); what is
773
+ * guaranteed is that their change cannot survive into the next unattended fire.
774
+ */
775
+ async _runViaSessionManager(task, ctx) {
776
+ if (!this._sm) return { status: 'error', error: 'no sessionManager wired — cannot run scheduled task' }
777
+
778
+ let sessionId
779
+ try {
780
+ sessionId = this._resolveSession(task, ctx)
781
+ } catch (err) {
782
+ if (err instanceof ScheduledRunRefusedError) return { status: REFUSED_STATUS, error: err.message }
783
+ return { status: 'error', error: `session create failed: ${err?.message || err}` }
784
+ }
785
+ if (!sessionId) return { status: 'error', error: 'session create failed (no sessionId)' }
786
+
787
+ // Register as an OWNED run before the turn starts, so the permission answerer
788
+ // is armed for the very first tool call.
789
+ const runState = { taskId: task.id, blocked: null }
790
+ this._ownedRuns.set(sessionId, runState)
791
+ this._attachPermissionListener()
792
+
793
+ try {
794
+ const driver = this._ensureTurnDriver()
795
+ await driver.driveTurn(sessionId, task.prompt, {
796
+ label: `scheduled:${task.id}`,
797
+ timeoutMs: ctx.runTimeoutMs,
798
+ })
799
+ // `success` is the NARROWEST outcome, asserted positively: the turn
800
+ // completed AND no permission prompt was ever raised on this run. Any
801
+ // permission activity at all sets `runState.blocked` (set before any other
802
+ // decision in _handleSessionEvent, so a malformed prompt we could not even
803
+ // answer still counts), because a denied permission usually lets the agent
804
+ // finish "successfully" with the tool call refused — which is NOT a
805
+ // successful scheduled run. Reporting success for a run whose every tool
806
+ // call was refused is the worst failure mode this engine has, so the
807
+ // default here is to disbelieve success.
808
+ if (runState.blocked) return this._blockedOutcome(runState, sessionId)
809
+ return { status: 'success', sessionId }
810
+ } catch (err) {
811
+ // ORDER IS LOAD-BEARING. `runState.blocked` is checked FIRST, ahead of the
812
+ // TURN_STOPPED arm below, because the engine's own deny path reaches this
813
+ // catch through exactly the same rejection: it answers `deny`, interrupts
814
+ // the turn, and TurnDriver rejects TURN_STOPPED (#7009). That run is a real
815
+ // failure — the agent asked for permission nobody could grant — and must
816
+ // keep the `error` status it has always had. Only an interrupt with NO
817
+ // permission activity is the benign operator Stop.
818
+ if (runState.blocked) return this._blockedOutcome(runState, sessionId)
819
+ if (err instanceof TurnError && err.code === 'TURN_TIMEOUT') {
820
+ return { status: 'timeout', sessionId, error: `run exceeded ${ctx.runTimeoutMs}ms` }
821
+ }
822
+ if (err instanceof TurnError && err.code === 'TURN_STOPPED') {
823
+ // #7038 — a deliberate Stop, not a fault. Its own status so an operator
824
+ // reading the registry (CLI / dashboard chip) can tell it apart from a
825
+ // provider crash instead of having to parse the error string.
826
+ return { status: INTERRUPTED_STATUS, sessionId, error: err?.message || 'turn interrupted before completing' }
827
+ }
828
+ return { status: 'error', sessionId, error: err?.message || String(err) }
829
+ } finally {
830
+ this._ownedRuns.delete(sessionId)
831
+ if (this._ownedRuns.size === 0) this._detachPermissionListener()
832
+ }
833
+ }
834
+
835
+ /** @private — the permission-blocked outcome (a visible failure, never silent). */
836
+ _blockedOutcome(runState, sessionId) {
837
+ return {
838
+ status: 'error',
839
+ sessionId,
840
+ error: `permission required for ${runState.blocked.toolName || 'a tool'} but no client is connected to approve it — scheduled run denied. Author an explicit permission rule if this task should be allowed to do this.`,
841
+ }
842
+ }
843
+
844
+ /**
845
+ * @private — reuse this task's still-live session, else create a fresh one.
846
+ * EITHER WAY the clamped permission mode is asserted before the caller drives a
847
+ * turn: createSession is passed it, and a reused session has it re-asserted and
848
+ * verified. A session that cannot be brought to the clamped mode is refused.
849
+ */
850
+ _resolveSession(task, ctx) {
851
+ const existing = this._sessionByTask.get(task.id)
852
+ if (existing) {
853
+ const entry = this._sm.getSession?.(existing)
854
+ if (entry?.session) {
855
+ // THE ESCALATION VECTOR (#6997 review C3): scheduled sessions are kept
856
+ // alive and reused, and an operator can flip any session to `auto` from
857
+ // the dashboard — even mid-turn. Without re-asserting here, one manual
858
+ // flip would silently put every future unattended fire of this task into
859
+ // bypass, forever, each recorded as a clean success.
860
+ this._assertPermissionMode(entry.session, ctx.permissionMode, existing)
861
+ return existing
862
+ }
863
+ // The session is gone (operator closed it) — drop the stale mapping so a
864
+ // fresh one is created below rather than resumed by id.
865
+ this._sessionByTask.delete(task.id)
866
+ }
867
+
868
+ const target = task.target || {}
869
+ const sessionId = this._sm.createSession({
870
+ name: task.name || `Scheduled: ${task.id.slice(0, 8)}`,
871
+ ...(target.cwd ? { cwd: target.cwd } : {}),
872
+ ...(target.provider ? { provider: target.provider } : {}),
873
+ ...(target.model ? { model: target.model } : {}),
874
+ // The clamped floor — never the task's raw value (see resolveScheduledPermissionMode).
875
+ permissionMode: ctx.permissionMode,
876
+ // EXPLICIT false so an unattended run can never inherit the server-wide
877
+ // `dangerouslySkipPermissions` default (session-manager.js:1473).
878
+ skipPermissions: false,
879
+ metadata: { scheduledTaskId: task.id },
880
+ })
881
+ // Trust nothing: verify the freshly-created session really came up at the
882
+ // clamped mode rather than assuming createSession honoured the option.
883
+ const created = this._sm.getSession?.(sessionId)
884
+ if (created?.session) this._assertPermissionMode(created.session, ctx.permissionMode, sessionId)
885
+ this._sessionByTask.set(task.id, sessionId)
886
+ return sessionId
887
+ }
888
+
889
+ /**
890
+ * @private — force `mode` onto a session and PROVE it took, or throw. The
891
+ * invariant this exists to hold: **a scheduled fire runs at the clamped mode,
892
+ * or it does not run.**
893
+ *
894
+ * Read-back is the only evidence accepted. `setPermissionMode` returns false
895
+ * both for a harmless no-op (already in that mode) and for a REFUSED change (a
896
+ * session mid-turn rejects every non-`auto` switch — base-session.js:1115-1133),
897
+ * so its return value cannot distinguish "fine" from "escalated and stuck".
898
+ * Only the value the session reports afterwards can.
899
+ *
900
+ * @throws {ScheduledRunRefusedError} when the mode cannot be verified
901
+ */
902
+ _assertPermissionMode(session, mode, sessionId) {
903
+ const read = () => (typeof session.permissionMode === 'string' ? session.permissionMode : null)
904
+ if (read() !== mode) {
905
+ try {
906
+ session.setPermissionMode?.(mode)
907
+ } catch (err) {
908
+ throw new ScheduledRunRefusedError(
909
+ `could not re-assert the '${mode}' permission mode on scheduled session ${sessionId}: ${err?.message || err} — refusing to fire an unattended run at an unverified permission mode`
910
+ )
911
+ }
912
+ }
913
+ const actual = read()
914
+ if (actual !== mode) {
915
+ throw new ScheduledRunRefusedError(
916
+ `scheduled session ${sessionId} reports permission mode '${actual ?? 'unknown'}' and could not be re-clamped to '${mode}' (the session is mid-turn, or its provider ignores the setter) — refusing to fire an unattended run at an unverified permission mode`
917
+ )
918
+ }
919
+ }
920
+
921
+ /** @private — build the TurnDriver on first real run. */
922
+ _ensureTurnDriver() {
923
+ if (!this._turnDriver) {
924
+ this._turnDriver = new TurnDriver({ sessionManager: this._sm, log: this._log })
925
+ }
926
+ return this._turnDriver
927
+ }
928
+
929
+ /**
930
+ * @private — arm the headless permission answerer. Scoped to sessions this
931
+ * engine owns (never a user's session), mirroring
932
+ * orchestration/permission-gate.js. Attached only while a run is in flight.
933
+ */
934
+ _attachPermissionListener() {
935
+ if (this._permissionListener || !this._sm?.on) return
936
+ this._permissionListener = (payload) => this._handleSessionEvent(payload)
937
+ this._sm.on('session_event', this._permissionListener)
938
+ }
939
+
940
+ /** @private */
941
+ _detachPermissionListener() {
942
+ if (!this._permissionListener) return
943
+ this._sm?.off?.('session_event', this._permissionListener)
944
+ this._permissionListener = null
945
+ }
946
+
947
+ /**
948
+ * @private — a permission prompt reached a scheduled run, which means no rule
949
+ * settled it and there is no human to answer. DENY it through the normal door,
950
+ * mark the run blocked, and interrupt the turn: the prompt is answered
951
+ * immediately (never left to sit out a permission timeout) and the run's outcome
952
+ * is decided immediately (a visible failure, never an auto-approval).
953
+ *
954
+ * The SLOT frees immediately too (#7009): SdkSession's interrupt path emits
955
+ * `stopped` rather than a result/error (sdk-session.js, #4881), and TurnDriver
956
+ * treats that as terminal → `driveTurn` rejects TURN_STOPPED right away instead
957
+ * of sitting out `runTimeoutMs`. The recorded outcome does not depend on which
958
+ * way the turn settled: `runState.blocked` is already set, so _runViaSessionManager
959
+ * reports the blocked failure whether the promise rejects or (on a provider that
960
+ * lets the turn finish with the tool call refused) resolves. Never `success`.
961
+ */
962
+ _handleSessionEvent({ sessionId, event, data } = {}) {
963
+ if (event !== 'permission_request') return
964
+ const runState = this._ownedRuns.get(sessionId)
965
+ if (!runState) return // never answer a session this engine does not own
966
+ const requestId = data?.requestId ?? data?.id ?? null
967
+ const toolName = data?.toolName ?? data?.tool ?? ''
968
+ // Mark the run blocked FIRST, before any other decision. A prompt was raised
969
+ // on an unattended run: that alone disqualifies the run from `success`,
970
+ // whether or not we manage to answer it. Bailing out on a malformed payload
971
+ // BEFORE this (the previous order) left `blocked` unset, so a prompt carrying
972
+ // no requestId went unanswered AND the run still reported success — the exact
973
+ // false-success this engine must never produce.
974
+ if (!runState.blocked) runState.blocked = { toolName }
975
+ this._log.warn(`Scheduled task ${runState.taskId} requested permission for ${toolName || 'a tool'} with no client connected — denying`)
976
+ if (requestId == null) {
977
+ this._log.warn(`Scheduled task ${runState.taskId} permission request carried no requestId — cannot answer it; the run is recorded as blocked`)
978
+ return
979
+ }
980
+
981
+ const entry = this._sm.getSession?.(sessionId)
982
+ const session = entry?.session
983
+ if (!session) return
984
+ if (typeof session.respondToPermission === 'function') {
985
+ try {
986
+ session.respondToPermission(requestId, 'deny')
987
+ } catch (err) {
988
+ this._log.warn(`Scheduler permission deny failed for ${sessionId}: ${err?.message || err}`)
989
+ }
990
+ }
991
+ // Abort the rest of the turn: the task cannot complete what it was asked to do,
992
+ // so there is no value in letting it continue spending tokens.
993
+ if (typeof session.interrupt === 'function') {
994
+ try {
995
+ const maybe = session.interrupt()
996
+ if (maybe && typeof maybe.catch === 'function') maybe.catch(() => {})
997
+ } catch { /* best effort */ }
998
+ }
999
+ }
1000
+ }
1001
+
1002
+ /**
1003
+ * Build the scheduler engine for the daemon, or return null when the enable gate
1004
+ * is closed. Mirrors buildOrchestrationManager (orchestration/build-manager.js):
1005
+ * server-cli.js gets one call and a nullable handle to dispose.
1006
+ *
1007
+ * @param {object} opts
1008
+ * @param {object} opts.sessionManager
1009
+ * @param {object} [opts.config]
1010
+ * @param {object} [opts.logger]
1011
+ * @returns {SchedulerEngine|null}
1012
+ */
1013
+ export function buildSchedulerEngine({ sessionManager, config = null, logger = log } = {}) {
1014
+ if (!isSchedulerEnabled(config)) return null
1015
+ if (!sessionManager?.scheduledTaskStore) {
1016
+ logger.warn('Scheduled execution enabled but no scheduled-task store is available — scheduler not started')
1017
+ return null
1018
+ }
1019
+ // Never throw out of here: a scheduler that fails to build must not break daemon
1020
+ // boot (same contract as buildOrchestrationManager).
1021
+ try {
1022
+ const engine = new SchedulerEngine({ sessionManager, config, logger })
1023
+ engine.start()
1024
+ return engine
1025
+ } catch (err) {
1026
+ logger.error(`Failed to start the scheduler engine — scheduled tasks will not fire: ${err?.stack || err}`)
1027
+ return null
1028
+ }
1029
+ }