@chroxy/server 0.11.0 → 0.11.11
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 +206 -18
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +166 -11
- package/package.json +16 -12
- 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 +958 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +304 -0
- package/src/agent-control/client.js +1645 -0
- package/src/agent-control/events.js +551 -0
- package/src/agent-control/local-connection.js +293 -0
- package/src/agent-control/mcp-server.js +547 -0
- package/src/anthropic-compatible-config.js +30 -4
- package/src/anthropic-compatible-session.js +15 -6
- package/src/anthropic-gemini-shim.js +444 -0
- package/src/anthropic-gemini-translate.js +1030 -0
- 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 +1520 -36
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +19 -0
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +11 -5
- package/src/bound-client-policy.js +291 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +69 -5
- 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 +92 -7
- package/src/byok-mcp-config.js +633 -122
- package/src/byok-mcp-fleet.js +49 -7
- package/src/byok-mcp-oauth-store.js +18 -16
- package/src/byok-mcp-trust.js +37 -23
- package/src/byok-session.js +707 -179
- package/src/byok-tool-executor.js +2742 -26
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +64 -46
- 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-setting-sources.js +74 -0
- package/src/claude-stream-parser.js +53 -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 +215 -88
- 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 +3563 -284
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-cmd.js +236 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +4 -4
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/connection-state.js +54 -0
- package/src/cli/deploy-cmd.js +45 -10
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/freshness-cmd.js +53 -0
- package/src/cli/init-cmd.js +15 -16
- package/src/cli/pages-cmd.js +6 -4
- package/src/cli/pair-code-cmd.js +7 -6
- package/src/cli/pair-discord-cmd.js +7 -6
- package/src/cli/providers-cmd.js +3 -3
- package/src/cli/schedule-cmd.js +91 -40
- package/src/cli/server-cmd.js +54 -1
- package/src/cli/service-cmd.js +33 -10
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +162 -11
- package/src/cli/shell-cmd.js +7 -4
- package/src/cli/status-cmd.js +19 -5
- package/src/cli/tokens-cmd.js +4 -5
- package/src/cli/tunnel-cmd.js +255 -24
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1250 -126
- package/src/cli.js +8 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +1517 -81
- package/src/codex-bundled-client.js +66 -0
- package/src/codex-error-text.js +114 -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 +450 -27
- package/src/config-dir-migration.js +449 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +306 -26
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +78 -23
- 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 +227 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +7 -20
- package/src/control-room/skills-inventory.js +2 -2
- package/src/conversation-scanner.js +42 -39
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +28 -39
- package/src/credential-store.js +23 -19
- 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 +170 -182
- package/src/device-preferences.js +2 -2
- 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 +172 -3
- package/src/docker-session.js +294 -11
- package/src/doctor.js +781 -64
- package/src/durable-write.js +35 -0
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +101 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +31 -10
- package/src/environments/backends/k8s.js +49 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +118 -13
- package/src/event-normalizer.js +186 -235
- package/src/folder-trust-wire.js +137 -0
- package/src/folder-trust-worker.js +17 -0
- package/src/folder-trust.js +1572 -0
- package/src/freshness/activity-meter.js +101 -0
- package/src/freshness/adapter.js +199 -0
- package/src/freshness/checks.js +239 -0
- package/src/freshness/config.js +98 -0
- package/src/freshness/core.js +185 -0
- package/src/freshness/derive.js +680 -0
- package/src/freshness/exchange.js +305 -0
- package/src/freshness/file-ledger.js +400 -0
- package/src/freshness/grade.js +81 -0
- package/src/freshness/hash.js +45 -0
- package/src/freshness/inbox.js +163 -0
- package/src/freshness/index.js +20 -0
- package/src/freshness/investigation.js +474 -0
- package/src/freshness/keys.js +177 -0
- package/src/freshness/ledger.js +122 -0
- package/src/freshness/outbox.js +131 -0
- package/src/freshness/policy.js +599 -0
- package/src/freshness/queue.js +843 -0
- package/src/freshness/read-errors.js +23 -0
- package/src/freshness/render.js +153 -0
- package/src/freshness/runtime.js +113 -0
- package/src/freshness/session-registry-adapter.js +161 -0
- package/src/freshness/state-file-adapter.js +167 -0
- package/src/freshness-runner/build-info.js +139 -0
- package/src/freshness-runner/cli.js +105 -0
- package/src/freshness-runner/run-tick.js +109 -0
- package/src/freshness-runner/stamp.js +57 -0
- package/src/freshness-sources/claude-transcript-adapter.js +211 -0
- package/src/freshness-sources/codex-transcript-adapter.js +33 -0
- package/src/freshness-sources/index.js +8 -0
- package/src/gemini-byok-session.js +292 -0
- package/src/gemini-credentials.js +67 -0
- package/src/gemini-key-safety.js +246 -0
- package/src/gemini-models.js +386 -0
- package/src/gemini-session.js +81 -5
- package/src/handler-utils.js +540 -80
- package/src/handlers/checkpoint-handlers.js +47 -4
- package/src/handlers/control-room-handlers.js +51 -11
- package/src/handlers/conversation-handlers.js +469 -56
- 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 +57 -13
- package/src/handlers/folder-trust-handlers.js +90 -0
- package/src/handlers/input-handlers.js +714 -48
- package/src/handlers/orchestration-handlers.js +3 -3
- package/src/handlers/principal-admin-handlers.js +229 -0
- package/src/handlers/principal-handlers.js +262 -0
- package/src/handlers/scheduler-handlers.js +92 -18
- package/src/handlers/session-handlers.js +551 -20
- 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 +372 -50
- package/src/handlers/skills-handlers.js +20 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/health-proof.js +40 -0
- package/src/history-page.js +112 -0
- package/src/http-routes.js +127 -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 +378 -91
- package/src/jsonl-subprocess-session.js +96 -9
- package/src/keychain.js +1 -1
- package/src/logger.js +166 -30
- package/src/mailbox-route.js +113 -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 +27 -4
- 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 +64 -23
- 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 +9 -2
- package/src/orchestration/git-ops.js +41 -7
- package/src/orchestration/orchestration-manager.js +112 -36
- package/src/orchestration/permission-gate.js +17 -2
- package/src/orchestration/run-model.js +2 -1
- package/src/orchestration/run-record.js +11 -0
- package/src/orchestration/turn-driver.js +185 -43
- package/src/orphan-reaper.js +470 -0
- package/src/outgoing-policy.js +189 -0
- package/src/pairing.js +92 -13
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1410 -43
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +737 -89
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolved-by.js +89 -0
- package/src/permission-resolver.js +126 -8
- package/src/permission-scope.js +43 -0
- package/src/platform.js +315 -47
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/principal-audit.js +189 -0
- package/src/principal-binding.js +25 -0
- package/src/principal-brakes.js +21 -0
- package/src/principal-effect.js +101 -0
- package/src/principal-journal.js +905 -0
- package/src/principal-kill-switch.js +183 -0
- package/src/principal-label.js +5 -0
- package/src/principal-pending-permissions.js +177 -0
- package/src/principal-policy.js +1094 -0
- package/src/principal-sessions-snapshot.js +208 -0
- package/src/principal-store.js +488 -0
- package/src/principal-subscriptions.js +283 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +209 -4
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +531 -20
- package/src/roster-broadcast.js +186 -0
- package/src/scheduled-task-store.js +330 -26
- package/src/scheduler.js +368 -11
- package/src/sdk-session.js +2114 -188
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +17 -3
- package/src/server-cli/server-orchestrator.js +28 -5
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +553 -38
- package/src/server-identity.js +15 -11
- package/src/service.js +396 -25
- 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 +1099 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +4062 -312
- package/src/session-message-history.js +841 -16
- package/src/session-name-allocator.js +685 -0
- 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-token-store.js +17 -8
- 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 +2 -3
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +100 -29
- package/src/summarize-session.js +53 -4
- package/src/supervisor.js +22 -11
- 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/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +372 -25
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +34 -31
- package/src/tunnel/index.js +9 -0
- package/src/tunnel/preview.js +64 -0
- package/src/turn-outcome.js +140 -0
- package/src/usage-normalize.js +9 -5
- package/src/user-shell-session.js +59 -5
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +770 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +639 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +29 -0
- package/src/utils/bounded-regex.js +162 -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 +133 -37
- 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/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/pid-liveness.js +47 -0
- package/src/utils/preflight.js +360 -16
- 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 +189 -4
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-provenance.js +406 -13
- package/src/web-task-manager.js +297 -16
- package/src/worktree-gc.js +202 -6
- package/src/ws-auth.js +163 -31
- package/src/ws-broadcaster.js +49 -5
- package/src/ws-client-manager.js +24 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +363 -58
- package/src/ws-file-ops/common.js +320 -14
- package/src/ws-file-ops/git.js +395 -42
- package/src/ws-file-ops/index.js +2 -0
- package/src/ws-file-ops/memory.js +137 -35
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +571 -113
- package/src/ws-forwarding.js +349 -39
- package/src/ws-handler-context.js +88 -2
- package/src/ws-history.js +1010 -175
- package/src/ws-message-handlers.js +25 -1
- package/src/ws-permissions.js +307 -37
- package/src/ws-schemas.js +5 -0
- package/src/ws-server.js +885 -98
- package/sidecar/node_modules/.package-lock.json +0 -29
- package/sidecar/node_modules/ws/LICENSE +0 -20
- package/sidecar/node_modules/ws/README.md +0 -548
- package/sidecar/node_modules/ws/browser.js +0 -8
- package/sidecar/node_modules/ws/index.js +0 -22
- package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
- package/sidecar/node_modules/ws/lib/constants.js +0 -19
- package/sidecar/node_modules/ws/lib/event-target.js +0 -292
- package/sidecar/node_modules/ws/lib/extension.js +0 -203
- package/sidecar/node_modules/ws/lib/limiter.js +0 -55
- package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
- package/sidecar/node_modules/ws/lib/receiver.js +0 -706
- package/sidecar/node_modules/ws/lib/sender.js +0 -602
- package/sidecar/node_modules/ws/lib/stream.js +0 -161
- package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
- package/sidecar/node_modules/ws/lib/validation.js +0 -152
- package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
- package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
- package/sidecar/node_modules/ws/package.json +0 -70
- package/sidecar/node_modules/ws/wrapper.mjs +0 -21
- 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/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
package/src/scheduler.js
CHANGED
|
@@ -102,9 +102,11 @@
|
|
|
102
102
|
import { EventEmitter } from 'events'
|
|
103
103
|
import { createLogger } from './logger.js'
|
|
104
104
|
import { isSchedulerEnabled } from './config.js'
|
|
105
|
+
import { RESOLVED_BY } from './permission-resolved-by.js'
|
|
105
106
|
import { getProvider, listProviders, DEFAULT_PROVIDER } from './providers.js'
|
|
106
107
|
import { validateCwdAllowed } from './handler-utils.js'
|
|
107
108
|
import { TurnDriver, TurnError } from './orchestration/turn-driver.js'
|
|
109
|
+
import { busyStateOf } from './session-busy-state.js'
|
|
108
110
|
|
|
109
111
|
const log = createLogger('scheduler')
|
|
110
112
|
|
|
@@ -115,6 +117,16 @@ const log = createLogger('scheduler')
|
|
|
115
117
|
* know to poke us, and a large wall-clock jump (suspend/resume, NTP step) can
|
|
116
118
|
* never park us on a stale multi-day deadline.
|
|
117
119
|
*/
|
|
120
|
+
// #9242: consecutive fires skipped because the session was mid-turn before the task
|
|
121
|
+
// is declared stuck (error outcome + ownership released, so the next fire mints a fresh
|
|
122
|
+
// session and the stuck one stays inspectable). Count-based on purpose: it needs no
|
|
123
|
+
// notion of how long a turn legitimately runs, and 3 slots of a stuck turn is already
|
|
124
|
+
// a task that has silently not run for 3 cadences. It counts SLOTS, not elapsed time: a
|
|
125
|
+
// task on a long cadence is declared stuck only after 3 of its own slots (accepted).
|
|
126
|
+
export const BUSY_SKIP_LIMIT = 3
|
|
127
|
+
// A one-shot task skipped for a busy session is NOT retired; it is retried after this.
|
|
128
|
+
const DEFAULT_BUSY_RETRY_MS = 60_000
|
|
129
|
+
|
|
118
130
|
export const MAX_SLEEP_MS = 60 * 1000
|
|
119
131
|
|
|
120
132
|
/**
|
|
@@ -123,6 +135,7 @@ export const MAX_SLEEP_MS = 60 * 1000
|
|
|
123
135
|
* concurrency slot (and thus every other task) forever.
|
|
124
136
|
*/
|
|
125
137
|
export const DEFAULT_RUN_TIMEOUT_MS = 15 * 60 * 1000
|
|
138
|
+
const MAX_TIMER_MS = 2 ** 31 - 1
|
|
126
139
|
|
|
127
140
|
/**
|
|
128
141
|
* How late an overdue task may still be fired. A daemon that was down (laptop
|
|
@@ -228,6 +241,21 @@ class ScheduledRunRefusedError extends Error {
|
|
|
228
241
|
}
|
|
229
242
|
}
|
|
230
243
|
|
|
244
|
+
/**
|
|
245
|
+
* Thrown internally when a fire must NOT drive its session because a person is
|
|
246
|
+
* using it (#9242): mid-turn, or taken over since it was resolved. The caller turns
|
|
247
|
+
* it into a `skipped` outcome — the slot passes, nothing is sent, and the schedule
|
|
248
|
+
* advances to the next slot (no retry loop, no second session minted beside a
|
|
249
|
+
* session that is merely busy).
|
|
250
|
+
*/
|
|
251
|
+
class ScheduledRunSkippedError extends Error {
|
|
252
|
+
constructor(message, { busy = false } = {}) {
|
|
253
|
+
super(message)
|
|
254
|
+
this.name = 'ScheduledRunSkippedError'
|
|
255
|
+
this.busy = busy
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
231
259
|
/**
|
|
232
260
|
* The provider ids a scheduled task MAY currently target: every registered,
|
|
233
261
|
* non-hidden provider that answers permissions in-process. Derived from the
|
|
@@ -265,9 +293,19 @@ export function listSchedulableProviders(list = listProviders) {
|
|
|
265
293
|
*
|
|
266
294
|
* @param {string} providerName - the provider the run would actually use
|
|
267
295
|
* @param {(name: string) => Function} [getProviderClass=getProvider] - registry seam
|
|
296
|
+
* @param {string|null} daemonDefaultProvider - the daemon's RESOLVED default provider
|
|
297
|
+
* (`resolveDaemonDefaultProvider(config)` / the manager's `providerType`), NOT the
|
|
298
|
+
* compiled-in DEFAULT_PROVIDER: a daemon configured `provider: claude-tui` refuses
|
|
299
|
+
* provider-less tasks, and only the resolved value can say so (#8279). REQUIRED: `undefined`
|
|
300
|
+
* throws; `null` means no resolved default is known (no clause).
|
|
268
301
|
* @returns {string|null} refusal reason, or null when the provider is supported
|
|
269
302
|
*/
|
|
270
|
-
export function scheduledProviderRefusalReason(providerName, getProviderClass = getProvider) {
|
|
303
|
+
export function scheduledProviderRefusalReason(providerName, getProviderClass = getProvider, daemonDefaultProvider) {
|
|
304
|
+
// REQUIRED (null = "no resolved default known", no clause): an optional
|
|
305
|
+
// argument lets a caller silently lose the clause (#8279).
|
|
306
|
+
if (daemonDefaultProvider === undefined) {
|
|
307
|
+
throw new TypeError('scheduledProviderRefusalReason: daemonDefaultProvider is required (pass null when no resolved default is known)')
|
|
308
|
+
}
|
|
271
309
|
if (typeof providerName !== 'string' || providerName.length === 0) {
|
|
272
310
|
return 'no provider could be resolved for this scheduled task — refusing to fire an unattended run at an unknown provider'
|
|
273
311
|
}
|
|
@@ -281,7 +319,7 @@ export function scheduledProviderRefusalReason(providerName, getProviderClass =
|
|
|
281
319
|
// Kept under the 500-char cap _recordRefusal applies, so the #7003 pointer and
|
|
282
320
|
// the supported-provider list survive into the registry rather than being cut.
|
|
283
321
|
const supported = listSchedulableProviders()
|
|
284
|
-
const isDefault = providerName ===
|
|
322
|
+
const isDefault = typeof daemonDefaultProvider === 'string' && providerName === daemonDefaultProvider
|
|
285
323
|
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
324
|
}
|
|
287
325
|
|
|
@@ -356,6 +394,7 @@ export class SchedulerEngine extends EventEmitter {
|
|
|
356
394
|
runTimeoutMs = DEFAULT_RUN_TIMEOUT_MS,
|
|
357
395
|
overdueGraceMs = DEFAULT_OVERDUE_GRACE_MS,
|
|
358
396
|
maxSleepMs = MAX_SLEEP_MS,
|
|
397
|
+
busyRetryMs = DEFAULT_BUSY_RETRY_MS,
|
|
359
398
|
logger = log,
|
|
360
399
|
} = {}) {
|
|
361
400
|
super()
|
|
@@ -376,10 +415,21 @@ export class SchedulerEngine extends EventEmitter {
|
|
|
376
415
|
this._setTimer = setTimer
|
|
377
416
|
this._clearTimer = clearTimer
|
|
378
417
|
this._maxConcurrentRuns = Math.max(1, Math.floor(maxConcurrentRuns) || 1)
|
|
379
|
-
|
|
418
|
+
// Normalised: the value reaches setTimeout (the start wait, and TurnDriver's
|
|
419
|
+
// turn timer). null / 0 / NaN / negative would fire at once (TurnDriver treats
|
|
420
|
+
// a non-finite value as ITS default, never as "no timeout", and 0 as an
|
|
421
|
+
// immediate timeout), and > 2^31-1 overflows to ~0ms. Fall back to the default.
|
|
422
|
+
this._runTimeoutMs = (Number.isFinite(runTimeoutMs) && runTimeoutMs > 0 && runTimeoutMs <= MAX_TIMER_MS)
|
|
423
|
+
? runTimeoutMs
|
|
424
|
+
: DEFAULT_RUN_TIMEOUT_MS
|
|
380
425
|
this._overdueGraceMs = overdueGraceMs
|
|
381
426
|
this._maxSleepMs = Math.max(1, Math.floor(maxSleepMs) || MAX_SLEEP_MS)
|
|
427
|
+
this._busyRetryMs = Number.isFinite(busyRetryMs) && busyRetryMs >= 0 ? busyRetryMs : DEFAULT_BUSY_RETRY_MS
|
|
382
428
|
this._log = logger
|
|
429
|
+
/** @type {Map<string,number>} taskId -> consecutive busy-skips (#9242). */
|
|
430
|
+
this._busySkips = new Map()
|
|
431
|
+
/** @type {Map<string,number>} taskId -> epoch ms before which a busy-skipped one-shot is not retried. */
|
|
432
|
+
this._retryAt = new Map()
|
|
383
433
|
|
|
384
434
|
this._timer = null
|
|
385
435
|
this._started = false
|
|
@@ -388,6 +438,9 @@ export class SchedulerEngine extends EventEmitter {
|
|
|
388
438
|
this._running = new Set()
|
|
389
439
|
/** @type {Map<string,string>} taskId -> sessionId, so a recurring task RESUMES its session. */
|
|
390
440
|
this._sessionByTask = new Map()
|
|
441
|
+
// #9286: last-seen task names, so the notice can name a task that is already deleted.
|
|
442
|
+
this._taskNames = new Map()
|
|
443
|
+
this._staleModelWarned = new Set()
|
|
391
444
|
/**
|
|
392
445
|
* @type {Set<string>} task ids whose outcome could not be persisted. Recording
|
|
393
446
|
* the run is what advances nextRun, so a task we cannot record would stay
|
|
@@ -416,6 +469,11 @@ export class SchedulerEngine extends EventEmitter {
|
|
|
416
469
|
return new Set(this._running)
|
|
417
470
|
}
|
|
418
471
|
|
|
472
|
+
/** taskId -> sessionId for every task whose session is currently cached (test/observability aid). */
|
|
473
|
+
get scheduledSessionIds() {
|
|
474
|
+
return new Map(this._sessionByTask)
|
|
475
|
+
}
|
|
476
|
+
|
|
419
477
|
/**
|
|
420
478
|
* Task ids this process has quarantined (their outcome could not be persisted,
|
|
421
479
|
* so they have STOPPED firing until the daemon restarts). Part of the engine's
|
|
@@ -446,6 +504,7 @@ export class SchedulerEngine extends EventEmitter {
|
|
|
446
504
|
}
|
|
447
505
|
this._started = true
|
|
448
506
|
this._log.info('Scheduled execution ENABLED — arming headless scheduler')
|
|
507
|
+
this._adoptLinkedSessions()
|
|
449
508
|
this._armNextTick()
|
|
450
509
|
return true
|
|
451
510
|
}
|
|
@@ -499,6 +558,10 @@ export class SchedulerEngine extends EventEmitter {
|
|
|
499
558
|
_armNextTick() {
|
|
500
559
|
if (this._destroyed || !this._started) return
|
|
501
560
|
this._clearArmedTimer()
|
|
561
|
+
// Every registry change and every settled run funnels through here, so this
|
|
562
|
+
// is the one place that notices a task has gone away (#7006).
|
|
563
|
+
this._adoptLinkedSessions()
|
|
564
|
+
this._releaseSessions()
|
|
502
565
|
const now = this._now()
|
|
503
566
|
let earliest = null
|
|
504
567
|
// At capacity nothing new can start, and a shed task stays due — computing a
|
|
@@ -508,7 +571,8 @@ export class SchedulerEngine extends EventEmitter {
|
|
|
508
571
|
for (const task of this._store.list()) {
|
|
509
572
|
if (!task.enabled || !Number.isFinite(task.nextRun)) continue
|
|
510
573
|
if (this._running.has(task.id) || this._quarantined.has(task.id)) continue
|
|
511
|
-
|
|
574
|
+
const due = Math.max(task.nextRun, this._retryAt.get(task.id) ?? 0)
|
|
575
|
+
if (earliest === null || due < earliest) earliest = due
|
|
512
576
|
}
|
|
513
577
|
}
|
|
514
578
|
// Even with nothing scheduled we re-check on the max-sleep cadence, so a task
|
|
@@ -519,6 +583,156 @@ export class SchedulerEngine extends EventEmitter {
|
|
|
519
583
|
this._timer = this._setTimer(() => this._tick(), delay)
|
|
520
584
|
}
|
|
521
585
|
|
|
586
|
+
/**
|
|
587
|
+
* @private — end the session lifecycle of tasks that no longer exist (#7006).
|
|
588
|
+
* A recurring task keeps exactly ONE session between fires (see
|
|
589
|
+
* _runViaSessionManager); this is the other half — what happens when the task
|
|
590
|
+
* is deleted.
|
|
591
|
+
*
|
|
592
|
+
* Only REMOVAL (the task is gone from the store) ends the session: it is
|
|
593
|
+
* destroyed and the mapping dropped, so a deleted task no longer leaves a
|
|
594
|
+
* provider session running until the daemon exits. Never while the task's run
|
|
595
|
+
* is in flight — the turn is still using it — so it is skipped here and
|
|
596
|
+
* released by the pass that follows the run settling (_fire re-arms after every
|
|
597
|
+
* run).
|
|
598
|
+
*
|
|
599
|
+
* A task that is merely DISABLED, or a `once` task that retired (nextRun null),
|
|
600
|
+
* keeps its mapping and its session. Resume reuses the same session (dropping
|
|
601
|
+
* the mapping on pause would strand one session per pause/resume cycle), and
|
|
602
|
+
* the session still holds what the last run did. If such a task is deleted
|
|
603
|
+
* later, the pass above destroys its session.
|
|
604
|
+
*
|
|
605
|
+
* The mapping itself is in-memory, but the session's `scheduledTaskId` is
|
|
606
|
+
* persisted as a restore hint, so a restart re-adopts it (_adoptLinkedSessions,
|
|
607
|
+
* #8571) and a task deleted afterwards is released here like any other. Only an
|
|
608
|
+
* ADOPTED (mapped) session is closed; a task deleted while the daemon was down
|
|
609
|
+
* leaves its session as an ordinary one. Never throws: a failing destroy must not take
|
|
610
|
+
* the scheduling tick down.
|
|
611
|
+
*/
|
|
612
|
+
_releaseSessions() {
|
|
613
|
+
for (const [taskId, sessionId] of [...this._sessionByTask]) {
|
|
614
|
+
if (this._store.get(taskId)) continue
|
|
615
|
+
if (this._running.has(taskId)) continue
|
|
616
|
+
this._sessionByTask.delete(taskId)
|
|
617
|
+
const taskName = this._taskNames.get(taskId)
|
|
618
|
+
this._taskNames.delete(taskId)
|
|
619
|
+
this._destroyTaskSession(taskId, sessionId, taskName)
|
|
620
|
+
}
|
|
621
|
+
for (const map of [this._busySkips, this._retryAt]) {
|
|
622
|
+
for (const id of [...map.keys()]) if (!this._store.get(id)) map.delete(id)
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/**
|
|
627
|
+
* @private (#8571) — adopt restored sessions into the task->session map. The
|
|
628
|
+
* persisted `scheduledTaskId` is only a restore HINT: the SessionManager holds it
|
|
629
|
+
* inert until this pass takes ownership of the session (which is what makes it
|
|
630
|
+
* `automation_owned`). For every task in the store with no LIVE mapped session, the
|
|
631
|
+
* most recently active live session linked to it (owned or hinted; ties: highest
|
|
632
|
+
* session id) is adopted and mapped. Run on start, on every re-arm (so a session
|
|
633
|
+
* that came back late — retryFailedRestore, an archive restore — is picked up)
|
|
634
|
+
* and before a fire creates a session. Idempotent and cheap; never throws.
|
|
635
|
+
*
|
|
636
|
+
* It NEVER unlinks or destroys. A task absent from the store is not evidence of a
|
|
637
|
+
* deletion (the store loads EMPTY when its file is unreadable), so sessions linked
|
|
638
|
+
* to an absent task, and non-chosen duplicates, keep their inert hint. A task
|
|
639
|
+
* deleted while the daemon was down therefore leaves its session as an ordinary
|
|
640
|
+
* one; only a session adopted in this process is closed on deletion
|
|
641
|
+
* (_releaseSessions): an adopted session belongs to its task, so deleting the task
|
|
642
|
+
* closes it and its worktree. A person typing into a session that still carries only
|
|
643
|
+
* a hint releases the hint (SessionManager.releaseRestoreHint), so a duplicate the
|
|
644
|
+
* user took over is never adopted later. An archive restore of a scheduled session
|
|
645
|
+
* comes back through restore and is re-adopted the same way.
|
|
646
|
+
* Sessions dropped by restore's staleness filter cannot be
|
|
647
|
+
* re-adopted, so a long-cadence task may still get a fresh session.
|
|
648
|
+
*
|
|
649
|
+
* @param {string} [onlyTaskId] - restrict the pass to one task
|
|
650
|
+
*/
|
|
651
|
+
_adoptLinkedSessions(onlyTaskId) {
|
|
652
|
+
try {
|
|
653
|
+
if (typeof this._sm?.listScheduledTaskSessions !== 'function') return
|
|
654
|
+
const linked = this._sm.listScheduledTaskSessions()
|
|
655
|
+
const tasks = onlyTaskId !== undefined
|
|
656
|
+
? [this._store.get(onlyTaskId)].filter(Boolean)
|
|
657
|
+
: this._store.list()
|
|
658
|
+
for (const task of tasks) {
|
|
659
|
+
if (typeof task.name === 'string' && task.name) this._taskNames.set(task.id, task.name)
|
|
660
|
+
const mapped = this._sessionByTask.get(task.id)
|
|
661
|
+
if (mapped) {
|
|
662
|
+
if (this._sm.getSession?.(mapped)?.session) {
|
|
663
|
+
// Live. Reassert OWNERSHIP: a session retried after a start failure comes
|
|
664
|
+
// back on the same id carrying only the hint, and the map alone would
|
|
665
|
+
// leave it driven without the `automation_owned` blocker. A session that
|
|
666
|
+
// is neither owned nor hinted any more (a person used it) cannot be
|
|
667
|
+
// reasserted, so it is dropped rather than driven.
|
|
668
|
+
if (typeof this._sm.adoptScheduledTask !== 'function' || this._sm.adoptScheduledTask(mapped, task.id)) continue
|
|
669
|
+
}
|
|
670
|
+
this._sessionByTask.delete(task.id)
|
|
671
|
+
}
|
|
672
|
+
// Owned beats hinted, then most recent activity, then highest id.
|
|
673
|
+
let best = null
|
|
674
|
+
for (const s of linked) {
|
|
675
|
+
if (s.taskId !== task.id) continue
|
|
676
|
+
if (!best
|
|
677
|
+
|| (s.owned !== best.owned ? s.owned
|
|
678
|
+
: s.lastActivityAt !== best.lastActivityAt ? s.lastActivityAt > best.lastActivityAt
|
|
679
|
+
: s.sessionId > best.sessionId)) {
|
|
680
|
+
best = s
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
if (!best) continue
|
|
684
|
+
if (this._sm.adoptScheduledTask?.(best.sessionId, task.id)) {
|
|
685
|
+
this._sessionByTask.set(task.id, best.sessionId)
|
|
686
|
+
this._log.info(`Adopted session ${best.sessionId} as the session of scheduled task ${task.id}`)
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
} catch (err) {
|
|
690
|
+
this._log.warn(`Could not adopt restored scheduled sessions: ${err?.message || err}`)
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
/** @private — destroy a removed task's session if it is still alive; never throws. */
|
|
695
|
+
_destroyTaskSession(taskId, sessionId, taskName) {
|
|
696
|
+
const warn = (err) => {
|
|
697
|
+
this._log.warn(`Could not destroy the session of removed scheduled task ${taskId}: ${err?.message || err}`)
|
|
698
|
+
}
|
|
699
|
+
try {
|
|
700
|
+
// Already gone (the operator closed it, or a teardown is in progress).
|
|
701
|
+
if (!this._sm?.getSession?.(sessionId)) return
|
|
702
|
+
// #9242: only a session this task STILL owns is the task's to close. One a
|
|
703
|
+
// person took over (ownership released) is an ordinary session now, whether
|
|
704
|
+
// or not the adoption pass has noticed yet.
|
|
705
|
+
if (typeof this._sm.ownsScheduledTask === 'function' && !this._sm.ownsScheduledTask(sessionId, taskId)) {
|
|
706
|
+
this._log.info(`Scheduled task ${taskId} was removed — leaving its session ${sessionId} open (no longer owned by the task)`)
|
|
707
|
+
return
|
|
708
|
+
}
|
|
709
|
+
// #9242: and never take work with it. A worktree with uncommitted changes (or
|
|
710
|
+
// commits nothing else reaches), or one whose state cannot be read, is KEPT:
|
|
711
|
+
// the session is released to an ordinary one and the person decides.
|
|
712
|
+
const unsaved = typeof this._sm.unsavedWorktreeWork === 'function'
|
|
713
|
+
? this._sm.unsavedWorktreeWork(sessionId)
|
|
714
|
+
: (typeof this._sm.hasUnsavedWorktreeWork === 'function' && this._sm.hasUnsavedWorktreeWork(sessionId)
|
|
715
|
+
? { has: true, kinds: [], samples: {} }
|
|
716
|
+
: null)
|
|
717
|
+
if (unsaved?.has) {
|
|
718
|
+
this._sm.releaseScheduledOwnership?.(sessionId, taskId)
|
|
719
|
+
// #9286: say so in the session itself; the log line alone is invisible to the person.
|
|
720
|
+
// The release and the note are two flushes: a crash between them keeps the session
|
|
721
|
+
// without a note (cosmetic), and a retry cannot duplicate the note.
|
|
722
|
+
this._sm.noteScheduledSessionKept?.(sessionId, taskId, unsaved, taskName)
|
|
723
|
+
this._log.warn(`Scheduled task ${taskId} was removed — keeping its session ${sessionId} open: its worktree has unsaved work (uncommitted changes, unreachable commits, or an unreadable status). It is an ordinary session now; close it yourself once the work is safe.`)
|
|
724
|
+
return
|
|
725
|
+
}
|
|
726
|
+
this._log.info(`Scheduled task ${taskId} was removed — closing its session ${sessionId}`)
|
|
727
|
+
const pending = typeof this._sm.destroySessionLocked === 'function'
|
|
728
|
+
? this._sm.destroySessionLocked(sessionId)
|
|
729
|
+
: this._sm.destroySession?.(sessionId)
|
|
730
|
+
if (pending && typeof pending.catch === 'function') pending.catch(warn)
|
|
731
|
+
} catch (err) {
|
|
732
|
+
warn(err)
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
|
|
522
736
|
/**
|
|
523
737
|
* @private — one evaluation pass: fire everything due (under the concurrency
|
|
524
738
|
* cap), then re-arm. Never throws; a per-task failure is recorded and the pass
|
|
@@ -563,7 +777,8 @@ export class SchedulerEngine extends EventEmitter {
|
|
|
563
777
|
return this._store
|
|
564
778
|
.list()
|
|
565
779
|
.filter((t) => t.enabled && Number.isFinite(t.nextRun) && t.nextRun <= now
|
|
566
|
-
&& !this._running.has(t.id) && !this._quarantined.has(t.id)
|
|
780
|
+
&& !this._running.has(t.id) && !this._quarantined.has(t.id)
|
|
781
|
+
&& !((this._retryAt.get(t.id) ?? 0) > now))
|
|
567
782
|
.sort((a, b) => a.nextRun - b.nextRun)
|
|
568
783
|
}
|
|
569
784
|
|
|
@@ -619,6 +834,17 @@ export class SchedulerEngine extends EventEmitter {
|
|
|
619
834
|
}
|
|
620
835
|
|
|
621
836
|
const status = outcome?.status
|
|
837
|
+
// #9242: a one-shot task skipped because its session was busy has not run, and
|
|
838
|
+
// recording the skip would retire it. Leave it unrecorded (still due) and retry
|
|
839
|
+
// after a delay so it cannot spin; the overdue grace bounds how long it keeps trying.
|
|
840
|
+
if (outcome?.busy === true && status === 'skipped' && task.cadence?.kind === 'once') {
|
|
841
|
+
const delay = outcome.retryNow === true ? 0 : this._busyRetryMs
|
|
842
|
+
this._retryAt.set(task.id, this._now() + delay)
|
|
843
|
+
this._log.warn(`Scheduled one-shot task ${task.id} not run: ${outcome.error} — retrying in ${delay}ms`)
|
|
844
|
+
this.emit('run-end', { taskId: task.id, at, status: 'skipped', ...(outcome.sessionId ? { sessionId: outcome.sessionId } : {}), error: String(outcome.error).slice(0, 500) })
|
|
845
|
+
this._armNextTick()
|
|
846
|
+
return
|
|
847
|
+
}
|
|
622
848
|
const result = {
|
|
623
849
|
at,
|
|
624
850
|
status: PASSTHROUGH_STATUSES.has(status) ? status : 'error',
|
|
@@ -626,6 +852,7 @@ export class SchedulerEngine extends EventEmitter {
|
|
|
626
852
|
...(outcome?.error ? { error: String(outcome.error).slice(0, 500) } : {}),
|
|
627
853
|
}
|
|
628
854
|
this._recordRun(task, result)
|
|
855
|
+
this._retryAt.delete(task.id) // an outcome is recorded: any busy-retry hold is over
|
|
629
856
|
this.emit('run-end', { taskId: task.id, ...result })
|
|
630
857
|
if (result.status === 'success') {
|
|
631
858
|
this._log.info(`Scheduled task ${task.id} completed`)
|
|
@@ -644,7 +871,11 @@ export class SchedulerEngine extends EventEmitter {
|
|
|
644
871
|
*/
|
|
645
872
|
_preflightRefusal(task) {
|
|
646
873
|
// (a) Can we actually govern this provider's permission prompts? (#7003)
|
|
647
|
-
const providerRefusal = scheduledProviderRefusalReason(
|
|
874
|
+
const providerRefusal = scheduledProviderRefusalReason(
|
|
875
|
+
this._resolveProviderName(task),
|
|
876
|
+
this._getProviderClass,
|
|
877
|
+
this._resolveProviderName({}),
|
|
878
|
+
)
|
|
648
879
|
if (providerRefusal) return providerRefusal
|
|
649
880
|
|
|
650
881
|
// (b) Is the cwd one a session may be created in at all? The registry is a
|
|
@@ -762,8 +993,16 @@ export class SchedulerEngine extends EventEmitter {
|
|
|
762
993
|
* task to ONE session instead of one per fire, keeps the recorded `sessionId`
|
|
763
994
|
* meaningful (the operator can open it and read what the run actually did), and
|
|
764
995
|
* gives a recurring task continuity across runs. Sessions are NOT auto-destroyed
|
|
765
|
-
*
|
|
766
|
-
*
|
|
996
|
+
* after a run — they are ordinary sessions the operator can inspect and close.
|
|
997
|
+
* A task keeps one session between fires while NOBODY ELSE uses it. The mapping
|
|
998
|
+
* is bounded by the number of tasks, but the SESSIONS are not: a person using the
|
|
999
|
+
* task's session (typing, answering a question, restoring files) releases it to an
|
|
1000
|
+
* ordinary session, and a stuck-busy one is released after BUSY_SKIP_LIMIT skips
|
|
1001
|
+
* (#9242); the next fire then mints a fresh session, so one task can leave one
|
|
1002
|
+
* ordinary session per takeover. There is no idle reap and no cap. (A restart
|
|
1003
|
+
* re-adopts the owned session, #8571.) The session ends when the task is DELETED
|
|
1004
|
+
* and still owns it with no unsaved worktree work: see _releaseSessions (#7006).
|
|
1005
|
+
* Pausing, resuming or retiring a task leaves it be.
|
|
767
1006
|
*
|
|
768
1007
|
* Because they are ordinary sessions, the operator can also change their
|
|
769
1008
|
* permission mode. That makes reuse an escalation vector, so the clamped mode is
|
|
@@ -780,10 +1019,21 @@ export class SchedulerEngine extends EventEmitter {
|
|
|
780
1019
|
sessionId = this._resolveSession(task, ctx)
|
|
781
1020
|
} catch (err) {
|
|
782
1021
|
if (err instanceof ScheduledRunRefusedError) return { status: REFUSED_STATUS, error: err.message }
|
|
1022
|
+
if (err instanceof ScheduledRunSkippedError) return this._skipOutcome(task, err, undefined)
|
|
783
1023
|
return { status: 'error', error: `session create failed: ${err?.message || err}` }
|
|
784
1024
|
}
|
|
785
1025
|
if (!sessionId) return { status: 'error', error: 'session create failed (no sessionId)' }
|
|
786
1026
|
|
|
1027
|
+
// #9245: a session whose provider start() is still in flight (a fresh one, or
|
|
1028
|
+
// a restored one) is not ready for input yet — BYOK's sendMessage rejects
|
|
1029
|
+
// 'Session not ready' until start() resolves (it sets _processReady and emits
|
|
1030
|
+
// 'ready' before resolving, byok-session.js start()). Take the settle handle
|
|
1031
|
+
// SYNCHRONOUSLY, before any await (the manager drops a failed start from
|
|
1032
|
+
// _sessions), and await it below. A settled or sync-start session resolves
|
|
1033
|
+
// immediately, so a reused session is never delayed.
|
|
1034
|
+
const waitStartedAt = Date.now()
|
|
1035
|
+
const startWait = this._sm.awaitSessionStart?.(sessionId, ctx.runTimeoutMs)
|
|
1036
|
+
|
|
787
1037
|
// Register as an OWNED run before the turn starts, so the permission answerer
|
|
788
1038
|
// is armed for the very first tool call.
|
|
789
1039
|
const runState = { taskId: task.id, blocked: null }
|
|
@@ -791,10 +1041,33 @@ export class SchedulerEngine extends EventEmitter {
|
|
|
791
1041
|
this._attachPermissionListener()
|
|
792
1042
|
|
|
793
1043
|
try {
|
|
1044
|
+
if (startWait) {
|
|
1045
|
+
// Bound: runTimeoutMs, the run's own budget. The manager already fails a
|
|
1046
|
+
// start at its provider deadline (60s default, START_TIMEOUT), so this
|
|
1047
|
+
// bound only matters for providers that declare no start deadline; it
|
|
1048
|
+
// is never longer than the run is allowed to take.
|
|
1049
|
+
const started = await startWait
|
|
1050
|
+
if (!started.ok) {
|
|
1051
|
+
return { status: 'error', sessionId, error: `session ${sessionId} did not finish starting: ${started.error?.message || started.error || 'start failed'}` }
|
|
1052
|
+
}
|
|
1053
|
+
if (started.pending) {
|
|
1054
|
+
return { status: 'error', sessionId, error: `session ${sessionId} did not finish starting within ${ctx.runTimeoutMs}ms` }
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
// #9242: the start wait is an await — a person may have taken the session over
|
|
1058
|
+
// (or started a turn in it) meanwhile. Judge again, right before the send.
|
|
1059
|
+
this._assertDrivable(task, sessionId)
|
|
1060
|
+
this._busySkips.delete(task.id) // reached dispatch: not stuck
|
|
794
1061
|
const driver = this._ensureTurnDriver()
|
|
1062
|
+
// The start wait spends part of the run budget: the turn gets the REMAINDER,
|
|
1063
|
+
// so `timeout` keeps meaning total run time (floored so it stays a valid timer).
|
|
1064
|
+
const remainingMs = Math.max(1, ctx.runTimeoutMs - (Date.now() - waitStartedAt))
|
|
795
1065
|
await driver.driveTurn(sessionId, task.prompt, {
|
|
796
1066
|
label: `scheduled:${task.id}`,
|
|
797
|
-
timeoutMs:
|
|
1067
|
+
timeoutMs: remainingMs,
|
|
1068
|
+
// #9242: asked again at dispatch (after the mutex, and at a provider's queue
|
|
1069
|
+
// flush): the person may have taken the session over since the check above.
|
|
1070
|
+
admit: () => !(typeof this._sm.ownsScheduledTask === 'function') || this._sm.ownsScheduledTask(sessionId, task.id),
|
|
798
1071
|
})
|
|
799
1072
|
// `success` is the NARROWEST outcome, asserted positively: the turn
|
|
800
1073
|
// completed AND no permission prompt was ever raised on this run. Any
|
|
@@ -808,6 +1081,7 @@ export class SchedulerEngine extends EventEmitter {
|
|
|
808
1081
|
if (runState.blocked) return this._blockedOutcome(runState, sessionId)
|
|
809
1082
|
return { status: 'success', sessionId }
|
|
810
1083
|
} catch (err) {
|
|
1084
|
+
if (err instanceof ScheduledRunSkippedError) return this._skipOutcome(task, err, sessionId)
|
|
811
1085
|
// ORDER IS LOAD-BEARING. `runState.blocked` is checked FIRST, ahead of the
|
|
812
1086
|
// TURN_STOPPED arm below, because the engine's own deny path reaches this
|
|
813
1087
|
// catch through exactly the same rejection: it answers `deny`, interrupts
|
|
@@ -816,6 +1090,9 @@ export class SchedulerEngine extends EventEmitter {
|
|
|
816
1090
|
// keep the `error` status it has always had. Only an interrupt with NO
|
|
817
1091
|
// permission activity is the benign operator Stop.
|
|
818
1092
|
if (runState.blocked) return this._blockedOutcome(runState, sessionId)
|
|
1093
|
+
if (err instanceof TurnError && err.code === 'NOT_ADMITTED') {
|
|
1094
|
+
return { status: 'skipped', sessionId, error: `session ${sessionId} was taken over before the scheduled prompt was dispatched — it was not sent` }
|
|
1095
|
+
}
|
|
819
1096
|
if (err instanceof TurnError && err.code === 'TURN_TIMEOUT') {
|
|
820
1097
|
return { status: 'timeout', sessionId, error: `run exceeded ${ctx.runTimeoutMs}ms` }
|
|
821
1098
|
}
|
|
@@ -832,6 +1109,46 @@ export class SchedulerEngine extends EventEmitter {
|
|
|
832
1109
|
}
|
|
833
1110
|
}
|
|
834
1111
|
|
|
1112
|
+
/**
|
|
1113
|
+
* @private (#9242) — the outcome of a fire that declined to drive its session. A
|
|
1114
|
+
* takeover is a plain `skipped`. A BUSY session is `skipped` too, up to
|
|
1115
|
+
* BUSY_SKIP_LIMIT fires in a row; past that the task is stuck behind a session that
|
|
1116
|
+
* never goes idle, so the outcome becomes a visible `error` and the session is
|
|
1117
|
+
* released to an ordinary one (still there to inspect) so the next fire mints a fresh
|
|
1118
|
+
* session instead of being skipped forever.
|
|
1119
|
+
*/
|
|
1120
|
+
_skipOutcome(task, err, sessionId) {
|
|
1121
|
+
if (!err.busy) {
|
|
1122
|
+
this._busySkips.delete(task.id)
|
|
1123
|
+
return { status: 'skipped', ...(sessionId ? { sessionId } : {}), error: err.message }
|
|
1124
|
+
}
|
|
1125
|
+
const n = (this._busySkips.get(task.id) ?? 0) + 1
|
|
1126
|
+
if (n < BUSY_SKIP_LIMIT) {
|
|
1127
|
+
this._busySkips.set(task.id, n)
|
|
1128
|
+
return { status: 'skipped', busy: true, ...(sessionId ? { sessionId } : {}), error: err.message }
|
|
1129
|
+
}
|
|
1130
|
+
this._busySkips.delete(task.id)
|
|
1131
|
+
const stuck = this._sessionByTask.get(task.id)
|
|
1132
|
+
if (stuck) {
|
|
1133
|
+
this._sm.releaseScheduledOwnership?.(stuck, task.id)
|
|
1134
|
+
this._sessionByTask.delete(task.id)
|
|
1135
|
+
}
|
|
1136
|
+
// A one-shot task has no later slot: recording an error would retire it unrun. The
|
|
1137
|
+
// stuck session is released as above and the task runs in a FRESH one at the next tick.
|
|
1138
|
+
if (task.cadence?.kind === 'once') {
|
|
1139
|
+
return {
|
|
1140
|
+
status: 'skipped', busy: true, retryNow: true,
|
|
1141
|
+
...(stuck ? { sessionId: stuck } : {}),
|
|
1142
|
+
error: `session ${stuck ?? ''} has been busy for ${n} consecutive attempts — it was released (it stays open to inspect) and this one-shot task will run in a fresh session`,
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
return {
|
|
1146
|
+
status: 'error',
|
|
1147
|
+
...(stuck ? { sessionId: stuck } : {}),
|
|
1148
|
+
error: `session ${stuck ?? ''} has been busy for ${n} consecutive scheduled fires — the task has not run; the session was released (it stays open to inspect) and the next fire starts a fresh one`,
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
|
|
835
1152
|
/** @private — the permission-blocked outcome (a visible failure, never silent). */
|
|
836
1153
|
_blockedOutcome(runState, sessionId) {
|
|
837
1154
|
return {
|
|
@@ -848,10 +1165,18 @@ export class SchedulerEngine extends EventEmitter {
|
|
|
848
1165
|
* verified. A session that cannot be brought to the clamped mode is refused.
|
|
849
1166
|
*/
|
|
850
1167
|
_resolveSession(task, ctx) {
|
|
1168
|
+
// Adopt (or reassert ownership of) a linked session before minting a fresh one:
|
|
1169
|
+
// it may have been restored late, or come back on its id after a start failure.
|
|
1170
|
+
// Idempotent; drops a dead or no-longer-owned mapping (#8571).
|
|
1171
|
+
this._adoptLinkedSessions(task.id)
|
|
851
1172
|
const existing = this._sessionByTask.get(task.id)
|
|
852
1173
|
if (existing) {
|
|
853
1174
|
const entry = this._sm.getSession?.(existing)
|
|
854
1175
|
if (entry?.session) {
|
|
1176
|
+
// #9242: never drive into a session a person is in the middle of using.
|
|
1177
|
+
// BEFORE the mode assert, which would otherwise mutate (or refuse) a busy
|
|
1178
|
+
// session's permission mode for a run that is not going to happen.
|
|
1179
|
+
this._assertDrivable(task, existing)
|
|
855
1180
|
// THE ESCALATION VECTOR (#6997 review C3): scheduled sessions are kept
|
|
856
1181
|
// alive and reused, and an operator can flip any session to `auto` from
|
|
857
1182
|
// the dashboard — even mid-turn. Without re-asserting here, one manual
|
|
@@ -870,7 +1195,7 @@ export class SchedulerEngine extends EventEmitter {
|
|
|
870
1195
|
name: task.name || `Scheduled: ${task.id.slice(0, 8)}`,
|
|
871
1196
|
...(target.cwd ? { cwd: target.cwd } : {}),
|
|
872
1197
|
...(target.provider ? { provider: target.provider } : {}),
|
|
873
|
-
...(target.model ? { model: target.model } : {}),
|
|
1198
|
+
...(target.model ? { model: target.model, modelSource: 'replay' } : {}),
|
|
874
1199
|
// The clamped floor — never the task's raw value (see resolveScheduledPermissionMode).
|
|
875
1200
|
permissionMode: ctx.permissionMode,
|
|
876
1201
|
// EXPLICIT false so an unattended run can never inherit the server-wide
|
|
@@ -881,11 +1206,42 @@ export class SchedulerEngine extends EventEmitter {
|
|
|
881
1206
|
// Trust nothing: verify the freshly-created session really came up at the
|
|
882
1207
|
// clamped mode rather than assuming createSession honoured the option.
|
|
883
1208
|
const created = this._sm.getSession?.(sessionId)
|
|
1209
|
+
// #7855: a saved model id that is no longer usable runs on the default instead of
|
|
1210
|
+
// failing every fire; say so once per task, naming it, so the owner can fix it.
|
|
1211
|
+
if (target.model && created?.session && (created.session.model ?? null) !== target.model
|
|
1212
|
+
&& !this._staleModelWarned.has(task.id)) {
|
|
1213
|
+
this._staleModelWarned.add(task.id)
|
|
1214
|
+
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.`)
|
|
1215
|
+
}
|
|
884
1216
|
if (created?.session) this._assertPermissionMode(created.session, ctx.permissionMode, sessionId)
|
|
885
1217
|
this._sessionByTask.set(task.id, sessionId)
|
|
1218
|
+
if (typeof task.name === 'string' && task.name) this._taskNames.set(task.id, task.name)
|
|
886
1219
|
return sessionId
|
|
887
1220
|
}
|
|
888
1221
|
|
|
1222
|
+
/**
|
|
1223
|
+
* @private (#9242) — a scheduled run only ever drives a session that is STILL the
|
|
1224
|
+
* task's and is NOT mid-turn. Ownership is released the moment a person sends
|
|
1225
|
+
* input (SessionManager.recordUserIntent), so a released session is never
|
|
1226
|
+
* driven; a mid-turn one (a person's turn, or the task's own previous run still
|
|
1227
|
+
* going after a timeout) would interleave the prompt with that turn, so the fire
|
|
1228
|
+
* is skipped instead. Only a mid-turn session blocks: one idle but held busy by
|
|
1229
|
+
* background shells is not in the middle of anything (busyReason 'turn').
|
|
1230
|
+
* A manager without the ownership API (a stub) is trusted as before.
|
|
1231
|
+
*
|
|
1232
|
+
* @throws {ScheduledRunSkippedError}
|
|
1233
|
+
*/
|
|
1234
|
+
_assertDrivable(task, sessionId) {
|
|
1235
|
+
if (typeof this._sm.ownsScheduledTask === 'function' && !this._sm.ownsScheduledTask(sessionId, task.id)) {
|
|
1236
|
+
this._sessionByTask.delete(task.id)
|
|
1237
|
+
throw new ScheduledRunSkippedError(`session ${sessionId} is no longer owned by this task (a person took it over) — not driving it`)
|
|
1238
|
+
}
|
|
1239
|
+
const session = this._sm.getSession?.(sessionId)?.session
|
|
1240
|
+
if (session && busyStateOf(session).busyReason === 'turn') {
|
|
1241
|
+
throw new ScheduledRunSkippedError(`session ${sessionId} is busy (a turn is in progress) — not driving a scheduled prompt into it; the next slot will run`, { busy: true })
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
1244
|
+
|
|
889
1245
|
/**
|
|
890
1246
|
* @private — force `mode` onto a session and PROVE it took, or throw. The
|
|
891
1247
|
* invariant this exists to hold: **a scheduled fire runs at the clamped mode,
|
|
@@ -983,7 +1339,8 @@ export class SchedulerEngine extends EventEmitter {
|
|
|
983
1339
|
if (!session) return
|
|
984
1340
|
if (typeof session.respondToPermission === 'function') {
|
|
985
1341
|
try {
|
|
986
|
-
|
|
1342
|
+
// #9119: nobody was there to ask; the daemon cleared it. Never a person.
|
|
1343
|
+
session.respondToPermission(requestId, 'deny', undefined, undefined, undefined, RESOLVED_BY.cleared)
|
|
987
1344
|
} catch (err) {
|
|
988
1345
|
this._log.warn(`Scheduler permission deny failed for ${sessionId}: ${err?.message || err}`)
|
|
989
1346
|
}
|