@chroxy/server 0.10.0 → 0.11.10
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.
- package/CONFIG.md +602 -19
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +416 -11
- package/package.json +20 -23
- package/sidecar/Dockerfile +1 -1
- package/sidecar/PROTOCOL.md +9 -1
- package/sidecar/agent.js +102 -10
- package/sidecar/package-lock.json +3 -3
- package/src/acp-config.js +206 -0
- package/src/acp-session.js +954 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +293 -0
- package/src/agent-control/client.js +1616 -0
- package/src/agent-control/events.js +547 -0
- package/src/agent-control/local-connection.js +275 -0
- package/src/agent-control/mcp-server.js +545 -0
- package/src/anthropic-compatible-config.js +29 -4
- package/src/anthropic-compatible-session.js +15 -6
- package/src/anthropic-openai-shim.js +0 -1
- package/src/archive-continuation.js +164 -0
- package/src/assistant-response.js +24 -0
- package/src/auth-probes.js +120 -13
- package/src/background-shell-tracker.js +27 -0
- package/src/base-session.js +1353 -41
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +24 -1
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +101 -0
- package/src/bound-client-policy.js +279 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +74 -9
- package/src/built-in-tools/tool-transforms.js +1113 -13
- package/src/byok-compose-state.js +6 -9
- package/src/byok-credentials.js +2 -3
- package/src/byok-mcp-client.js +1153 -20
- package/src/byok-mcp-config.js +1712 -8
- package/src/byok-mcp-fleet.js +416 -29
- package/src/byok-mcp-oauth-store.js +329 -0
- package/src/byok-mcp-oauth.js +635 -0
- package/src/byok-mcp-trust.js +257 -40
- package/src/byok-session.js +1400 -149
- package/src/byok-tool-executor.js +2681 -38
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +96 -51
- package/src/chroxy-host-metadata.js +122 -0
- package/src/claude-channel-session.js +16 -10
- package/src/claude-model-catalog.js +131 -16
- package/src/claude-model-refresh.js +385 -0
- package/src/claude-model-request.js +103 -0
- package/src/claude-stream-parser.js +109 -3
- package/src/claude-tui/diagnostic-tail.js +83 -0
- package/src/claude-tui/form-driver.js +44 -7
- package/src/claude-tui/model-error.js +41 -0
- package/src/claude-tui/pty-driver.js +223 -60
- package/src/claude-tui/sanitize-question-payload.js +109 -0
- package/src/claude-tui/usage-limit.js +239 -0
- package/src/claude-tui-session.js +3611 -286
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +6 -6
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/deploy-cmd.js +46 -11
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/init-cmd.js +16 -17
- package/src/cli/providers-cmd.js +6 -6
- package/src/cli/schedule-cmd.js +804 -0
- package/src/cli/server-cmd.js +64 -2
- package/src/cli/service-cmd.js +70 -27
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +168 -14
- package/src/cli/tokens-cmd.js +212 -0
- package/src/cli/tunnel-cmd.js +256 -25
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1117 -116
- package/src/cli.js +8 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +2108 -101
- package/src/codex-bundled-client.js +66 -0
- package/src/codex-model-catalog.js +548 -0
- package/src/codex-model-rejections.js +87 -0
- package/src/codex-native-resume.js +104 -0
- package/src/codex-protocol-capabilities.js +188 -0
- package/src/codex-session.js +571 -45
- package/src/config-dir-migration.js +444 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +738 -52
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +5 -9
- package/src/connection-locality.js +60 -0
- package/src/container-liveness-monitor.js +189 -0
- package/src/continuation-metadata-worker.js +17 -0
- package/src/continuations.js +114 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +23 -30
- package/src/control-room/skills-inventory.js +8 -3
- package/src/control-room/survey.js +32 -0
- package/src/conversation-scanner.js +40 -18
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +24 -22
- package/src/credential-store.js +279 -29
- package/src/daemon-commit.js +92 -0
- package/src/daemon-idle-state.js +171 -0
- package/src/daemon-update-status.js +314 -0
- package/src/dashboard-build.js +70 -0
- package/src/declared-status.js +90 -0
- package/src/deepseek-credentials.js +2 -3
- package/src/dev-preview.js +169 -182
- package/src/device-preferences.js +2 -2
- package/src/diagnostics.js +3 -0
- package/src/diff-parser.js +87 -0
- package/src/discord-credentials.js +2 -3
- package/src/docker-byok-pool.js +3 -1
- package/src/docker-byok-session.js +678 -78
- package/src/docker-image-allowlist.js +23 -1
- package/src/docker-sdk-session.js +188 -4
- package/src/docker-session.js +293 -10
- package/src/doctor.js +783 -66
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +95 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +39 -10
- package/src/environments/backends/k8s.js +58 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +137 -14
- package/src/event-normalizer.js +363 -110
- package/src/external-session-registry.js +0 -0
- package/src/gemini-session.js +100 -7
- package/src/github-webhook.js +188 -4
- package/src/handler-utils.js +563 -62
- package/src/handlers/checkpoint-handlers.js +162 -20
- package/src/handlers/control-room-handlers.js +99 -29
- package/src/handlers/conversation-handlers.js +563 -25
- package/src/handlers/credential-handlers.js +43 -2
- package/src/handlers/daemon-update-handlers.js +81 -0
- package/src/handlers/evaluator-handlers.js +14 -1
- package/src/handlers/feature-handlers.js +186 -69
- package/src/handlers/file-handlers.js +101 -13
- package/src/handlers/github-webhook-handlers.js +204 -0
- package/src/handlers/input-handlers.js +689 -48
- package/src/handlers/orchestration-handlers.js +238 -0
- package/src/handlers/scheduler-handlers.js +584 -0
- package/src/handlers/session-handlers.js +546 -16
- package/src/handlers/session-pr-status-handlers.js +283 -0
- package/src/handlers/session-pr-threads-handlers.js +247 -0
- package/src/handlers/settings-handlers.js +822 -35
- package/src/handlers/skills-handlers.js +13 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/handlers/token-handlers.js +11 -2
- package/src/health-proof.js +40 -0
- package/src/history-page.js +104 -0
- package/src/http-routes.js +286 -8
- package/src/ide/search.js +24 -6
- package/src/ide/symbols.js +20 -6
- package/src/input-context.js +117 -0
- package/src/instruction-policy-compiler.js +229 -0
- package/src/instruction-policy.js +250 -0
- package/src/jsonl-reader.js +309 -48
- package/src/jsonl-subprocess-session.js +122 -9
- package/src/keychain.js +160 -13
- package/src/logger.js +240 -31
- package/src/mailbox-route.js +11 -22
- package/src/message-wire.js +386 -0
- package/src/model-discovery.js +43 -3
- package/src/models.js +1276 -174
- package/src/notification-prefs.js +100 -10
- package/src/notifications/discord-billing-sink.js +22 -5
- package/src/notifications/discord-ci-sink.js +243 -0
- package/src/notifications/discord-webhook-client.js +71 -0
- package/src/notifications/discord-webhook-sink.js +82 -12
- package/src/notifications/expo-push-sink.js +85 -6
- package/src/notifications/ready-body.js +16 -5
- package/src/ollama-session.js +34 -2
- package/src/orchestration/build-manager.js +63 -0
- package/src/orchestration/decision-contract.js +245 -0
- package/src/orchestration/git-ops.js +381 -0
- package/src/orchestration/orchestration-manager.js +1342 -0
- package/src/orchestration/permission-gate.js +121 -0
- package/src/orchestration/role-prompts.js +136 -0
- package/src/orchestration/run-budget.js +81 -0
- package/src/orchestration/run-ledger.js +487 -0
- package/src/orchestration/run-model.js +206 -0
- package/src/orchestration/run-record.js +336 -0
- package/src/orchestration/run-report.js +194 -0
- package/src/orchestration/to-wire.js +201 -0
- package/src/orchestration/turn-driver.js +422 -0
- package/src/orphan-reaper.js +413 -0
- package/src/outgoing-policy.js +183 -0
- package/src/pairing.js +236 -12
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-audit.js +79 -3
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1770 -0
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +1175 -94
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolver.js +174 -12
- package/src/permission-rule-store.js +411 -0
- package/src/permission-scope.js +43 -0
- package/src/platform.js +483 -23
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +228 -6
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +360 -8
- package/src/roster-broadcast.js +186 -0
- package/src/schedule-parser.js +311 -0
- package/src/scheduled-task-store.js +945 -0
- package/src/scheduler.js +1099 -0
- package/src/sdk-session.js +2374 -168
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +11 -2
- package/src/server-cli/server-orchestrator.js +50 -4
- package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +760 -62
- package/src/server-identity.js +42 -14
- package/src/service.js +682 -53
- package/src/session-archive-limits.js +15 -0
- package/src/session-archive.js +1029 -0
- package/src/session-busy-state.js +72 -0
- package/src/session-ci-watcher.js +926 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +3879 -308
- package/src/session-message-history.js +749 -37
- package/src/session-pr-status.js +654 -0
- package/src/session-pr-threads.js +271 -0
- package/src/session-preset-trust.js +3 -3
- package/src/session-preset.js +10 -5
- package/src/session-state-persistence.js +94 -17
- package/src/session-timeout-manager.js +20 -0
- package/src/session-title.js +168 -0
- package/src/session-token-store.js +70 -36
- package/src/session-wake.js +240 -0
- package/src/shell-approval-info.js +2 -2
- package/src/shell-approval-store.js +3 -1
- package/src/skills-loader.js +7 -4
- package/src/skills-manager.js +2 -2
- package/src/skills-trust.js +95 -13
- package/src/skills-usage.js +22 -5
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +596 -0
- package/src/subagent-counter.js +9 -1
- package/src/summarize-session.js +51 -4
- package/src/supervisor.js +99 -38
- package/src/sweep-stale-provider-dirs.js +95 -0
- package/src/thinking-level-wire.js +39 -0
- package/src/thinking-stream.js +179 -0
- package/src/token-manager.js +39 -9
- package/src/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +413 -31
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +145 -35
- package/src/tunnel/index.js +13 -1
- package/src/tunnel/preview.js +64 -0
- package/src/tunnel-check.js +1 -1
- package/src/turn-outcome.js +137 -0
- package/src/turn-tracker.js +0 -0
- package/src/usage-normalize.js +122 -0
- package/src/user-shell-session.js +157 -37
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +741 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +597 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +25 -0
- package/src/utils/bounded-regex.js +153 -0
- package/src/utils/claude-binary.js +43 -0
- package/src/utils/claude-config-dir.js +245 -0
- package/src/utils/claude-login-command.js +16 -0
- package/src/utils/claude-native-route.js +81 -0
- package/src/utils/componentwise-resolver.js +301 -0
- package/src/utils/composite-key.js +45 -0
- package/src/utils/deploy-control-files.js +87 -0
- package/src/utils/exec-failure-reason.js +21 -0
- package/src/utils/git-repo.js +42 -0
- package/src/utils/is-entry-point.js +137 -0
- package/src/utils/iso-datetime.js +51 -0
- package/src/utils/node-pty-probe.js +95 -0
- package/src/utils/node-pty-support.js +118 -0
- package/src/utils/opened-file-path.js +167 -0
- package/src/utils/path-containment.js +165 -0
- package/src/utils/permission-mode-sidecar.js +51 -0
- package/src/utils/preflight.js +485 -29
- package/src/utils/read-limiter.js +217 -0
- package/src/utils/regular-file.js +375 -0
- package/src/utils/safe-regex.js +113 -0
- package/src/utils/small-file.js +129 -0
- package/src/utils/spawn-env.js +196 -5
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-binary.js +276 -0
- package/src/utils/verify-provenance.js +634 -0
- package/src/utils/wire-counters.js +48 -0
- package/src/web-task-manager.js +256 -16
- package/src/worktree-gc.js +11 -3
- package/src/ws-auth.js +69 -21
- package/src/ws-broadcaster.js +14 -2
- package/src/ws-client-manager.js +16 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +370 -66
- package/src/ws-file-ops/common.js +384 -11
- package/src/ws-file-ops/git.js +615 -44
- package/src/ws-file-ops/index.js +7 -0
- package/src/ws-file-ops/memory.js +460 -0
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +676 -94
- package/src/ws-forwarding.js +373 -55
- package/src/ws-handler-context.js +89 -2
- package/src/ws-history.js +1018 -177
- package/src/ws-message-handlers.js +23 -1
- package/src/ws-outbound-schemas.js +207 -0
- package/src/ws-permissions.js +589 -38
- package/src/ws-schemas.js +6 -0
- package/src/ws-server.js +936 -105
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
- package/src/dashboard-next/dist/index.html +0 -13
package/src/scheduler.js
ADDED
|
@@ -0,0 +1,1099 @@
|
|
|
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
|
+
this._staleModelWarned = new Set()
|
|
392
|
+
/**
|
|
393
|
+
* @type {Set<string>} task ids whose outcome could not be persisted. Recording
|
|
394
|
+
* the run is what advances nextRun, so a task we cannot record would stay
|
|
395
|
+
* permanently due and be re-fired on every tick. Quarantining it (for this
|
|
396
|
+
* process only — a restart re-reads the file) turns a storage fault into one
|
|
397
|
+
* logged error instead of a hot loop of unattended agent sessions.
|
|
398
|
+
*/
|
|
399
|
+
this._quarantined = new Set()
|
|
400
|
+
/** @type {Map<string,{taskId:string,blocked:null|{toolName:string}}>} sessionId -> live run, for the permission answerer. */
|
|
401
|
+
this._ownedRuns = new Map()
|
|
402
|
+
|
|
403
|
+
// Lazily built on first real run so a disabled daemon (and every unit test
|
|
404
|
+
// using the runTask seam) never constructs a TurnDriver or attaches its
|
|
405
|
+
// SessionManager listeners.
|
|
406
|
+
this._turnDriver = null
|
|
407
|
+
this._permissionListener = null
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/** Whether the enable gate is open for this daemon. */
|
|
411
|
+
get enabled() {
|
|
412
|
+
return isSchedulerEnabled(this._config)
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/** Task ids currently mid-run (test/observability aid). */
|
|
416
|
+
get runningTaskIds() {
|
|
417
|
+
return new Set(this._running)
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/** taskId -> sessionId for every task whose session is currently cached (test/observability aid). */
|
|
421
|
+
get scheduledSessionIds() {
|
|
422
|
+
return new Map(this._sessionByTask)
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* Task ids this process has quarantined (their outcome could not be persisted,
|
|
427
|
+
* so they have STOPPED firing until the daemon restarts). Part of the engine's
|
|
428
|
+
* gate state that #6868/#6871 read: a quarantined task's registry entry may
|
|
429
|
+
* still show an old healthy-looking lastRun, so this is the authoritative
|
|
430
|
+
* "why has this task gone quiet?" signal alongside the `task-quarantined` event.
|
|
431
|
+
*/
|
|
432
|
+
get quarantinedTaskIds() {
|
|
433
|
+
return new Set(this._quarantined)
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/** Whether a timer is currently armed (test/observability aid). */
|
|
437
|
+
get armed() {
|
|
438
|
+
return this._timer !== null
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/**
|
|
442
|
+
* Arm the engine. A NO-OP when the enable gate is closed: no timer is armed, so
|
|
443
|
+
* a daemon with the feature off behaves exactly as it did before this slice
|
|
444
|
+
* existed. Idempotent.
|
|
445
|
+
* @returns {boolean} whether the engine actually started
|
|
446
|
+
*/
|
|
447
|
+
start() {
|
|
448
|
+
if (this._destroyed || this._started) return this._started
|
|
449
|
+
if (!this.enabled) {
|
|
450
|
+
this._log.info('Scheduled execution is disabled (features.scheduler / CHROXY_ENABLE_SCHEDULER=1) — no scheduled tasks will fire')
|
|
451
|
+
return false
|
|
452
|
+
}
|
|
453
|
+
this._started = true
|
|
454
|
+
this._log.info('Scheduled execution ENABLED — arming headless scheduler')
|
|
455
|
+
this._armNextTick()
|
|
456
|
+
return true
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/**
|
|
460
|
+
* Re-evaluate the schedule now (e.g. after the CLI/dashboard mutated the
|
|
461
|
+
* registry). Cheap and safe to call often; a no-op when not started.
|
|
462
|
+
*/
|
|
463
|
+
refresh() {
|
|
464
|
+
if (!this._started || this._destroyed) return
|
|
465
|
+
this._armNextTick()
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/**
|
|
469
|
+
* Clear every timer, detach listeners, and stop firing. Idempotent — the
|
|
470
|
+
* daemon's shutdown path may call it more than once. In-flight runs are left to
|
|
471
|
+
* settle (their recording is guarded on `_destroyed`), so shutdown never blocks
|
|
472
|
+
* on a provider.
|
|
473
|
+
*/
|
|
474
|
+
destroy() {
|
|
475
|
+
this._destroyed = true
|
|
476
|
+
this._started = false
|
|
477
|
+
this._clearArmedTimer()
|
|
478
|
+
this._detachPermissionListener()
|
|
479
|
+
if (this._turnDriver) {
|
|
480
|
+
try { this._turnDriver.dispose() } catch (err) {
|
|
481
|
+
this._log.warn(`Scheduler turn-driver dispose failed: ${err?.message || err}`)
|
|
482
|
+
}
|
|
483
|
+
this._turnDriver = null
|
|
484
|
+
}
|
|
485
|
+
this._running.clear()
|
|
486
|
+
this._ownedRuns.clear()
|
|
487
|
+
this._sessionByTask.clear()
|
|
488
|
+
this._quarantined.clear()
|
|
489
|
+
this.removeAllListeners()
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/** @private */
|
|
493
|
+
_clearArmedTimer() {
|
|
494
|
+
if (this._timer !== null) {
|
|
495
|
+
this._clearTimer(this._timer)
|
|
496
|
+
this._timer = null
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/**
|
|
501
|
+
* @private — arm ONE timer for the earliest interesting moment, clamped to
|
|
502
|
+
* [0, maxSleepMs]. Replaces any previously armed timer, so repeated calls can
|
|
503
|
+
* never stack timers up.
|
|
504
|
+
*/
|
|
505
|
+
_armNextTick() {
|
|
506
|
+
if (this._destroyed || !this._started) return
|
|
507
|
+
this._clearArmedTimer()
|
|
508
|
+
// Every registry change and every settled run funnels through here, so this
|
|
509
|
+
// is the one place that notices a task has gone away (#7006).
|
|
510
|
+
this._releaseSessions()
|
|
511
|
+
const now = this._now()
|
|
512
|
+
let earliest = null
|
|
513
|
+
// At capacity nothing new can start, and a shed task stays due — computing a
|
|
514
|
+
// 0ms delay off it would spin the CPU until the in-flight run finished. Sleep
|
|
515
|
+
// the full cadence instead; _fire() re-arms the moment a slot frees.
|
|
516
|
+
if (this._running.size < this._maxConcurrentRuns) {
|
|
517
|
+
for (const task of this._store.list()) {
|
|
518
|
+
if (!task.enabled || !Number.isFinite(task.nextRun)) continue
|
|
519
|
+
if (this._running.has(task.id) || this._quarantined.has(task.id)) continue
|
|
520
|
+
if (earliest === null || task.nextRun < earliest) earliest = task.nextRun
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
// Even with nothing scheduled we re-check on the max-sleep cadence, so a task
|
|
524
|
+
// added by another surface is noticed without an explicit refresh() call.
|
|
525
|
+
const delay = earliest === null
|
|
526
|
+
? this._maxSleepMs
|
|
527
|
+
: Math.min(this._maxSleepMs, Math.max(0, earliest - now))
|
|
528
|
+
this._timer = this._setTimer(() => this._tick(), delay)
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/**
|
|
532
|
+
* @private — end the session lifecycle of tasks that no longer exist (#7006).
|
|
533
|
+
* A recurring task keeps exactly ONE session between fires (see
|
|
534
|
+
* _runViaSessionManager); this is the other half — what happens when the task
|
|
535
|
+
* is deleted.
|
|
536
|
+
*
|
|
537
|
+
* Only REMOVAL (the task is gone from the store) ends the session: it is
|
|
538
|
+
* destroyed and the mapping dropped, so a deleted task no longer leaves a
|
|
539
|
+
* provider session running until the daemon exits. Never while the task's run
|
|
540
|
+
* is in flight — the turn is still using it — so it is skipped here and
|
|
541
|
+
* released by the pass that follows the run settling (_fire re-arms after every
|
|
542
|
+
* run).
|
|
543
|
+
*
|
|
544
|
+
* A task that is merely DISABLED, or a `once` task that retired (nextRun null),
|
|
545
|
+
* keeps its mapping and its session. Resume reuses the same session (dropping
|
|
546
|
+
* the mapping on pause would strand one session per pause/resume cycle), and
|
|
547
|
+
* the session still holds what the last run did. If such a task is deleted
|
|
548
|
+
* later, the pass above destroys its session.
|
|
549
|
+
*
|
|
550
|
+
* The mapping is in-memory only, so a restart forgets every task->session link
|
|
551
|
+
* without destroying anything. Never throws: a failing destroy must not take
|
|
552
|
+
* the scheduling tick down.
|
|
553
|
+
*/
|
|
554
|
+
_releaseSessions() {
|
|
555
|
+
for (const [taskId, sessionId] of [...this._sessionByTask]) {
|
|
556
|
+
if (this._store.get(taskId)) continue
|
|
557
|
+
if (this._running.has(taskId)) continue
|
|
558
|
+
this._sessionByTask.delete(taskId)
|
|
559
|
+
this._destroyTaskSession(taskId, sessionId)
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/** @private — destroy a removed task's session if it is still alive; never throws. */
|
|
564
|
+
_destroyTaskSession(taskId, sessionId) {
|
|
565
|
+
const warn = (err) => {
|
|
566
|
+
this._log.warn(`Could not destroy the session of removed scheduled task ${taskId}: ${err?.message || err}`)
|
|
567
|
+
}
|
|
568
|
+
try {
|
|
569
|
+
// Already gone (the operator closed it, or a teardown is in progress).
|
|
570
|
+
if (!this._sm?.getSession?.(sessionId)) return
|
|
571
|
+
this._log.info(`Scheduled task ${taskId} was removed — closing its session ${sessionId}`)
|
|
572
|
+
const pending = typeof this._sm.destroySessionLocked === 'function'
|
|
573
|
+
? this._sm.destroySessionLocked(sessionId)
|
|
574
|
+
: this._sm.destroySession?.(sessionId)
|
|
575
|
+
if (pending && typeof pending.catch === 'function') pending.catch(warn)
|
|
576
|
+
} catch (err) {
|
|
577
|
+
warn(err)
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
/**
|
|
582
|
+
* @private — one evaluation pass: fire everything due (under the concurrency
|
|
583
|
+
* cap), then re-arm. Never throws; a per-task failure is recorded and the pass
|
|
584
|
+
* continues.
|
|
585
|
+
*/
|
|
586
|
+
_tick() {
|
|
587
|
+
if (this._destroyed || !this._started) return
|
|
588
|
+
this._timer = null
|
|
589
|
+
const now = this._now()
|
|
590
|
+
try {
|
|
591
|
+
for (const task of this._dueTasks(now)) {
|
|
592
|
+
if (this._isTooOverdue(task, now)) {
|
|
593
|
+
// Persist a `skipped` result so the schedule ADVANCES (and a one-time
|
|
594
|
+
// task retires) instead of re-evaluating as overdue forever.
|
|
595
|
+
this._recordSkip(task, now, `overdue by ${now - task.nextRun}ms (grace ${this._overdueGraceMs}ms)`, { persist: true })
|
|
596
|
+
continue
|
|
597
|
+
}
|
|
598
|
+
if (this._running.size >= this._maxConcurrentRuns) {
|
|
599
|
+
// Thundering-herd guard: shed the rest of this burst WITHOUT persisting.
|
|
600
|
+
// The task is still genuinely due and fires on a later tick.
|
|
601
|
+
this._recordSkip(task, now, `concurrency cap reached (${this._maxConcurrentRuns})`)
|
|
602
|
+
continue
|
|
603
|
+
}
|
|
604
|
+
// Fire-and-forget: _fire() owns its error handling and records its own
|
|
605
|
+
// outcome, so an in-flight run never blocks the evaluation pass. The
|
|
606
|
+
// trailing catch is the backstop for anything _fire's own try/catch cannot
|
|
607
|
+
// cover (chiefly a listener throwing inside emit) — an unhandled rejection
|
|
608
|
+
// here would take the daemon down.
|
|
609
|
+
void this._fire(task, now).catch((err) => {
|
|
610
|
+
this._running.delete(task.id)
|
|
611
|
+
this._log.error(`Scheduled task ${task.id} fire failed unexpectedly: ${err?.stack || err}`)
|
|
612
|
+
})
|
|
613
|
+
}
|
|
614
|
+
} catch (err) {
|
|
615
|
+
this._log.error(`Scheduler tick failed: ${err?.stack || err}`)
|
|
616
|
+
}
|
|
617
|
+
this._armNextTick()
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
/** @private — enabled tasks whose nextRun has arrived, oldest-due first. */
|
|
621
|
+
_dueTasks(now) {
|
|
622
|
+
return this._store
|
|
623
|
+
.list()
|
|
624
|
+
.filter((t) => t.enabled && Number.isFinite(t.nextRun) && t.nextRun <= now
|
|
625
|
+
&& !this._running.has(t.id) && !this._quarantined.has(t.id))
|
|
626
|
+
.sort((a, b) => a.nextRun - b.nextRun)
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
/** @private — whether a due task's slot is staler than the grace window. */
|
|
630
|
+
_isTooOverdue(task, now) {
|
|
631
|
+
if (!Number.isFinite(this._overdueGraceMs) || this._overdueGraceMs < 0) return false
|
|
632
|
+
return now - task.nextRun > this._overdueGraceMs
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
/** @private — record a non-run (shed / too-overdue). */
|
|
636
|
+
_recordSkip(task, at, reason, { persist = false } = {}) {
|
|
637
|
+
this._log.warn(`Scheduled task ${task.id} not fired: ${reason}`)
|
|
638
|
+
if (persist) this._recordRun(task, { at, status: 'skipped', error: reason })
|
|
639
|
+
this.emit('run-skip', { taskId: task.id, at, reason })
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
/**
|
|
643
|
+
* @private — execute one task end-to-end: mark it in-flight (overlap guard),
|
|
644
|
+
* run it, then record the outcome and re-arm. Never rejects.
|
|
645
|
+
*/
|
|
646
|
+
async _fire(task, at) {
|
|
647
|
+
const ctx = {
|
|
648
|
+
at,
|
|
649
|
+
permissionMode: resolveScheduledPermissionMode(task.target?.permissionMode),
|
|
650
|
+
runTimeoutMs: this._runTimeoutMs,
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
// ── PREFLIGHT: refuse before firing ──────────────────────────────────────
|
|
654
|
+
// Runs BEFORE the overlap guard, BEFORE `run-start`, and BEFORE any session
|
|
655
|
+
// exists — a refused task never spawns a session and is never reported as a
|
|
656
|
+
// run that started. Placed here (the single chokepoint every run passes
|
|
657
|
+
// through) rather than inside the default executor so a future second
|
|
658
|
+
// executor cannot bypass it: a check that lives on only one path is exactly
|
|
659
|
+
// the class of bug this fixes (validateCwdAllowed was handler-only).
|
|
660
|
+
const refusal = this._preflightRefusal(task)
|
|
661
|
+
if (refusal) {
|
|
662
|
+
this._recordRefusal(task, at, refusal)
|
|
663
|
+
return
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
this._running.add(task.id)
|
|
667
|
+
this.emit('run-start', { taskId: task.id, at })
|
|
668
|
+
this._log.info(`Firing scheduled task ${task.id}${task.name ? ` (${task.name})` : ''}`)
|
|
669
|
+
|
|
670
|
+
let outcome
|
|
671
|
+
try {
|
|
672
|
+
const exec = this._injectedRunTask || ((t, c) => this._runViaSessionManager(t, c))
|
|
673
|
+
outcome = await exec(task, ctx)
|
|
674
|
+
} catch (err) {
|
|
675
|
+
outcome = { status: 'error', error: err?.message || String(err) }
|
|
676
|
+
} finally {
|
|
677
|
+
this._running.delete(task.id)
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
const status = outcome?.status
|
|
681
|
+
const result = {
|
|
682
|
+
at,
|
|
683
|
+
status: PASSTHROUGH_STATUSES.has(status) ? status : 'error',
|
|
684
|
+
...(outcome?.sessionId ? { sessionId: outcome.sessionId } : {}),
|
|
685
|
+
...(outcome?.error ? { error: String(outcome.error).slice(0, 500) } : {}),
|
|
686
|
+
}
|
|
687
|
+
this._recordRun(task, result)
|
|
688
|
+
this.emit('run-end', { taskId: task.id, ...result })
|
|
689
|
+
if (result.status === 'success') {
|
|
690
|
+
this._log.info(`Scheduled task ${task.id} completed`)
|
|
691
|
+
} else {
|
|
692
|
+
this._log.warn(`Scheduled task ${task.id} finished status=${result.status}${result.error ? `: ${result.error}` : ''}`)
|
|
693
|
+
}
|
|
694
|
+
// A finished run frees a concurrency slot and changed nextRun — re-evaluate.
|
|
695
|
+
this._armNextTick()
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
/**
|
|
699
|
+
* @private — the pre-fire safety gate: everything that must hold BEFORE an
|
|
700
|
+
* unattended turn is allowed to exist. Returns a refusal reason, or null to
|
|
701
|
+
* proceed. Both checks are things the engine cannot recover from by retrying —
|
|
702
|
+
* they are misconfigurations in the stored task definition.
|
|
703
|
+
*/
|
|
704
|
+
_preflightRefusal(task) {
|
|
705
|
+
// (a) Can we actually govern this provider's permission prompts? (#7003)
|
|
706
|
+
const providerRefusal = scheduledProviderRefusalReason(this._resolveProviderName(task), this._getProviderClass)
|
|
707
|
+
if (providerRefusal) return providerRefusal
|
|
708
|
+
|
|
709
|
+
// (b) Is the cwd one a session may be created in at all? The registry is a
|
|
710
|
+
// user-writable JSON file, so `target.cwd` is untrusted input — and neither
|
|
711
|
+
// the store (trims the string) nor createSession (statSync only) applies the
|
|
712
|
+
// real allowlist. Validate the EFFECTIVE cwd: the task's own, else whatever
|
|
713
|
+
// createSession would default to. (#7005 moves this into createSession.)
|
|
714
|
+
const cwd = this._resolveTaskCwd(task)
|
|
715
|
+
if (cwd) {
|
|
716
|
+
let cwdError
|
|
717
|
+
try {
|
|
718
|
+
cwdError = this._validateCwd(cwd)
|
|
719
|
+
} catch (err) {
|
|
720
|
+
// A throwing validator must fail CLOSED, never fall through to allowed.
|
|
721
|
+
return `working directory ${cwd} could not be validated for a scheduled run: ${err?.message || err}`
|
|
722
|
+
}
|
|
723
|
+
if (cwdError) {
|
|
724
|
+
return `working directory ${cwd} is not allowed for a scheduled run: ${cwdError}`
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
return null
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
/**
|
|
731
|
+
* @private — the provider a run would ACTUALLY use, resolved the same way
|
|
732
|
+
* SessionManager.createSession resolves it (`provider || this._providerType`),
|
|
733
|
+
* so the capability gate judges the real provider rather than the stored field.
|
|
734
|
+
* Falls back to DEFAULT_PROVIDER when no manager is wired.
|
|
735
|
+
*/
|
|
736
|
+
_resolveProviderName(task) {
|
|
737
|
+
const explicit = task.target?.provider
|
|
738
|
+
if (typeof explicit === 'string' && explicit.length > 0) return explicit
|
|
739
|
+
const managerDefault = this._sm?.providerType
|
|
740
|
+
if (typeof managerDefault === 'string' && managerDefault.length > 0) return managerDefault
|
|
741
|
+
return DEFAULT_PROVIDER
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
/**
|
|
745
|
+
* @private — the cwd a run would ACTUALLY use: the task's own, else the
|
|
746
|
+
* manager's default (what createSession falls back to). Null when neither is
|
|
747
|
+
* knowable, in which case there is no manager and the run fails anyway.
|
|
748
|
+
*/
|
|
749
|
+
_resolveTaskCwd(task) {
|
|
750
|
+
const explicit = task.target?.cwd
|
|
751
|
+
if (typeof explicit === 'string' && explicit.length > 0) return explicit
|
|
752
|
+
const managerDefault = this._sm?.defaultCwd
|
|
753
|
+
if (typeof managerDefault === 'string' && managerDefault.length > 0) return managerDefault
|
|
754
|
+
return null
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
/**
|
|
758
|
+
* @private — record a run the engine refused to start. A VISIBLE, explicit
|
|
759
|
+
* non-success outcome: never `success`, and distinguishable from both `error`
|
|
760
|
+
* (the run happened and failed) and `skipped` (the slot passed) by its own
|
|
761
|
+
* status, so #6868/#6871 can tell the operator nothing ran and why.
|
|
762
|
+
*/
|
|
763
|
+
_recordRefusal(task, at, reason) {
|
|
764
|
+
this._log.error(`Scheduled task ${task.id} REFUSED — nothing was run: ${reason}`)
|
|
765
|
+
const result = { at, status: REFUSED_STATUS, error: String(reason).slice(0, 500) }
|
|
766
|
+
this._recordRun(task, result)
|
|
767
|
+
this.emit('run-end', { taskId: task.id, ...result })
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
/**
|
|
771
|
+
* @private — persist a lastRun result. The store recomputes nextRun off the
|
|
772
|
+
* cadence on update(), which is what retires a one-time task (computeNextRun
|
|
773
|
+
* returns null for a `once` cadence that has a lastRun) and advances a recurring
|
|
774
|
+
* one to its next slot with no backfill of missed slots.
|
|
775
|
+
*/
|
|
776
|
+
_recordRun(task, result) {
|
|
777
|
+
try {
|
|
778
|
+
this._store.update(task.id, { lastRun: result })
|
|
779
|
+
} catch (err) {
|
|
780
|
+
// A rejected result value or a storage fault must not take the engine down.
|
|
781
|
+
// It must ALSO not be retried forever: without a recorded run its nextRun
|
|
782
|
+
// never advances, so quarantine it for this process rather than re-firing it
|
|
783
|
+
// every tick.
|
|
784
|
+
this._quarantine(task, result?.at ?? this._now(), `its run outcome could not be recorded: ${err?.message || err}`)
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
/**
|
|
789
|
+
* @private — stop firing a task for the rest of this process, and make that
|
|
790
|
+
* VISIBLE. Quarantine used to be a log line only, so a task that had
|
|
791
|
+
* permanently stopped firing still showed its last healthy `lastRun` to every
|
|
792
|
+
* registry-reading surface — indistinguishable from a task that is fine. Now
|
|
793
|
+
* the engine (a) best-effort writes the quarantine onto the task itself, (b)
|
|
794
|
+
* emits `task-quarantined`, and (c) exposes it on `quarantinedTaskIds`. The
|
|
795
|
+
* write is best-effort ON PURPOSE: the usual reason to quarantine is that the
|
|
796
|
+
* store itself is failing, so (b) and (c) are the fallbacks that always work.
|
|
797
|
+
*
|
|
798
|
+
* Quarantine stays process-scoped (a restart re-reads the file), so the task is
|
|
799
|
+
* NOT disabled in the registry.
|
|
800
|
+
*/
|
|
801
|
+
_quarantine(task, at, reason) {
|
|
802
|
+
const firstTime = !this._quarantined.has(task.id)
|
|
803
|
+
this._quarantined.add(task.id)
|
|
804
|
+
this._log.error(`Scheduled task ${task.id} QUARANTINED until daemon restart — it will not fire again: ${reason}`)
|
|
805
|
+
try {
|
|
806
|
+
this._store.update(task.id, {
|
|
807
|
+
lastRun: { at, status: REFUSED_STATUS, error: `quarantined until daemon restart: ${reason}`.slice(0, 500) },
|
|
808
|
+
})
|
|
809
|
+
} catch { /* the store is usually the thing that's broken — the event + getter carry the signal */ }
|
|
810
|
+
if (firstTime) this.emit('task-quarantined', { taskId: task.id, at, reason })
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
// ── the default (production) executor ──────────────────────────────────────
|
|
814
|
+
|
|
815
|
+
/**
|
|
816
|
+
* @private — the real headless run: create (or RESUME) this task's session and
|
|
817
|
+
* drive the task prompt through it with no client connected.
|
|
818
|
+
*
|
|
819
|
+
* Session reuse is deliberate (the issue's "spins up (or resumes) a session"):
|
|
820
|
+
* one session per task id, reused while it is still alive. That bounds a daily
|
|
821
|
+
* task to ONE session instead of one per fire, keeps the recorded `sessionId`
|
|
822
|
+
* meaningful (the operator can open it and read what the run actually did), and
|
|
823
|
+
* gives a recurring task continuity across runs. Sessions are NOT auto-destroyed
|
|
824
|
+
* after a run — they are ordinary sessions the operator can inspect and close.
|
|
825
|
+
* A recurring task therefore keeps exactly one session between fires, so within
|
|
826
|
+
* one daemon process the cache is bounded by the number of tasks in the registry;
|
|
827
|
+
* there is no idle reap and no cap. (A restart restores old sessions without
|
|
828
|
+
* their task link.) The session ends when the task is DELETED: see
|
|
829
|
+
* _releaseSessions (#7006). Pausing, resuming or retiring a task leaves it be.
|
|
830
|
+
*
|
|
831
|
+
* Because they are ordinary sessions, the operator can also change their
|
|
832
|
+
* permission mode. That makes reuse an escalation vector, so the clamped mode is
|
|
833
|
+
* re-asserted and verified on EVERY fire — see _assertPermissionMode. The
|
|
834
|
+
* interactive mode switch is deliberately left working (an operator inspecting a
|
|
835
|
+
* scheduled session may legitimately want to drive it by hand); what is
|
|
836
|
+
* guaranteed is that their change cannot survive into the next unattended fire.
|
|
837
|
+
*/
|
|
838
|
+
async _runViaSessionManager(task, ctx) {
|
|
839
|
+
if (!this._sm) return { status: 'error', error: 'no sessionManager wired — cannot run scheduled task' }
|
|
840
|
+
|
|
841
|
+
let sessionId
|
|
842
|
+
try {
|
|
843
|
+
sessionId = this._resolveSession(task, ctx)
|
|
844
|
+
} catch (err) {
|
|
845
|
+
if (err instanceof ScheduledRunRefusedError) return { status: REFUSED_STATUS, error: err.message }
|
|
846
|
+
return { status: 'error', error: `session create failed: ${err?.message || err}` }
|
|
847
|
+
}
|
|
848
|
+
if (!sessionId) return { status: 'error', error: 'session create failed (no sessionId)' }
|
|
849
|
+
|
|
850
|
+
// Register as an OWNED run before the turn starts, so the permission answerer
|
|
851
|
+
// is armed for the very first tool call.
|
|
852
|
+
const runState = { taskId: task.id, blocked: null }
|
|
853
|
+
this._ownedRuns.set(sessionId, runState)
|
|
854
|
+
this._attachPermissionListener()
|
|
855
|
+
|
|
856
|
+
try {
|
|
857
|
+
const driver = this._ensureTurnDriver()
|
|
858
|
+
await driver.driveTurn(sessionId, task.prompt, {
|
|
859
|
+
label: `scheduled:${task.id}`,
|
|
860
|
+
timeoutMs: ctx.runTimeoutMs,
|
|
861
|
+
})
|
|
862
|
+
// `success` is the NARROWEST outcome, asserted positively: the turn
|
|
863
|
+
// completed AND no permission prompt was ever raised on this run. Any
|
|
864
|
+
// permission activity at all sets `runState.blocked` (set before any other
|
|
865
|
+
// decision in _handleSessionEvent, so a malformed prompt we could not even
|
|
866
|
+
// answer still counts), because a denied permission usually lets the agent
|
|
867
|
+
// finish "successfully" with the tool call refused — which is NOT a
|
|
868
|
+
// successful scheduled run. Reporting success for a run whose every tool
|
|
869
|
+
// call was refused is the worst failure mode this engine has, so the
|
|
870
|
+
// default here is to disbelieve success.
|
|
871
|
+
if (runState.blocked) return this._blockedOutcome(runState, sessionId)
|
|
872
|
+
return { status: 'success', sessionId }
|
|
873
|
+
} catch (err) {
|
|
874
|
+
// ORDER IS LOAD-BEARING. `runState.blocked` is checked FIRST, ahead of the
|
|
875
|
+
// TURN_STOPPED arm below, because the engine's own deny path reaches this
|
|
876
|
+
// catch through exactly the same rejection: it answers `deny`, interrupts
|
|
877
|
+
// the turn, and TurnDriver rejects TURN_STOPPED (#7009). That run is a real
|
|
878
|
+
// failure — the agent asked for permission nobody could grant — and must
|
|
879
|
+
// keep the `error` status it has always had. Only an interrupt with NO
|
|
880
|
+
// permission activity is the benign operator Stop.
|
|
881
|
+
if (runState.blocked) return this._blockedOutcome(runState, sessionId)
|
|
882
|
+
if (err instanceof TurnError && err.code === 'TURN_TIMEOUT') {
|
|
883
|
+
return { status: 'timeout', sessionId, error: `run exceeded ${ctx.runTimeoutMs}ms` }
|
|
884
|
+
}
|
|
885
|
+
if (err instanceof TurnError && err.code === 'TURN_STOPPED') {
|
|
886
|
+
// #7038 — a deliberate Stop, not a fault. Its own status so an operator
|
|
887
|
+
// reading the registry (CLI / dashboard chip) can tell it apart from a
|
|
888
|
+
// provider crash instead of having to parse the error string.
|
|
889
|
+
return { status: INTERRUPTED_STATUS, sessionId, error: err?.message || 'turn interrupted before completing' }
|
|
890
|
+
}
|
|
891
|
+
return { status: 'error', sessionId, error: err?.message || String(err) }
|
|
892
|
+
} finally {
|
|
893
|
+
this._ownedRuns.delete(sessionId)
|
|
894
|
+
if (this._ownedRuns.size === 0) this._detachPermissionListener()
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
/** @private — the permission-blocked outcome (a visible failure, never silent). */
|
|
899
|
+
_blockedOutcome(runState, sessionId) {
|
|
900
|
+
return {
|
|
901
|
+
status: 'error',
|
|
902
|
+
sessionId,
|
|
903
|
+
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.`,
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
/**
|
|
908
|
+
* @private — reuse this task's still-live session, else create a fresh one.
|
|
909
|
+
* EITHER WAY the clamped permission mode is asserted before the caller drives a
|
|
910
|
+
* turn: createSession is passed it, and a reused session has it re-asserted and
|
|
911
|
+
* verified. A session that cannot be brought to the clamped mode is refused.
|
|
912
|
+
*/
|
|
913
|
+
_resolveSession(task, ctx) {
|
|
914
|
+
const existing = this._sessionByTask.get(task.id)
|
|
915
|
+
if (existing) {
|
|
916
|
+
const entry = this._sm.getSession?.(existing)
|
|
917
|
+
if (entry?.session) {
|
|
918
|
+
// THE ESCALATION VECTOR (#6997 review C3): scheduled sessions are kept
|
|
919
|
+
// alive and reused, and an operator can flip any session to `auto` from
|
|
920
|
+
// the dashboard — even mid-turn. Without re-asserting here, one manual
|
|
921
|
+
// flip would silently put every future unattended fire of this task into
|
|
922
|
+
// bypass, forever, each recorded as a clean success.
|
|
923
|
+
this._assertPermissionMode(entry.session, ctx.permissionMode, existing)
|
|
924
|
+
return existing
|
|
925
|
+
}
|
|
926
|
+
// The session is gone (operator closed it) — drop the stale mapping so a
|
|
927
|
+
// fresh one is created below rather than resumed by id.
|
|
928
|
+
this._sessionByTask.delete(task.id)
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
const target = task.target || {}
|
|
932
|
+
const sessionId = this._sm.createSession({
|
|
933
|
+
name: task.name || `Scheduled: ${task.id.slice(0, 8)}`,
|
|
934
|
+
...(target.cwd ? { cwd: target.cwd } : {}),
|
|
935
|
+
...(target.provider ? { provider: target.provider } : {}),
|
|
936
|
+
...(target.model ? { model: target.model, modelSource: 'replay' } : {}),
|
|
937
|
+
// The clamped floor — never the task's raw value (see resolveScheduledPermissionMode).
|
|
938
|
+
permissionMode: ctx.permissionMode,
|
|
939
|
+
// EXPLICIT false so an unattended run can never inherit the server-wide
|
|
940
|
+
// `dangerouslySkipPermissions` default (session-manager.js:1473).
|
|
941
|
+
skipPermissions: false,
|
|
942
|
+
metadata: { scheduledTaskId: task.id },
|
|
943
|
+
})
|
|
944
|
+
// Trust nothing: verify the freshly-created session really came up at the
|
|
945
|
+
// clamped mode rather than assuming createSession honoured the option.
|
|
946
|
+
const created = this._sm.getSession?.(sessionId)
|
|
947
|
+
// #7855: a saved model id that is no longer usable runs on the default instead of
|
|
948
|
+
// failing every fire; say so once per task, naming it, so the owner can fix it.
|
|
949
|
+
if (target.model && created?.session && (created.session.model ?? null) !== target.model
|
|
950
|
+
&& !this._staleModelWarned.has(task.id)) {
|
|
951
|
+
this._staleModelWarned.add(task.id)
|
|
952
|
+
this._log.warn(`Scheduled task ${task.id}${task.name ? ` (${task.name})` : ''}: saved model '${target.model}' is not usable; running on the provider default. Edit the task's model to fix.`)
|
|
953
|
+
}
|
|
954
|
+
if (created?.session) this._assertPermissionMode(created.session, ctx.permissionMode, sessionId)
|
|
955
|
+
this._sessionByTask.set(task.id, sessionId)
|
|
956
|
+
return sessionId
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
/**
|
|
960
|
+
* @private — force `mode` onto a session and PROVE it took, or throw. The
|
|
961
|
+
* invariant this exists to hold: **a scheduled fire runs at the clamped mode,
|
|
962
|
+
* or it does not run.**
|
|
963
|
+
*
|
|
964
|
+
* Read-back is the only evidence accepted. `setPermissionMode` returns false
|
|
965
|
+
* both for a harmless no-op (already in that mode) and for a REFUSED change (a
|
|
966
|
+
* session mid-turn rejects every non-`auto` switch — base-session.js:1115-1133),
|
|
967
|
+
* so its return value cannot distinguish "fine" from "escalated and stuck".
|
|
968
|
+
* Only the value the session reports afterwards can.
|
|
969
|
+
*
|
|
970
|
+
* @throws {ScheduledRunRefusedError} when the mode cannot be verified
|
|
971
|
+
*/
|
|
972
|
+
_assertPermissionMode(session, mode, sessionId) {
|
|
973
|
+
const read = () => (typeof session.permissionMode === 'string' ? session.permissionMode : null)
|
|
974
|
+
if (read() !== mode) {
|
|
975
|
+
try {
|
|
976
|
+
session.setPermissionMode?.(mode)
|
|
977
|
+
} catch (err) {
|
|
978
|
+
throw new ScheduledRunRefusedError(
|
|
979
|
+
`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`
|
|
980
|
+
)
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
const actual = read()
|
|
984
|
+
if (actual !== mode) {
|
|
985
|
+
throw new ScheduledRunRefusedError(
|
|
986
|
+
`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`
|
|
987
|
+
)
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
/** @private — build the TurnDriver on first real run. */
|
|
992
|
+
_ensureTurnDriver() {
|
|
993
|
+
if (!this._turnDriver) {
|
|
994
|
+
this._turnDriver = new TurnDriver({ sessionManager: this._sm, log: this._log })
|
|
995
|
+
}
|
|
996
|
+
return this._turnDriver
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
/**
|
|
1000
|
+
* @private — arm the headless permission answerer. Scoped to sessions this
|
|
1001
|
+
* engine owns (never a user's session), mirroring
|
|
1002
|
+
* orchestration/permission-gate.js. Attached only while a run is in flight.
|
|
1003
|
+
*/
|
|
1004
|
+
_attachPermissionListener() {
|
|
1005
|
+
if (this._permissionListener || !this._sm?.on) return
|
|
1006
|
+
this._permissionListener = (payload) => this._handleSessionEvent(payload)
|
|
1007
|
+
this._sm.on('session_event', this._permissionListener)
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
/** @private */
|
|
1011
|
+
_detachPermissionListener() {
|
|
1012
|
+
if (!this._permissionListener) return
|
|
1013
|
+
this._sm?.off?.('session_event', this._permissionListener)
|
|
1014
|
+
this._permissionListener = null
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
/**
|
|
1018
|
+
* @private — a permission prompt reached a scheduled run, which means no rule
|
|
1019
|
+
* settled it and there is no human to answer. DENY it through the normal door,
|
|
1020
|
+
* mark the run blocked, and interrupt the turn: the prompt is answered
|
|
1021
|
+
* immediately (never left to sit out a permission timeout) and the run's outcome
|
|
1022
|
+
* is decided immediately (a visible failure, never an auto-approval).
|
|
1023
|
+
*
|
|
1024
|
+
* The SLOT frees immediately too (#7009): SdkSession's interrupt path emits
|
|
1025
|
+
* `stopped` rather than a result/error (sdk-session.js, #4881), and TurnDriver
|
|
1026
|
+
* treats that as terminal → `driveTurn` rejects TURN_STOPPED right away instead
|
|
1027
|
+
* of sitting out `runTimeoutMs`. The recorded outcome does not depend on which
|
|
1028
|
+
* way the turn settled: `runState.blocked` is already set, so _runViaSessionManager
|
|
1029
|
+
* reports the blocked failure whether the promise rejects or (on a provider that
|
|
1030
|
+
* lets the turn finish with the tool call refused) resolves. Never `success`.
|
|
1031
|
+
*/
|
|
1032
|
+
_handleSessionEvent({ sessionId, event, data } = {}) {
|
|
1033
|
+
if (event !== 'permission_request') return
|
|
1034
|
+
const runState = this._ownedRuns.get(sessionId)
|
|
1035
|
+
if (!runState) return // never answer a session this engine does not own
|
|
1036
|
+
const requestId = data?.requestId ?? data?.id ?? null
|
|
1037
|
+
const toolName = data?.toolName ?? data?.tool ?? ''
|
|
1038
|
+
// Mark the run blocked FIRST, before any other decision. A prompt was raised
|
|
1039
|
+
// on an unattended run: that alone disqualifies the run from `success`,
|
|
1040
|
+
// whether or not we manage to answer it. Bailing out on a malformed payload
|
|
1041
|
+
// BEFORE this (the previous order) left `blocked` unset, so a prompt carrying
|
|
1042
|
+
// no requestId went unanswered AND the run still reported success — the exact
|
|
1043
|
+
// false-success this engine must never produce.
|
|
1044
|
+
if (!runState.blocked) runState.blocked = { toolName }
|
|
1045
|
+
this._log.warn(`Scheduled task ${runState.taskId} requested permission for ${toolName || 'a tool'} with no client connected — denying`)
|
|
1046
|
+
if (requestId == null) {
|
|
1047
|
+
this._log.warn(`Scheduled task ${runState.taskId} permission request carried no requestId — cannot answer it; the run is recorded as blocked`)
|
|
1048
|
+
return
|
|
1049
|
+
}
|
|
1050
|
+
|
|
1051
|
+
const entry = this._sm.getSession?.(sessionId)
|
|
1052
|
+
const session = entry?.session
|
|
1053
|
+
if (!session) return
|
|
1054
|
+
if (typeof session.respondToPermission === 'function') {
|
|
1055
|
+
try {
|
|
1056
|
+
session.respondToPermission(requestId, 'deny')
|
|
1057
|
+
} catch (err) {
|
|
1058
|
+
this._log.warn(`Scheduler permission deny failed for ${sessionId}: ${err?.message || err}`)
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
// Abort the rest of the turn: the task cannot complete what it was asked to do,
|
|
1062
|
+
// so there is no value in letting it continue spending tokens.
|
|
1063
|
+
if (typeof session.interrupt === 'function') {
|
|
1064
|
+
try {
|
|
1065
|
+
const maybe = session.interrupt()
|
|
1066
|
+
if (maybe && typeof maybe.catch === 'function') maybe.catch(() => {})
|
|
1067
|
+
} catch { /* best effort */ }
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
/**
|
|
1073
|
+
* Build the scheduler engine for the daemon, or return null when the enable gate
|
|
1074
|
+
* is closed. Mirrors buildOrchestrationManager (orchestration/build-manager.js):
|
|
1075
|
+
* server-cli.js gets one call and a nullable handle to dispose.
|
|
1076
|
+
*
|
|
1077
|
+
* @param {object} opts
|
|
1078
|
+
* @param {object} opts.sessionManager
|
|
1079
|
+
* @param {object} [opts.config]
|
|
1080
|
+
* @param {object} [opts.logger]
|
|
1081
|
+
* @returns {SchedulerEngine|null}
|
|
1082
|
+
*/
|
|
1083
|
+
export function buildSchedulerEngine({ sessionManager, config = null, logger = log } = {}) {
|
|
1084
|
+
if (!isSchedulerEnabled(config)) return null
|
|
1085
|
+
if (!sessionManager?.scheduledTaskStore) {
|
|
1086
|
+
logger.warn('Scheduled execution enabled but no scheduled-task store is available — scheduler not started')
|
|
1087
|
+
return null
|
|
1088
|
+
}
|
|
1089
|
+
// Never throw out of here: a scheduler that fails to build must not break daemon
|
|
1090
|
+
// boot (same contract as buildOrchestrationManager).
|
|
1091
|
+
try {
|
|
1092
|
+
const engine = new SchedulerEngine({ sessionManager, config, logger })
|
|
1093
|
+
engine.start()
|
|
1094
|
+
return engine
|
|
1095
|
+
} catch (err) {
|
|
1096
|
+
logger.error(`Failed to start the scheduler engine — scheduled tasks will not fire: ${err?.stack || err}`)
|
|
1097
|
+
return null
|
|
1098
|
+
}
|
|
1099
|
+
}
|