@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
|
@@ -79,6 +79,9 @@ async function fetchWithRetry(url, options) {
|
|
|
79
79
|
// Exported for testing (re-exported from push.js for existing importers)
|
|
80
80
|
export { fetchWithRetry, FETCH_TIMEOUT_MS, MAX_RETRIES, BACKOFF_BASE_MS }
|
|
81
81
|
|
|
82
|
+
// The owner recorded for a registration restored from disk (see _loadFromDisk).
|
|
83
|
+
const RESTORED_OWNER = Symbol('restored-registration')
|
|
84
|
+
|
|
82
85
|
export class ExpoPushSink extends NotificationSink {
|
|
83
86
|
constructor({ storagePath } = {}) {
|
|
84
87
|
super({ name: 'expo-push' })
|
|
@@ -95,6 +98,11 @@ export class ExpoPushSink extends NotificationSink {
|
|
|
95
98
|
// review on PR #2806). Owner IDs are client connection IDs in
|
|
96
99
|
// production; tests can use any unique string.
|
|
97
100
|
this._tokenOwners = new Map()
|
|
101
|
+
// Session scope of a registration: token -> Map<ownerId, sessionId> for the
|
|
102
|
+
// owners that registered it on behalf of ONE session (a session-scoped
|
|
103
|
+
// connection). An owner absent from the inner map registered it unscoped.
|
|
104
|
+
// See `_sessionsFor`.
|
|
105
|
+
this._ownerSessions = new Map()
|
|
98
106
|
this._loadFromDisk()
|
|
99
107
|
}
|
|
100
108
|
|
|
@@ -109,6 +117,10 @@ export class ExpoPushSink extends NotificationSink {
|
|
|
109
117
|
for (const token of pushTokens) {
|
|
110
118
|
if (typeof token === 'string' && token.length > 0) {
|
|
111
119
|
this.tokens.add(token)
|
|
120
|
+
// A destination restored from disk was registered unscoped, by the host.
|
|
121
|
+
// Record that as an owner so a session-scoped registration of the same
|
|
122
|
+
// token can neither narrow it nor remove it when that connection leaves.
|
|
123
|
+
this._tokenOwners.set(token, new Set([RESTORED_OWNER]))
|
|
112
124
|
}
|
|
113
125
|
}
|
|
114
126
|
for (const token of laTokens) {
|
|
@@ -127,7 +139,10 @@ export class ExpoPushSink extends NotificationSink {
|
|
|
127
139
|
try {
|
|
128
140
|
mkdirSync(dirname(this._storagePath), { recursive: true })
|
|
129
141
|
writeFileRestricted(this._storagePath, JSON.stringify({
|
|
130
|
-
|
|
142
|
+
// A session-scoped registration lasts as long as its connection (it is
|
|
143
|
+
// released when that connection goes), so it is never written down:
|
|
144
|
+
// restored from disk it would come back without its scope.
|
|
145
|
+
tokens: [...this.tokens].filter((t) => this._sessionsFor(t) === null),
|
|
131
146
|
liveActivityTokens: [...this._liveActivityTokens],
|
|
132
147
|
}))
|
|
133
148
|
} catch (err) {
|
|
@@ -150,7 +165,14 @@ export class ExpoPushSink extends NotificationSink {
|
|
|
150
165
|
* registered token to the connection that registered it, so tokens get
|
|
151
166
|
* pruned on client disconnect.
|
|
152
167
|
*/
|
|
153
|
-
registerToken(token, ownerId = null) {
|
|
168
|
+
registerToken(token, ownerId = null, { sessionId = null } = {}) {
|
|
169
|
+
// A registration made on behalf of one session (`sessionId`) needs an owner:
|
|
170
|
+
// its scope is tracked per owner and ends with it. Without one there would be
|
|
171
|
+
// nothing to release it, and it would outlive the connection unscoped.
|
|
172
|
+
if (sessionId != null && ownerId == null) {
|
|
173
|
+
log.warn('Rejected session-scoped push credential without an owner')
|
|
174
|
+
return false
|
|
175
|
+
}
|
|
154
176
|
if (typeof token !== 'string' || token.length === 0) {
|
|
155
177
|
log.warn(`Rejected invalid push credential: ${String(token).slice(0, 40)}`)
|
|
156
178
|
return false
|
|
@@ -159,10 +181,11 @@ export class ExpoPushSink extends NotificationSink {
|
|
|
159
181
|
log.warn(`Rejected malformed push credential (unrecognized format): ${token.slice(0, 40)}`)
|
|
160
182
|
return false
|
|
161
183
|
}
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
184
|
+
const isNew = !this.tokens.has(token)
|
|
185
|
+
if (isNew) this.tokens.add(token)
|
|
186
|
+
// An unscoped owner joining a token that only scoped owners held makes it
|
|
187
|
+
// unscoped, which is what the persisted set is keyed on.
|
|
188
|
+
const widens = sessionId == null && this._ownerSessions.has(token)
|
|
166
189
|
// Track ownership for ref-counted prune-on-disconnect (2026-04-11
|
|
167
190
|
// audit blocker 6 + Copilot review on PR #2806). Multiple clients
|
|
168
191
|
// may register the same token (reconnect race, multi-device); the
|
|
@@ -174,11 +197,51 @@ export class ExpoPushSink extends NotificationSink {
|
|
|
174
197
|
this._tokenOwners.set(token, owners)
|
|
175
198
|
}
|
|
176
199
|
owners.add(ownerId)
|
|
200
|
+
let scoped = this._ownerSessions.get(token)
|
|
201
|
+
if (sessionId != null) {
|
|
202
|
+
if (!scoped) {
|
|
203
|
+
scoped = new Map()
|
|
204
|
+
this._ownerSessions.set(token, scoped)
|
|
205
|
+
}
|
|
206
|
+
scoped.set(ownerId, sessionId)
|
|
207
|
+
} else if (scoped) {
|
|
208
|
+
scoped.delete(ownerId)
|
|
209
|
+
if (scoped.size === 0) this._ownerSessions.delete(token)
|
|
210
|
+
}
|
|
177
211
|
}
|
|
212
|
+
// After the owner and scope bookkeeping above: what is written to disk
|
|
213
|
+
// depends on it (a session-scoped registration is never persisted).
|
|
214
|
+
if (isNew || widens) this._persistToDisk()
|
|
178
215
|
log.info(`Registered push credential ${token.slice(0, 30)}...`)
|
|
179
216
|
return true
|
|
180
217
|
}
|
|
181
218
|
|
|
219
|
+
/**
|
|
220
|
+
* The sessions a registered token may receive notifications for, or null when
|
|
221
|
+
* it may receive all of them.
|
|
222
|
+
*
|
|
223
|
+
* A token is limited only when EVERY owner holding it registered it for a
|
|
224
|
+
* session; one unscoped owner (the host's own device) makes it unscoped, and a
|
|
225
|
+
* token with no recorded owner (restored from disk) is unscoped. So a
|
|
226
|
+
* session-scoped connection can narrow what it receives but can never widen the
|
|
227
|
+
* delivery of a token someone else registered.
|
|
228
|
+
* @param {string} token
|
|
229
|
+
* @returns {Set<string>|null}
|
|
230
|
+
*/
|
|
231
|
+
_sessionsFor(token) {
|
|
232
|
+
const scoped = this._ownerSessions.get(token)
|
|
233
|
+
if (!scoped || scoped.size === 0) return null
|
|
234
|
+
const owners = this._tokenOwners.get(token)
|
|
235
|
+
if (!owners || owners.size === 0) return null
|
|
236
|
+
const sessions = new Set()
|
|
237
|
+
for (const owner of owners) {
|
|
238
|
+
const sid = scoped.get(owner)
|
|
239
|
+
if (sid === undefined) return null
|
|
240
|
+
sessions.add(sid)
|
|
241
|
+
}
|
|
242
|
+
return sessions
|
|
243
|
+
}
|
|
244
|
+
|
|
182
245
|
/**
|
|
183
246
|
* Release one owner's claim on a token. If the last owner goes away,
|
|
184
247
|
* the token is removed from the registry entirely. Returns true if
|
|
@@ -195,10 +258,19 @@ export class ExpoPushSink extends NotificationSink {
|
|
|
195
258
|
return this.removeToken(token)
|
|
196
259
|
}
|
|
197
260
|
owners.delete(ownerId)
|
|
261
|
+
const scoped = this._ownerSessions.get(token)
|
|
262
|
+
let hadScope = false
|
|
263
|
+
if (scoped) {
|
|
264
|
+
hadScope = scoped.delete(ownerId)
|
|
265
|
+
if (scoped.size === 0) this._ownerSessions.delete(token)
|
|
266
|
+
}
|
|
198
267
|
if (owners.size === 0) {
|
|
199
268
|
this._tokenOwners.delete(token)
|
|
200
269
|
return this.removeToken(token)
|
|
201
270
|
}
|
|
271
|
+
// The registration that was limited to a session may have been the only thing
|
|
272
|
+
// keeping the token off disk: persist now that it may be unscoped.
|
|
273
|
+
if (hadScope) this._persistToDisk()
|
|
202
274
|
return false
|
|
203
275
|
}
|
|
204
276
|
|
|
@@ -242,6 +314,7 @@ export class ExpoPushSink extends NotificationSink {
|
|
|
242
314
|
removeToken(token) {
|
|
243
315
|
if (this.tokens.delete(token)) {
|
|
244
316
|
this._tokenOwners.delete(token)
|
|
317
|
+
this._ownerSessions.delete(token)
|
|
245
318
|
this._persistToDisk()
|
|
246
319
|
return true
|
|
247
320
|
}
|
|
@@ -314,7 +387,13 @@ export class ExpoPushSink extends NotificationSink {
|
|
|
314
387
|
const shouldBypassQuietHours = context.shouldBypassQuietHours ?? (() => false)
|
|
315
388
|
|
|
316
389
|
const eligibleTokens = []
|
|
390
|
+
const notificationSession = typeof data?.sessionId === 'string' ? data.sessionId : null
|
|
317
391
|
for (const token of this.tokens) {
|
|
392
|
+
// A token registered for specific sessions receives only notifications
|
|
393
|
+
// that name one of them. One with no session (a host-wide notice) is not
|
|
394
|
+
// for it.
|
|
395
|
+
const sessions = this._sessionsFor(token)
|
|
396
|
+
if (sessions && !(notificationSession !== null && sessions.has(notificationSession))) continue
|
|
318
397
|
if (!isCategoryEnabled(category, token)) continue
|
|
319
398
|
if (isInQuietHours(now, token) && !shouldBypassQuietHours(category, token)) continue
|
|
320
399
|
eligibleTokens.push(token)
|
|
@@ -114,8 +114,8 @@ function formatRelativeWakeup(at, now) {
|
|
|
114
114
|
*
|
|
115
115
|
* @param {{ backgroundTasks?: Array<{toolUseId:string, description?:string, startedAt?:number}>,
|
|
116
116
|
* scheduledWakeup?: { at:number, reason?:string } | null } | null | undefined} snapshot
|
|
117
|
-
* Output of `
|
|
118
|
-
* type doesn't expose one / the transcript scan degraded.
|
|
117
|
+
* Output of `peekBackgroundTaskSnapshot()` (#5436 / #8052), or null when
|
|
118
|
+
* the session type doesn't expose one / the transcript scan degraded.
|
|
119
119
|
* @param {number} [now] Reference epoch ms for the relative wakeup offset —
|
|
120
120
|
* defaults to `Date.now()`. Parameterized so tests can pin the offset against
|
|
121
121
|
* a fixed `at` without freezing the global clock.
|
|
@@ -162,14 +162,25 @@ export function composeReadyNotificationBody(snapshot, now = Date.now()) {
|
|
|
162
162
|
/**
|
|
163
163
|
* Read a session's background-task snapshot for notification enrichment.
|
|
164
164
|
* Returns null (= "no information", body unchanged) when the session type
|
|
165
|
-
* doesn't implement `
|
|
165
|
+
* doesn't implement `peekBackgroundTaskSnapshot()` or the read throws —
|
|
166
166
|
* the same degrade-to-plain-ready posture as event-normalizer's
|
|
167
167
|
* backgroundTaskFields().
|
|
168
|
+
*
|
|
169
|
+
* #8052: this call is deliberately side-effect-free — it goes through
|
|
170
|
+
* `peekBackgroundTaskSnapshot()`, never `getBackgroundTaskSnapshot()`. This
|
|
171
|
+
* composes an idle-push body whenever the session has no active viewers, so
|
|
172
|
+
* nothing here ever broadcasts a `claude_ready` / `background_tasks_changed`
|
|
173
|
+
* message to a client. Reading through the side-effecting method would
|
|
174
|
+
* silently advance the idle-poll's dedup baseline (and could stop the poll
|
|
175
|
+
* outright on a drained snapshot) with nobody ever told what changed —
|
|
176
|
+
* stranding a client's already-shown background-task indicator forever
|
|
177
|
+
* (`ws-history.js` replays a bare `claude_ready`, where an absent field means
|
|
178
|
+
* "keep state").
|
|
168
179
|
*/
|
|
169
180
|
export function readBackgroundTaskSnapshot(session) {
|
|
170
181
|
try {
|
|
171
|
-
return typeof session?.
|
|
172
|
-
? session.
|
|
182
|
+
return typeof session?.peekBackgroundTaskSnapshot === 'function'
|
|
183
|
+
? session.peekBackgroundTaskSnapshot()
|
|
173
184
|
: null
|
|
174
185
|
} catch {
|
|
175
186
|
return null
|
package/src/ollama-session.js
CHANGED
|
@@ -17,8 +17,14 @@
|
|
|
17
17
|
* `getAllowedModels()` returns null (session-manager treats a
|
|
18
18
|
* non-array as "no restriction"). `getFallbackModels()` seeds the
|
|
19
19
|
* dashboard picker with Ollama's recommended coder models; dynamic
|
|
20
|
-
* discovery via GET /api/tags (#5421, ollama-tags.js)
|
|
21
|
-
*
|
|
20
|
+
* discovery via GET /api/tags (#5421, ollama-tags.js) ADDS the
|
|
21
|
+
* actually-installed list when the daemon is reachable. It does not
|
|
22
|
+
* replace the seed — this line said "replaces" until #7761 and the code
|
|
23
|
+
* never did, which is the comment-claims-more-than-the-code class
|
|
24
|
+
* (#7290/#7291): the recommendations stay in the picker so a machine
|
|
25
|
+
* that has pulled two models is still offered the other three. That
|
|
26
|
+
* union is now declared, not incidental — see
|
|
27
|
+
* `staticModelsAreRecommendations` below.
|
|
22
28
|
* Discovery is ADVISORY only — it feeds the picker, never validation.
|
|
23
29
|
* - Zero pricing. Local inference is free; `_getPricing` returns a
|
|
24
30
|
* zero-rate entry (not null) so byok-session's "no pricing entry"
|
|
@@ -42,6 +48,7 @@ import Anthropic from '@anthropic-ai/sdk'
|
|
|
42
48
|
import { ClaudeByokSession } from './byok-session.js'
|
|
43
49
|
import { resolveOllamaBaseUrl, ollamaEnvOverride, refreshOllamaModels } from './ollama-tags.js'
|
|
44
50
|
import { BILLING_CLASSES } from './billing-class.js'
|
|
51
|
+
import { BYOK_CUSTOMIZATION, customizationWithEgress } from './provider-customization.js'
|
|
45
52
|
|
|
46
53
|
// Compatibility re-export — resolution moved to ollama-tags.js (#5421).
|
|
47
54
|
export { resolveOllamaBaseUrl }
|
|
@@ -71,6 +78,13 @@ const OLLAMA_FALLBACK_MODELS = Object.freeze([
|
|
|
71
78
|
const OLLAMA_ZERO_PRICING = Object.freeze({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0 })
|
|
72
79
|
|
|
73
80
|
export class OllamaSession extends ClaudeByokSession {
|
|
81
|
+
static get customizationDescriptor() {
|
|
82
|
+
// Localhost is the default, but both CHROXY_OLLAMA_BASE_URL and OLLAMA_HOST
|
|
83
|
+
// may point at a remote origin. The descriptor must not claim local-only.
|
|
84
|
+
return customizationWithEgress(BYOK_CUSTOMIZATION, 'unknown')
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
static agentConnectionRoutes = ['local']
|
|
74
88
|
// #5858: NOT Claude-family — Ollama rides ClaudeByokSession's agent loop but
|
|
75
89
|
// serves locally-pulled models (getAllowedModels() returns null, #5418), so
|
|
76
90
|
// override the inherited flag to false (never soft-fall-back to claude).
|
|
@@ -133,6 +147,24 @@ export class OllamaSession extends ClaudeByokSession {
|
|
|
133
147
|
return OLLAMA_FALLBACK_MODELS
|
|
134
148
|
}
|
|
135
149
|
|
|
150
|
+
/**
|
|
151
|
+
* #7761 — this provider's static seed is a RECOMMENDATION list, not a roster
|
|
152
|
+
* claim: `OLLAMA_FALLBACK_MODELS` names coder models worth pulling, and
|
|
153
|
+
* `/api/tags` reports the ones this machine has actually pulled. The two are
|
|
154
|
+
* different facts, so a discovery refresh must UNION rather than replace, or
|
|
155
|
+
* the picker stops suggesting anything the user has not already installed
|
|
156
|
+
* (pinned in ollama-tags.test.js: "merged fallbacks").
|
|
157
|
+
*
|
|
158
|
+
* Every other non-Claude provider leaves this false — for them the refresh IS
|
|
159
|
+
* the provider's own roster, and unioning a hand-maintained table back in is
|
|
160
|
+
* exactly how a retired model reached the wire forever (#7761).
|
|
161
|
+
*
|
|
162
|
+
* @returns {boolean}
|
|
163
|
+
*/
|
|
164
|
+
static get staticModelsAreRecommendations() {
|
|
165
|
+
return true
|
|
166
|
+
}
|
|
167
|
+
|
|
136
168
|
static getAllowedModels() {
|
|
137
169
|
// null = no restriction. Valid models are whatever `ollama list`
|
|
138
170
|
// shows on this machine; the daemon can't know that statically, and
|
|
@@ -41,10 +41,17 @@ export function buildOrchestrationManager({ sessionManager, config, chroxyDir, l
|
|
|
41
41
|
})
|
|
42
42
|
// The factory owns construction, so it owns teardown: extend dispose() to
|
|
43
43
|
// also stop the turn driver (SessionManager listeners) and flush the ledger.
|
|
44
|
+
//
|
|
45
|
+
// Async since #7142: the manager's dispose settles once its backgrounded
|
|
46
|
+
// starts have. The order is load-bearing — mark the manager disposed, then
|
|
47
|
+
// abort in-flight turns (the driver rejects them), wait for the starts that
|
|
48
|
+
// rejection unwinds, and only THEN flush and close the ledger they would
|
|
49
|
+
// otherwise journal to.
|
|
44
50
|
const managerDispose = manager.dispose.bind(manager)
|
|
45
|
-
manager.dispose = () => {
|
|
46
|
-
managerDispose()
|
|
51
|
+
manager.dispose = async () => {
|
|
52
|
+
const drained = managerDispose()
|
|
47
53
|
try { turnDriver.dispose() } catch { /* idempotent best-effort */ }
|
|
54
|
+
try { await drained } catch { /* allSettled never rejects; belt and braces */ }
|
|
48
55
|
try { ledger.dispose() } catch { /* flushes pending snapshot writes */ }
|
|
49
56
|
}
|
|
50
57
|
log?.info?.('Orchestration engine enabled (features.orchestration)')
|
|
@@ -27,9 +27,10 @@
|
|
|
27
27
|
import { execFile as execFileCb } from 'node:child_process'
|
|
28
28
|
import { promisify } from 'node:util'
|
|
29
29
|
import { join, resolve, sep } from 'node:path'
|
|
30
|
-
import { homedir } from 'node:os'
|
|
31
30
|
import { rmSync, mkdirSync, existsSync } from 'node:fs'
|
|
32
31
|
import { GIT } from '../git.js'
|
|
32
|
+
import { configDir } from '../config-dir.js'
|
|
33
|
+
import { assertSafeArgvValue } from '../utils/argv-safety.js'
|
|
33
34
|
|
|
34
35
|
const execFileAsync = promisify(execFileCb)
|
|
35
36
|
|
|
@@ -44,9 +45,28 @@ const DIFF_MAX_BUFFER = 64 * 1024 * 1024
|
|
|
44
45
|
// carries a NUL/newline — defense-in-depth so a caller can never turn a branch
|
|
45
46
|
// name into a git flag. execFile already blocks SHELL injection; this blocks
|
|
46
47
|
// ARGUMENT injection.
|
|
48
|
+
//
|
|
49
|
+
// #7290: the CHECK now lives in utils/argv-safety.js and is shared with
|
|
50
|
+
// ws-file-ops/reader.js. This wrapper exists only to translate its Error into
|
|
51
|
+
// a GitOpsError; both messages (`empty <kind>` / `unsafe <kind>: <json>`) are
|
|
52
|
+
// produced there, and orchestration-git-ops.test.js pins the `unsafe` half.
|
|
53
|
+
// Do not re-inline the check here — #7290 was filed because a SECOND, weaker
|
|
54
|
+
// spelling had grown in reader.js. A THIRD spelling — `rejectGitOptionLike`
|
|
55
|
+
// in environments/backends/k8s.js, scoped to gitRepo fields — was folded
|
|
56
|
+
// into the shared guard by #7869.
|
|
47
57
|
function assertSafeRef(name, kind = 'ref') {
|
|
48
|
-
|
|
49
|
-
|
|
58
|
+
try {
|
|
59
|
+
assertSafeArgvValue(name, kind)
|
|
60
|
+
} catch (err) {
|
|
61
|
+
// Only validation errors are expected here. Anything else would be a bug
|
|
62
|
+
// inside the shared guard, so keep the original rather than silently
|
|
63
|
+
// relabelling it as an unsafe ref. GitOpsError's constructor takes
|
|
64
|
+
// { args, stderr } and does not forward `cause` to super(), so it is set
|
|
65
|
+
// here rather than passed in — passing it would be dropped on the floor.
|
|
66
|
+
const wrapped = new GitOpsError(err.message)
|
|
67
|
+
wrapped.cause = err
|
|
68
|
+
throw wrapped
|
|
69
|
+
}
|
|
50
70
|
}
|
|
51
71
|
|
|
52
72
|
// Byte-accurate UTF-8 truncation that drops an incomplete trailing multibyte
|
|
@@ -64,10 +84,10 @@ function byteSliceUtf8(str, maxBytes) {
|
|
|
64
84
|
// written to any user config.
|
|
65
85
|
const ORCH_IDENTITY = { name: 'chroxy-orch', email: 'orch@chroxy.local' }
|
|
66
86
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
}
|
|
87
|
+
// Re-exported for the orchestration tests, which resolve the root the same way
|
|
88
|
+
// the provisioner does. The resolver itself lives in config-dir.js (#7052) —
|
|
89
|
+
// this module used to carry its own copy.
|
|
90
|
+
export { configDir }
|
|
71
91
|
|
|
72
92
|
/** The root the orphan sweep and the provisioner MUST agree on. Never `runs/`. */
|
|
73
93
|
export function defaultWorktreesRoot() {
|
|
@@ -147,6 +167,17 @@ export function createGitOps({ git = GIT, now = () => Date.now(), worktreesRoot
|
|
|
147
167
|
// and total byte caps with explicit truncation markers so a small worker
|
|
148
168
|
// model isn't handed a 2MB patch.
|
|
149
169
|
const computeCappedDiff = async ({ repoDir, baseSha, headRef = 'HEAD', maxBytes = 65_536, maxFileBytes = 8_192 }) => {
|
|
170
|
+
// #7342: these were the only ref slots in this module that skipped the
|
|
171
|
+
// guard every neighbour applies. `<base>..<head>` is a positional REVISION,
|
|
172
|
+
// and a `--` separator does NOT protect one (measured in
|
|
173
|
+
// utils/argv-safety.js: `git diff -O/etc/nope --` still reads the
|
|
174
|
+
// orderfile), so rejection is the only correct shape. Both values come
|
|
175
|
+
// from captureHead()'s rev-parse output today — this closes the gap before
|
|
176
|
+
// a caller wires a client-supplied ref in. Unlike a git failure (returned
|
|
177
|
+
// as a structured result below), an unsafe ref is a programming error and
|
|
178
|
+
// throws.
|
|
179
|
+
assertSafeRef(baseSha, 'base ref')
|
|
180
|
+
assertSafeRef(headRef, 'head ref')
|
|
150
181
|
const statR = await run(['-C', repoDir, 'diff', '--stat', `${baseSha}..${headRef}`], { maxBuffer: DIFF_MAX_BUFFER })
|
|
151
182
|
const patchR = await run(['-C', repoDir, 'diff', `${baseSha}..${headRef}`], { maxBuffer: DIFF_MAX_BUFFER })
|
|
152
183
|
const stat = statR.ok ? statR.stdout : ''
|
|
@@ -249,6 +280,9 @@ export function createGitOps({ git = GIT, now = () => Date.now(), worktreesRoot
|
|
|
249
280
|
|
|
250
281
|
const createIntegrationWorktree = async ({ repoDir, runId, branchName, baseSha }) => {
|
|
251
282
|
assertSafeRef(branchName, 'branch')
|
|
283
|
+
// #7342: `baseSha` is the final positional operand of `worktree add`, so a
|
|
284
|
+
// dash-leading value would be read as an option there too.
|
|
285
|
+
assertSafeRef(baseSha, 'base ref')
|
|
252
286
|
const worktreePath = integrationWorktreePath(runId)
|
|
253
287
|
fs.mkdirSync(runWorktreesDir(runId), { recursive: true })
|
|
254
288
|
await runOrThrow(['-C', repoDir, 'worktree', 'add', '-b', branchName, worktreePath, baseSha])
|
|
@@ -37,6 +37,7 @@ import {
|
|
|
37
37
|
} from './role-prompts.js'
|
|
38
38
|
import { createGitOps } from './git-ops.js'
|
|
39
39
|
import { TurnError } from './turn-driver.js'
|
|
40
|
+
import { hasSpend } from './run-record.js'
|
|
40
41
|
import { recordToRunSummary, recordToRunDetail, gateToWire } from './to-wire.js'
|
|
41
42
|
import { buildRunReport, renderReportMarkdown } from './run-report.js'
|
|
42
43
|
|
|
@@ -76,34 +77,26 @@ const AUDIT_ELIGIBLE_PROVIDERS = new Set(['claude-sdk', 'claude-byok', 'codex'])
|
|
|
76
77
|
// `stopped` land on turn 2. None of the three below emit `stopped` after a
|
|
77
78
|
// `result`, so excluding claude-cli removes this failure by construction.
|
|
78
79
|
//
|
|
79
|
-
//
|
|
80
|
-
// claude-
|
|
81
|
-
//
|
|
82
|
-
//
|
|
83
|
-
//
|
|
84
|
-
//
|
|
85
|
-
//
|
|
86
|
-
//
|
|
87
|
-
//
|
|
88
|
-
//
|
|
89
|
-
// Client exit and the result-timeout also reach `_failTurn`, so an `error`
|
|
90
|
-
// notification is sufficient but not necessary — which of these the real
|
|
91
|
-
// binary actually does is unverified in-repo (#7072).
|
|
92
|
-
// Closing that needs the provider-side `interrupted: true` flag the turn-driver
|
|
93
|
-
// doc-block names, so a terminal-looking result can be marked
|
|
94
|
-
// terminal-but-not-successful. Tracked separately; it is a cross-provider wire
|
|
95
|
-
// change, not something this gate can express.
|
|
80
|
+
// CLOSED (#7072) — false success on an interrupted turn, for claude-sdk and
|
|
81
|
+
// claude-byok. A `result` payload carries `interrupted: true` when the turn
|
|
82
|
+
// ended by abort/interrupt/stall rather than completion, and TurnDriver rejects
|
|
83
|
+
// it (TURN_STOPPED, or TURN_ERROR for a stall) instead of resolving it:
|
|
84
|
+
// * claude-byok: an interrupt landing in the TOOL phase (not mid-stream) ends
|
|
85
|
+
// the loop at the `signal.aborted` check and emits its `result` marked
|
|
86
|
+
// stopped + interrupted.
|
|
87
|
+
// * claude-sdk: the stream-STALL synthetic `result` is marked interrupted and
|
|
88
|
+
// names the failure; a Stop the SDK answers with an `aborted_*` result is
|
|
89
|
+
// marked by BaseSession.emit for every result whose turnOutcome is `stopped`.
|
|
96
90
|
//
|
|
97
|
-
//
|
|
98
|
-
//
|
|
91
|
+
// codex app-server (#9241): `_finishTurn` now reads `turn.status` and reports an
|
|
92
|
+
// `interrupted` turn as a `stopped` result, which closes this the same way. The
|
|
93
|
+
// `turn/completed {status: 'interrupted'}` answer is documented by OpenAI but not
|
|
94
|
+
// pinned against a live binary here (#7072 follow-up), so an operator Stop on a
|
|
95
|
+
// codex architect session could still settle as a completed turn if it differs.
|
|
99
96
|
//
|
|
100
|
-
//
|
|
101
|
-
//
|
|
102
|
-
//
|
|
103
|
-
// would re-encode the very mistake this comment exists to correct, namely set
|
|
104
|
-
// membership implying a safety property it does not deliver. That position holds
|
|
105
|
-
// only while #7072 is open and honest; if #7072 is ever closed wontfix, revisit
|
|
106
|
-
// byok's membership rather than leaving this comment to rot.
|
|
97
|
+
// So this set means "vetted to not kill the NEXT turn", and — for claude-sdk and
|
|
98
|
+
// claude-byok — "cannot report an interrupted turn as complete". Anything outside
|
|
99
|
+
// it is unvetted for either.
|
|
107
100
|
const ARCHITECT_ELIGIBLE_PROVIDERS = new Set(['claude-sdk', 'claude-byok', 'codex'])
|
|
108
101
|
|
|
109
102
|
// v1: write/implement workers are codex-ONLY. codexSandbox:'workspace-write' is a
|
|
@@ -153,6 +146,11 @@ export class OrchestrationManager extends EventEmitter {
|
|
|
153
146
|
this._now = now
|
|
154
147
|
this._log = log
|
|
155
148
|
this._runs = new Map() // runId -> engine state
|
|
149
|
+
// #7142: the backgrounded `startRun` promises `createAndStartRun` launches.
|
|
150
|
+
// A start is a multi-minute architect turn that nothing awaits, so without a
|
|
151
|
+
// handle `dispose()` could neither wait for it nor tell it the manager is
|
|
152
|
+
// gone. Each entry removes itself when it settles (it never rejects).
|
|
153
|
+
this._starts = new Set()
|
|
156
154
|
this._reports = new Map() // runId -> the architect's synthesis narrative markdown
|
|
157
155
|
this._reportDocs = new Map() // runId -> { json, markdown } — the persisted M-4 report artifacts
|
|
158
156
|
this._maxReports = 32
|
|
@@ -184,11 +182,29 @@ export class OrchestrationManager extends EventEmitter {
|
|
|
184
182
|
}
|
|
185
183
|
}
|
|
186
184
|
|
|
185
|
+
/**
|
|
186
|
+
* Tear the engine down. Everything that stops the manager from touching its
|
|
187
|
+
* collaborators happens SYNCHRONOUSLY, before this returns: `_disposed` is set
|
|
188
|
+
* first, and `_failRun`, the background-start handlers and `startRun`'s
|
|
189
|
+
* post-plan continuation all check it (#7142). So a start still in flight
|
|
190
|
+
* when the manager goes away can no longer journal onto — or log through — a
|
|
191
|
+
* torn-down ledger/log, whether or not the caller waits.
|
|
192
|
+
*
|
|
193
|
+
* The returned promise resolves once every backgrounded start has settled.
|
|
194
|
+
* An in-flight start only settles when its architect turn does, and the turn
|
|
195
|
+
* is the TurnDriver's to abort, not this class's — the driver is injected and
|
|
196
|
+
* its owner disposes it (`dispose()` rejects in-flight turns SESSION_GONE).
|
|
197
|
+
* Dispose the driver BEFORE awaiting this, and before disposing the ledger the
|
|
198
|
+
* start would otherwise journal to.
|
|
199
|
+
*
|
|
200
|
+
* @returns {Promise<void>}
|
|
201
|
+
*/
|
|
187
202
|
dispose() {
|
|
188
203
|
this._disposed = true
|
|
189
204
|
if (this._onSessionFreed && typeof this._sm.off === 'function') this._sm.off('session_destroyed', this._onSessionFreed)
|
|
190
205
|
this._onSessionFreed = null
|
|
191
206
|
this._gate?.dispose?.()
|
|
207
|
+
return Promise.allSettled([...this._starts]).then(() => undefined)
|
|
192
208
|
}
|
|
193
209
|
|
|
194
210
|
// --- status writes: the FSM choke point (#6732) --------------------------
|
|
@@ -313,6 +329,10 @@ export class OrchestrationManager extends EventEmitter {
|
|
|
313
329
|
try {
|
|
314
330
|
plan = await this._plan(run)
|
|
315
331
|
} catch (err) {
|
|
332
|
+
// The owner disposed the manager (and so its TurnDriver) mid-plan: the
|
|
333
|
+
// turn rejecting SESSION_GONE is the teardown, not a plan failure, and
|
|
334
|
+
// there is no ledger left to journal it to (#7142).
|
|
335
|
+
if (this._disposed) return { runId, phase: run.phase }
|
|
316
336
|
return this._failRun(run, `PLAN_${err instanceof DecisionParseError ? 'PARSE' : 'FAILED'}`, err)
|
|
317
337
|
}
|
|
318
338
|
// A cancel that landed while this turn was in flight wins. Destroying a
|
|
@@ -323,6 +343,10 @@ export class OrchestrationManager extends EventEmitter {
|
|
|
323
343
|
// record ends up with phantom subtasks AND a rejected startRun.) `_runSubtask`
|
|
324
344
|
// makes the same re-check after its awaits.
|
|
325
345
|
if (run.cancelled) return { runId, phase: run.phase }
|
|
346
|
+
// Same for a dispose (#7142): the plan resolved after the manager went away,
|
|
347
|
+
// and everything below journals to a ledger its owner is about to (or has
|
|
348
|
+
// already) disposed.
|
|
349
|
+
if (this._disposed) return { runId, phase: run.phase }
|
|
326
350
|
// Materialize subtasks. A subtask runs 'implement' (write-capable) ONLY when
|
|
327
351
|
// the architect asked for it AND the run's worker provider is
|
|
328
352
|
// implement-eligible (codex, #6735) AND no preset forces audit. Otherwise it
|
|
@@ -370,25 +394,36 @@ export class OrchestrationManager extends EventEmitter {
|
|
|
370
394
|
*/
|
|
371
395
|
createAndStartRun(opts = {}) {
|
|
372
396
|
const record = this.createRun(opts)
|
|
373
|
-
this.startRun(record.runId)
|
|
397
|
+
const start = this.startRun(record.runId)
|
|
374
398
|
.catch((err) => {
|
|
375
399
|
// The run may already be gone (cancelled, or _failRun ran inside startRun).
|
|
376
400
|
const run = this._runs.get(record.runId)
|
|
377
|
-
if (!run) return null
|
|
401
|
+
if (!run || this._disposed) return null
|
|
378
402
|
return this._failRun(run, 'START_FAILED', err)
|
|
379
403
|
})
|
|
380
404
|
.catch((err) => {
|
|
405
|
+
// A disposed manager's log/ledger belong to someone else now (#7142).
|
|
406
|
+
if (this._disposed) return
|
|
381
407
|
this._log?.warn?.(`orchestration: run ${record.runId} failed to start and could not be journaled: ${err?.message || String(err)}`)
|
|
382
408
|
})
|
|
409
|
+
// Track it so `dispose()` can wait for it (#7142). `start` should never reject, but if
|
|
410
|
+
// the final handler itself throws, removal still runs and no derived promise
|
|
411
|
+
// is left rejecting unhandled.
|
|
412
|
+
this._starts.add(start)
|
|
413
|
+
const forget = () => { this._starts.delete(start) }
|
|
414
|
+
start.then(forget, forget)
|
|
383
415
|
return record
|
|
384
416
|
}
|
|
385
417
|
|
|
386
418
|
/**
|
|
387
419
|
* Wire-level run control (`orchestration_run_action`). `cancel` is the only
|
|
388
|
-
* action this engine implements
|
|
389
|
-
* have no user-driven implementation —
|
|
390
|
-
* are internal stalls the scheduler
|
|
391
|
-
*
|
|
420
|
+
* action this engine implements, and the only one the wire schema carries
|
|
421
|
+
* (#7140). `pause`/`resume` have no user-driven implementation —
|
|
422
|
+
* `_pauseForBudget`/`_pauseForResources` are internal stalls the scheduler
|
|
423
|
+
* clears itself, not a pause a client can hold — so the schema no longer
|
|
424
|
+
* admits them. This refusal stays as the engine's own backstop for a caller
|
|
425
|
+
* that reaches it without the wire validator: fail loudly rather than ack a
|
|
426
|
+
* no-op.
|
|
392
427
|
*/
|
|
393
428
|
async runAction(runId, action) {
|
|
394
429
|
if (action === 'cancel') {
|
|
@@ -435,7 +470,12 @@ export class OrchestrationManager extends EventEmitter {
|
|
|
435
470
|
|
|
436
471
|
if (gate.kind === 'epic_plan') {
|
|
437
472
|
if (decision === 'approve') return this._beginExecuting(run)
|
|
438
|
-
|
|
473
|
+
// Any non-approve decision on the plan (reject, revise, skip) declines it,
|
|
474
|
+
// and a declined plan is a cancellation, not a failure (design §3.2:
|
|
475
|
+
// plan_review --reject--> cancelled; #7131). The reason code tells it apart
|
|
476
|
+
// from a manual cancel ('user'); the reviewer's note is already journaled on
|
|
477
|
+
// the gate_resolved timeline entry.
|
|
478
|
+
return this.cancelRun(run.runId, { reason: 'plan_rejected' })
|
|
439
479
|
}
|
|
440
480
|
if (gate.kind === 'escalation') {
|
|
441
481
|
return this._resolveEscalation(run, gate, decision, note)
|
|
@@ -644,6 +684,8 @@ export class OrchestrationManager extends EventEmitter {
|
|
|
644
684
|
const st = subtaskId ? run.subtasks.get(subtaskId) : null
|
|
645
685
|
if (!st) return { runId: run.runId, resolved: true }
|
|
646
686
|
if (decision === 'skip') { await this._finishSubtask(run, subtaskId, 'skipped'); return { runId: run.runId, subtaskId, skipped: true } }
|
|
687
|
+
// The escalation verb is `fail-run` (engine.md §3.3): the user is deliberately
|
|
688
|
+
// failing the run, unlike a rejected plan, which cancels it (#7131).
|
|
647
689
|
if (decision === 'reject') return this._failRun(run, 'ESCALATION_REJECTED', new Error(note || 'user failed the run'))
|
|
648
690
|
// approve / revise → re-drive the subtask (iteration reset via a fresh worker)
|
|
649
691
|
st.state = 'pending'
|
|
@@ -770,16 +812,45 @@ export class OrchestrationManager extends EventEmitter {
|
|
|
770
812
|
let attempt = 0
|
|
771
813
|
let currentPrompt = prompt
|
|
772
814
|
let lastError = null
|
|
773
|
-
|
|
774
|
-
const { text, result } = await this._driver.driveTurn(sessionId, currentPrompt, { label: turnLabel, timeoutMs: this._cfg.turnTimeoutMs })
|
|
815
|
+
const recordUsageUnsafe = (result, terminalEvent = 'result') => {
|
|
775
816
|
const roleClass = run.ownedSessions.get(sessionId)?.role ?? null
|
|
776
817
|
// dotted ledger role: architect plan/synthesis vs architect.review, worker.audit
|
|
777
818
|
const ledgerRole = roleClass === 'architect'
|
|
778
819
|
? (turnLabel === 'poa_review' || turnLabel === 'result_review' ? 'architect.review' : 'architect')
|
|
779
820
|
: `worker.${roleClass}`
|
|
780
821
|
this._ledger.recordTurnUsage(run.runId, {
|
|
781
|
-
subtaskId, sessionId, role: ledgerRole, turnLabel, terminalEvent
|
|
822
|
+
subtaskId, sessionId, role: ledgerRole, turnLabel, terminalEvent, data: result,
|
|
782
823
|
})
|
|
824
|
+
}
|
|
825
|
+
// #9147 — the ledger is bookkeeping about the turn, never the turn's outcome: a
|
|
826
|
+
// failed write is logged and swallowed so the TurnError being rethrown (and so
|
|
827
|
+
// the TURN_STOPPED -> `interrupted` subtask mapping) or the resolved result
|
|
828
|
+
// propagates unchanged.
|
|
829
|
+
const recordUsage = (result, terminalEvent = 'result') => {
|
|
830
|
+
try { recordUsageUnsafe(result, terminalEvent) } catch (err) {
|
|
831
|
+
this._log?.warn?.(`orchestration: recording ${turnLabel} usage failed: ${err?.stack || err?.message || err}`)
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
// Skip null/empty synthetic stalls using the same token normalization as the
|
|
835
|
+
// ledger reducer.
|
|
836
|
+
while (attempt <= this._cfg.maxParseRetries) {
|
|
837
|
+
let turn
|
|
838
|
+
try {
|
|
839
|
+
turn = await this._driver.driveTurn(sessionId, currentPrompt, { label: turnLabel, timeoutMs: this._cfg.turnTimeoutMs,
|
|
840
|
+
// #9147: spend that arrives while a TURN_TIMEOUT drains (a bare `stopped`
|
|
841
|
+
// carries none, see TurnDriver.driveTurn). TurnDriver delivers it at most once and never to the next turn.
|
|
842
|
+
onLateUsage: (result, terminalEvent) => { if (hasSpend(result)) recordUsage(result, terminalEvent) },
|
|
843
|
+
})
|
|
844
|
+
} catch (err) {
|
|
845
|
+
// A rejected terminal result OR error can still have spent money/tokens
|
|
846
|
+
// (#8554). Require TurnDriver's explicit event provenance; thrown send
|
|
847
|
+
// failures are not accounting evidence.
|
|
848
|
+
const result = err instanceof TurnError && (err.terminalEvent === 'result' || err.terminalEvent === 'error') ? err.result : null
|
|
849
|
+
if (hasSpend(result)) recordUsage(result, err.terminalEvent)
|
|
850
|
+
throw err // an interrupted decision must never enter the parse/repair path
|
|
851
|
+
}
|
|
852
|
+
const { text, result } = turn
|
|
853
|
+
recordUsage(result)
|
|
783
854
|
try {
|
|
784
855
|
return { decision: extractDecision(text, kind).decision }
|
|
785
856
|
} catch (err) {
|
|
@@ -966,6 +1037,11 @@ export class OrchestrationManager extends EventEmitter {
|
|
|
966
1037
|
}
|
|
967
1038
|
|
|
968
1039
|
async _failRun(run, code, err) {
|
|
1040
|
+
// A manager that has been disposed owns nothing any more: its ledger may be
|
|
1041
|
+
// flushed and closed, its log gone. A start that was in flight at dispose
|
|
1042
|
+
// time is rejected by the TurnDriver teardown and lands here a tick later;
|
|
1043
|
+
// journaling `failed` then would write to a disposed ledger (#7142).
|
|
1044
|
+
if (this._disposed) return { runId: run.runId, phase: run.phase }
|
|
969
1045
|
// A cancel that already tore the run down wins: don't overwrite the
|
|
970
1046
|
// terminal 'cancelled' status with 'failed' (or double-emit lifecycle
|
|
971
1047
|
// events) when an in-flight turn rejects SESSION_GONE on the next tick.
|