@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
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { getRegisteredProviderNames } from './providers.js'
|
|
2
|
+
import { isClaudeProvider, usesDefaultModelsRegistry, resolveRosterProvider } from './models.js'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* #7722 — the provider a client is currently looking at, or null when it has no
|
|
6
|
+
* active session. Null is NOT an error signal: it is the "no session yet" case,
|
|
7
|
+
* which `overlayBroadcastReachesProvider` routes to the default roster exactly
|
|
8
|
+
* as the pre-#7722 broadcast did.
|
|
9
|
+
*
|
|
10
|
+
* Deliberately fail-OPEN toward that default: a session lookup that throws (or a
|
|
11
|
+
* SessionManager torn down mid-reload) yields null, so the client still receives
|
|
12
|
+
* the Claude roster it would have received before this change rather than
|
|
13
|
+
* silently receiving nothing.
|
|
14
|
+
*
|
|
15
|
+
* @param {{ activeSessionId?: string|null }} client
|
|
16
|
+
* @param {{ getSession?: (id: string) => ({ provider?: string|null }|undefined) }} sessionManager
|
|
17
|
+
* @returns {string|null}
|
|
18
|
+
*/
|
|
19
|
+
export function clientActiveProvider(client, sessionManager) {
|
|
20
|
+
try {
|
|
21
|
+
const sessionId = client?.activeSessionId
|
|
22
|
+
if (!sessionId) return null
|
|
23
|
+
return sessionManager?.getSession?.(sessionId)?.provider || null
|
|
24
|
+
} catch {
|
|
25
|
+
return null
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* #7722 — the recipient rule for ONE `available_models` roster broadcast: does
|
|
31
|
+
* a client whose ACTIVE session runs `activeProvider` receive this message?
|
|
32
|
+
*
|
|
33
|
+
* The rule:
|
|
34
|
+
* - the DEFAULT (Claude) roster reaches every client whose active provider
|
|
35
|
+
* shares the default registry — Claude-family, an unknown/unregistered
|
|
36
|
+
* name, and no active session at all.
|
|
37
|
+
* - every other tag names a PER-PROVIDER registry, and those are keyed by
|
|
38
|
+
* name (`providerRegistryCache`), so only that exact provider matches.
|
|
39
|
+
*
|
|
40
|
+
* `usesDefaultModelsRegistry` is imported rather than re-derived: it is the same
|
|
41
|
+
* predicate `reloadModelsOverlay` uses to decide which rosters are worth
|
|
42
|
+
* reporting, and a second copy here would be free to disagree about the
|
|
43
|
+
* unknown-name and docker-* edges that motivate it.
|
|
44
|
+
*
|
|
45
|
+
* A throw resolves to the default roster (fail-open) — see `clientActiveProvider`'s
|
|
46
|
+
* docstring for why: `WsBroadcaster._broadcast`'s filter SKIPS a client whose
|
|
47
|
+
* filter threw, which would deliver *nothing* to a client that received the
|
|
48
|
+
* `claude-sdk` roster before #7722.
|
|
49
|
+
*
|
|
50
|
+
* @param {{ provider?: string|null }} message one roster broadcast (this
|
|
51
|
+
* module's `message` shape, or one entry from `buildOverlayReloadBroadcasts`)
|
|
52
|
+
* @param {string|null|undefined} activeProvider the client's active session provider
|
|
53
|
+
* @param {boolean} [tagIsDefault] precomputed `usesDefaultModelsRegistry(message.provider)`.
|
|
54
|
+
* Omit it and the same value is derived here — callers that route many clients
|
|
55
|
+
* through one message pass it so the tag is resolved once.
|
|
56
|
+
* @returns {boolean}
|
|
57
|
+
*/
|
|
58
|
+
export function overlayBroadcastReachesProvider(message, activeProvider, tagIsDefault) {
|
|
59
|
+
const tag = message?.provider ?? null
|
|
60
|
+
const isDefaultTag = tagIsDefault === undefined ? usesDefaultModelsRegistry(tag) : tagIsDefault
|
|
61
|
+
if (!isDefaultTag) return activeProvider === tag
|
|
62
|
+
try {
|
|
63
|
+
return usesDefaultModelsRegistry(activeProvider)
|
|
64
|
+
} catch {
|
|
65
|
+
// Fail OPEN toward the default roster — see the paragraph above.
|
|
66
|
+
return true
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* #7895 — the single per-recipient tagging routine for an `available_models`
|
|
72
|
+
* roster broadcast.
|
|
73
|
+
*
|
|
74
|
+
* #7756's `createOverlayReloadBroadcaster` (server-cli.js) first solved this
|
|
75
|
+
* for the models-overlay hot-reload path: `claude-sdk`, `claude-cli`,
|
|
76
|
+
* `claude-tui` and `claude-byok` all share ONE registry, so
|
|
77
|
+
* `overlayBroadcastReachesProvider` correctly decides all four should receive
|
|
78
|
+
* a default-registry roster — but the client keys each roster by the EXACT tag
|
|
79
|
+
* it arrived under (`modelsByProvider`, store-core/src/models-by-provider.ts),
|
|
80
|
+
* so a single literal tag never refreshes the other three clients' OWN bucket
|
|
81
|
+
* even though routing already decided they should receive something. #7895
|
|
82
|
+
* found two MORE `available_models` send sites with the identical hardcoded-tag
|
|
83
|
+
* shape (`ws-forwarding.js`'s `models_updated` forward and its legacy
|
|
84
|
+
* single-session path) — this function is the ONE place all of them now
|
|
85
|
+
* resolve a recipient's tag, instead of a third hand-rolled copy of the same
|
|
86
|
+
* per-recipient loop.
|
|
87
|
+
*
|
|
88
|
+
* Given ONE roster message (whatever its `provider` tag), sends it to every
|
|
89
|
+
* relevant client:
|
|
90
|
+
* - a NON-default tag (a real per-provider registry, e.g. `codex`) reaches
|
|
91
|
+
* only the exact-match clients, tag unchanged — `overlayBroadcastReachesProvider`
|
|
92
|
+
* already decided that's correct and no re-tagging is needed.
|
|
93
|
+
* - the DEFAULT (Claude-family) tag is instead RE-SENT once per known
|
|
94
|
+
* Claude-family provider name, each copy re-tagged with that name and
|
|
95
|
+
* filtered to the clients `resolveRosterProvider` resolves to it — so a
|
|
96
|
+
* reload/refresh and a reconnect agree on what a session's roster is
|
|
97
|
+
* called. A residual broadcast (tagged with the message's own literal)
|
|
98
|
+
* covers whatever does not resolve to a known tag — an unregistered/custom
|
|
99
|
+
* provider name, or one whose own registry build throws — preserving
|
|
100
|
+
* fail-open delivery for that edge case.
|
|
101
|
+
*
|
|
102
|
+
* The concrete known-tag set is derived from the provider REGISTRY
|
|
103
|
+
* (`getRegisteredProviderNames` + `isClaudeProvider`, #5858's single source of
|
|
104
|
+
* truth), never a hand-maintained name literal — the exact defect class #5855
|
|
105
|
+
* fixed for `isClaudeProvider` itself.
|
|
106
|
+
*
|
|
107
|
+
* @param {object} deps
|
|
108
|
+
* @param {(msg: object, filter?: (client: object) => boolean) => void} deps.broadcast
|
|
109
|
+
* the caller's broadcast primitive — `wsServer._broadcast` /
|
|
110
|
+
* `ctx.broadcast`, both already `(msg, filter) => void`.
|
|
111
|
+
* @param {object} deps.sessionManager
|
|
112
|
+
* @param {string|null} [deps.defaultProvider] - this daemon's resolved default
|
|
113
|
+
* (`resolveDaemonDefaultProvider(config)`, `./providers.js`) — the same value
|
|
114
|
+
* `ws-history.js` feeds `resolveRosterProvider` via
|
|
115
|
+
* `billingCanary.defaultProvider`. Omitted, `resolveRosterProvider` falls
|
|
116
|
+
* back to `DEFAULT_PROVIDER` itself.
|
|
117
|
+
* @param {{ type: string, models: Array, defaultModel?: string|null, provider?: string|null }} deps.message
|
|
118
|
+
* @returns {void}
|
|
119
|
+
*/
|
|
120
|
+
export function broadcastRosterPerRecipient({ broadcast, sessionManager, defaultProvider = null, message }) {
|
|
121
|
+
const tagIsDefault = usesDefaultModelsRegistry(message?.provider ?? null)
|
|
122
|
+
|
|
123
|
+
if (!tagIsDefault) {
|
|
124
|
+
// Per-provider (non-default) roster: the tag already names the exact
|
|
125
|
+
// registry it came from, so the recipient's own provider must match it
|
|
126
|
+
// exactly. No re-tagging needed: a codex roster is never right for anyone
|
|
127
|
+
// but a codex session.
|
|
128
|
+
broadcast(message, (client) => overlayBroadcastReachesProvider(
|
|
129
|
+
message,
|
|
130
|
+
clientActiveProvider(client, sessionManager),
|
|
131
|
+
tagIsDefault,
|
|
132
|
+
))
|
|
133
|
+
return
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// The concrete Claude-family names this daemon currently has registered
|
|
137
|
+
// (built-ins + docker-* once registerDockerProvider() has run + any
|
|
138
|
+
// config-driven endpoint), INCLUDING claude-byok — same registry as
|
|
139
|
+
// claude-sdk/cli/tui. Read fresh on every call rather than cached, so a
|
|
140
|
+
// provider registered after this module was first imported (docker-*,
|
|
141
|
+
// hot-registered endpoints) is still covered.
|
|
142
|
+
const knownTags = new Set(
|
|
143
|
+
getRegisteredProviderNames().filter((name) => isClaudeProvider(name)),
|
|
144
|
+
)
|
|
145
|
+
// The tag a client with no active session — or a session reporting no
|
|
146
|
+
// provider — is served. Same resolution `ws-history.js` uses on connect, so
|
|
147
|
+
// an idle client's bucket key matches whichever of the two sent last.
|
|
148
|
+
//
|
|
149
|
+
// Only added when it NAMES the default registry — i.e. when this daemon's
|
|
150
|
+
// own configured default is itself Claude-family (the ordinary case:
|
|
151
|
+
// DEFAULT_PROVIDER is 'claude-sdk') or an unregistered/custom name (which
|
|
152
|
+
// `getRegistryForProvider` also falls back to the default registry for).
|
|
153
|
+
// A daemon explicitly defaulted to a REAL non-Claude provider (`--provider
|
|
154
|
+
// codex`) resolves this to `'codex'` — a REGISTERED tag with its OWN
|
|
155
|
+
// registry and its own real recipients. Adding it unconditionally used to
|
|
156
|
+
// re-tag THIS Claude roster as `'codex'` and hand it to every codex-active
|
|
157
|
+
// (and idle) client on that daemon: a Claude model list filed under the
|
|
158
|
+
// exact bucket key a codex session reads, with `set_model` live on tap —
|
|
159
|
+
// the precise cross-provider leak #7728 exists to prevent, reintroduced by
|
|
160
|
+
// this fallback tag. An idle client on such a daemon has no business
|
|
161
|
+
// receiving a Claude roster at all (ws-history.js's connect path would tag
|
|
162
|
+
// ITS roster 'codex' too, from the codex registry, never Claude) — it falls
|
|
163
|
+
// through to the residual broadcast below instead, tagged with the
|
|
164
|
+
// message's own literal, which no codex session's bucket key matches.
|
|
165
|
+
const idleTag = resolveRosterProvider(null, defaultProvider)
|
|
166
|
+
if (usesDefaultModelsRegistry(idleTag)) {
|
|
167
|
+
knownTags.add(idleTag)
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
for (const tag of knownTags) {
|
|
171
|
+
broadcast({ ...message, provider: tag }, (client) => resolveRosterProvider(
|
|
172
|
+
clientActiveProvider(client, sessionManager),
|
|
173
|
+
defaultProvider,
|
|
174
|
+
) === tag)
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// Residual fallback — see the docstring above. `claude-byok` IS in
|
|
178
|
+
// `knownTags`, so it is excluded from the residual by the same generic
|
|
179
|
+
// `knownTags.has(...)` check every other known Claude-family provider is —
|
|
180
|
+
// no separate byok guard needed or wanted.
|
|
181
|
+
broadcast(message, (client) => {
|
|
182
|
+
const activeProvider = clientActiveProvider(client, sessionManager)
|
|
183
|
+
if (knownTags.has(resolveRosterProvider(activeProvider, defaultProvider))) return false
|
|
184
|
+
return overlayBroadcastReachesProvider(message, activeProvider, tagIsDefault)
|
|
185
|
+
})
|
|
186
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import fs from 'fs'
|
|
2
|
-
import { randomUUID } from 'crypto'
|
|
2
|
+
import { createHash, randomUUID } from 'crypto'
|
|
3
3
|
import { dirname, resolve } from 'path'
|
|
4
4
|
import { writeFileRestricted } from './platform.js'
|
|
5
5
|
import { createLogger } from './logger.js'
|
|
@@ -18,6 +18,9 @@ const STORE_VERSION = 1
|
|
|
18
18
|
// the cap are dropped on load (oldest kept) and refused on add.
|
|
19
19
|
const MAX_TASKS = 500
|
|
20
20
|
|
|
21
|
+
/** Exported so the wire-cap parity test can pin the snapshot's `tasks` bound to it. */
|
|
22
|
+
export const MAX_STORED_TASKS = MAX_TASKS
|
|
23
|
+
|
|
21
24
|
const CADENCE_KINDS = new Set(['once', 'interval', 'cron'])
|
|
22
25
|
|
|
23
26
|
/**
|
|
@@ -60,11 +63,12 @@ const MAX_CRON_EXPRESSION_LENGTH = 256
|
|
|
60
63
|
* omits it. The reachable path is therefore a hand-edited registry file.
|
|
61
64
|
*
|
|
62
65
|
* Since #7050 a refused entry is PRESERVED on disk rather than erased, so
|
|
63
|
-
* refusing here does not destroy the operator's task.
|
|
64
|
-
*
|
|
65
|
-
*
|
|
66
|
-
*
|
|
67
|
-
*
|
|
66
|
+
* refusing here does not destroy the operator's task. An over-cap id is
|
|
67
|
+
* unaddressable at the wire (`ScheduledTaskActionSchema.taskId` is capped too)
|
|
68
|
+
* and absent from `store.list()`, so since #7079 the operator reaches such an
|
|
69
|
+
* entry through an opaque server-derived HANDLE (`listUnreadable()` /
|
|
70
|
+
* `discardUnreadable()`), not through its id; hand-editing the file remains a
|
|
71
|
+
* supported recovery path (#7077) — see the class docblock.
|
|
68
72
|
*/
|
|
69
73
|
const MAX_WIRE_ID_LENGTH = 256
|
|
70
74
|
|
|
@@ -93,6 +97,18 @@ function requireIdWithinWireCap(id) {
|
|
|
93
97
|
}
|
|
94
98
|
}
|
|
95
99
|
|
|
100
|
+
/**
|
|
101
|
+
* #8571 — whether `value` has the shape of a task id this store would accept:
|
|
102
|
+
* a non-empty string, already trimmed (`add` trims before storing) and within the
|
|
103
|
+
* wire cap. Shape only; it does not say the task exists. Used to vet a task id read
|
|
104
|
+
* back from persisted session state before it is trusted as a link.
|
|
105
|
+
* @param {unknown} value
|
|
106
|
+
* @returns {boolean}
|
|
107
|
+
*/
|
|
108
|
+
export function isScheduledTaskIdShape(value) {
|
|
109
|
+
return typeof value === 'string' && value.length > 0 && value.length <= MAX_WIRE_ID_LENGTH && value === value.trim()
|
|
110
|
+
}
|
|
111
|
+
|
|
96
112
|
/**
|
|
97
113
|
* The largest absolute epoch-ms a JS `Date` can represent (±8.64e15, i.e. ±100M
|
|
98
114
|
* days around the epoch — year ±275760). Beyond it `new Date(ms)` is an Invalid
|
|
@@ -287,6 +303,97 @@ function normalizeLastRun(lastRun) {
|
|
|
287
303
|
return out
|
|
288
304
|
}
|
|
289
305
|
|
|
306
|
+
/**
|
|
307
|
+
* Canonical JSON: object keys sorted recursively, so two structurally-equal
|
|
308
|
+
* values serialise identically regardless of key order. Used for two things that
|
|
309
|
+
* must agree on "is this the same raw entry?": reconciling a preserved entry
|
|
310
|
+
* against the file (#7077) and deriving its wire handle (#7079). A raw entry may
|
|
311
|
+
* be any JSON value, not only an object — a hand-edited file can hold anything.
|
|
312
|
+
*/
|
|
313
|
+
function canonicalJson(value) {
|
|
314
|
+
// ITERATIVE on purpose. A hand-edited registry can hold an entry nested
|
|
315
|
+
// thousands of levels deep; a recursive walk threw RangeError out of load() and
|
|
316
|
+
// crashed the daemon at boot, where the pre-#7077 loader read the same file
|
|
317
|
+
// fine. Work items are `[isLiteral, payload]` so a value that happens to look
|
|
318
|
+
// like a literal can never be mistaken for one.
|
|
319
|
+
const out = []
|
|
320
|
+
const work = [[false, value]]
|
|
321
|
+
while (work.length > 0) {
|
|
322
|
+
const [isLiteral, item] = work.pop()
|
|
323
|
+
if (isLiteral) { out.push(item); continue }
|
|
324
|
+
if (item === null || typeof item !== 'object') { out.push(String(JSON.stringify(item))); continue }
|
|
325
|
+
if (Array.isArray(item)) {
|
|
326
|
+
out.push('[')
|
|
327
|
+
work.push([true, ']'])
|
|
328
|
+
for (let i = item.length - 1; i >= 0; i--) {
|
|
329
|
+
work.push([false, item[i]])
|
|
330
|
+
if (i > 0) work.push([true, ','])
|
|
331
|
+
}
|
|
332
|
+
continue
|
|
333
|
+
}
|
|
334
|
+
const keys = Object.keys(item).sort()
|
|
335
|
+
out.push('{')
|
|
336
|
+
work.push([true, '}'])
|
|
337
|
+
for (let i = keys.length - 1; i >= 0; i--) {
|
|
338
|
+
work.push([false, item[keys[i]]])
|
|
339
|
+
work.push([true, `${JSON.stringify(keys[i])}:`])
|
|
340
|
+
if (i > 0) work.push([true, ','])
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
return out.join('')
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* A persist that did not reach disk, for the callers that must report it
|
|
348
|
+
* (`remove()`, `discardUnreadable()`). Deliberately generic: the cause (a path,
|
|
349
|
+
* an errno) is logged server-side, not sent to a client.
|
|
350
|
+
*/
|
|
351
|
+
function persistFailure() {
|
|
352
|
+
return new Error('Could not write the scheduled-task registry; nothing was changed')
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* A preserved entry that is a well-formed task whose id a live task already
|
|
357
|
+
* owns. `duplicateOf` marks it so deleting that live task drops it too: left
|
|
358
|
+
* behind, a restart would load it as the task the operator just deleted.
|
|
359
|
+
*/
|
|
360
|
+
function duplicateOfLive(entry, id) {
|
|
361
|
+
return {
|
|
362
|
+
raw: entry,
|
|
363
|
+
id: usableId(entry),
|
|
364
|
+
duplicateOf: id,
|
|
365
|
+
reason: `duplicates the id of a live task (${id}) — edit that task through the panel, or discard this entry`,
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** Multiset (canonical JSON -> count) of a list of raw entries. */
|
|
370
|
+
function countCanonical(entries) {
|
|
371
|
+
const counts = new Map()
|
|
372
|
+
for (const entry of entries) {
|
|
373
|
+
const key = canonicalJson(entry)
|
|
374
|
+
counts.set(key, (counts.get(key) ?? 0) + 1)
|
|
375
|
+
}
|
|
376
|
+
return counts
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** The trimmed string id of a raw entry, or null when it has no usable one. */
|
|
380
|
+
function usableId(raw) {
|
|
381
|
+
return typeof raw?.id === 'string' && raw.id.trim().length > 0 ? raw.id.trim() : null
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* #7079 — the opaque wire handle of an unreadable entry: the first 16 hex chars
|
|
386
|
+
* (64 bits) of the sha256 of its canonical JSON. It is the ONLY way a client
|
|
387
|
+
* names a preserved entry, because the entry's own id may be absent, a non-string,
|
|
388
|
+
* or longer than the wire's 256-char task-id cap (which is correct and must not
|
|
389
|
+
* be widened to carry a malformed record). Derived server-side from content, so a
|
|
390
|
+
* client can neither forge a handle for a live task nor address anything the
|
|
391
|
+
* server did not itself derive. Never contains raw contents.
|
|
392
|
+
*/
|
|
393
|
+
function handleOf(canonical) {
|
|
394
|
+
return createHash('sha256').update(canonical).digest('hex').slice(0, 16)
|
|
395
|
+
}
|
|
396
|
+
|
|
290
397
|
/**
|
|
291
398
|
* The scheduled-task data model (#6862). A standing, persisted schedule for a
|
|
292
399
|
* future/recurring agent run — explicitly SEPARATE from live session state and
|
|
@@ -317,6 +424,48 @@ function normalizeLastRun(lastRun) {
|
|
|
317
424
|
* atomically (temp + rename via writeFileRestricted, mode 0600), version-gated,
|
|
318
425
|
* and fail-open-empty on a corrupt/unknown-version file. Loaded once on daemon
|
|
319
426
|
* start; keyed by task id.
|
|
427
|
+
*
|
|
428
|
+
* ── Unreadable (load-refused) entries (#7050, #7077, #7079, #8523) ────────────
|
|
429
|
+
* An entry the loader cannot read is never served as a task and never erased: it
|
|
430
|
+
* is kept verbatim and written back by every persist. Two ways to resolve one:
|
|
431
|
+
*
|
|
432
|
+
* 1. DISCARD (preferred) — the dashboard shows each entry with the reason it
|
|
433
|
+
* was refused and a Discard control; `discardUnreadable(handle)` removes it
|
|
434
|
+
* through the store, atomically, with no file editing.
|
|
435
|
+
* 2. HAND-EDIT — supported WHILE THE DAEMON RUNS.
|
|
436
|
+
*
|
|
437
|
+
* ── The hand-editing contract: the daemon only ever rewrites entries it wrote ──
|
|
438
|
+
* The store remembers exactly what it last wrote to the file (`_lastWritten`, a
|
|
439
|
+
* multiset of the canonical JSON of every entry, seeded from the raw entries as
|
|
440
|
+
* read at `load()`, and replaced only after an atomic write SUCCEEDS). At every
|
|
441
|
+
* persist it re-reads the file, and anything on disk that is not in that multiset
|
|
442
|
+
* is the OPERATOR's — an edit or an addition — and is never overwritten:
|
|
443
|
+
*
|
|
444
|
+
* | an entry on disk that is… | result |
|
|
445
|
+
* |----------------------------------------------|-------------------------------------|
|
|
446
|
+
* | one the daemon wrote (live or preserved) | the daemon's in-memory copy wins |
|
|
447
|
+
* | one the daemon wrote, now neither live nor preserved | gone on purpose (a delete or discard): NOT resurrected |
|
|
448
|
+
* | new, and it normalises, its id is free, cap allows | ADOPTED as a task |
|
|
449
|
+
* | new, and its id is a live task's (or was just adopted) | preserved as unreadable, "duplicates the id of …"; never armed |
|
|
450
|
+
* | new, and it does not normalise / cap reached | preserved as unreadable (reason re-derived) |
|
|
451
|
+
* | a preserved entry the operator edited or removed | the old capture is dropped; an edit is picked up as a new entry |
|
|
452
|
+
* | file missing / unparsable / wrong version or shape | no reconciliation: the in-memory set is written as before (nothing dropped) |
|
|
453
|
+
*
|
|
454
|
+
* New entries are processed in DISK ORDER, so when two share an id the first
|
|
455
|
+
* wins — exactly what `load()` of the same file would do. There is no identity
|
|
456
|
+
* inference (matching an edited entry to "the one it was" by id or position):
|
|
457
|
+
* each such guess had a hole that could resurrect a deleted task, arm a duplicate
|
|
458
|
+
* a restart would reject, or overwrite a live task. Editing a LIVE task's entry
|
|
459
|
+
* by hand therefore does not change the task; the edit is kept as an unreadable
|
|
460
|
+
* duplicate to discard or copy from. Such a duplicate is kept across restarts
|
|
461
|
+
* (`load()` preserves a duplicate id rather than dropping it; the first in file
|
|
462
|
+
* order is the task) and is dropped together with its task when that task is
|
|
463
|
+
* deleted, so deleting a task cannot leave a copy that a restart would arm. Edits are noticed only at a persist (any
|
|
464
|
+
* add/update/remove/discard or an engine run result), and an edit saved between
|
|
465
|
+
* that persist's read and its atomic rename is lost — the window any two writers
|
|
466
|
+
* of one file have. A persist that FAILS commits nothing (neither the adoption
|
|
467
|
+
* nor the new `_lastWritten`), and `remove()`/`discardUnreadable()` restore their
|
|
468
|
+
* in-memory change and throw so the caller reports the failure.
|
|
320
469
|
*/
|
|
321
470
|
export class ScheduledTaskStore {
|
|
322
471
|
/**
|
|
@@ -337,6 +486,9 @@ export class ScheduledTaskStore {
|
|
|
337
486
|
// tasks; they exist so an operator's unreadable task survives the next
|
|
338
487
|
// unrelated mutation instead of being silently deleted from disk.
|
|
339
488
|
this._unreadable = []
|
|
489
|
+
// #7077: canonical JSON -> count of every entry in the last SUCCESSFUL write
|
|
490
|
+
// (seeded at load()). What is on disk and NOT in here is the operator's.
|
|
491
|
+
this._lastWritten = new Map()
|
|
340
492
|
this._loaded = false
|
|
341
493
|
}
|
|
342
494
|
|
|
@@ -365,6 +517,7 @@ export class ScheduledTaskStore {
|
|
|
365
517
|
// and `_persist()` would write them back into a file that no longer has them,
|
|
366
518
|
// resurrecting records the operator deleted.
|
|
367
519
|
this._unreadable = []
|
|
520
|
+
this._lastWritten = new Map()
|
|
368
521
|
let raw
|
|
369
522
|
try {
|
|
370
523
|
raw = fs.readFileSync(this._filePath, 'utf-8')
|
|
@@ -390,6 +543,10 @@ export class ScheduledTaskStore {
|
|
|
390
543
|
}
|
|
391
544
|
const tasks = parsed.tasks
|
|
392
545
|
if (!Array.isArray(tasks)) return this
|
|
546
|
+
// #7077: everything in the file as read is, by definition, already known — the
|
|
547
|
+
// daemon is about to own it. Seeded BEFORE the loop so a refused or dropped
|
|
548
|
+
// entry is known too.
|
|
549
|
+
this._lastWritten = countCanonical(tasks)
|
|
393
550
|
for (const [i, entry] of tasks.entries()) {
|
|
394
551
|
if (this._tasks.size >= MAX_TASKS) {
|
|
395
552
|
// #7050: the remainder is never even examined, so it would be erased on
|
|
@@ -409,7 +566,11 @@ export class ScheduledTaskStore {
|
|
|
409
566
|
continue
|
|
410
567
|
}
|
|
411
568
|
if (this._tasks.has(record.id)) {
|
|
412
|
-
|
|
569
|
+
// Kept, not dropped: a duplicate may be an operator's edit that a running
|
|
570
|
+
// daemon preserved (see `_reconcile`), and dropping it here would erase
|
|
571
|
+
// it at the next write after a restart. First in file order wins, as ever.
|
|
572
|
+
this._log.warn(`Scheduled-task id ${record.id} appears more than once — keeping the first, preserving the duplicate (not scheduled)`)
|
|
573
|
+
this._unreadable.push(duplicateOfLive(entry, record.id))
|
|
413
574
|
continue
|
|
414
575
|
}
|
|
415
576
|
this._tasks.set(record.id, record)
|
|
@@ -522,8 +683,17 @@ export class ScheduledTaskStore {
|
|
|
522
683
|
*/
|
|
523
684
|
remove(id) {
|
|
524
685
|
if (this._tasks.has(id)) {
|
|
686
|
+
const before = new Map(this._tasks)
|
|
687
|
+
const beforeUnreadable = this._unreadable
|
|
525
688
|
this._tasks.delete(id)
|
|
526
|
-
this
|
|
689
|
+
// The duplicates kept for this id go with it: otherwise a restart loads one
|
|
690
|
+
// as the very task that was just deleted.
|
|
691
|
+
this._unreadable = beforeUnreadable.filter((u) => u.duplicateOf !== id)
|
|
692
|
+
if (!this._persist()) {
|
|
693
|
+
this._tasks = before
|
|
694
|
+
this._unreadable = beforeUnreadable
|
|
695
|
+
throw persistFailure()
|
|
696
|
+
}
|
|
527
697
|
return true
|
|
528
698
|
}
|
|
529
699
|
// #7050: a preserved (unreadable) entry must stay deletable — otherwise
|
|
@@ -535,10 +705,13 @@ export class ScheduledTaskStore {
|
|
|
535
705
|
// once and report success. `listUnreadable()` publicly emits those null rows,
|
|
536
706
|
// so this is reachable the moment a caller forwards one back.
|
|
537
707
|
if (typeof id !== 'string' || id.length === 0) return false
|
|
538
|
-
const before = this._unreadable
|
|
539
|
-
this._unreadable =
|
|
540
|
-
if (this._unreadable.length === before) return false
|
|
541
|
-
this._persist()
|
|
708
|
+
const before = this._unreadable
|
|
709
|
+
this._unreadable = before.filter((u) => u.id !== id)
|
|
710
|
+
if (this._unreadable.length === before.length) return false
|
|
711
|
+
if (!this._persist()) {
|
|
712
|
+
this._unreadable = before
|
|
713
|
+
throw persistFailure()
|
|
714
|
+
}
|
|
542
715
|
return true
|
|
543
716
|
}
|
|
544
717
|
|
|
@@ -553,17 +726,125 @@ export class ScheduledTaskStore {
|
|
|
553
726
|
}
|
|
554
727
|
|
|
555
728
|
/**
|
|
556
|
-
* #7050 — the refused entries' ids and reasons (never their
|
|
557
|
-
* may be any shape). `id` is null when the entry had no
|
|
558
|
-
*
|
|
729
|
+
* #7050 / #7079 — the refused entries' handles, ids and reasons (never their
|
|
730
|
+
* raw contents, which may be any shape). `id` is null when the entry had no
|
|
731
|
+
* usable string id. `handle` is the opaque, wire-legal token a client uses to
|
|
732
|
+
* name the entry (see {@link handleOf}); byte-identical entries get a `-<n>`
|
|
733
|
+
* suffix so each stays individually addressable.
|
|
734
|
+
*
|
|
735
|
+
* This reflects the daemon's view as of the last load or persist; it does not
|
|
736
|
+
* re-read the file (a read must not change what is armed to fire).
|
|
737
|
+
* @returns {{ handle: string, id: string|null, reason: string }[]}
|
|
559
738
|
*/
|
|
560
739
|
listUnreadable() {
|
|
561
|
-
|
|
740
|
+
const seen = new Map()
|
|
741
|
+
return this._unreadable.map(({ raw, id, reason }) => {
|
|
742
|
+
const base = handleOf(canonicalJson(raw))
|
|
743
|
+
const n = (seen.get(base) ?? 0) + 1
|
|
744
|
+
seen.set(base, n)
|
|
745
|
+
return { handle: n === 1 ? base : `${base}-${n}`, id, reason }
|
|
746
|
+
})
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
/**
|
|
750
|
+
* #7079 — discard ONE unreadable entry by the handle `listUnreadable()` derived
|
|
751
|
+
* for it, and persist. Returns false (changing nothing) for an unknown, stale or
|
|
752
|
+
* non-string handle. Re-derives handles server-side after refreshing the
|
|
753
|
+
* preserved set from disk, so a handle the operator saw before hand-editing the
|
|
754
|
+
* file no longer matches: their newer edit is never discarded blind.
|
|
755
|
+
* @param {string} handle
|
|
756
|
+
* @returns {boolean}
|
|
757
|
+
*/
|
|
758
|
+
discardUnreadable(handle) {
|
|
759
|
+
if (typeof handle !== 'string' || handle.length === 0) return false
|
|
760
|
+
const index = this.listUnreadable().findIndex((u) => u.handle === handle)
|
|
761
|
+
if (index === -1) return false
|
|
762
|
+
// A handle derives from the daemon's in-memory capture. If the operator has
|
|
763
|
+
// since edited or removed that entry in the file, the capture is stale and
|
|
764
|
+
// the handle no longer names what is on disk: refuse, and refresh (a persist
|
|
765
|
+
// reconciles) so the next listing carries the entry as it is now.
|
|
766
|
+
const disk = this._readDiskEntries()
|
|
767
|
+
const key = canonicalJson(this._unreadable[index].raw)
|
|
768
|
+
if (disk !== null && !disk.some((entry) => canonicalJson(entry) === key)) {
|
|
769
|
+
this._persist()
|
|
770
|
+
return false
|
|
771
|
+
}
|
|
772
|
+
const before = this._unreadable
|
|
773
|
+
this._unreadable = before.filter((_, i) => i !== index)
|
|
774
|
+
if (!this._persist()) {
|
|
775
|
+
this._unreadable = before
|
|
776
|
+
throw persistFailure()
|
|
777
|
+
}
|
|
778
|
+
return true
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
/**
|
|
782
|
+
* @private — #7077: read the file's task entries for reconciliation, or null
|
|
783
|
+
* when they cannot be trusted (missing / unreadable / unparsable / wrong
|
|
784
|
+
* version / `tasks` not an array). Null means "fall back to the captured raw
|
|
785
|
+
* entries", never "there are none".
|
|
786
|
+
*/
|
|
787
|
+
_readDiskEntries() {
|
|
788
|
+
try {
|
|
789
|
+
const parsed = JSON.parse(fs.readFileSync(this._filePath, 'utf-8'))
|
|
790
|
+
if (!parsed || typeof parsed !== 'object' || parsed.version !== STORE_VERSION) return null
|
|
791
|
+
return Array.isArray(parsed.tasks) ? parsed.tasks : null
|
|
792
|
+
} catch {
|
|
793
|
+
return null
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
/**
|
|
798
|
+
* @private — #7077/#8523: classify what is on disk against what the daemon last
|
|
799
|
+
* wrote. PURE — returns the result; `_persist()` commits it only if the write
|
|
800
|
+
* succeeds. See the class docblock for the table. `disk` is trusted.
|
|
801
|
+
* @returns {{ adopted: object[], unreadable: object[] }}
|
|
802
|
+
*/
|
|
803
|
+
_reconcile(disk) {
|
|
804
|
+
const diskKeys = disk.map(canonicalJson)
|
|
805
|
+
// A preserved entry the file still holds verbatim stays; one it does not was
|
|
806
|
+
// edited or removed by the operator, so the capture is dropped (an edit
|
|
807
|
+
// reappears below as a new entry).
|
|
808
|
+
const onDisk = countCanonical(disk)
|
|
809
|
+
const unreadable = []
|
|
810
|
+
for (const p of this._unreadable) {
|
|
811
|
+
const key = canonicalJson(p.raw)
|
|
812
|
+
const n = onDisk.get(key) ?? 0
|
|
813
|
+
if (n > 0) {
|
|
814
|
+
onDisk.set(key, n - 1)
|
|
815
|
+
unreadable.push(p)
|
|
816
|
+
} else {
|
|
817
|
+
this._log.info('A preserved unreadable scheduled-task entry was edited or removed in the registry file — dropping the stale copy')
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
// Everything the daemon did not write is the operator's, in DISK ORDER.
|
|
821
|
+
const known = new Map(this._lastWritten)
|
|
822
|
+
const taken = new Set(this._tasks.keys())
|
|
823
|
+
const adopted = []
|
|
824
|
+
disk.forEach((entry, i) => {
|
|
825
|
+
const n = known.get(diskKeys[i]) ?? 0
|
|
826
|
+
if (n > 0) { known.set(diskKeys[i], n - 1); return }
|
|
827
|
+
try {
|
|
828
|
+
const record = this._normalizeStoredTask(entry)
|
|
829
|
+
if (taken.has(record.id)) {
|
|
830
|
+
unreadable.push(duplicateOfLive(entry, record.id))
|
|
831
|
+
} else if (taken.size >= MAX_TASKS) {
|
|
832
|
+
unreadable.push({ raw: entry, id: usableId(entry), reason: `store cap (${MAX_TASKS}) reached` })
|
|
833
|
+
} else {
|
|
834
|
+
taken.add(record.id)
|
|
835
|
+
adopted.push(record)
|
|
836
|
+
this._log.info(`Adopted scheduled task ${record.id}: it was added or repaired in the registry file`)
|
|
837
|
+
}
|
|
838
|
+
} catch (err) {
|
|
839
|
+
unreadable.push({ raw: entry, id: usableId(entry), reason: String(err.message) })
|
|
840
|
+
}
|
|
841
|
+
})
|
|
842
|
+
return { adopted, unreadable }
|
|
562
843
|
}
|
|
563
844
|
|
|
564
845
|
/** @private — keep a refused raw entry so `_persist()` cannot erase it (#7050). */
|
|
565
846
|
_preserveUnreadable(raw, reason) {
|
|
566
|
-
const id =
|
|
847
|
+
const id = usableId(raw)
|
|
567
848
|
this._unreadable.push({ raw, id, reason: String(reason) })
|
|
568
849
|
}
|
|
569
850
|
|
|
@@ -618,25 +899,48 @@ export class ScheduledTaskStore {
|
|
|
618
899
|
}
|
|
619
900
|
}
|
|
620
901
|
|
|
621
|
-
/**
|
|
902
|
+
/**
|
|
903
|
+
* @private — atomic write of the whole store. Returns true when the file was
|
|
904
|
+
* written, false when it was not (the failure is logged; nothing is committed).
|
|
905
|
+
* add()/update() keep their long-standing best-effort contract and ignore it;
|
|
906
|
+
* remove()/discardUnreadable() report it.
|
|
907
|
+
*/
|
|
622
908
|
_persist() {
|
|
623
909
|
try {
|
|
624
910
|
const dir = dirname(this._filePath)
|
|
625
911
|
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true })
|
|
626
|
-
// #
|
|
627
|
-
//
|
|
628
|
-
//
|
|
629
|
-
//
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
912
|
+
// #7077/#8523: pick up the operator's edits and additions BEFORE writing, so
|
|
913
|
+
// the daemon only ever rewrites entries it wrote itself. A store that never
|
|
914
|
+
// loaded has no baseline to compare against and writes as before; so does a
|
|
915
|
+
// file that is missing / unparsable / the wrong shape (nothing is dropped).
|
|
916
|
+
let adopted = []
|
|
917
|
+
let unreadable = this._unreadable
|
|
918
|
+
if (this._loaded) {
|
|
919
|
+
const disk = this._readDiskEntries()
|
|
920
|
+
if (disk !== null) ({ adopted, unreadable } = this._reconcile(disk))
|
|
633
921
|
}
|
|
634
|
-
|
|
922
|
+
// The preserved raw entries ride along so an unrelated mutation cannot erase
|
|
923
|
+
// a task the loader merely could not READ. They are appended (never
|
|
924
|
+
// re-serialized from a normalized record) so nothing is lost in a round trip
|
|
925
|
+
// through a shape this version does not understand.
|
|
926
|
+
const text = JSON.stringify({
|
|
927
|
+
version: STORE_VERSION,
|
|
928
|
+
tasks: [...this._tasks.values(), ...adopted, ...unreadable.map((u) => u.raw)],
|
|
929
|
+
}, null, 2)
|
|
930
|
+
writeFileRestricted(this._filePath, text, { tmpSuffix: `.tmp-${process.pid}` })
|
|
931
|
+
// Committed only now that the file really holds it. A failed write leaves the
|
|
932
|
+
// baseline and the preserved set as they were, so the next persist reconciles
|
|
933
|
+
// against the truth instead of against something that never reached disk.
|
|
934
|
+
for (const record of adopted) this._tasks.set(record.id, record)
|
|
935
|
+
this._unreadable = unreadable
|
|
936
|
+
this._lastWritten = countCanonical(JSON.parse(text).tasks)
|
|
937
|
+
return true
|
|
635
938
|
} catch (err) {
|
|
636
939
|
// Best-effort: a failed persist leaves the in-memory set intact for this
|
|
637
940
|
// process; the prior good file (if any) survives (atomic write). Surface
|
|
638
941
|
// it so an operator can see the schedule won't survive a restart.
|
|
639
942
|
this._log.error(`Failed to persist scheduled tasks to ${this._filePath}: ${err?.stack || err}`)
|
|
943
|
+
return false
|
|
640
944
|
}
|
|
641
945
|
}
|
|
642
946
|
}
|