@chroxy/server 0.10.0 → 0.11.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONFIG.md +602 -19
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +416 -11
- package/package.json +20 -23
- package/sidecar/Dockerfile +1 -1
- package/sidecar/PROTOCOL.md +9 -1
- package/sidecar/agent.js +102 -10
- package/sidecar/package-lock.json +3 -3
- package/src/acp-config.js +206 -0
- package/src/acp-session.js +954 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +293 -0
- package/src/agent-control/client.js +1616 -0
- package/src/agent-control/events.js +547 -0
- package/src/agent-control/local-connection.js +275 -0
- package/src/agent-control/mcp-server.js +545 -0
- package/src/anthropic-compatible-config.js +29 -4
- package/src/anthropic-compatible-session.js +15 -6
- package/src/anthropic-openai-shim.js +0 -1
- package/src/archive-continuation.js +164 -0
- package/src/assistant-response.js +24 -0
- package/src/auth-probes.js +120 -13
- package/src/background-shell-tracker.js +27 -0
- package/src/base-session.js +1353 -41
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +24 -1
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +101 -0
- package/src/bound-client-policy.js +279 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +74 -9
- package/src/built-in-tools/tool-transforms.js +1113 -13
- package/src/byok-compose-state.js +6 -9
- package/src/byok-credentials.js +2 -3
- package/src/byok-mcp-client.js +1153 -20
- package/src/byok-mcp-config.js +1712 -8
- package/src/byok-mcp-fleet.js +416 -29
- package/src/byok-mcp-oauth-store.js +329 -0
- package/src/byok-mcp-oauth.js +635 -0
- package/src/byok-mcp-trust.js +257 -40
- package/src/byok-session.js +1400 -149
- package/src/byok-tool-executor.js +2681 -38
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +96 -51
- package/src/chroxy-host-metadata.js +122 -0
- package/src/claude-channel-session.js +16 -10
- package/src/claude-model-catalog.js +131 -16
- package/src/claude-model-refresh.js +385 -0
- package/src/claude-model-request.js +103 -0
- package/src/claude-stream-parser.js +109 -3
- package/src/claude-tui/diagnostic-tail.js +83 -0
- package/src/claude-tui/form-driver.js +44 -7
- package/src/claude-tui/model-error.js +41 -0
- package/src/claude-tui/pty-driver.js +223 -60
- package/src/claude-tui/sanitize-question-payload.js +109 -0
- package/src/claude-tui/usage-limit.js +239 -0
- package/src/claude-tui-session.js +3611 -286
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +6 -6
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/deploy-cmd.js +46 -11
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/init-cmd.js +16 -17
- package/src/cli/providers-cmd.js +6 -6
- package/src/cli/schedule-cmd.js +804 -0
- package/src/cli/server-cmd.js +64 -2
- package/src/cli/service-cmd.js +70 -27
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +168 -14
- package/src/cli/tokens-cmd.js +212 -0
- package/src/cli/tunnel-cmd.js +256 -25
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1117 -116
- package/src/cli.js +8 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +2108 -101
- package/src/codex-bundled-client.js +66 -0
- package/src/codex-model-catalog.js +548 -0
- package/src/codex-model-rejections.js +87 -0
- package/src/codex-native-resume.js +104 -0
- package/src/codex-protocol-capabilities.js +188 -0
- package/src/codex-session.js +571 -45
- package/src/config-dir-migration.js +444 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +738 -52
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +5 -9
- package/src/connection-locality.js +60 -0
- package/src/container-liveness-monitor.js +189 -0
- package/src/continuation-metadata-worker.js +17 -0
- package/src/continuations.js +114 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +23 -30
- package/src/control-room/skills-inventory.js +8 -3
- package/src/control-room/survey.js +32 -0
- package/src/conversation-scanner.js +40 -18
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +24 -22
- package/src/credential-store.js +279 -29
- package/src/daemon-commit.js +92 -0
- package/src/daemon-idle-state.js +171 -0
- package/src/daemon-update-status.js +314 -0
- package/src/dashboard-build.js +70 -0
- package/src/declared-status.js +90 -0
- package/src/deepseek-credentials.js +2 -3
- package/src/dev-preview.js +169 -182
- package/src/device-preferences.js +2 -2
- package/src/diagnostics.js +3 -0
- package/src/diff-parser.js +87 -0
- package/src/discord-credentials.js +2 -3
- package/src/docker-byok-pool.js +3 -1
- package/src/docker-byok-session.js +678 -78
- package/src/docker-image-allowlist.js +23 -1
- package/src/docker-sdk-session.js +188 -4
- package/src/docker-session.js +293 -10
- package/src/doctor.js +783 -66
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +95 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +39 -10
- package/src/environments/backends/k8s.js +58 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +137 -14
- package/src/event-normalizer.js +363 -110
- package/src/external-session-registry.js +0 -0
- package/src/gemini-session.js +100 -7
- package/src/github-webhook.js +188 -4
- package/src/handler-utils.js +563 -62
- package/src/handlers/checkpoint-handlers.js +162 -20
- package/src/handlers/control-room-handlers.js +99 -29
- package/src/handlers/conversation-handlers.js +563 -25
- package/src/handlers/credential-handlers.js +43 -2
- package/src/handlers/daemon-update-handlers.js +81 -0
- package/src/handlers/evaluator-handlers.js +14 -1
- package/src/handlers/feature-handlers.js +186 -69
- package/src/handlers/file-handlers.js +101 -13
- package/src/handlers/github-webhook-handlers.js +204 -0
- package/src/handlers/input-handlers.js +689 -48
- package/src/handlers/orchestration-handlers.js +238 -0
- package/src/handlers/scheduler-handlers.js +584 -0
- package/src/handlers/session-handlers.js +546 -16
- package/src/handlers/session-pr-status-handlers.js +283 -0
- package/src/handlers/session-pr-threads-handlers.js +247 -0
- package/src/handlers/settings-handlers.js +822 -35
- package/src/handlers/skills-handlers.js +13 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/handlers/token-handlers.js +11 -2
- package/src/health-proof.js +40 -0
- package/src/history-page.js +104 -0
- package/src/http-routes.js +286 -8
- package/src/ide/search.js +24 -6
- package/src/ide/symbols.js +20 -6
- package/src/input-context.js +117 -0
- package/src/instruction-policy-compiler.js +229 -0
- package/src/instruction-policy.js +250 -0
- package/src/jsonl-reader.js +309 -48
- package/src/jsonl-subprocess-session.js +122 -9
- package/src/keychain.js +160 -13
- package/src/logger.js +240 -31
- package/src/mailbox-route.js +11 -22
- package/src/message-wire.js +386 -0
- package/src/model-discovery.js +43 -3
- package/src/models.js +1276 -174
- package/src/notification-prefs.js +100 -10
- package/src/notifications/discord-billing-sink.js +22 -5
- package/src/notifications/discord-ci-sink.js +243 -0
- package/src/notifications/discord-webhook-client.js +71 -0
- package/src/notifications/discord-webhook-sink.js +82 -12
- package/src/notifications/expo-push-sink.js +85 -6
- package/src/notifications/ready-body.js +16 -5
- package/src/ollama-session.js +34 -2
- package/src/orchestration/build-manager.js +63 -0
- package/src/orchestration/decision-contract.js +245 -0
- package/src/orchestration/git-ops.js +381 -0
- package/src/orchestration/orchestration-manager.js +1342 -0
- package/src/orchestration/permission-gate.js +121 -0
- package/src/orchestration/role-prompts.js +136 -0
- package/src/orchestration/run-budget.js +81 -0
- package/src/orchestration/run-ledger.js +487 -0
- package/src/orchestration/run-model.js +206 -0
- package/src/orchestration/run-record.js +336 -0
- package/src/orchestration/run-report.js +194 -0
- package/src/orchestration/to-wire.js +201 -0
- package/src/orchestration/turn-driver.js +422 -0
- package/src/orphan-reaper.js +413 -0
- package/src/outgoing-policy.js +183 -0
- package/src/pairing.js +236 -12
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-audit.js +79 -3
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1770 -0
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +1175 -94
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolver.js +174 -12
- package/src/permission-rule-store.js +411 -0
- package/src/permission-scope.js +43 -0
- package/src/platform.js +483 -23
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +228 -6
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +360 -8
- package/src/roster-broadcast.js +186 -0
- package/src/schedule-parser.js +311 -0
- package/src/scheduled-task-store.js +945 -0
- package/src/scheduler.js +1099 -0
- package/src/sdk-session.js +2374 -168
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +11 -2
- package/src/server-cli/server-orchestrator.js +50 -4
- package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +760 -62
- package/src/server-identity.js +42 -14
- package/src/service.js +682 -53
- package/src/session-archive-limits.js +15 -0
- package/src/session-archive.js +1029 -0
- package/src/session-busy-state.js +72 -0
- package/src/session-ci-watcher.js +926 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +3879 -308
- package/src/session-message-history.js +749 -37
- package/src/session-pr-status.js +654 -0
- package/src/session-pr-threads.js +271 -0
- package/src/session-preset-trust.js +3 -3
- package/src/session-preset.js +10 -5
- package/src/session-state-persistence.js +94 -17
- package/src/session-timeout-manager.js +20 -0
- package/src/session-title.js +168 -0
- package/src/session-token-store.js +70 -36
- package/src/session-wake.js +240 -0
- package/src/shell-approval-info.js +2 -2
- package/src/shell-approval-store.js +3 -1
- package/src/skills-loader.js +7 -4
- package/src/skills-manager.js +2 -2
- package/src/skills-trust.js +95 -13
- package/src/skills-usage.js +22 -5
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +596 -0
- package/src/subagent-counter.js +9 -1
- package/src/summarize-session.js +51 -4
- package/src/supervisor.js +99 -38
- package/src/sweep-stale-provider-dirs.js +95 -0
- package/src/thinking-level-wire.js +39 -0
- package/src/thinking-stream.js +179 -0
- package/src/token-manager.js +39 -9
- package/src/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +413 -31
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +145 -35
- package/src/tunnel/index.js +13 -1
- package/src/tunnel/preview.js +64 -0
- package/src/tunnel-check.js +1 -1
- package/src/turn-outcome.js +137 -0
- package/src/turn-tracker.js +0 -0
- package/src/usage-normalize.js +122 -0
- package/src/user-shell-session.js +157 -37
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +741 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +597 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +25 -0
- package/src/utils/bounded-regex.js +153 -0
- package/src/utils/claude-binary.js +43 -0
- package/src/utils/claude-config-dir.js +245 -0
- package/src/utils/claude-login-command.js +16 -0
- package/src/utils/claude-native-route.js +81 -0
- package/src/utils/componentwise-resolver.js +301 -0
- package/src/utils/composite-key.js +45 -0
- package/src/utils/deploy-control-files.js +87 -0
- package/src/utils/exec-failure-reason.js +21 -0
- package/src/utils/git-repo.js +42 -0
- package/src/utils/is-entry-point.js +137 -0
- package/src/utils/iso-datetime.js +51 -0
- package/src/utils/node-pty-probe.js +95 -0
- package/src/utils/node-pty-support.js +118 -0
- package/src/utils/opened-file-path.js +167 -0
- package/src/utils/path-containment.js +165 -0
- package/src/utils/permission-mode-sidecar.js +51 -0
- package/src/utils/preflight.js +485 -29
- package/src/utils/read-limiter.js +217 -0
- package/src/utils/regular-file.js +375 -0
- package/src/utils/safe-regex.js +113 -0
- package/src/utils/small-file.js +129 -0
- package/src/utils/spawn-env.js +196 -5
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-binary.js +276 -0
- package/src/utils/verify-provenance.js +634 -0
- package/src/utils/wire-counters.js +48 -0
- package/src/web-task-manager.js +256 -16
- package/src/worktree-gc.js +11 -3
- package/src/ws-auth.js +69 -21
- package/src/ws-broadcaster.js +14 -2
- package/src/ws-client-manager.js +16 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +370 -66
- package/src/ws-file-ops/common.js +384 -11
- package/src/ws-file-ops/git.js +615 -44
- package/src/ws-file-ops/index.js +7 -0
- package/src/ws-file-ops/memory.js +460 -0
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +676 -94
- package/src/ws-forwarding.js +373 -55
- package/src/ws-handler-context.js +89 -2
- package/src/ws-history.js +1018 -177
- package/src/ws-message-handlers.js +23 -1
- package/src/ws-outbound-schemas.js +207 -0
- package/src/ws-permissions.js +589 -38
- package/src/ws-schemas.js +6 -0
- package/src/ws-server.js +936 -105
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
- package/src/dashboard-next/dist/index.html +0 -13
package/src/ws-server.js
CHANGED
|
@@ -5,40 +5,50 @@ import { WebSocketServer } from 'ws'
|
|
|
5
5
|
import { readFileSync } from 'fs'
|
|
6
6
|
import { fileURLToPath } from 'url'
|
|
7
7
|
import { dirname, join } from 'path'
|
|
8
|
-
import { homedir } from 'os'
|
|
9
8
|
import { PagesStore } from './pages-store.js'
|
|
10
9
|
import { ShellApprovalStore } from './shell-approval-store.js'
|
|
11
10
|
import { finalizeShellCreate } from './handlers/session-handlers.js'
|
|
12
11
|
import { decrypt, DIRECTION_CLIENT } from '@chroxy/store-core/crypto'
|
|
13
12
|
import { safeTokenCompare } from './token-compare.js'
|
|
14
13
|
import { createClientSender } from './ws-client-sender.js'
|
|
14
|
+
import { isAuthorityRevoked } from './connection-authority.js'
|
|
15
15
|
import { ClientMessageSchema, EncryptedEnvelopeSchema } from './ws-schemas.js'
|
|
16
16
|
import { EventNormalizer } from './event-normalizer.js'
|
|
17
17
|
import { createFileOps } from './ws-file-ops/index.js'
|
|
18
18
|
import { createPermissionHandler } from './ws-permissions.js'
|
|
19
19
|
import { setupForwarding } from './ws-forwarding.js'
|
|
20
20
|
import { handleSessionMessage, handleCliMessage } from './ws-message-handlers.js'
|
|
21
|
+
import { refuseBoundMessage } from './bound-client-policy.js'
|
|
21
22
|
import { handleAuthMessage, handlePairMessage, handlePairRequestMessage, handleKeyExchange, BENIGN_PAIR_WINDOW_MS } from './ws-auth.js'
|
|
22
23
|
import { postPairLinkToDiscord } from './discord-pair-delivery.js'
|
|
23
|
-
import { sendPostAuthInfo, replayHistory, flushPostAuthQueue, sendSessionInfo } from './ws-history.js'
|
|
24
|
+
import { sendPostAuthInfo, replayHistory, flushPostAuthQueue, sendSessionInfo, reseedActiveAgents, resendPendingQuestions, resendPendingPermissionsForSession } from './ws-history.js'
|
|
24
25
|
import { createDevicePreferences } from './device-preferences.js'
|
|
25
|
-
import { isUserShellEnabled, isIdeFeatureEnabled } from './config.js'
|
|
26
|
+
import { isUserShellEnabled, isIdeFeatureEnabled, isOrchestrationEnabled, DEFAULT_MAX_PAYLOAD_BYTES } from './config.js'
|
|
26
27
|
import { createHttpHandler } from './http-routes.js'
|
|
28
|
+
import { getDashboardBuildId } from './dashboard-build.js'
|
|
29
|
+
import { setMcpOAuthCallbackBase } from './byok-mcp-oauth.js'
|
|
27
30
|
import { CheckpointManager } from './checkpoint-manager.js'
|
|
28
31
|
import { DevPreviewManager } from './dev-preview.js'
|
|
32
|
+
import { broadcastEnvironmentList, isBoundClient, isBoundToOtherSession, CONVERSATION_FRAME } from './environments/authority.js'
|
|
29
33
|
import { WebTaskManager } from './web-task-manager.js'
|
|
30
34
|
import { RateLimiter, getClientIp, getRateLimitKey, LOOPBACK_ADDRESSES } from './rate-limiter.js'
|
|
31
35
|
import { isUserShellApprovalRequired } from './config.js'
|
|
32
36
|
import { writeShellApprovalInfo, removeShellApprovalInfo } from './shell-approval-info.js'
|
|
33
|
-
import { createLogger, addLogListener, removeLogListener } from './logger.js'
|
|
37
|
+
import { createLogger, addLogListener, removeLogListener, loggableValue } from './logger.js'
|
|
34
38
|
import { PermissionAuditLog } from './permission-audit.js'
|
|
35
39
|
import { WsBroadcaster } from './ws-broadcaster.js'
|
|
36
40
|
import { WsClientManager } from './ws-client-manager.js'
|
|
37
|
-
import { terminalMirrorRecipient } from './handler-utils.js'
|
|
38
|
-
import {
|
|
39
|
-
import {
|
|
41
|
+
import { terminalMirrorRecipient, canClientSeeWebTask } from './handler-utils.js'
|
|
42
|
+
import { frameForBoundClient } from './outgoing-policy.js'
|
|
43
|
+
import { captureBearer, bearerStillValid } from './bearer-recheck.js'
|
|
44
|
+
import { getProviderDataDirs, getProviderTranscriptSources, resolveDaemonDefaultProvider } from './providers.js'
|
|
45
|
+
import { assertCtxShape, buildMessageCtx } from './ws-handler-context.js'
|
|
40
46
|
import { isLoopbackHost } from './bind-host.js'
|
|
47
|
+
import { getLanIp } from './lan-ip.js'
|
|
48
|
+
import { deriveWebhookPayloadUrl } from './github-webhook.js'
|
|
41
49
|
import { isLocalOrLanPeer } from './connection-locality.js'
|
|
50
|
+
import { configPath } from './config-dir.js'
|
|
51
|
+
import { QuestionRouteMap } from './question-route-map.js'
|
|
42
52
|
|
|
43
53
|
const __filename = fileURLToPath(import.meta.url)
|
|
44
54
|
const __dirname = dirname(__filename)
|
|
@@ -181,6 +191,13 @@ export const TUNNEL_STATUS_MIN_PROTOCOL_VERSION = 2
|
|
|
181
191
|
let _latestVersionCache = { version: null, checkedAt: 0 }
|
|
182
192
|
const VERSION_CHECK_TTL = 3600_000 // 1 hour
|
|
183
193
|
|
|
194
|
+
// #7053: how long the panic-revoke ack waits on its durable-write persist before
|
|
195
|
+
// reporting the outcome as UNKNOWN. Long enough that a slow-but-working fsync or
|
|
196
|
+
// keychain call still reports the truthful result, short enough that an operator
|
|
197
|
+
// who just hit the panic button is not left staring at nothing. Overridable per
|
|
198
|
+
// instance via `_revokeAckTimeoutMs` (tests use a few ms).
|
|
199
|
+
const REVOKE_ACK_TIMEOUT_MS = 10_000
|
|
200
|
+
|
|
184
201
|
// #5555.6 — keepalive sweep cadence. Previously 30s, which (with the
|
|
185
202
|
// two-phase mark-then-terminate cycle) held a zombie client up to ~60s — ~6×
|
|
186
203
|
// longer than a client holds a zombie server (15s ping + 5s pong timeout =
|
|
@@ -191,6 +208,20 @@ const VERSION_CHECK_TTL = 3600_000 // 1 hour
|
|
|
191
208
|
// Cloudflare / mobile-OS idle timeouts open for clients that don't initiate.
|
|
192
209
|
export const KEEPALIVE_SWEEP_MS = 15_000
|
|
193
210
|
|
|
211
|
+
// Application close code sent when a connection's credential stops being valid
|
|
212
|
+
// (the pairing token was revoked, expired or evicted). Distinct from the
|
|
213
|
+
// protocol-level 1008 so a client re-pairs instead of retrying the dead token.
|
|
214
|
+
export const WS_CLOSE_CREDENTIAL_INVALID = 4401
|
|
215
|
+
|
|
216
|
+
// The revoke acknowledgement's error codes (the only errors a stripped connection still gets).
|
|
217
|
+
const REVOKE_NOTICE_ERROR_CODES = new Set(['REVOKE_NOT_DURABLE', 'REVOKE_DURABILITY_UNKNOWN'])
|
|
218
|
+
|
|
219
|
+
// Frames that belong to the authentication handshake and are never withheld.
|
|
220
|
+
const AUTH_FLOW_FRAME_TYPES = new Set([
|
|
221
|
+
'auth_ok', 'auth_fail', 'key_exchange_ok', 'pair_fail', 'pair_result',
|
|
222
|
+
'pair_request_pending', 'pair_request_ack',
|
|
223
|
+
])
|
|
224
|
+
|
|
194
225
|
async function checkLatestVersion(packageName) {
|
|
195
226
|
const now = Date.now()
|
|
196
227
|
if (_latestVersionCache.checkedAt > 0 && (now - _latestVersionCache.checkedAt) < VERSION_CHECK_TTL) {
|
|
@@ -256,7 +287,7 @@ function _isSecureRequest(req) {
|
|
|
256
287
|
* { type: 'cancel_queued', clientMessageId, sessionId? } — cancel ONE queued send-while-busy follow-up (#5943); server emits message_dequeued(reason: 'cancelled')
|
|
257
288
|
* { type: 'set_model', model: '...' } — change model on active session
|
|
258
289
|
* { type: 'set_permission_mode', mode: '...', confirmed? } — change permission mode (confirmed: true required for 'auto')
|
|
259
|
-
* { type: 'permission_response', requestId, decision } — respond to permission prompt
|
|
290
|
+
* { type: 'permission_response', requestId, decision, scope? } — respond to permission prompt; `scope: 'session'` beside `allow` labels an "Allow for Session" answer (#8517: a label only, shown on permission_resolved and in the journal; the session rule is a separate set_permission_rules)
|
|
260
291
|
* { type: 'list_sessions' } — request session list
|
|
261
292
|
* { type: 'switch_session', sessionId } — switch to a different session
|
|
262
293
|
* { type: 'create_session', name?, cwd?, provider?, agentCommId? } — create a new session
|
|
@@ -265,9 +296,11 @@ function _isSecureRequest(req) {
|
|
|
265
296
|
* { type: 'register_push_token', token } — register push token for notifications
|
|
266
297
|
* { type: 'user_question_response', answer } — respond to AskUserQuestion prompt
|
|
267
298
|
* { type: 'list_directory', path? } — request directory listing for file browser
|
|
299
|
+
* { type: 'check_git_repo', path, requestId? } — is path a git repo? (New Session worktree switch, #8972)
|
|
268
300
|
* { type: 'browse_files', path? } — request file/directory listing for file browser
|
|
269
301
|
* { type: 'read_file', path } — request file content for file viewer
|
|
270
302
|
* { type: 'write_file', path, content } — write file content (path validated, 5MB limit)
|
|
303
|
+
* { type: 'memory_read', requestId? } — request the effective merged CLAUDE.md memory stack + auto-memory descriptor (#6864, epic #6760); no client-supplied path (server-chosen locations only)
|
|
271
304
|
* { type: 'list_slash_commands' } — request available slash commands
|
|
272
305
|
* { type: 'list_agents' } — request available custom agents
|
|
273
306
|
* { type: 'request_full_history', sessionId? } — request full JSONL history for a session
|
|
@@ -286,10 +319,12 @@ function _isSecureRequest(req) {
|
|
|
286
319
|
* { type: 'get_diff', path? } — request git diff for working directory
|
|
287
320
|
* { type: 'git_branches' } — request git branch list
|
|
288
321
|
* { type: 'git_commit', message, files? } — commit staged/specified files
|
|
322
|
+
* { type: 'git_create_pr', title, body?, base?, draft? } — push current branch + open a PR via gh (#6876)
|
|
289
323
|
* { type: 'git_stage', files } — stage files for commit
|
|
290
324
|
* { type: 'git_status' } — request git status
|
|
291
325
|
* { type: 'git_unstage', files } — unstage files
|
|
292
326
|
* { type: 'list_conversations' } — request saved conversation list
|
|
327
|
+
* { type: 'request_conversation_transcript', conversationId, cwd? } — read-only replay of a CLOSED conversation from disk (no provider spawn; #6860)
|
|
293
328
|
* { type: 'list_files', path? } — request file listing for a path
|
|
294
329
|
* { type: 'list_symbols', path? } — request workspace symbol table (#6471, opt-in IDE — features.ide)
|
|
295
330
|
* { type: 'resolve_symbol', symbol, file? } — resolve a symbol name to its definition (#6475, opt-in IDE — features.ide)
|
|
@@ -312,8 +347,16 @@ function _isSecureRequest(req) {
|
|
|
312
347
|
* { type: 'terminal_unsubscribe', sessionId } — #5835 opt OUT of a session's live PTY mirror
|
|
313
348
|
* { type: 'terminal_resize', sessionId, cols, rows } — #5835 Phase 2 request to resize the live claude-tui PTY; applied only for the session's primary owner (or an unclaimed session), then broadcast back as terminal_size
|
|
314
349
|
* { type: 'terminal_input', sessionId, data } — #5835 Phase 3 raw keystrokes → live claude-tui PTY (true remote control); authority mirrors `input` (bound-session check + single-driver primary gate; an observer's keystroke is rejected with input_conflict)
|
|
315
|
-
* { type: 'set_thinking_level', level } — set
|
|
350
|
+
* { type: 'set_thinking_level', level } — set the reasoning level; `level: null` CLEARS the session's override back to the provider/model default with no roster check (#7786). Otherwise the accepted values are whatever the session's ACTIVE MODEL advertises (`reasoningLevels`), falling back to the Claude triple for a model row that carries none (#7730)
|
|
316
351
|
* { type: 'set_permission_rules', rules, sessionId } — set per-session auto-approval rules
|
|
352
|
+
* { type: 'set_mcp_server_enabled', server, enabled, sessionId?, requestId? } — #6824 runtime park/unpark of an ALREADY-CONFIGURED MCP server (BYOK lane; own-session gate)
|
|
353
|
+
* { type: 'submit_mcp_auth_code', server, code, sessionId?, requestId? } — #6822 submit a pasted OAuth authorization code for a remote MCP server (BYOK lane)
|
|
354
|
+
* { type: 'add_mcp_server', name, config, scope?, sessionId?, requestId? } — #6974 ADD an MCP server, persisting it to the user's MCP config (BYOK lane; STRICT-PRIMARY gate — any non-primary token is rejected, since a configured server is a command this machine will spawn; #7001)
|
|
355
|
+
* { type: 'remove_mcp_server', name, scope?, sessionId?, requestId? } — #6974 permanently REMOVE a configured MCP server from the user's MCP config (BYOK lane; same strict-primary gate)
|
|
356
|
+
* { type: 'scheduled_tasks_request', requestId? } — #6871 read the standing scheduled-task registry + the scheduler gate state (host-level: a pairing-BOUND client is rejected)
|
|
357
|
+
* { type: 'scheduled_task_action', action, taskId?, handle?, task?, requestId? } — #6871 create/update/pause/resume/delete a scheduled task, or (#7079) `discard_unreadable` a load-refused stored entry by its opaque server-derived `handle` (UNBOUND-STRICT-PRIMARY gate — a scheduled task makes this machine run an agent session unattended; a pairing-BOUND client is rejected even if it is primary, #7025)
|
|
358
|
+
* { type: 'set_scheduler_enabled', enabled, requestId? } — #6871 flip the PERSISTED global scheduled-execution gate (features.scheduler); same unbound-strict-primary gate, and a daemon restart is required for it to take effect (reported as scheduler.restartRequired)
|
|
359
|
+
* { type: 'daemon_update_action', action: 'restart-now'|'postpone', target, confirmBusy?, requestId? } — #8331 apply or hold off the update the idle-only auto-deploy has queued for the daily daemon (STRICT-PRIMARY + UNBOUND gate — restarting kills every live session; a pairing or bound client gets daemon_update_action_result{code:NOT_AUTHORIZED} and nothing is written). restart-now with busy sessions and no confirmBusy replies daemon_update_confirm_required instead of writing
|
|
317
360
|
* { type: 'set_prompt_evaluator', value: boolean, sessionId? } — toggle the per-session promptEvaluator (#3185)
|
|
318
361
|
* { type: 'set_prompt_evaluator_skip_pattern', value: string|null, sessionId? } — set the per-session evaluator skip-pattern source (#3639)
|
|
319
362
|
* { type: 'set_chroxy_context_hint', value: boolean, sessionId? } — toggle the per-session Chroxy context hint (#3805)
|
|
@@ -325,52 +368,77 @@ function _isSecureRequest(req) {
|
|
|
325
368
|
* { type: 'extension_message', ... } — opaque extension payload (passthrough, no server handling)
|
|
326
369
|
* { type: 'create_environment', name, cwd, image?, ... } — create persistent container environment
|
|
327
370
|
* { type: 'list_environments' } — list all persistent environments
|
|
328
|
-
* { type: 'destroy_environment', environmentId }
|
|
371
|
+
* { type: 'destroy_environment', environmentId, force? } — destroy an environment and its container. #7562: REFUSES while sessions are running inside it (environment_error, code ENVIRONMENT_HAS_LIVE_SESSIONS) unless `force: true`, which destroys those sessions cleanly FIRST and then the environment
|
|
329
372
|
* { type: 'get_environment', environmentId } — get single environment details
|
|
373
|
+
* { type: 'list_failed_restores' } — #7625 roster of sessions the boot restore could not bring back (BOUND-REFUSED: rows carry cwd, an absolute host path, plus a sibling-session roster — same reasoning as list_environments #7596. Replies with a degraded, schema-valid failed_restores_list carrying refused+code, not an error, so the caller never waits on a reply that never comes)
|
|
374
|
+
* { type: 'retry_failed_restore', sessionId } — #7625 re-attempt one parked failed restore (BOUND-REFUSED, at the UNBOUND bar rather than strict primary: the caller supplies a sessionId and nothing else — provider, cwd and every spawn input come from the entry the daemon itself persisted, so there is no caller-chosen binary/argv/env)
|
|
375
|
+
* { type: 'get_failed_restore_history', sessionId, offset?, limit? } — #8860 read one page (oldest first; limit clamped 1..100, default 50) of a parked failed restore's PRESERVED history, so a session that can never be resumed (e.g. a Codex auto-mode session with no native locator) is still readable. READ-ONLY: resumes, rebuilds and creates nothing, so the native-resume contract is unchanged. BOUND-REFUSED, at least as strict as list_failed_restores — the history is transcript content, more sensitive than the roster's cwd. Replies with a degraded, schema-valid failed_restore_history carrying ok:false+refused+code, not an error
|
|
376
|
+
* { type: 'list_archived_sessions' } — provider-neutral session archive: the roster of ended sessions whose chroxy-held history was kept (closed, idle-timed-out, stale at boot, dismissed/expired failed restores). READ-ONLY. BOUND-REFUSED like get_failed_restore_history (rows carry cwd and the names of sibling sessions); replies with a degraded, schema-valid archived_sessions_list carrying refused+code, not an error
|
|
377
|
+
* { type: 'get_archived_session_history', archiveId, offset?, limit? } — read one page (oldest first; limit clamped 1..100, default 50, ~256 KiB per page) of an archived session's history. READ-ONLY: resumes and creates nothing. BOUND-REFUSED before the archiveId is validated or looked up. archiveId is a server-generated token; only a known one is accepted and no path is ever built from client input
|
|
378
|
+
* { type: 'delete_archived_session', archiveId? | all: true } — remove one archive record, or all of them. Touches only archive records (no live session, no failed restore). BOUND-REFUSED. Exactly one of archiveId / all:true
|
|
379
|
+
* { type: 'restore_archived_session', archiveId, mode: 'native' | 'new_thread' } — #8866 continue an archived session, on an explicit request only. native resumes the SAME conversation (the boot / retry recipe) and the record leaves the archive (released, no tombstone); new_thread starts a NEW session in the archived cwd/provider/model (no permissionMode, sandbox, locator or worktree carried; container binding kept or refused) that carries a bounded (32 KiB) transcript of the archived history with its FIRST user message, and the record stays. BOUND-REFUSED before the archiveId is validated or looked up
|
|
380
|
+
* { type: 'set_session_archive_policy', enabled, maxEntries, maxAgeDays, maxMegabytes, purge?, requestId? } — #8869 replace the archive retention policy of the running daemon (retention re-runs now) and persist it to config. All four fields required and validated like the sessionArchive config block (maxEntries above 1000 is rejected, not clamped); purge:true (delete every existing archive) is only valid with enabled:false. UNBOUND-ONLY (BOUND-REFUSED, the delete_archived_session bar)
|
|
330
381
|
*
|
|
331
382
|
* Server -> Client:
|
|
332
383
|
* All session-scoped messages include a `sessionId` field for background sync.
|
|
333
|
-
*
|
|
334
|
-
*
|
|
335
|
-
*
|
|
384
|
+
* Field lists below are PINNED to the protocol schemas by tests/ws-outbound-coverage.test.js (#7107):
|
|
385
|
+
* every schema-backed line must name every field of its Server*Schema (bar `type` and the
|
|
386
|
+
* broadcaster-injected `sessionId`) and nothing the schema lacks, and a `?` must be optional in
|
|
387
|
+
* the schema. Fields a producer sends that the schema does not declare are the checked
|
|
388
|
+
* ROSTER_FIELDS_SCHEMA_LACKS list in that test. Lines whose type has no schema are unpinned.
|
|
389
|
+
* { type: 'auth_ok', clientId, serverMode, serverVersion, latestVersion, dashboardBuildId?, serverCommit, cwd, defaultCwd, connectedClients, encryption, protocolVersion, minProtocolVersion, maxProtocolVersion, webFeatures, features, capabilities?, availablePermissionModes?, availablePermissionModesProvider?, resultTimeoutMs, hardTimeoutMs, streamStallTimeoutMs, exposure?, billingCanary?, serverPublicKey?, serverKeySig?, newIdentityKey?, rotationCert? } — auth succeeded (encryption: 'required'|'disabled'; resultTimeoutMs = soft-warning window in ms, hardTimeoutMs = hard-kill window in ms, streamStallTimeoutMs = stream-stall recovery window in ms (0 = disabled) — #3760, #3905, #4477)
|
|
390
|
+
* { type: 'key_exchange_ok', publicKey, serverKeySig?, newIdentityKey?, rotationCert? } — server's ephemeral X25519 public key (E2E encryption)
|
|
391
|
+
* { type: 'auth_bootstrap', providers, slashCommands, agents, defaultProvider?, sessionId?, tunnelUrl?, sessionToken?, credentialConfirmation? } — #5555: connect-time burst folding the provider/slash-command/agent lists so a new client skips its 3-request list_* round trip; tunnelUrl re-advertises the live public URL (sub-item 7)
|
|
392
|
+
* { type: 'provider_runtime_info', sessionId, provider, binaryVersion, binaryPath?, newerBinary?, rejectedModels?, inputRequiresReady, capabilities, customization, projectInstructions } — #7745/#7835 live provider identity plus bounded customization and instruction-delivery evidence; resent on connect, switch, reconnect and late join, then refreshed on ready
|
|
336
393
|
* { type: 'tunnel_url_changed', url, previousUrl? } — #5555 (sub-item 7): quick-tunnel recovery rotated the public URL; clients repoint their stored endpoint. Best-effort for tunnel-connected clients (their socket rode the now-dead old tunnel); durable recovery is auth_bootstrap.tunnelUrl on reconnect
|
|
337
394
|
* { type: 'auth_fail', reason: '...' } — auth failed
|
|
338
395
|
* { type: 'server_mode', mode: 'cli' } — which backend mode is active
|
|
339
|
-
* { type: 'message',
|
|
340
|
-
* { type: '
|
|
341
|
-
* { type: '
|
|
342
|
-
* { type: '
|
|
396
|
+
* { type: 'message', messageType, content, tool?, options?, timestamp, code?, subtype?, compactMetadata?, mcpPromptExpansion?, attemptedResumeId?, authCause?, stdout?, stderr?, timeoutMs?, retrySafe?, delivery?, kind?, thinkingDurationMs?, thinkingTokens?, thinkingPrecedes?, historySeq? } — parsed chat message
|
|
397
|
+
* { type: 'input_ack', sessionId, clientMessageId, status, delivery, retrySafe, retentionExpiresAt?, dedupScope, acceptedAt?, reason?, message?, context? } — #7822 correlated input validation/queue acceptance; never provider completion
|
|
398
|
+
* { type: 'stream_start', messageId: '...', serverTs?, thinking?, thinkingPrecedes? } — beginning of streaming response
|
|
399
|
+
* { type: 'stream_delta', messageId, delta, serverTs?, thinking? } — token-by-token text
|
|
400
|
+
* { type: 'stream_end', messageId: '...', serverTs?, thinking?, thinkingDurationMs?, thinkingTokens? } — streaming response complete
|
|
343
401
|
* { type: 'terminal_output', sessionId, data } — #5835 live claude-tui PTY mirror (raw, ANSI-intact, coalesced ~50ms); emitted from ws-forwarding.js to clients that opted in via terminal_subscribe; the remote-viewer / authenticity surface
|
|
344
402
|
* { type: 'terminal_size', sessionId, cols, rows } — #5835 Phase 2 authoritative live-PTY grid size; sent to a client on terminal_subscribe and broadcast to all terminal subscribers on a primary-driven terminal_resize so observers re-letterbox to the same grid
|
|
345
|
-
* { type: 'tool_start', messageId, toolUseId, tool, input, serverName? } — tool invocation (serverName present for MCP tools)
|
|
403
|
+
* { type: 'tool_start', messageId, toolUseId, tool, input, serverName?, historySeq? } — tool invocation (serverName present for MCP tools)
|
|
346
404
|
* { type: 'tool_input_delta', messageId, toolUseId, partialJson } — #4080/#4081: incremental partial JSON for the streaming tool_use `input`; concatenate per-toolUseId for the live bubble preview
|
|
347
|
-
* { type: 'tool_result',
|
|
348
|
-
* { type: 'mcp_servers', servers: [{ name, status }] }
|
|
349
|
-
* { type: 'result',
|
|
405
|
+
* { type: 'tool_result', toolUseId, result, truncated, images?, isError?, terminatedReason?, input?, historySeq? } — tool result (images: [{mediaType, data}]; #6712 isError flags a failed tool for the error affordance)
|
|
406
|
+
* { type: 'mcp_servers', servers: [{ name, status, enabled?, canToggle?, authUrl? }] } — configured MCP servers (#6824: enabled + canToggle per-server; BYOK lane sets canToggle:true so clients render the enable/disable toggle; status 'disabled' = parked; #6822: status 'oauth-required' + authUrl surfaces the browser authorization URL a remote server needs)
|
|
407
|
+
* { type: 'result', cost?, duration?, usage?, queueLength?, contextOccupancy?, turnOutcome?, timestamp?, historySeq?, replayed? } — query stats; #8965 replayed:true marks a result the server is replaying from history; #7326 turnOutcome? ('completed'|'truncated'|'refused'|'stopped') says how the turn ended, timestamp? is the marker's identity for the marked ones
|
|
350
408
|
* { type: 'status', connected: true } — connection status
|
|
351
|
-
* { type: 'claude_ready' } — Claude Code ready for input
|
|
409
|
+
* { type: 'claude_ready', backgroundTasks?, scheduledWakeup? } — Claude Code ready for input
|
|
352
410
|
* { type: 'model_changed', model: '...' } — active model updated
|
|
411
|
+
* { type: 'thinking_level_changed', level: '...', effective?: '...'|null, sessionId? } — #7803 active thinking/reasoning level updated (four senders, one builder in thinking-level-wire.js: ws-history.js's reconnect/tab-switch replay, settings-handlers.js after an accepted set_thinking_level, event-normalizer.js's `ready` burst for the level a fresh codex session booted at, and event-normalizer.js's own entry for a level the session changed or learned). #8700: `effective` is the level the provider reports it applied, sent only by a provider declaring `capabilities.thinkingLevelEffective` (claude-sdk: Claude Code's applied effort); null = not reported yet
|
|
353
412
|
* { type: 'available_models', models: [...], provider?, defaultModel? } — models the active provider accepts
|
|
354
413
|
* { type: 'permission_input', requestId, found, tool?, input?, error? } — #6543 (IDE P3 feature B) reply to a `get_permission_input` pull: the FULL secret-redacted tool input for a pending permission (the `permission_request` broadcast truncates `input` at ~10K), so a client can build a per-hunk pre-write diff. `found:false` (+ `error`) when the request is unknown / already resolved / owned by another session — the handler is session-bound (a client only gets input for a permission its session owns).
|
|
355
|
-
* { type: '
|
|
414
|
+
* { type: 'permission_audit_result', entries } — #6772 reply to a `query_permission_audit` pull: recent permission audit entries (mode changes / session-rule changes / allow-deny decisions) matching the query's optional sessionId/auditType/since/limit. Consumed by the dashboard's per-session "Permission history" view.
|
|
415
|
+
* { type: 'permission_request', requestId, tool, description, input, remainingMs, floored, explicitConsent?, nonDelegable?, toolUseId? } — permission prompt and consent policy; `toolUseId` (#8357) is the provider's id for the tool call, sent on a hook-routed prompt whose payload names it, and is the same id the AskUserQuestion `user_question` carries
|
|
416
|
+
* { type: 'permission_resolved', decision, requestId?, toolUseId?, reason?, scope?, sessionId? } — a pending permission prompt was resolved (broadcast so every client drops its card). `requestId` names a tool-permission prompt; `toolUseId` instead names a superseded AskUserQuestion (#8470), never both. `reason` says why (#8374: 'stopped' vs a user deny); `scope: 'session'` marks an "Allow for Session" answer (#8517)
|
|
356
417
|
* { type: 'confirm_permission_mode', mode, warning } — server challenges auto mode (client must re-send with confirmed: true)
|
|
357
418
|
* { type: 'permission_mode_changed', mode: '...' } — permission mode updated
|
|
358
|
-
* { type: 'available_permission_modes', modes: [...] } — permission modes
|
|
419
|
+
* { type: 'available_permission_modes', modes: [...], provider? } — permission modes for ONE provider (#8224: `provider` names it; clients file the roster under it and derive the active session's picker, so a session of a provider that has no roster yet never inherits another provider's "Plan (unavailable)"). Sent with the connect burst and by `sendSessionInfo` for every session surfaced to a client
|
|
359
420
|
* { type: 'session_list', sessions: [...] } — all sessions
|
|
360
|
-
* { type: 'session_switched', sessionId, name, cwd, conversationId?, sessionPreset? } — switched active session. On a fresh create-confirm `sessionPreset` (#5553) discloses the resolved per-repo preset (length-only preamble — the text is already folded into the prompt server-side — plus the seed staged editable into the composer + trust metadata); omitted when the session has no preset.
|
|
361
|
-
* { type: 'session_created', sessionId, name } — new session created
|
|
421
|
+
* { type: 'session_switched', sessionId, name, cwd, conversationId?, agentConnection?, sessionPreset?, requestId? } — switched active session. #7977: the create-confirm echoes the `create_session` `requestId` when one was sent; a re-home/switch never carries one. On a fresh create-confirm `sessionPreset` (#5553) discloses the resolved per-repo preset (length-only preamble — the text is already folded into the prompt server-side — plus the seed staged editable into the composer + trust metadata); omitted when the session has no preset.
|
|
362
422
|
* { type: 'session_destroyed', sessionId } — session removed
|
|
363
|
-
* { type: 'session_stopped', sessionId?, code? } — user-initiated Stop confirmation (#4756); CliSession emitted `stopped` after a clean SIGINT exit; pairs with the louder `session_error` crash toast
|
|
364
|
-
* { type: 'session_restore_failed', sessionId, name, provider, cwd?, model?, permissionMode?, errorCode, errorMessage, originalHistoryPreserved, historyLength? }
|
|
423
|
+
* { type: 'session_stopped', sessionId?, code? } — user-initiated Stop confirmation (#4756); CliSession emitted `stopped` after a clean SIGINT exit; pairs with the louder `session_error` crash toast; #8497: on a turn that ended without a `result` the server follows it with `agent_idle` and a `session_activity` isBusy=false so the client leaves busy
|
|
424
|
+
* { type: 'session_restore_failed', sessionId, name, provider, cwd?, model?, permissionMode?, errorCode, errorMessage, originalHistoryPreserved, historyLength?, agentConnection? }
|
|
365
425
|
* — session in persisted state could not be restored (e.g. missing env var); history kept on disk for retry
|
|
366
426
|
* { type: 'session_persist_failed', sessionId, name|null }
|
|
367
427
|
* — a session-list mutation (create/rename/destroy) could not be flushed to disk and will be lost on restart (#5714).
|
|
368
428
|
* `name` is null on the destroy path where the entry was already removed before the flush.
|
|
369
|
-
* { type: '
|
|
370
|
-
* { type: '
|
|
371
|
-
* { type: '
|
|
429
|
+
* { type: 'failed_restores_list', generatedAt, restores[], refused?, code? } — #7625 reply to list_failed_restores. Per-row shape matches session_restore_failed (both built from getFailedRestores()); historyLength only, never the history itself. `refused: true` is the bound-client degraded snapshot, and is what distinguishes a refusal from a genuinely empty roster. DASHBOARD-ONLY (PLATFORM_SPECIFIC), like the environment_* family
|
|
430
|
+
* { type: 'retry_failed_restore_result', sessionId, ok, code?, message? } — #7625 reply to retry_failed_restore. code FAILED_RESTORE_NOT_FOUND means the entry was already gone (a concurrent retry won, or the 30-day TTL pruned it) — i.e. a stale button, deliberately distinguishable from a retry that ran and re-failed. `ok` reflects the SETTLED provider start (#8861): `ok:true` means start() resolved or is still pending after the settle timeout, and `ok:false` covers a start() that rejected within it (code = the provider's error code, default START_FAILED). A re-failure ALSO arrives as a fresh session_restore_failed broadcast (followed by a session_list refresh). DASHBOARD-ONLY (PLATFORM_SPECIFIC)
|
|
431
|
+
* { type: 'failed_restore_history', sessionId, ok, total?, offset?, entries?[], refused?, code?, message? } — #8860 reply to get_failed_restore_history. entries are saved history entries oldest-first, each through the persistence truncation with server bookkeeping (_seq) dropped; offset echoes the page start served. code FAILED_RESTORE_NOT_FOUND = entry already gone (stale view); refused:true = bound-client degraded reply. DASHBOARD-ONLY (PLATFORM_SPECIFIC)
|
|
432
|
+
* { type: 'archived_sessions_list', generatedAt, policy{enabled,maxEntries,maxAgeDays,maxMegabytes}, sessions[], truncated?, refused?, code? } — reply to list_archived_sessions. sessions are newest-first rows of typed metadata only (archiveId, sessionId, name, provider, cwd, model, reason, archivedAt, lastActivityAt, createdAt, historyLength, bytes), never transcript content. truncated:true means the roster was cut to fit one frame (512 KiB of rows, newest first; older sessions exist but are not listed). refused:true is the bound-client degraded snapshot. DASHBOARD-ONLY (PLATFORM_SPECIFIC)
|
|
433
|
+
* { type: 'archived_session_history', archiveId, ok, total?, offset?, entries?[], refused?, code?, message? } — reply to get_archived_session_history; entries use the failed_restore_history entry shape and bounds. code ARCHIVED_SESSION_NOT_FOUND = unknown id or the record aged out / was deleted. DASHBOARD-ONLY (PLATFORM_SPECIFIC)
|
|
434
|
+
* { type: 'delete_archived_session_result', ok, deleted, archiveId?, refused?, code?, message? } — reply to delete_archived_session; deleted is the number of records removed. ok:false codes: ARCHIVED_SESSION_NOT_FOUND (no such record), ARCHIVED_SESSION_DELETE_FAILED (the record could not be unlinked and is still on disk), ARCHIVED_SESSIONS_DELETE_PARTIAL (all:true; deleted went, the rest remain). DASHBOARD-ONLY (PLATFORM_SPECIFIC)
|
|
435
|
+
* { type: 'restore_archived_session_result', archiveId, mode?, ok, sessionId?, seed?{messagesIncluded,messagesTotal,bytes}, refused?, code?, message? } — reply to restore_archived_session; sessionId is the live session (switch to it). seed (new_thread) says how much of the transcript rides with the first message. The roster rows of archived_sessions_list also carry restore{native,nativeReason?,newThread,newThreadReason?} (advisory, cheap checks). ok:false codes: ARCHIVED_SESSION_NOT_FOUND, ARCHIVED_SESSION_INVALID, ARCHIVE_RESTORE_PROVIDER_UNAVAILABLE, ARCHIVE_RESTORE_FORBIDDEN_USER_SHELL, ARCHIVE_RESTORE_CWD_MISSING, ARCHIVE_RESTORE_NATIVE_UNSUPPORTED, ARCHIVE_RESTORE_LOCATOR_MISSING, ARCHIVE_RESTORE_ALREADY_LIVE (sessionId names the live/parked owner of that conversation), ENVIRONMENT_UNAVAILABLE, provider start codes, ARCHIVED_SESSION_FORBIDDEN_BOUND_CLIENT (refused:true). DASHBOARD-ONLY (PLATFORM_SPECIFIC)
|
|
436
|
+
* { type: 'session_archive_policy_result', ok, policy?{enabled,maxEntries,maxAgeDays,maxMegabytes}, deleted?, requestId?, refused?, code?, message? } — reply to set_session_archive_policy; policy is what is now in force. ok:false codes: SESSION_ARCHIVE_POLICY_INVALID, SESSION_ARCHIVE_POLICY_PERSIST_FAILED (nothing applied), SESSION_ARCHIVE_PURGE_PARTIAL (policy applied, some records could not be removed), SESSION_ARCHIVE_POLICY_FORBIDDEN_BOUND_CLIENT (refused:true). DASHBOARD-ONLY (PLATFORM_SPECIFIC)
|
|
437
|
+
* { type: 'session_error', message, category?, sessionId?, recoverable?, code?, reason?, requestId?, boundSessionId?, boundSessionName?, primaryClientId? } — session operation error
|
|
438
|
+
* { type: 'history_replay_start', sessionId, fullHistory?, truncated?, conversationId?, latestSeq? } — beginning of history replay
|
|
439
|
+
* { type: 'history_replay_end', sessionId, latestSeq? } — end of history replay
|
|
372
440
|
* { type: 'conversation_id', sessionId, conversationId } — SDK conversation ID for session portability
|
|
373
|
-
* { type: 'user_question', toolUseId, questions } — AskUserQuestion prompt from Claude
|
|
441
|
+
* { type: 'user_question', toolUseId, questions, historySeq?, interrupted?, superseded? } — AskUserQuestion prompt from Claude
|
|
374
442
|
* { type: 'agent_busy' } — agent started processing (per-session)
|
|
375
443
|
* { type: 'agent_idle' } — agent finished processing (per-session)
|
|
376
444
|
* { type: 'plan_started' } — Claude entered plan mode (transient)
|
|
@@ -378,11 +446,12 @@ function _isSecureRequest(req) {
|
|
|
378
446
|
* { type: 'inactivity_warning', messageId, idleMs, prefab } — soft check-in prompt, session stays alive (#3899)
|
|
379
447
|
* { type: 'multi_question_intervention', toolUseId, questionCount, reason, timestamp } — chroxy permission-hook denied a multi-question AskUserQuestion (#4653)
|
|
380
448
|
* { type: 'server_shutdown', reason, restartEtaMs } — server shutting down (reason: 'restart'|'shutdown')
|
|
381
|
-
* { type: 'server_status', message } — non-error status update (e.g., recovery)
|
|
382
|
-
* { type: 'server_error', category
|
|
383
|
-
* { type: 'directory_listing', path, parentPath, entries, error } — directory listing response for file browser
|
|
449
|
+
* { type: 'server_status', message, phase?, tunnelMode?, tunnelUrl?, attempt?, maxAttempts? } — non-error status update (e.g., recovery)
|
|
450
|
+
* { type: 'server_error', category?, message, recoverable, correlationId?, sessionId? } — server-side error forwarded to app
|
|
451
|
+
* { type: 'directory_listing', path, parentPath, entries, error, requestId? } — directory listing response for file browser (requestId echoes the request's, when it carried one)
|
|
452
|
+
* { type: 'git_repo_check_result', path, isGitRepo, requestId? } — is the New Session dir a git repo (true/false, null = cannot tell) (#8972)
|
|
384
453
|
* { type: 'file_listing', path, parentPath, entries, error } — file browser listing response
|
|
385
|
-
* { type: 'file_content', path, content, language, size, truncated, error } — file content response
|
|
454
|
+
* { type: 'file_content', path, content, language, size, truncated, error, requestId? } — file content response
|
|
386
455
|
* { type: 'symbols_snapshot', path, symbols: [{ name, kind, file, line, exported }], truncated, error } — #6471 workspace symbol table (opt-in IDE, features.ide; dashboard-only v1)
|
|
387
456
|
* { type: 'symbol_location', symbol, file, line, error } — #6475 go-to-definition result (opt-in IDE, features.ide; dashboard-only v1)
|
|
388
457
|
* { type: 'code_search_results', query, results: [{ file, line, column, text }], truncated, error } — #6474 find-in-project results (opt-in IDE, features.ide; dashboard-only v1)
|
|
@@ -394,16 +463,20 @@ function _isSecureRequest(req) {
|
|
|
394
463
|
* { type: 'client_focus_changed', clientId, sessionId, timestamp } — another client changed session focus
|
|
395
464
|
* { type: 'checkpoint_created', sessionId, checkpoint } — checkpoint created (auto or manual)
|
|
396
465
|
* { type: 'checkpoint_list', sessionId, checkpoints } — list of checkpoints
|
|
397
|
-
* { type: 'checkpoint_restored', checkpointId,
|
|
466
|
+
* { type: 'checkpoint_restored', checkpointId, mode, newSessionId?, name?, filesOnly? } — checkpoint restored (#6766/#6767: mode 'files' keeps the current session — no newSessionId, name = the checkpoint's name; 'conversation'/'both' create + re-home to a rewound session, name = its name; filesOnly true = working tree only, conversation NOT branched)
|
|
398
467
|
* { type: 'primary_changed', sessionId, clientId } — last-writer-wins primary changed (null on disconnect)
|
|
399
468
|
* { type: 'session_role', sessionId, primaryClientId } — #5589/#5281: explicit primary-ownership; client derives its role (primary iff primaryClientId === own clientId, observer if another holds it, null = unclaimed)
|
|
400
|
-
* { type: 'pong' } — heartbeat response
|
|
469
|
+
* { type: 'pong', serverTs? } — heartbeat response
|
|
401
470
|
* { type: 'permission_expired', requestId, sessionId, message } — permission response could not be routed (expired/handled)
|
|
402
|
-
* { type: '
|
|
471
|
+
* { type: 'permission_outcome', requestId, tool, description, outcome, input?, decision?, toolUseId?, sessionId, timestamp, historySeq } — #8348: how a permission prompt ended (outcome 'allowed' | 'denied' | 'expired' | 'stopped'), delivered ONLY inside a history replay so a session switch or reload still shows the prompt, with the same sanitized, capped `input` the live permission_request carried and, on an allowed outcome, which allow was chosen (`decision`: allow | allowSession | allowAlways) (#8503, both absent on older entries); the live permission_request / permission_resolved / permission_expired frames stay transient and are not replayed
|
|
472
|
+
* { type: 'credential_invalidated', reason } — sent just before the server ends a connection whose stored pairing credential is no longer valid (reason: 'revoked' | 'expired' | 'evicted' | 'invalid'); close code 4401 follows. It travels the normal (possibly encrypted) channel, so it is the authenticated evidence a client may forget that credential on; the close code alone is not
|
|
473
|
+
* { type: 'token_rotated', token?, expiresAt, reason? } — API token changed. Scheduled rotation carries the new `token` to encrypted clients that authenticated with the primary token (transparent re-key, sessions survive); session-bound and pairing-issued connections receive no frame, since rotation does not touch their credential. A `reason: 'revoke'` (#6006) carries NO token: the operator revoked, so the server severed user-shell sessions and cleared this connection's auth — the client must re-authenticate with the current token (obtained out-of-band). #6965: for a revoke this message is WITHHELD until the daemon's token persist reports success, so the ack can never precede the revocation being stored — that persist is an fsync of the temp file + containing directory on the `config.json` fallback, while on the OS-keychain path (the macOS/libsecret default) durability is delegated to the keychain and no fsync is performed here. If the persist FAILS the connection receives an `error` with `code: 'REVOKE_NOT_DURABLE'` FIRST and then this message anyway: enforcement already ran unconditionally, so the client must still re-authenticate — the message carries no token and makes no durability claim, and the caveat rides the error. #7053: the wait is BOUNDED (`REVOKE_ACK_TIMEOUT_MS`), because an `onPersist` that never settles would otherwise emit nothing at all and make the panic button look like a no-op; on timeout the connection gets `code: 'REVOKE_DURABILITY_UNKNOWN'` — deliberately NOT `REVOKE_NOT_DURABLE`, since a timeout means the outcome is unknown and may still land, not that the write is known to have failed — followed by this message on the same reasoning.
|
|
403
474
|
* { type: 'session_warning', sessionId, name, reason, message, remainingMs } — session about to timeout
|
|
404
475
|
* { type: 'session_timeout', sessionId, name, idleMs } — session destroyed due to idle timeout
|
|
405
|
-
* { type: '
|
|
476
|
+
* { type: 'statusline_output', sessionId, text, active?, truncated? } — #6791: rendered stdout of the user's own Claude Code statusLine script (active:false + empty text clears it)
|
|
477
|
+
* { type: 'dev_preview', port, url, target?, exposure?, sessionId } — approved HTTP preview opened
|
|
406
478
|
* { type: 'dev_preview_stopped', port, sessionId } — dev server preview tunnel closed
|
|
479
|
+
* { type: 'dev_preview_status', sessionId, requestId, port, state, reason? } — explicit HTTP preview request lifecycle
|
|
407
480
|
* { type: 'web_task_created', task } — cloud task launched
|
|
408
481
|
* { type: 'web_task_updated', task } — cloud task status changed
|
|
409
482
|
* { type: 'web_task_error', taskId?, message, code?, boundSessionId?, boundSessionName? } — cloud task error
|
|
@@ -412,34 +485,39 @@ function _isSecureRequest(req) {
|
|
|
412
485
|
* are populated on SESSION_TOKEN_MISMATCH only;
|
|
413
486
|
* see docs/error-taxonomy.md)
|
|
414
487
|
* { type: 'web_task_list', tasks } — response to list_web_tasks
|
|
415
|
-
* { type: 'diff_result',
|
|
416
|
-
* { type: 'error', message }
|
|
417
|
-
* { type: 'file_list',
|
|
418
|
-
*
|
|
419
|
-
*
|
|
420
|
-
* { type: '
|
|
421
|
-
* { type: '
|
|
422
|
-
* { type: '
|
|
423
|
-
* { type: '
|
|
424
|
-
* { type: '
|
|
488
|
+
* { type: 'diff_result', files, error } — git diff result
|
|
489
|
+
* { type: 'error', message, requestId?, code?, fatal?, correlationId?, details?, actualAuthor? } — general error message (actualAuthor: only on the skill_trust_grant INVALID_AUTHOR arm)
|
|
490
|
+
* { type: 'file_list', files, resources, error, sessionId? } — file listing response;
|
|
491
|
+
* files[].path is cwd-relative
|
|
492
|
+
* and '/'-separated on every OS (#7282)
|
|
493
|
+
* { type: 'git_branches_result', branches, currentBranch, error } — git branches result
|
|
494
|
+
* { type: 'git_commit_result', hash, message, error } — git commit result
|
|
495
|
+
* { type: 'git_create_pr_result', url, number, branch, base, error, existingUrl? } — in-app PR creation result (#6876; dashboard-only v1)
|
|
496
|
+
* { type: 'git_stage_result', error } — git stage result
|
|
497
|
+
* { type: 'git_status_result', branch, staged, unstaged, untracked, error } — git status result
|
|
498
|
+
* { type: 'git_unstage_result', error } — git unstage result
|
|
499
|
+
* { type: 'write_file_result', path, error } — write file result
|
|
500
|
+
* { type: 'append_memory_result', path, created, error } — `#`-quick-append ack (#6861)
|
|
501
|
+
* { type: 'memory_stack_result', entries, memoryFile, error, requestId? } — reply to `memory_read` (#6864, epic #6760): ordered global/project/local CLAUDE.md stack with per-file provenance (+ recursively-resolved @imports, path-confined to the session cwd + ~/.claude) plus the auto-generated MEMORY.md descriptor. Server-only for v1 — no client handler yet; the dashboard/mobile memory-panel consumers are the sibling slices #6867/#6870
|
|
502
|
+
* { type: 'log_entry', component, level, message, timestamp, sessionId? } — server log entry for dashboard
|
|
425
503
|
* { type: 'session_activity', sessionId, isBusy, lastCost } — session busy/idle state change
|
|
426
|
-
* { type: 'session_context', sessionId,
|
|
504
|
+
* { type: 'session_context', sessionId, gitBranch, gitDirty, gitAhead, projectName } — session context data
|
|
427
505
|
* { type: 'session_updated', sessionId, name } — session metadata updated
|
|
428
|
-
* { type: 'discovered_sessions', sessions } — discovered local Claude sessions
|
|
429
506
|
* { type: 'pair_fail', reason } — pairing failed
|
|
430
507
|
* { type: 'pairing_refreshed' } — pairing ID consumed; clients should re-fetch /qr (#2916)
|
|
431
508
|
* { type: 'pair_request_pending', requestId, verifyCode } — pairing-approval primitive (#5510, epic #5509): ack to the camera-less requester carrying the 6-digit code to DISPLAY. Sent only over the requester's own pre-auth connection; the code travels server→requester only and is never echoed back.
|
|
432
509
|
* { type: 'pair_pending', requestId, deviceName, verifyCode, expiresAt } — pairing-approval fan-out (#5510) to HOST-LEVEL (unbound) surfaces only; carries the verify code to COMPARE and the attacker-controlled (schema-capped, plain-text) deviceName. Bound/session-scoped clients never receive it.
|
|
433
510
|
* { type: 'pair_result', requestId, ok, token?, reason? } — pairing-approval terminal result (#5510) to the requester over its still-open connection. On approve `ok: true` + the unbound (host-authority) session token, delivered exactly once and never logged; on deny/expire/disconnect `ok: false` + reason.
|
|
434
511
|
* { type: 'pair_resolved', requestId, reason } — pairing-approval retraction (#5510) to host-level surfaces so every banner drops a request that was approved/denied/expired/disconnected elsewhere.
|
|
435
|
-
* { type: 'rate_limited', message } — client rate-limited
|
|
436
|
-
* { type: 'agent_spawned', sessionId, agentId, parentToolId, model
|
|
437
|
-
* { type: 'agent_completed', sessionId,
|
|
512
|
+
* { type: 'rate_limited', message, retryAfterMs } — client rate-limited
|
|
513
|
+
* { type: 'agent_spawned', sessionId, toolUseId, description, startedAt } — a Task/Agent subagent spawned. #7340: the field list here read `agentId, parentToolId, model` — three names the emitter has never sent (see event-normalizer's `agent_spawned`); corrected alongside the lifecycle fix. `toolUseId` is the spawning tool_use block's id, and is the key `agent_completed` / `agent_event` correlate on.
|
|
514
|
+
* { type: 'agent_completed', sessionId, toolUseId } — that subagent reached a terminal state: the provider's own terminal signal (the CLI/SDK `task_notification`, byok's child returning, or a cancel), or turn end, whichever comes first. Turn end completes every tracked subagent EXCEPT one whose backgrounding the provider itself confirmed (#7340) — those outlive their turn deliberately, and `task_notification` is then their only finalizer. The exemption applies on the claude-cli path only, where a persistent child can still deliver it; see `_clearMessageState` in base-session.js.
|
|
438
515
|
* { type: 'agent_event', sessionId, parentToolUseId, eventType, payload } — Task subagent intermediate wire event re-emit (#5016, transient; eventType is one of `tool_start` / `tool_input_delta` / `tool_result` / `stream_delta`)
|
|
439
|
-
* { type: 'background_work_changed', sessionId, pending } — pending background shells snapshot changed (#4307, transient; `pending: [{ shellId, command, startedAt }, …]`)
|
|
440
|
-
* { type: 'shell_pending_approval', approvalId, hint? } — #6277 host-local user-shell approval: a requested user-shell spawn is HELD pending the host operator's out-of-band approval (`chroxy shell approve <id>`). Informational; dashboard-only banner for v1. The normal `session_switched` confirms on approval, a `session_error` (SHELL_APPROVAL_DENIED) on deny.
|
|
516
|
+
* { type: 'background_work_changed', sessionId, pending, busyReason?, backgroundShellCount? } — pending background shells snapshot changed (#4307, transient; `pending: [{ shellId, command, startedAt }, …]`; #8302: `busyReason` is `'turn'` | `'background-shells'` | `null` and `backgroundShellCount` is the tracker size, quiesced shells included — both omitted when the session cannot be resolved)
|
|
517
|
+
* { type: 'shell_pending_approval', approvalId, hint?, requestId? } — #6277 host-local user-shell approval: a requested user-shell spawn is HELD pending the host operator's out-of-band approval (`chroxy shell approve <id>`). Informational; dashboard-only banner for v1. The normal `session_switched` confirms on approval, a `session_error` (SHELL_APPROVAL_DENIED) on deny.
|
|
441
518
|
* { type: 'activity_snapshot', sessionId, schemaVersion, entries } — Control Room full activity tree for a session, on subscribe/resync (#5161 schema; emitter #5160; `entries: [{ id, kind, label, status, startedAt, endedAt?, parentId?, outputRef? }, …]`)
|
|
442
519
|
* { type: 'activity_delta', sessionId, schemaVersion, op, entry } — Control Room incremental activity-entry change (#5161 schema; emitter #5160; `op` is one of `started` / `updated` / `ended`; `entry` is the full node)
|
|
520
|
+
* { type: 'cancel_activity_ack', activityId, sessionId?, requestId? } — positive ack for a `cancel_activity`, echoing the activity (scoped by sessionId, #5277) and the request id so the dashboard can correlate the click; failures arrive as a `CANCEL_ACTIVITY_FAILED` session_error
|
|
443
521
|
* { type: 'message_queued', sessionId, clientMessageId?, text, queueLength } — a send-while-busy follow-up entered the server's outgoing-message queue (#5936/#5937, transient; mirrors `_outgoingQueue`)
|
|
444
522
|
* { type: 'message_dequeued', sessionId, clientMessageId?, queueLength, reason } — a queued follow-up left the queue (#5936/#5937/#5943, transient; `reason` is `flush` (auto-sent on turn-complete), `interrupted` (whole queue cancelled by a Stop), or `cancelled` (one item cancelled via `cancel_queued`))
|
|
445
523
|
* { type: 'host_status_snapshot', requestId?, generatedAt, root, summary, repos, error? } — Control Room Host/Repo Status survey reply (#5171 schema; emitter #5174); reply to a `host_status_request`. Always carries the full snapshot shape (so it is protocol-schema-valid); on failure `repos` is empty, `summary` is zeroed, and an additive `error: { code, message }` annotation is present for the consumer to branch on. `requestId` echoes the request when provided.
|
|
@@ -454,20 +532,24 @@ function _isSecureRequest(req) {
|
|
|
454
532
|
* { type: 'emulator_action_ack', action, avd?, serial?, requestId?, status } — Control Room Android emulator action ack (#6137, epic #5530); reply to a successful `emulator_action` (boot/kill). The server re-surveys, validates the target (boot → a stopped `avd`, kill → a running `serial`) + state-gates it, runs `emulator -avd` (detached) / `adb emu kill`, and echoes `action` + the relevant `avd`/`serial` (+ `requestId`) plus the resulting `status` ("starting"/"killed"). Failures surface as an EMULATOR_ACTION_FAILED `session_error` echoing the same correlation fields.
|
|
455
533
|
* { type: 'wsl_status_snapshot', requestId?, generatedAt, available, note, defaultDistro, distros, error? } — Control Room WSL2 distro survey reply (#6138, epic #5530); reply to a `wsl_status_request`. Read-only (Windows hosts). `distros` is the `wsl.exe -l -v` inventory (name/state/version/isDefault); `defaultDistro` names the `*`-marked default. `available:false` (with `note`, empty distros) off Windows / no wsl.exe is a first-class state. Same degraded-snapshot-with-`error` posture as the sibling surveys.
|
|
456
534
|
* { type: 'wsl_action_ack', action, distro, requestId?, status } — Control Room WSL2 action ack (#6138, epic #5530); reply to a successful `wsl_action` (start/terminate). The server re-surveys `wsl.exe -l -v`, validates the `distro` is enumerated + state-gated (start a non-running distro, terminate a running one), runs `wsl.exe -d <distro> -e true` / `wsl.exe --terminate <distro>`, and echoes `action`/`distro` (+ `requestId`) plus the resulting `status` ("running"/"stopped"). Failures surface as a WSL_ACTION_FAILED `session_error` echoing the same correlation fields.
|
|
457
|
-
* { type: 'integration_status_snapshot', requestId?, generatedAt, root, summary, repos, repoMemoryCli?, error? } — Control Room Integrations survey reply (#5499 schema + emitter, epic #5498); reply to an `integration_status_request`. Per-repo repo-memory status (config, cache stats, telemetry report); `repoMemoryCli` notes the once-per-snapshot binary probe. Same degraded-snapshot-with-`error` posture as the host/runner surveys. `requestId` echoes the request when provided.
|
|
458
|
-
* { type: 'containers_action_ack', action, environmentId, requestId?, status? } — Control Room container lifecycle action ack (#6134, epic #5530); reply to a successful `containers_action` (stop/restart/destroy). Echoes `action`/`environmentId` (+ `requestId` when provided) and carries the resulting `status` (stopped/running/destroyed). Failures surface as a CONTAINER_ACTION_FAILED `session_error` echoing the same correlation fields.
|
|
535
|
+
* { type: 'integration_status_snapshot', requestId?, generatedAt, root, summary, repos, repoMemoryCli?, ghCli?, error? } — Control Room Integrations survey reply (#5499 schema + emitter, epic #5498); reply to an `integration_status_request`. Per-repo repo-memory status (config, cache stats, telemetry report); `repoMemoryCli` notes the once-per-snapshot binary probe. Same degraded-snapshot-with-`error` posture as the host/runner surveys. `requestId` echoes the request when provided.
|
|
536
|
+
* { type: 'containers_action_ack', action, environmentId, requestId?, status? } — Control Room container lifecycle action ack (#6134, epic #5530); reply to a successful `containers_action` (stop/restart/destroy). Echoes `action`/`environmentId` (+ `requestId` when provided) and carries the resulting `status` (stopped/running/destroyed). Failures surface as a CONTAINER_ACTION_FAILED `session_error` echoing the same correlation fields — including the #7562 live-session destroy refusal, which uses `reason: 'live-sessions'` and is escaped with `force: true` on the request.
|
|
459
537
|
* { type: 'byok_pool_action_ack', action, requestId?, key?, drained?, evicted?, limits?, configured? } — Control Room BYOK pool mutating action ack (#6135 slice 2, epic #5530); reply to a successful `byok_pool_action` (drain/recycle/resize). Echoes `action` (+ `requestId`/`key` when provided) and carries the result: `drained` (containers evicted by drain/recycle), `evicted` (containers evicted to honor a tightened resize), `limits` (new effective caps after resize), `configured` (the operator-configured cap ceiling resize clamps to). Failures surface as a BYOK_POOL_ACTION_FAILED `session_error` echoing the same correlation fields.
|
|
460
538
|
* { type: 'simulator_action_ack', action, udid, requestId?, status } — Control Room iOS simulator action ack (#6136 slice 2, epic #5530); reply to a successful `simulator_action` (boot/shutdown). The server re-surveys `xcrun simctl list devices`, validates the `udid` is enumerated + state-gated (boot a non-booted device, shutdown a booted one), runs `simctl <action> <udid>`, and echoes `action`/`udid` (+ `requestId` when provided) plus the resulting `status` ("Booted"/"Shutdown"). Failures surface as a SIMULATOR_ACTION_FAILED `session_error` echoing the same correlation fields.
|
|
461
|
-
* { type: 'integration_action_ack', action, repoPath, requestId?, counts } — Control Room Integrations action ack (#5500, epic #5498); reply to a successful `integration_action` (currently `repo_memory_reindex`). Echoes `action`/`repoPath` (+ `requestId` when provided) cloning the cancel_activity_ack correlation contract; `counts` carries the parsed scanned/summarized/fresh/skipped index result, or null when the CLI output was unparseable. Failures surface as an INTEGRATION_ACTION_FAILED `session_error` echoing the same correlation fields.
|
|
539
|
+
* { type: 'integration_action_ack', action, repoPath, requestId?, counts, runId? } — Control Room Integrations action ack (#5500, epic #5498); reply to a successful `integration_action` (currently `repo_memory_reindex`). Echoes `action`/`repoPath` (+ `requestId` when provided) cloning the cancel_activity_ack correlation contract; `counts` carries the parsed scanned/summarized/fresh/skipped index result, or null when the CLI output was unparseable. Failures surface as an INTEGRATION_ACTION_FAILED `session_error` echoing the same correlation fields.
|
|
462
540
|
* { type: 'skills_inventory_snapshot', requestId?, generatedAt, root, global, globalError?, repos, error? } — Control Room Skills inventory survey reply (#5554 schema + emitter, epic #5159); reply to a `skills_inventory_request`. `global` is the `~/.chroxy/skills/` tier and `repos` the per-repo `.chroxy/skills/` overlays, each entry carrying name/description/activation/trust/hash/installed + usage (lastUsed/count/repos). Skill BODIES never leave the server. Same degraded-snapshot-with-`error` posture as the host/runner/integration surveys; `globalError` / per-repo `error` degrade a single tier without blanking the snapshot. `requestId` echoes the request when provided.
|
|
463
541
|
* { type: 'mailbox_status_snapshot', requestId?, generatedAt, registrations, recentEvents, error? } — Control Room "Mailbox" tab survey reply (#5914 follow-up); reply to a `mailbox_status_request`. `registrations` is the live agentCommId→session map (each with sessionName/isBusy/isTui) and `recentEvents` a bounded newest-first ring buffer of recent live-interrupt deliveries (to/from/unreadCount/outcome). Host-level: a session-bound token is refused with an additive `error: { code, message }` on an otherwise-empty (schema-valid) snapshot. `requestId` echoes the request when provided.
|
|
542
|
+
* { type: 'session_status', sessionId, declaredStatus } — bounded agent-declared status, independent of provider busy state; replayed on session-info delivery.
|
|
464
543
|
* { type: 'external_sessions_snapshot', requestId?, generatedAt, sessions, error? } — Control Room mission-control external-session survey reply (#5969, epic #5422 phase 4); reply to an `external_sessions_request`. `sessions` lists the LIVE external Claude Code sessions the daemon learned about over `POST /api/events` (#5413) — sessions it did NOT launch — each carrying source/sessionId/name/project/cwd, a read-only `status` ('running'|'idle'), active `subagents`, and `lastActivityTs`. Read-only (no PTY/control handle exists for these). Host-level: a session-bound token is refused with an additive `error: { code, message }` on an otherwise-empty (schema-valid) snapshot. `requestId` echoes the request when provided.
|
|
465
544
|
* { type: 'repo_events_delta', generatedAt, event } — Control Room repo-events LIVE delta (#6536, PR-2 of #5966); server-INITIATED (no request) push of a single newly-buffered repo-event when a GitHub webhook delivery lands, so the pane updates without a Refresh. Host-level: broadcast ONLY to unbound (host-authority) clients — a session-bound (share-a-session) token never receives host repo activity. A client that hasn't run the survey ignores it; a client with a snapshot appends the event (bounded). No `error`/`requestId` — degraded surveys still flow through the pull `repo_events_snapshot`.
|
|
466
|
-
* { type: 'repo_events_snapshot', requestId?, generatedAt, events, error? } — Control Room repo-events survey reply (#5966, epic #5422 phase 5); reply to a `repo_events_request`. `events` is the tail (most-recent-last) of the daemon's bounded RepoEventStore — GitHub-webhook activity (push/pull_request/issues/ping) ingested HMAC-verified over `POST /api/github/webhook` (#6468) — each carrying kind/repo/actor/at plus kind-specific branch/action/number/title/url and a pre-rendered `summary`. Read-only; no delta stream (a full snapshot per pull, like the host/mailbox/external surveys). Host-level: a session-bound token is refused with an additive `error: { code, message }` on an otherwise-empty (schema-valid) snapshot. `requestId` echoes the request when provided.
|
|
545
|
+
* { type: 'repo_events_snapshot', requestId?, generatedAt, events, activeRepos?, error? } — Control Room repo-events survey reply (#5966, epic #5422 phase 5); reply to a `repo_events_request`. `events` is the tail (most-recent-last) of the daemon's bounded RepoEventStore — GitHub-webhook activity (push/pull_request/issues/ping) ingested HMAC-verified over `POST /api/github/webhook` (#6468) — each carrying kind/repo/actor/at plus kind-specific branch/action/number/title/url and a pre-rendered `summary`. Read-only; no delta stream (a full snapshot per pull, like the host/mailbox/external surveys). Host-level: a session-bound token is refused with an additive `error: { code, message }` on an otherwise-empty (schema-valid) snapshot. `requestId` echoes the request when provided.
|
|
546
|
+
* { type: 'github_webhook_config', requestId?, generatedAt, configured, source, payloadUrl, lanOnly, note?, recommendedEvents, deliveries, error? } — Control Room repo-events webhook-secret config reply (#6540, item 3 of #6536); reply to a `github_webhook_config_request` and to a `github_webhook_set_secret` / `github_webhook_clear_secret` write. Reports whether an HMAC secret is configured and its `source` ('store'|'env'|'none') — never the value — plus the `payloadUrl` to paste into GitHub (derived from the live tunnel URL, else the LAN address, `lanOnly` + `note` when GitHub can't reach it), the `recommendedEvents`, and the recent-`deliveries` readout (count / last / verify result). Writes are host-authority gated (a session-bound token is rejected with a generic `error`); the read is open to any authenticated client. `requestId` echoes the request when provided.
|
|
547
|
+
* { type: 'session_pr_status', requestId?, sessionId, generatedAt, branch, repo, pr, checks, merge, reason } — the session's pull-request / CI status (#7344, display slice); reply to a `session_pr_status_request`. SESSION-scoped, not host-scoped: a pairing-bound token may ask about the session it is bound to and no other. Assembled from ONE `gh pr list` response (plus git for branch/remote) using the user's existing local `gh auth`, so `checks` and `merge` always describe the same head SHA (`pr.headRefOid`). `checks.state:'none'` means this head produced NO run and is NOT a green; `checks` and `merge` are separate facts and must never be collapsed into one "ready to merge?" badge (21/21 green alongside `mergeStateStatus:'BLOCKED'` is the case that motivated the issue). `pr:null` with `reason:null` is the quiet negative (no open PR for this branch) — on a fork checkout it is BEST-EFFORT, since a transiently-failed upstream widening reports the same shape (#7435; the distinction is held server-side for the CI watcher and not transmitted); `pr:null` with a `reason` means the survey could not determine it, and must never render as an implied green.
|
|
548
|
+
* { type: 'session_pr_threads', requestId?, sessionId, countedAt, prNumber, unresolvedCount, totalCount, truncated, reason } — the unresolved REVIEW-THREAD COUNT for the session's pull request (#7430, on-demand follow-on to #7344); reply to a `session_pr_threads_request`. Same SESSION-scoped authority as `session_pr_status`: a pairing-bound token may ask about the session it is bound to and no other. A SEPARATE message from `session_pr_status` on purpose — the count needs a GraphQL `reviewThreads` read that `gh pr list --json` cannot serve, and since #7426 that survey runs on a daemon-side sweep over every session, so folding the count in would put a second `gh` subprocess on every tick of a background poll for a field only a click wants. This pair is sent by the click and never by the sweep. `countedAt` is its OWN timestamp, not the status snapshot's `generatedAt` — the two go stale on different schedules. `unresolvedCount: 0` means the server COUNTED and found none; `unresolvedCount: null` (always with a `reason`) means it could not find out, and a client MUST render those differently — a missing count printed as "0 unresolved threads" reads as "nothing is blocking this PR", the exact false green this surface exists to prevent. `truncated: true` means more threads exist than one page read, so the count is a LOWER BOUND and a truncated 0 is not a definite zero. `prNumber` names the PR the count describes so a consumer can check it agrees with the PR its `session_pr_status` snapshot names.
|
|
467
549
|
* { type: 'summarize_session_result', sessionId, summary, truncated?, requestId? } — reply to a `summarize_session` (#5547); the model-written continuation brief built from the session's persisted history, seeded editable into the dashboard's create-session composer. `truncated` flags a windowed history. Failures surface as a SUMMARIZE_FAILED `session_error` echoing `sessionId`/`requestId` (curated message — no token/key material).
|
|
468
550
|
* { type: 'session_preset_snapshot', cwd, preset: { source, active, trustState, enabled, preamble, seed, preambleLength, seedLength, capped, repoPath } | null, requestId? } — Control Room per-repo session-preset reply (#5553, epic #5159); reply to a host-authority `session_preset_get` / `session_preset_set` / `session_preset_approve` / `session_preset_revoke`. `preset` is null when the repo has no preset. Full preamble + seed text reaches HOST-level clients only (the four requests are rejected for session-bound pairing clients). `requestId` echoes the request when provided.
|
|
469
|
-
* { type: 'provider_list', providers } — available providers
|
|
470
|
-
* { type: 'byok_credentials_status', requestId?, status, source, masked?, reason? } — BYOK credentials state for the dashboard (#4052)
|
|
551
|
+
* { type: 'provider_list', providers, defaultProvider? } — available providers
|
|
552
|
+
* { type: 'byok_credentials_status', requestId?, status, source, masked?, reason?, fileExists? } — BYOK credentials state for the dashboard (#4052)
|
|
471
553
|
* { type: 'credentials_status', requestId?, credentials: [{ key, provider, label, kind, status, source, masked?, oauth }], fileExists?, fileError? } — generalized provider-credential status for the dashboard (#3855); masked, value-free; sent to requester + broadcast after set/delete
|
|
472
554
|
* { type: 'credential_test_result', requestId?, key, ok, error?, model?, latencyMs? } — result of a test_credential ping (#3855)
|
|
473
555
|
* { type: 'notification_prefs', requestId?, prefs: { categories, devices, quietHours } } — current notification preferences snapshot (#4541/#4542); echoed back on `notification_prefs_get` and broadcast after every `notification_prefs_set`
|
|
@@ -481,19 +563,21 @@ function _isSecureRequest(req) {
|
|
|
481
563
|
* { type: 'skill_trust_grant_ok', requestId, sessionId, skillName, author } — ack for skill_trust_grant handler (#3297)
|
|
482
564
|
* { type: 'push_token_error', message } — push token registration error
|
|
483
565
|
* { type: 'cost_update', sessionId, sessionCost, totalCost, budget } — session cost update (budget-oriented; sessionId injected by _broadcastToSession)
|
|
484
|
-
* { type: 'session_usage', sessionId, cumulativeUsage } — per-session cumulative tokens + cost; cumulativeUsage = { inputTokens, outputTokens, cacheReadTokens, cacheCreationTokens, costUsd, turnsBilled } (#4072)
|
|
566
|
+
* { type: 'session_usage', sessionId, cumulativeUsage, agentConnection? } — per-session cumulative tokens + cost; cumulativeUsage = { inputTokens, outputTokens, cacheReadTokens, cacheCreationTokens, costUsd, turnsBilled } (#4072)
|
|
485
567
|
* { type: 'session_cost_threshold_crossed', sessionId, costUsd, thresholdUsd } — soft "you've spent $X" warning; fires ONCE per session when cumulativeUsage.costUsd >= threshold (#4075)
|
|
486
|
-
* { type: 'budget_warning', sessionId, message,
|
|
487
|
-
* { type: 'budget_exceeded', sessionId, message,
|
|
488
|
-
* { type: '
|
|
489
|
-
* { type: '
|
|
490
|
-
* { type: '
|
|
491
|
-
* { type: '
|
|
568
|
+
* { type: 'budget_warning', sessionId, message, sessionCost, budget, percent } — budget approaching limit
|
|
569
|
+
* { type: 'budget_exceeded', sessionId, message, sessionCost, budget, percent } — budget exceeded
|
|
570
|
+
* { type: 'budget_resume_ack', sessionId, wasPaused, requestId? } — ack for a `resume_budget` (#5752), sent to the requester unconditionally; `wasPaused: false` means the session was not paused (no-op, no `budget_resumed` broadcast)
|
|
571
|
+
* { type: 'billing_canary', eraStarted, defaultProvider, defaultBillingClass, warnings } — billing-canary snapshot, broadcast when it changes (including back to all-clear); the same snapshot seeds `auth_ok.billingCanary` for late joiners (#5821)
|
|
572
|
+
* { type: 'monthly_budget', month, spentUsd, budgetUsd, percent, warning, exceeded, turnsBilled, warningPercent, justWarned?, justExceeded?, billingClass? } — machine-wide monthly programmatic-credit meter (#5665); broadcast to ALL clients after each programmatic-credit turn + sent once on connect
|
|
573
|
+
* { type: 'web_feature_status', available, remote, teleport } — web feature availability. CONSUMED, NEVER SENT (#7109): no server code builds this frame (the data ships as `auth_ok.webFeatures`), but both clients dispatch on it through store-core. Not a phantom — keep it.
|
|
574
|
+
* { type: 'permission_rules_updated', sessionId, rules, persistentRules } — per-session auto-approval rules changed
|
|
575
|
+
* { type: 'extension_message', provider, subtype, data? } — opaque extension payload (passthrough, no server handling)
|
|
492
576
|
* { type: 'environment_created', environmentId, name, status } — environment created
|
|
493
577
|
* { type: 'environment_list', environments: [...] } — list of all environments
|
|
494
578
|
* { type: 'environment_destroyed', environmentId } — environment destroyed
|
|
495
579
|
* { type: 'environment_info', environment: {...} } — single environment details
|
|
496
|
-
* { type: 'environment_error', error, environmentId? } — environment operation error
|
|
580
|
+
* { type: 'environment_error', error, environmentId?, code?, sessions? } — environment operation error. `code` is 'DOCKER_IMAGE_NOT_ALLOWED' (image allowlist) or 'ENVIRONMENT_HAS_LIVE_SESSIONS' (#7562 destroy refusal); `sessions` accompanies the latter with the ids still running inside the environment
|
|
497
581
|
* { type: 'evaluate_draft_result', requestId, verdict?, rewritten?, clarification?, reasoning?, error? } — prompt evaluator response (#3068)
|
|
498
582
|
* { type: 'prompt_evaluator_changed', sessionId, value: boolean } — per-session promptEvaluator toggle changed (#3185)
|
|
499
583
|
* { type: 'prompt_evaluator_skip_pattern_changed', sessionId, value: string|null } — per-session evaluator skip pattern changed (#3639)
|
|
@@ -502,6 +586,14 @@ function _isSecureRequest(req) {
|
|
|
502
586
|
* { type: 'evaluator_rewrite', sessionId, originalDraft, rewritten, reasoning, evaluatorIterationId } — auto-evaluator rewrite verdict broadcast (#3208 schema, #3186 emit, #3188 dashboard handler)
|
|
503
587
|
* { type: 'evaluator_clarify', sessionId, originalDraft, clarification, reasoning, evaluatorIterationId, evaluatorIteration } — auto-evaluator clarify verdict broadcast (#3208 schema, #3186 emit, #3188 dashboard handler)
|
|
504
588
|
* { type: 'stdin_dropped_totals', sessionId, bytes, count, reason, escalated } — cumulative SidecarProcess pre-dial-cap drop totals (#3544, transient)
|
|
589
|
+
* { type: 'orchestration_runs_snapshot', requestId?, generatedAt, runs: [RunSummary], error? } — orchestration runs-list survey (#6691, dashboard-only v1)
|
|
590
|
+
* { type: 'orchestration_run_snapshot', requestId?, generatedAt, seq, run: RunDetail|null, error? } — one run's full detail (pull-only; run:null = degraded reply) (#6691)
|
|
591
|
+
* { type: 'orchestration_run_delta', runId, seq, generatedAt, run?, node?, gate?, timeline? } — live run update pushed to host-level clients; client applies iff seq===held+1 (#6691)
|
|
592
|
+
* { type: 'scheduled_tasks', generatedAt, scheduler: { enabled, engineArmed, restartRequired, source }, schedulableProviders, defaultProvider, defaultProviderRefusal, tasks[], unreadableCount?, unreadable?: [{ handle, reason }] (#7079 — load-refused stored entries, never their contents), requestId?, error? } — #6871 scheduled-task registry snapshot for the dashboard panel; sent to the REQUESTING client only, and re-emitted as the ack for every accepted mutation. Each task carries the engine's own verdicts (providerRefusal / effectivePermissionMode / permissionModeClamped / quarantined) so a client never re-derives a safety decision
|
|
593
|
+
* { type: 'daemon_update_status', running, pending, lastDeploy, postponedUntil, requestPending, applying } — #8331 the queued daily-daemon update + last deploy result; sent on auth and on change to STRICT-PRIMARY, UNBOUND clients ONLY
|
|
594
|
+
* { type: 'daemon_update_confirm_required', requestId, target, reasons[], sessions[] } — #8331 reply to restart-now while sessions are busy; nothing was written
|
|
595
|
+
* { type: 'daemon_update_action_result', requestId, action, ok, force?, postponedUntil?, code?, message? } — #8331 outcome of daemon_update_action (codes: NOT_AUTHORIZED, STALE_TARGET, NO_PENDING_UPDATE, APPLYING, WRITE_FAILED, UNAVAILABLE, UNSUPPORTED_ACTION)
|
|
596
|
+
* { type: 'orchestration_action_ack', requestId?, action, runId, gateId? } — terminal success echo for a mutating orchestration action (#6691)
|
|
505
597
|
*
|
|
506
598
|
* Encrypted envelope (bidirectional, wraps any message above after key exchange):
|
|
507
599
|
* { type: 'encrypted', d: '<base64 ciphertext>', n: <nonce counter> }
|
|
@@ -543,7 +635,7 @@ function _isSecureRequest(req) {
|
|
|
543
635
|
* - A session operation failed in an expected, user-facing way → `session_error`
|
|
544
636
|
*/
|
|
545
637
|
export class WsServer {
|
|
546
|
-
constructor({ port, apiToken, cliSession, sessionManager, defaultSessionId, authRequired = true, pushManager = null, maxPayload, noEncrypt, keyExchangeTimeoutMs, localhostBypass, tokenManager, pairingManager, serverIdentity = null, maxPendingConnections, backpressureThreshold, environmentManager, config = null, diagnosticsRateLimit = null, devicePreferences = null, pagesStore = null, pagesRateLimiter } = {}) {
|
|
638
|
+
constructor({ port, apiToken, cliSession, sessionManager, defaultSessionId, authRequired = true, pushManager = null, maxPayload, noEncrypt, keyExchangeTimeoutMs, localhostBypass, tokenManager, pairingManager, serverIdentity = null, maxPendingConnections, backpressureThreshold, environmentManager, orchestrationManager = null, schedulerEngine = null, sessionCiWatcher = null, daemonUpdate = null, config = null, diagnosticsRateLimit = null, devicePreferences = null, pagesStore = null, pagesRateLimiter } = {}) {
|
|
547
639
|
this.port = port
|
|
548
640
|
this.apiToken = apiToken
|
|
549
641
|
this._tokenManager = tokenManager || null
|
|
@@ -558,7 +650,9 @@ export class WsServer {
|
|
|
558
650
|
// can read settings (e.g. workspaceRoots for cwd allowlist) at
|
|
559
651
|
// message time. May be null in tests that don't pass it through.
|
|
560
652
|
this.config = config || null
|
|
561
|
-
|
|
653
|
+
// #7011 — default comes from config.js so the `--max-payload` help text and
|
|
654
|
+
// CONFIG.md quote the same number this fallback applies.
|
|
655
|
+
this._maxPayload = maxPayload || DEFAULT_MAX_PAYLOAD_BYTES
|
|
562
656
|
this.authRequired = authRequired
|
|
563
657
|
this._encryptionEnabled = !noEncrypt
|
|
564
658
|
this._keyExchangeTimeoutMs = keyExchangeTimeoutMs ?? 10_000
|
|
@@ -610,13 +704,13 @@ export class WsServer {
|
|
|
610
704
|
? pagesRateLimiter
|
|
611
705
|
: new RateLimiter({ name: 'pages', windowMs: 60_000, maxMessages: 120, burst: 30 })
|
|
612
706
|
this.pagesStore = pagesStore || new PagesStore({
|
|
613
|
-
pagesDir:
|
|
707
|
+
pagesDir: configPath('pages'),
|
|
614
708
|
})
|
|
615
709
|
// #6277: host-local user-shell approval store. The create gate holds a spawn
|
|
616
710
|
// here when userShell.requireApproval is on; the host operator approves it
|
|
617
711
|
// out-of-band via the loopback /api/shell routes (or `chroxy shell approve`).
|
|
618
712
|
this._shellApprovalStore = new ShellApprovalStore()
|
|
619
|
-
this._clientSend = createClientSender(log)
|
|
713
|
+
this._clientSend = createClientSender(log, { mayDeliver: (client, message) => this._mayDeliverTo(client, message) })
|
|
620
714
|
// audit P1-2: when a client's active session changes, re-sync the live
|
|
621
715
|
// terminal mirror gate for BOTH the session it left and the one it joined.
|
|
622
716
|
// Without this a client opted into session A's terminal that switches to B
|
|
@@ -697,6 +791,15 @@ export class WsServer {
|
|
|
697
791
|
// would never fire in production. Cleaned up by `_sessionDestroyedHandler`
|
|
698
792
|
// so a long-running server doesn't leak entries for destroyed sessions.
|
|
699
793
|
this._evaluatorIterations = new Map() // sessionId -> iteration count
|
|
794
|
+
// Per-session evaluator-await lock (#3636/#3666). Lives here for the same
|
|
795
|
+
// reason as the counter above: the handler ctx is spread per message, so a
|
|
796
|
+
// lock stored on the ctx itself would be a fresh, empty one every time.
|
|
797
|
+
this._pendingEvaluatorAwaits = new Map() // sessionId -> in-flight promise
|
|
798
|
+
// #7822: bounded process-local input acceptance records. The handler scopes
|
|
799
|
+
// these by session and clientMessageId; session destruction drops the whole
|
|
800
|
+
// bucket. They are intentionally not persisted, so acks describe process
|
|
801
|
+
// retention rather than promising exactly-once across daemon restarts.
|
|
802
|
+
this._inputDedupRecords = new Map() // sessionId -> Map<clientMessageId, record>
|
|
700
803
|
this._permissionSessionMap = new Map() // requestId -> sessionId (for routing responses to correct session)
|
|
701
804
|
// #5704: refcount of permission-INDUCED session subscriptions, per client.
|
|
702
805
|
// clientId -> Map<sessionId, refcount>. _registerPermissionRoute increments
|
|
@@ -713,7 +816,7 @@ export class WsServer {
|
|
|
713
816
|
this._permissionSubs = new Map() // clientId -> Map<sessionId, refcount>
|
|
714
817
|
this._hookSecrets = new Set() // per-session hook secrets registered by active CliSessions
|
|
715
818
|
this._sessionHookSecrets = new Map() // sessionId -> hookSecret (for cleanup on session_destroyed)
|
|
716
|
-
this._questionSessionMap = new
|
|
819
|
+
this._questionSessionMap = new QuestionRouteMap() // toolUseId -> sessionId (for routing question responses; remembers just-removed routes, #8470)
|
|
717
820
|
// #5563: primary-ownership now lives on the WsClientManager (sessionId →
|
|
718
821
|
// primary clientId) with explicit claim/observe/hand-off semantics, not a
|
|
719
822
|
// last-writer-wins map. `primaryClients` is no longer a server-owned Map;
|
|
@@ -744,8 +847,12 @@ export class WsServer {
|
|
|
744
847
|
this._permissions = createPermissionHandler({
|
|
745
848
|
sendFn,
|
|
746
849
|
broadcastFn,
|
|
747
|
-
|
|
850
|
+
// Used by POST /permission-response, which limits a scoped token to its
|
|
851
|
+
// own session itself — opt in explicitly.
|
|
852
|
+
validateBearerAuth: (req, res) => self._validateBearerAuth(req, res, { allowScoped: true }),
|
|
748
853
|
validateHookAuth: (req, res) => self._validateHookAuth(req, res),
|
|
854
|
+
captureBearer: (req) => captureBearer(self, req),
|
|
855
|
+
bearerStillValid: (captured) => bearerStillValid(self, captured),
|
|
749
856
|
pushManager,
|
|
750
857
|
pendingPermissions: this._pendingPermissions,
|
|
751
858
|
permissionSessionMap: this._permissionSessionMap,
|
|
@@ -812,6 +919,7 @@ export class WsServer {
|
|
|
812
919
|
self._adoptPermissionSubscription(client.id, sid)
|
|
813
920
|
self._clientManager.unsubscribe(client, sid)
|
|
814
921
|
},
|
|
922
|
+
isConnectionAuthorized: (client) => self._isConnectionAuthorized(client),
|
|
815
923
|
setActiveSession: (client, sid) => self._clientManager.setActiveSession(client, sid),
|
|
816
924
|
// #5563: explicit primary-ownership surface. `updatePrimary` is the
|
|
817
925
|
// first-input adoption path (claims if unclaimed, no-op if already
|
|
@@ -830,6 +938,18 @@ export class WsServer {
|
|
|
830
938
|
syncTerminalMirror: (sid) => self._syncTerminalMirror(sid),
|
|
831
939
|
sendSessionInfo: (ws, sid) => self._sendSessionInfo(ws, sid),
|
|
832
940
|
replayHistory: (ws, sid, opts) => self._replayHistory(ws, sid, opts),
|
|
941
|
+
// #7340: re-assert a session's live subagents after a replay wiped them.
|
|
942
|
+
reseedActiveAgents: (ws, sid) => self._reseedActiveAgents(ws, sid),
|
|
943
|
+
// #7457: re-assert the questions a session is still blocked on, after a
|
|
944
|
+
// replay's end frame let the client's sweep stamp them '(resolved)'.
|
|
945
|
+
resendPendingQuestions: (ws, sid) => self._resendPendingQuestions(ws, sid),
|
|
946
|
+
// #8340: the permission-card counterpart, for the replay path that ends
|
|
947
|
+
// its own `history_replay_end` outside `replayHistory` (request_full_history).
|
|
948
|
+
// Wired straight to the per-session implementation, NOT through a
|
|
949
|
+
// `_resendPendingPermissions` method: that name is the legacy `(ws)`
|
|
950
|
+
// connect-time delegate (test compat), and a same-named wrapper here was
|
|
951
|
+
// silently shadowed by it, dropping `sid` (unfiltered resend).
|
|
952
|
+
resendPendingPermissions: (ws, sid) => resendPendingPermissionsForSession(self._historyCtx, ws, sid),
|
|
833
953
|
get clients() { return self.clients },
|
|
834
954
|
},
|
|
835
955
|
sessions: {
|
|
@@ -884,16 +1004,49 @@ export class WsServer {
|
|
|
884
1004
|
// Lazily created on the first webhook delivery, so null until then —
|
|
885
1005
|
// the survey handler treats a null store as an empty (schema-valid) feed.
|
|
886
1006
|
get repoEventStore() { return self._repoEventStore ?? null },
|
|
1007
|
+
// #6540: repo-events webhook-secret config surface. `webhookPayloadUrl`
|
|
1008
|
+
// derives the GitHub payload URL from the live tunnel/LAN origin;
|
|
1009
|
+
// `repoWebhookDeliveries` is the in-memory recent-delivery ring the HTTP
|
|
1010
|
+
// webhook receiver fills (null until the first delivery);
|
|
1011
|
+
// `setWebhookSecretCache` lets the config handler refresh the in-process
|
|
1012
|
+
// hot cache after a set/rotate/clear so live deliveries pick it up without
|
|
1013
|
+
// a keychain re-read (and a rotate never serves a stale cached value).
|
|
1014
|
+
get webhookPayloadUrl() { return self.getWebhookPayloadUrl() },
|
|
1015
|
+
get repoWebhookDeliveries() { return self._repoWebhookDeliveries ?? null },
|
|
1016
|
+
setWebhookSecretCache: (value) => {
|
|
1017
|
+
self._githubWebhookSecret = (typeof value === 'string' && value.length > 0) ? value : null
|
|
1018
|
+
},
|
|
1019
|
+
// #6691: the OrchestrationManager, wired for real in E-4. Null until then
|
|
1020
|
+
// (and whenever the feature is off) — the handlers treat a null manager
|
|
1021
|
+
// as "engine not running" and reply with an unavailable error.
|
|
1022
|
+
get orchestrationManager() { return self._orchestrationManager ?? null },
|
|
1023
|
+
// #6871: the SchedulerEngine, for the scheduled-tasks panel's gate +
|
|
1024
|
+
// quarantine readout. Null whenever scheduled execution is disabled (the
|
|
1025
|
+
// default) — the handlers report that as "not armed" rather than hiding
|
|
1026
|
+
// it. Late-bound so it tracks the server instance.
|
|
1027
|
+
get schedulerEngine() { return self._schedulerEngine ?? null },
|
|
1028
|
+
// #7427: the SessionCiWatcher. The `session_pr_status_request` handler
|
|
1029
|
+
// feeds its survey snapshot to `observe()`, so opening the dashboard
|
|
1030
|
+
// ARMS the watch rather than waiting on the sweep's five-minute
|
|
1031
|
+
// discovery pass. Null when the watcher is off; the handler no-ops.
|
|
1032
|
+
get sessionCiWatcher() { return self._sessionCiWatcher ?? null },
|
|
1033
|
+
// #8331: the daily-daemon update banner's status + request files.
|
|
1034
|
+
get daemonUpdate() { return self._daemonUpdate ?? null },
|
|
887
1035
|
},
|
|
888
1036
|
runtime: {
|
|
889
1037
|
get draining() { return self._draining },
|
|
890
1038
|
// Multi-provider data dirs (#2965): computed fresh each access so new
|
|
891
1039
|
// provider registrations are reflected without restarting the server.
|
|
892
1040
|
get projectsDirs() { return getProviderDataDirs().map(d => join(d, 'projects')) },
|
|
1041
|
+
// #7828: the same dirs, TAGGED with the provider that owns each, so a
|
|
1042
|
+
// discovered conversation carries its provider instead of being assumed Claude.
|
|
1043
|
+
get transcriptSources() { return getProviderTranscriptSources() },
|
|
893
1044
|
get userAgentsDirs() { return getProviderDataDirs().map(d => join(d, 'agents')) },
|
|
894
1045
|
// #3637: stable per-session auto-evaluator iteration counter (#3186).
|
|
895
1046
|
// See WsServer constructor for the lifecycle rationale.
|
|
896
1047
|
evaluatorIterations: this._evaluatorIterations,
|
|
1048
|
+
pendingEvaluatorAwaits: this._pendingEvaluatorAwaits,
|
|
1049
|
+
inputDedupRecords: this._inputDedupRecords,
|
|
897
1050
|
},
|
|
898
1051
|
}
|
|
899
1052
|
// Fail loudly if the production ctx ever drifts from the declared shape.
|
|
@@ -922,6 +1075,9 @@ export class WsServer {
|
|
|
922
1075
|
get serverMode() { return self.serverMode },
|
|
923
1076
|
serverVersion: SERVER_VERSION,
|
|
924
1077
|
get latestVersion() { return self._latestVersion },
|
|
1078
|
+
// #8268 — id of the dashboard bundle on disk NOW (re-evaluated per auth_ok, so a
|
|
1079
|
+
// rebuilt dist is seen without a restart). null when no dist is built.
|
|
1080
|
+
get dashboardBuildId() { return getDashboardBuildId() },
|
|
925
1081
|
get gitInfo() { return self._gitInfo },
|
|
926
1082
|
get encryptionEnabled() { return self._encryptionEnabled },
|
|
927
1083
|
// #5536 — identity keypair for signing the eager exchange public key.
|
|
@@ -937,9 +1093,10 @@ export class WsServer {
|
|
|
937
1093
|
protocolVersion: SERVER_PROTOCOL_VERSION,
|
|
938
1094
|
minProtocolVersion: MIN_PROTOCOL_VERSION,
|
|
939
1095
|
get webTaskManager() { return self._webTaskManager },
|
|
1096
|
+
get agentConnections() { return self.config?.agentConnections ?? [] },
|
|
940
1097
|
send: sendFn,
|
|
941
1098
|
broadcast: broadcastFn,
|
|
942
|
-
getConnectedClientList: () => self._getConnectedClientList(),
|
|
1099
|
+
getConnectedClientList: (forClient) => self._getConnectedClientList(forClient),
|
|
943
1100
|
get permissions() { return self._permissions },
|
|
944
1101
|
// #3760: effective inactivity timeout, surfaced in auth_ok so clients
|
|
945
1102
|
// render their ActivityIndicator timeout warning against the real
|
|
@@ -964,6 +1121,17 @@ export class WsServer {
|
|
|
964
1121
|
// `ide` capability so clients gate IDE UI. Late-bound getter so a test
|
|
965
1122
|
// mutating self.config is seen.
|
|
966
1123
|
get ideEnabled() { return isIdeFeatureEnabled(self.config) },
|
|
1124
|
+
// #8619: whether the operator has opted in to Auto permission mode
|
|
1125
|
+
// (`allowAutoPermissionMode: true` in the local config) — the same gate
|
|
1126
|
+
// `set_permission_mode` enforces (settings-handlers.js). Surfaced as the
|
|
1127
|
+
// `autoPermissionMode` capability so a client can disable Auto in its
|
|
1128
|
+
// mode pickers and say WHY. Late-bound getter so a test mutating
|
|
1129
|
+
// self.config is seen.
|
|
1130
|
+
get autoPermissionModeAllowed() { return self.config?.allowAutoPermissionMode === true },
|
|
1131
|
+
// #6691: whether the orchestration harness is enabled on THIS server,
|
|
1132
|
+
// surfaced as the `orchestration` capability so the dashboard reveals the
|
|
1133
|
+
// Runs surface. Server-wide gate, not token-scoped; fail-closed.
|
|
1134
|
+
get orchestrationEnabled() { return isOrchestrationEnabled(self.config) },
|
|
967
1135
|
// #6006: whether the operator panic button (revoke_token) can fire — true
|
|
968
1136
|
// iff a usable rotating TokenManager exists (i.e. auth is on). Mirrors the
|
|
969
1137
|
// token-handlers availability check (`typeof revoke === 'function'`) so the
|
|
@@ -980,6 +1148,8 @@ export class WsServer {
|
|
|
980
1148
|
// surfaced in auth_ok so the dashboard can render a warning banner.
|
|
981
1149
|
// null until start() has bound a socket.
|
|
982
1150
|
get exposure() { return self.exposure },
|
|
1151
|
+
// #8331: the update-banner status, sent post-auth to strict-primary clients only.
|
|
1152
|
+
get daemonUpdate() { return self._daemonUpdate ?? null },
|
|
983
1153
|
// #5821: current billing-canary snapshot, seeded into auth_ok so a
|
|
984
1154
|
// freshly-connected client renders the billing banner immediately. null
|
|
985
1155
|
// until a provider is wired (server-cli sets it post-construct) — live
|
|
@@ -994,6 +1164,23 @@ export class WsServer {
|
|
|
994
1164
|
// letting the client skip its 3-request connect-time round trip.
|
|
995
1165
|
get fileOps() { return self._fileOps },
|
|
996
1166
|
get userAgentsDirs() { return getProviderDataDirs().map(d => join(d, 'agents')) },
|
|
1167
|
+
// #8151 round-2 review (Critical 1) — `sendAuthBootstrap`
|
|
1168
|
+
// (ws-history.js) reads this to resolve the daemon's actual default
|
|
1169
|
+
// provider (`resolveDaemonDefaultProvider`), the same value
|
|
1170
|
+
// `_handlerCtx.services.config` feeds to the `list_providers`
|
|
1171
|
+
// handler (settings-handlers.js). Before this getter existed,
|
|
1172
|
+
// `_historyCtx` had no `config`/`services` key at all, so
|
|
1173
|
+
// `auth_bootstrap.defaultProvider` was unconditionally
|
|
1174
|
+
// `DEFAULT_PROVIDER` (then claude-tui) in every real connection — the C3
|
|
1175
|
+
// fix's own test only ever built its ctx by hand and never caught
|
|
1176
|
+
// this, because a hand-built ctx is exactly the shape the fix
|
|
1177
|
+
// assumed, not the shape the real server actually produces. Both
|
|
1178
|
+
// ctx objects read the SAME `self.config` — the one property on the
|
|
1179
|
+
// WsServer instance itself — so `provider_list` and `auth_bootstrap`
|
|
1180
|
+
// cannot report two different "daemon default" values again, even
|
|
1181
|
+
// though `_handlerCtx` nests its copy under `services` and this one
|
|
1182
|
+
// is flat (matching this ctx's existing `fileOps`/`tunnelUrl` shape).
|
|
1183
|
+
get config() { return self.config },
|
|
997
1184
|
// #5555 (sub-item 7): the current public tunnel URL (wss://), folded into
|
|
998
1185
|
// the auth_bootstrap burst so a reconnecting client always re-learns the
|
|
999
1186
|
// live URL — the durable recovery path when a quick-tunnel rotation
|
|
@@ -1060,6 +1247,83 @@ export class WsServer {
|
|
|
1060
1247
|
// Multi-session support: prefer sessionManager, fall back to single cliSession
|
|
1061
1248
|
this.sessionManager = sessionManager || null
|
|
1062
1249
|
this.environmentManager = environmentManager || null
|
|
1250
|
+
// #7552: a session opening or closing inside a container environment changes
|
|
1251
|
+
// `EnvironmentInfo.sessions`, which the dashboard's Environments panel both
|
|
1252
|
+
// RENDERS ("N connected") and gates its Destroy button on. Nothing else
|
|
1253
|
+
// re-sends the list on session lifecycle — the four `environment_list` emit
|
|
1254
|
+
// sites in feature-handlers.js fire on env list/create/destroy requests
|
|
1255
|
+
// only — so without this the panel would show a stale count for as long as
|
|
1256
|
+
// it stays mounted, and the destroy guard would be deciding from it. Cheap
|
|
1257
|
+
// and quiet: EnvironmentManager emits only on a REAL tag change.
|
|
1258
|
+
if (this.environmentManager && typeof this.environmentManager.on === 'function') {
|
|
1259
|
+
this._environmentSessionsChangedHandler = () => {
|
|
1260
|
+
try {
|
|
1261
|
+
// #7596: fan the environment list to UNBOUND (host) clients only.
|
|
1262
|
+
// This is the most frequent leak path — it fires on every session
|
|
1263
|
+
// open/close — so a plain broadcast would stream the host-level
|
|
1264
|
+
// surface to every bound (share-a-session) listener continuously.
|
|
1265
|
+
broadcastEnvironmentList(
|
|
1266
|
+
(msg, filter) => this._broadcast(msg, filter),
|
|
1267
|
+
this.environmentManager.list(),
|
|
1268
|
+
)
|
|
1269
|
+
} catch (err) {
|
|
1270
|
+
log.warn(`environment_list re-broadcast failed: ${err?.message || err}`)
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
this.environmentManager.on('environment_sessions_changed', this._environmentSessionsChangedHandler)
|
|
1274
|
+
|
|
1275
|
+
// #7601: fast-path for a CHROXY-initiated environment stop/restart. The
|
|
1276
|
+
// #7601 liveness poll is the mandatory detector (an EXTERNAL `docker stop`
|
|
1277
|
+
// fires no event), but a `containers_action stop`/`restart` DOES emit here
|
|
1278
|
+
// — so surface CONTAINER_VANISHED on the environment's bound sessions
|
|
1279
|
+
// immediately rather than waiting up to a poll interval. A restart bounces
|
|
1280
|
+
// the container (stop then start), severing every session's `docker exec`
|
|
1281
|
+
// binding, so it surfaces a vanish too (the #7599 message covers "stopped,
|
|
1282
|
+
// restarted, or removed"; #7602 owns the re-attach). Bridged via
|
|
1283
|
+
// `env.sessions` reusing the destroy-with-sessions fan-out shape — NO
|
|
1284
|
+
// SessionManager handle is injected into EnvironmentManager.
|
|
1285
|
+
this._environmentStoppedHandler = ({ id } = {}) => this._surfaceContainerVanishedForEnvironment(id, 'environment_stopped')
|
|
1286
|
+
// #7602: a RESTART ends with the container running again, and `restart()`
|
|
1287
|
+
// has already awaited `docker restart` and set `status: 'running'` before
|
|
1288
|
+
// emitting — so re-attach right here instead of leaving it to the poll.
|
|
1289
|
+
// Order is load-bearing: the vanish must surface FIRST (that is what arms
|
|
1290
|
+
// the latch whose clearing IS the recovery edge). A `stop` gets no
|
|
1291
|
+
// re-attach — its container is, correctly, still down.
|
|
1292
|
+
this._environmentRestartedHandler = ({ id } = {}) => {
|
|
1293
|
+
this._surfaceContainerVanishedForEnvironment(id, 'environment_restarted')
|
|
1294
|
+
try {
|
|
1295
|
+
this.sessionManager?.reattachEnvironmentSessions?.(id, 'environment_restarted')
|
|
1296
|
+
} catch (err) {
|
|
1297
|
+
log.warn(`[environment_restarted] re-attach fan-out failed for env ${id}: ${err?.message || err}`)
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
this.environmentManager.on('environment_stopped', this._environmentStoppedHandler)
|
|
1301
|
+
this.environmentManager.on('environment_restarted', this._environmentRestartedHandler)
|
|
1302
|
+
} else {
|
|
1303
|
+
this._environmentSessionsChangedHandler = null
|
|
1304
|
+
this._environmentStoppedHandler = null
|
|
1305
|
+
this._environmentRestartedHandler = null
|
|
1306
|
+
}
|
|
1307
|
+
// #6691 (E-4): the OrchestrationManager (null when the feature is off). Its
|
|
1308
|
+
// run_delta events are forwarded to host-level clients by server-cli via
|
|
1309
|
+
// _broadcastOrchestrationDelta; the handlers read it off ctx.services.
|
|
1310
|
+
this._orchestrationManager = orchestrationManager || null
|
|
1311
|
+
// #6871: nullable by design — null whenever scheduled execution is disabled.
|
|
1312
|
+
this._schedulerEngine = schedulerEngine || null
|
|
1313
|
+
// #7427: the CI watcher, so the on-demand PR-survey handler can arm it.
|
|
1314
|
+
// Null when `sessionCi.watch` is off. The WsServer only hands it to
|
|
1315
|
+
// handlers — it never starts, stops or ticks it (server-cli owns that).
|
|
1316
|
+
this._sessionCiWatcher = sessionCiWatcher || null
|
|
1317
|
+
// #8331: the daily-daemon update status (null unless server-cli built and
|
|
1318
|
+
// started one). Its `change` events fan out to STRICT-PRIMARY, UNBOUND clients
|
|
1319
|
+
// only. close() unsubscribes AND closes it, so every teardown path that closes
|
|
1320
|
+
// this server (shutdown, emergencyCleanup) also stops its watcher and timers.
|
|
1321
|
+
this._daemonUpdate = daemonUpdate || null
|
|
1322
|
+
this._daemonUpdateChangeHandler = null
|
|
1323
|
+
if (this._daemonUpdate && typeof this._daemonUpdate.on === 'function') {
|
|
1324
|
+
this._daemonUpdateChangeHandler = (status) => this._broadcastDaemonUpdateStatus(status)
|
|
1325
|
+
this._daemonUpdate.on('change', this._daemonUpdateChangeHandler)
|
|
1326
|
+
}
|
|
1063
1327
|
this.defaultSessionId = defaultSessionId || null
|
|
1064
1328
|
this._checkpointManager = new CheckpointManager()
|
|
1065
1329
|
|
|
@@ -1071,6 +1335,7 @@ export class WsServer {
|
|
|
1071
1335
|
this._sessionCreatedHandler = ({ sessionId }) => {
|
|
1072
1336
|
const entry = sessionManager.getSession(sessionId)
|
|
1073
1337
|
this._registerSessionHookSecretIfMissing(sessionId, entry)
|
|
1338
|
+
this._attachPermissionAuditSink(sessionId, entry)
|
|
1074
1339
|
}
|
|
1075
1340
|
this._sessionDestroyedHandler = ({ sessionId }) => {
|
|
1076
1341
|
// Look up the stored secret — the session is already removed from the map
|
|
@@ -1114,6 +1379,16 @@ export class WsServer {
|
|
|
1114
1379
|
// but a long-running server with many session destroys would
|
|
1115
1380
|
// accumulate dead entries.
|
|
1116
1381
|
this._evaluatorIterations.delete(sessionId)
|
|
1382
|
+
this._pendingEvaluatorAwaits.delete(sessionId)
|
|
1383
|
+
this._inputDedupRecords.delete(sessionId)
|
|
1384
|
+
// #7450's survey-throttle prune used to live here, keyed on this
|
|
1385
|
+
// EVENT — but #8092 found a teardown path (the restore-rebind branch
|
|
1386
|
+
// of `_handleAsyncStartFailure()`) that removes a session without
|
|
1387
|
+
// ever emitting `session_destroyed`, so an event-based prune missed
|
|
1388
|
+
// it. The prune now lives in `SessionManager._cleanupSessionMaps()`
|
|
1389
|
+
// (and `destroyAll()`, which bypasses that method) instead — the
|
|
1390
|
+
// removal itself, reached by every teardown path rather than only
|
|
1391
|
+
// the ones that happen to fire this particular event.
|
|
1117
1392
|
}
|
|
1118
1393
|
// #3057: audit auto-deny resolution paths (timeout / aborted / cleared).
|
|
1119
1394
|
// The WS inline response path in settings-handlers.js audits user
|
|
@@ -1158,16 +1433,25 @@ export class WsServer {
|
|
|
1158
1433
|
if (sessionManager._sessions instanceof Map && typeof sessionManager.getSession === 'function') {
|
|
1159
1434
|
for (const [sessionId, entry] of sessionManager._sessions) {
|
|
1160
1435
|
if (entry?._destroying) continue
|
|
1161
|
-
|
|
1436
|
+
const resolved = sessionManager.getSession(sessionId)
|
|
1437
|
+
this._registerSessionHookSecretIfMissing(sessionId, resolved)
|
|
1438
|
+
// #6830 — restored sessions predate this WsServer (restoreState runs
|
|
1439
|
+
// before construction, same shape as the #3716 hook-secret gap), so
|
|
1440
|
+
// their persisted-rule audit sinks must be wired retroactively too.
|
|
1441
|
+
this._attachPermissionAuditSink(sessionId, resolved)
|
|
1162
1442
|
}
|
|
1163
1443
|
}
|
|
1164
1444
|
}
|
|
1165
1445
|
|
|
1166
1446
|
// Dev server preview tunneling
|
|
1167
|
-
this._devPreview = new DevPreviewManager()
|
|
1447
|
+
this._devPreview = new DevPreviewManager({ daemonPort: port, authRequired, getSession: id => this.sessionManager?.getSession(id),
|
|
1448
|
+
tunnelConfig: { binaryProvenance: this.sessionManager?._binaryProvenanceOptions?.() } })
|
|
1168
1449
|
|
|
1169
|
-
// Web task manager (Claude Code Web cloud delegation)
|
|
1170
|
-
|
|
1450
|
+
// Web task manager (Claude Code Web cloud delegation). #8039: pass
|
|
1451
|
+
// sessionManager so every spawn (feature detection, launch, teleport)
|
|
1452
|
+
// routes through the verified SessionManager.verifyOneShotExecutable()
|
|
1453
|
+
// gate instead of a bare, unverified `claude` PATH lookup.
|
|
1454
|
+
this._webTaskManager = new WebTaskManager({ cwd: sessionManager?.defaultCwd || process.cwd(), sessionManager })
|
|
1171
1455
|
|
|
1172
1456
|
// Legacy single-session mode: wrap cliSession in a minimal shim
|
|
1173
1457
|
if (!sessionManager && cliSession) {
|
|
@@ -1208,8 +1492,15 @@ export class WsServer {
|
|
|
1208
1492
|
this._draining = false
|
|
1209
1493
|
this._latestVersion = null
|
|
1210
1494
|
|
|
1211
|
-
// Background version check (non-blocking, skipped in test/CI)
|
|
1212
|
-
|
|
1495
|
+
// Background version check (non-blocking, skipped in test/CI). #7265: this
|
|
1496
|
+
// used to be gated on `process.env.NODE_ENV !== 'test'`, but nothing in this
|
|
1497
|
+
// repo's harness or CI ever sets NODE_ENV=test, so the skip never fired and
|
|
1498
|
+
// every WsServer construction in the test suite made a real outbound request
|
|
1499
|
+
// to registry.npmjs.org. Gate on an explicit, harness-set switch instead —
|
|
1500
|
+
// matches the CHROXY_DISABLE_KEYCHAIN / CHROXY_CRED_DISABLE_KEYCHAIN pattern
|
|
1501
|
+
// in tests/_setup.mjs — so this changes exactly one behaviour and can't
|
|
1502
|
+
// re-arm (or fail to arm) any other NODE_ENV gate.
|
|
1503
|
+
if (process.env.CHROXY_DISABLE_UPDATE_CHECK !== '1') {
|
|
1213
1504
|
checkLatestVersion(packageJson.name).then((v) => { this._latestVersion = v }).catch((err) => {
|
|
1214
1505
|
log.warn(`Failed to check latest npm version: ${err.message} (non-critical, update check skipped)`)
|
|
1215
1506
|
})
|
|
@@ -1219,6 +1510,7 @@ export class WsServer {
|
|
|
1219
1510
|
// authenticated dashboard clients so they can auto-refresh the QR code (#2916).
|
|
1220
1511
|
this._pairingRefreshedHandler = null
|
|
1221
1512
|
this._pendingRequestExpiredHandler = null
|
|
1513
|
+
this._sessionTokenRemovedHandler = null
|
|
1222
1514
|
if (this._pairingManager) {
|
|
1223
1515
|
this._pairingRefreshedHandler = () => {
|
|
1224
1516
|
this._broadcast({ type: 'pairing_refreshed' })
|
|
@@ -1234,12 +1526,30 @@ export class WsServer {
|
|
|
1234
1526
|
this._broadcastPairResolved(requestId, 'expired')
|
|
1235
1527
|
}
|
|
1236
1528
|
this._pairingManager.on('pending_request_expired', this._pendingRequestExpiredHandler)
|
|
1529
|
+
|
|
1530
|
+
// A stored pairing token stopped being valid (revoked, expired, evicted):
|
|
1531
|
+
// end every connection that authenticated with it.
|
|
1532
|
+
this._sessionTokenRemovedHandler = ({ token, reason }) => {
|
|
1533
|
+
// Daemon teardown (reason 'destroyed') clears the store from memory only: the
|
|
1534
|
+
// tokens stay valid on disk. _endCredentialConnection sees the destroyed
|
|
1535
|
+
// pairing manager and ends the connection quietly, without a notice.
|
|
1536
|
+
for (const [ws, client] of [...this.clients]) {
|
|
1537
|
+
if (client.pairingCredential != null && client.pairingCredential === token) {
|
|
1538
|
+
this._endCredentialConnection(ws, client, reason)
|
|
1539
|
+
}
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
this._pairingManager.on('session_token_removed', this._sessionTokenRemovedHandler)
|
|
1237
1543
|
}
|
|
1238
1544
|
|
|
1239
1545
|
// Wire TokenManager rotation events — broadcast new token to all clients
|
|
1240
1546
|
this._tokenRotatedHandler = null
|
|
1547
|
+
// #6965: the in-flight revoke-ack gate (a promise resolving to
|
|
1548
|
+
// `{ ok, error? }`), or null when the last revoke had nothing to wait on.
|
|
1549
|
+
// Exposed so a test can await the gate deterministically.
|
|
1550
|
+
this._lastRevokeAck = null
|
|
1241
1551
|
if (this._tokenManager) {
|
|
1242
|
-
this._tokenRotatedHandler = ({ newToken, expiresAt, reason }) => {
|
|
1552
|
+
this._tokenRotatedHandler = ({ newToken, expiresAt, reason, persisted = null }) => {
|
|
1243
1553
|
// Update our reference so subsequent auth checks use the new token
|
|
1244
1554
|
this.apiToken = newToken
|
|
1245
1555
|
|
|
@@ -1263,7 +1573,11 @@ export class WsServer {
|
|
|
1263
1573
|
} catch (err) {
|
|
1264
1574
|
log.error(`Failed to sever user-shell sessions on revoke: ${err.message}`)
|
|
1265
1575
|
}
|
|
1266
|
-
|
|
1576
|
+
//
|
|
1577
|
+
// ENFORCEMENT (severing above + stripping authority below) is immediate
|
|
1578
|
+
// and unconditional — it must NEVER wait on, or be skipped because of,
|
|
1579
|
+
// disk I/O. Only the client-facing ACK is gated on durability (#6965).
|
|
1580
|
+
const forcedSockets = []
|
|
1267
1581
|
for (const [ws, client] of this.clients) {
|
|
1268
1582
|
// Skip connections still mid-handshake (not yet authenticated): they
|
|
1269
1583
|
// hold no authority to strip and will fail their pending auth step
|
|
@@ -1271,10 +1585,149 @@ export class WsServer {
|
|
|
1271
1585
|
if (!client.authenticated || ws.readyState !== 1) continue
|
|
1272
1586
|
client.authenticated = false
|
|
1273
1587
|
client.isPrimaryToken = false
|
|
1274
|
-
|
|
1275
|
-
|
|
1588
|
+
forcedSockets.push(ws)
|
|
1589
|
+
}
|
|
1590
|
+
log.warn(`Token REVOKED — severed ${severed} user-shell session(s), forced re-auth on ${forcedSockets.length} connection(s)`)
|
|
1591
|
+
|
|
1592
|
+
const sendRevokeAck = () => {
|
|
1593
|
+
for (const ws of forcedSockets) {
|
|
1594
|
+
if (ws.readyState !== 1) continue
|
|
1595
|
+
this._send(ws, { type: 'token_rotated', expiresAt, reason: 'revoke' })
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
|
|
1599
|
+
// #6965: the revoke ack must not precede its durable write. #6963 made the
|
|
1600
|
+
// panic-revoke's token write durable, but `onPersist` was fire-and-forget
|
|
1601
|
+
// and this ack raced it — so the operator could be told the highest-authority
|
|
1602
|
+
// token was dead while a power loss inside the OS writeback window brought the
|
|
1603
|
+
// daemon back still honouring it. Wait for the persist to report success —
|
|
1604
|
+
// an fsync of the temp file + containing directory on the `config.json`
|
|
1605
|
+
// fallback, while the OS-keychain path delegates durability to the
|
|
1606
|
+
// keychain and performs no fsync here — THEN ack. On failure the client
|
|
1607
|
+
// ALSO gets an explicit error — see below.
|
|
1608
|
+
if (!persisted) {
|
|
1609
|
+
// Nothing to wait on (no persist callback configured — e.g. a test
|
|
1610
|
+
// TokenManager, or a deployment with no token persistence). Unchanged
|
|
1611
|
+
// synchronous behaviour.
|
|
1612
|
+
this._lastRevokeAck = null
|
|
1613
|
+
sendRevokeAck()
|
|
1614
|
+
return
|
|
1276
1615
|
}
|
|
1277
|
-
|
|
1616
|
+
// #7053: BOUND the gate. Waiting on `persisted` is right, but waiting
|
|
1617
|
+
// FOREVER is its own false safety: a persist that never settles emits
|
|
1618
|
+
// no ack and no error, so the operator sees a panic-revoke that appears
|
|
1619
|
+
// to do nothing — while enforcement above has already run. Today's
|
|
1620
|
+
// `onPersist` (server-cli) is synchronous, so this is latent rather
|
|
1621
|
+
// than live; the moment it becomes async, an unbounded gate turns the
|
|
1622
|
+
// most consequential control in the daemon into a silent no-op.
|
|
1623
|
+
//
|
|
1624
|
+
// A timeout is NOT the same verdict as a rejection: a rejection means
|
|
1625
|
+
// the write is KNOWN to have failed, a timeout means the outcome is
|
|
1626
|
+
// UNKNOWN and may still land. It gets its own code so the operator is
|
|
1627
|
+
// not told something the daemon does not know.
|
|
1628
|
+
let settled = false
|
|
1629
|
+
let resolveAck
|
|
1630
|
+
const ackSettled = new Promise((res) => { resolveAck = res })
|
|
1631
|
+
this._lastRevokeAck = ackSettled
|
|
1632
|
+
const timeoutMs = this._revokeAckTimeoutMs ?? REVOKE_ACK_TIMEOUT_MS
|
|
1633
|
+
const timer = setTimeout(() => {
|
|
1634
|
+
if (settled) return
|
|
1635
|
+
settled = true
|
|
1636
|
+
log.error(
|
|
1637
|
+
`Token REVOKE persist did not report within ${timeoutMs}ms — the revoke HOLDS in this process, ` +
|
|
1638
|
+
`but whether it reached disk is UNKNOWN. Check the storage layer; re-revoke after a restart to be sure.`,
|
|
1639
|
+
)
|
|
1640
|
+
// Same ordering as the rejection branch, and for the same reason: the
|
|
1641
|
+
// diagnostic first, then the state transition (which tears the socket
|
|
1642
|
+
// down client-side, so a frame queued after it can be lost).
|
|
1643
|
+
for (const ws of forcedSockets) {
|
|
1644
|
+
if (ws.readyState !== 1) continue
|
|
1645
|
+
this._send(ws, {
|
|
1646
|
+
type: 'error',
|
|
1647
|
+
code: 'REVOKE_DURABILITY_UNKNOWN',
|
|
1648
|
+
message:
|
|
1649
|
+
`Token revoke is enforced for the running daemon, but its write did not report within ${timeoutMs}ms — ` +
|
|
1650
|
+
'whether it reached disk is unknown. After a restart the daemon may come back on either token. ' +
|
|
1651
|
+
'Check the storage layer and revoke again to be certain.',
|
|
1652
|
+
})
|
|
1653
|
+
}
|
|
1654
|
+
// Still send the transition. It carries no token and claims no
|
|
1655
|
+
// durability; it is the client's ONLY automatic trigger to drop the
|
|
1656
|
+
// now-dead credential and re-authenticate. Withholding it would leave
|
|
1657
|
+
// every device "connected" holding a revoked token.
|
|
1658
|
+
sendRevokeAck()
|
|
1659
|
+
resolveAck({ ok: false, timedOut: true })
|
|
1660
|
+
}, timeoutMs)
|
|
1661
|
+
// Never let the bound hold the event loop open (a pending timer here
|
|
1662
|
+
// would keep the process — and the test runner — alive).
|
|
1663
|
+
timer.unref?.()
|
|
1664
|
+
|
|
1665
|
+
persisted.then(
|
|
1666
|
+
() => {
|
|
1667
|
+
if (settled) {
|
|
1668
|
+
log.warn('Token REVOKE persist landed AFTER the durability bound had already been reported as unknown.')
|
|
1669
|
+
return
|
|
1670
|
+
}
|
|
1671
|
+
settled = true
|
|
1672
|
+
clearTimeout(timer)
|
|
1673
|
+
sendRevokeAck()
|
|
1674
|
+
resolveAck({ ok: true })
|
|
1675
|
+
},
|
|
1676
|
+
(err) => {
|
|
1677
|
+
const message = err?.message || String(err)
|
|
1678
|
+
if (settled) {
|
|
1679
|
+
// error, not warn: this is a CONFIRMED non-durable write — strictly
|
|
1680
|
+
// worse than the "unknown" the operator was already told — and no
|
|
1681
|
+
// client frame is sent for it (that would double-send), so this
|
|
1682
|
+
// line is the only surviving artifact. It must not rank below the
|
|
1683
|
+
// on-time failure in alerting.
|
|
1684
|
+
log.error(
|
|
1685
|
+
`Token REVOKE persist FAILED (${message}) after the durability bound had already reported unknown — ` +
|
|
1686
|
+
`the write is now known NOT to be durable. Fix the storage error and revoke again.`,
|
|
1687
|
+
)
|
|
1688
|
+
return
|
|
1689
|
+
}
|
|
1690
|
+
settled = true
|
|
1691
|
+
clearTimeout(timer)
|
|
1692
|
+
log.error(
|
|
1693
|
+
`Token REVOKE could not be confirmed durable (${message}) — the revoke HOLDS in this process, ` +
|
|
1694
|
+
`but a restart is not guaranteed to come back on the new token. Fix the storage error and revoke again.`,
|
|
1695
|
+
)
|
|
1696
|
+
// Send the operator DIAGNOSTIC first, then the revoke transition.
|
|
1697
|
+
//
|
|
1698
|
+
// Both, deliberately. The `error` envelope is the operator's report that
|
|
1699
|
+
// durability is unproven; `token_rotated{reason:'revoke'}` is the CLIENT
|
|
1700
|
+
// STATE TRANSITION — for the mobile app it is the sole automatic trigger
|
|
1701
|
+
// for clearing the now-dead credential and prompting re-auth (app
|
|
1702
|
+
// message-handler `case 'token_rotated'` with no token →
|
|
1703
|
+
// clearSavedConnection() + disconnect() + re-scan alert). `case 'error'`
|
|
1704
|
+
// shows an alert and touches neither the socket nor secure storage, so
|
|
1705
|
+
// withholding the transition left every connected device "connected" while
|
|
1706
|
+
// holding a REVOKED token with its server-side authority already stripped:
|
|
1707
|
+
// privileged ops failing opaquely, nothing prompting a re-pair.
|
|
1708
|
+
//
|
|
1709
|
+
// Sending it is not a false success: the message carries NO token and makes
|
|
1710
|
+
// NO durability claim. It says "this connection's authority is gone, you must
|
|
1711
|
+
// re-authenticate", which is TRUE here — enforcement above already ran,
|
|
1712
|
+
// unconditionally. The durability caveat rides the error, not this message.
|
|
1713
|
+
//
|
|
1714
|
+
// Diagnostic first because the transition tears the socket down client-side;
|
|
1715
|
+
// a frame queued after it can be dropped before the client reads it.
|
|
1716
|
+
for (const ws of forcedSockets) {
|
|
1717
|
+
if (ws.readyState !== 1) continue
|
|
1718
|
+
this._send(ws, {
|
|
1719
|
+
type: 'error',
|
|
1720
|
+
code: 'REVOKE_NOT_DURABLE',
|
|
1721
|
+
message:
|
|
1722
|
+
'Token revoke is enforced for the running daemon but its write could NOT be confirmed durable on disk — ' +
|
|
1723
|
+
'after a restart the daemon may come back on either the new token or the previous one. ' +
|
|
1724
|
+
'Resolve the storage error and revoke again.',
|
|
1725
|
+
})
|
|
1726
|
+
}
|
|
1727
|
+
sendRevokeAck()
|
|
1728
|
+
resolveAck({ ok: false, error: message })
|
|
1729
|
+
},
|
|
1730
|
+
)
|
|
1278
1731
|
return
|
|
1279
1732
|
}
|
|
1280
1733
|
|
|
@@ -1282,9 +1735,15 @@ export class WsServer {
|
|
|
1282
1735
|
// Send the new token to encrypted clients (they need it for reconnection).
|
|
1283
1736
|
// Unencrypted clients (e.g. localhost dashboard) get the event without the
|
|
1284
1737
|
// raw token to avoid leaking credentials over plaintext connections.
|
|
1738
|
+
//
|
|
1739
|
+
// The rotated token is the PRIMARY credential, so only a connection that
|
|
1740
|
+
// authenticated with the primary token is told about it. A session-scoped
|
|
1741
|
+
// or pairing-issued connection holds its own stored credential, which
|
|
1742
|
+
// rotation does not touch: it receives nothing and keeps that credential.
|
|
1285
1743
|
let encrypted = 0, unencrypted = 0
|
|
1286
1744
|
for (const [ws, client] of this.clients) {
|
|
1287
1745
|
if (!client.authenticated || ws.readyState !== 1) continue
|
|
1746
|
+
if (!this._holdsPrimaryCredential(client)) continue
|
|
1288
1747
|
// Carry `reason: 'scheduled'` so the wire is self-describing and
|
|
1289
1748
|
// matches the documented contract + TokenManager's event payload.
|
|
1290
1749
|
if (client.encryptionState) {
|
|
@@ -1296,7 +1755,9 @@ export class WsServer {
|
|
|
1296
1755
|
// and de-auths instead, so a compromised connection can't gain
|
|
1297
1756
|
// currency this way. Unencrypted clients get no token, so theirs
|
|
1298
1757
|
// stays stale (they must reconnect) — handled by the else branch.
|
|
1299
|
-
|
|
1758
|
+
// A session-scoped connection was not sent the token (see
|
|
1759
|
+
// outgoing-policy.js), so its recorded credential stays its own.
|
|
1760
|
+
if (!isBoundClient(client)) client.authToken = newToken
|
|
1300
1761
|
encrypted++
|
|
1301
1762
|
} else {
|
|
1302
1763
|
this._send(ws, { type: 'token_rotated', expiresAt, reason: 'scheduled' })
|
|
@@ -1338,7 +1799,7 @@ export class WsServer {
|
|
|
1338
1799
|
}
|
|
1339
1800
|
const queryToken = dashUrl.searchParams.get('token')
|
|
1340
1801
|
const token = queryToken || bearerToken || cookieVal
|
|
1341
|
-
if (!token || !this._isTokenValid(token)) {
|
|
1802
|
+
if (!token || !this._isTokenValid(token) || this._isSessionScopedToken(token)) {
|
|
1342
1803
|
res.writeHead(403, { 'Content-Type': 'text/html', ...securityHeaders })
|
|
1343
1804
|
res.end('<h1>403 Forbidden</h1><p>Invalid or missing token.</p>')
|
|
1344
1805
|
return false
|
|
@@ -1354,11 +1815,30 @@ export class WsServer {
|
|
|
1354
1815
|
return true
|
|
1355
1816
|
}
|
|
1356
1817
|
|
|
1818
|
+
/**
|
|
1819
|
+
* True when `token` is a pairing-issued token bound to one session.
|
|
1820
|
+
* Linking-mode (unbound) session tokens and the primary token are not.
|
|
1821
|
+
*/
|
|
1822
|
+
_isSessionScopedToken(token) {
|
|
1823
|
+
const pm = this._pairingManager
|
|
1824
|
+
if (!pm || !token) return false
|
|
1825
|
+
// Fail closed: a manager that cannot report a token's binding is treated
|
|
1826
|
+
// as having bound it. Any stored session id (including an empty string)
|
|
1827
|
+
// counts as bound; only null/undefined is unscoped.
|
|
1828
|
+
if (typeof pm.getSessionIdForToken !== 'function') return true
|
|
1829
|
+
return pm.getSessionIdForToken(token) != null
|
|
1830
|
+
}
|
|
1831
|
+
|
|
1357
1832
|
/**
|
|
1358
1833
|
* Validate Bearer token on an HTTP request. Returns true if auth passes
|
|
1359
1834
|
* (or auth is disabled). On failure, writes a 403 response and returns false.
|
|
1835
|
+
*
|
|
1836
|
+
* A session-scoped token is refused by default: routes guarded by this check
|
|
1837
|
+
* serve host-wide data. A route that a scoped client legitimately calls opts
|
|
1838
|
+
* in with `{ allowScoped: true }` and MUST itself limit the request to the
|
|
1839
|
+
* token's bound session.
|
|
1360
1840
|
*/
|
|
1361
|
-
_validateBearerAuth(req, res) {
|
|
1841
|
+
_validateBearerAuth(req, res, { allowScoped = false } = {}) {
|
|
1362
1842
|
if (!this.authRequired) return true
|
|
1363
1843
|
const authHeader = req.headers['authorization'] || ''
|
|
1364
1844
|
const token = authHeader.startsWith('Bearer ') ? authHeader.slice(7) : null
|
|
@@ -1367,6 +1847,11 @@ export class WsServer {
|
|
|
1367
1847
|
res.end(JSON.stringify({ error: 'unauthorized' }))
|
|
1368
1848
|
return false
|
|
1369
1849
|
}
|
|
1850
|
+
if (!allowScoped && this._isSessionScopedToken(token)) {
|
|
1851
|
+
res.writeHead(403, { 'Content-Type': 'application/json' })
|
|
1852
|
+
res.end(JSON.stringify({ error: 'session_scoped_token' }))
|
|
1853
|
+
return false
|
|
1854
|
+
}
|
|
1370
1855
|
return true
|
|
1371
1856
|
}
|
|
1372
1857
|
|
|
@@ -1425,6 +1910,7 @@ export class WsServer {
|
|
|
1425
1910
|
tokenClass: entry.tokenClass || 'primary',
|
|
1426
1911
|
deviceName: entry.deviceName,
|
|
1427
1912
|
clientId: entry.clientId,
|
|
1913
|
+
requestId: entry.requestId || undefined,
|
|
1428
1914
|
})
|
|
1429
1915
|
}
|
|
1430
1916
|
|
|
@@ -1440,6 +1926,7 @@ export class WsServer {
|
|
|
1440
1926
|
type: 'session_error',
|
|
1441
1927
|
code: 'SHELL_APPROVAL_DENIED',
|
|
1442
1928
|
message: 'The host operator declined this shell.',
|
|
1929
|
+
...(entry.requestId ? { requestId: entry.requestId } : {}),
|
|
1443
1930
|
})
|
|
1444
1931
|
break
|
|
1445
1932
|
}
|
|
@@ -1561,7 +2048,7 @@ export class WsServer {
|
|
|
1561
2048
|
}
|
|
1562
2049
|
// No hook secrets registered — fall back to main token validation
|
|
1563
2050
|
// (handles legacy single-session setups and tests that don't register secrets)
|
|
1564
|
-
if (!this._isTokenValid(token)) {
|
|
2051
|
+
if (!this._isTokenValid(token) || this._isSessionScopedToken(token)) {
|
|
1565
2052
|
res.writeHead(403, { 'Content-Type': 'application/json' })
|
|
1566
2053
|
res.end(JSON.stringify({ error: 'unauthorized' }))
|
|
1567
2054
|
return false
|
|
@@ -1585,6 +2072,38 @@ export class WsServer {
|
|
|
1585
2072
|
log.debug(`Registered hook secret for session ${sessionId}`)
|
|
1586
2073
|
}
|
|
1587
2074
|
|
|
2075
|
+
/**
|
|
2076
|
+
* #6830 (PR #6842 review) — wire this server's PermissionAuditLog straight
|
|
2077
|
+
* into a session's persisted-rule audit path. Called from the
|
|
2078
|
+
* `session_created` handler AND the constructor's retroactive scan (same
|
|
2079
|
+
* dual wiring as _registerSessionHookSecretIfMissing, for the same #3716
|
|
2080
|
+
* restored-session reason).
|
|
2081
|
+
*
|
|
2082
|
+
* A persisted-rule auto-approve deliberately bypasses the whole
|
|
2083
|
+
* session-event pipeline: emitting `permission_resolved` for it would ride
|
|
2084
|
+
* ws-forwarding → broadcastToSession to every client on EVERY rule-matched
|
|
2085
|
+
* tool call (the PR #6842 review finding). The sink is a plain callback
|
|
2086
|
+
* into logPersistedRuleApproval, which also COALESCES repeats per
|
|
2087
|
+
* (sessionId, tool, projectKey) so the 500-entry ring is never flooded.
|
|
2088
|
+
*
|
|
2089
|
+
* The closure captures ONLY the audit log + sessionId — never `this` — so
|
|
2090
|
+
* a session outliving a retired WsServer pins a small ring buffer, not the
|
|
2091
|
+
* whole server (the #3060 concern that motivated the removable
|
|
2092
|
+
* session_event listeners). Single-slot on the manager side: a replacement
|
|
2093
|
+
* WsServer's attach overwrites this one (last writer wins).
|
|
2094
|
+
*
|
|
2095
|
+
* @param {string} sessionId
|
|
2096
|
+
* @param {object|null} entry - SessionManager entry ({ session, ... })
|
|
2097
|
+
*/
|
|
2098
|
+
_attachPermissionAuditSink(sessionId, entry) {
|
|
2099
|
+
const session = entry?.session
|
|
2100
|
+
if (typeof session?.setPermissionAuditSink !== 'function') return
|
|
2101
|
+
const audit = this._permissionAudit
|
|
2102
|
+
session.setPermissionAuditSink((info) => {
|
|
2103
|
+
audit.logPersistedRuleApproval({ sessionId, tool: info?.tool, projectKey: info?.projectKey ?? null })
|
|
2104
|
+
})
|
|
2105
|
+
}
|
|
2106
|
+
|
|
1588
2107
|
/**
|
|
1589
2108
|
* Register a per-session hook secret so POST /permission accepts it.
|
|
1590
2109
|
* Called by session-manager when a CliSession is created.
|
|
@@ -1702,6 +2221,27 @@ export class WsServer {
|
|
|
1702
2221
|
}
|
|
1703
2222
|
}
|
|
1704
2223
|
|
|
2224
|
+
/**
|
|
2225
|
+
* #6540 — derive the public `…/api/github/webhook` payload URL an operator
|
|
2226
|
+
* pastes into GitHub, from the server's live origin. Prefers the tunnel URL
|
|
2227
|
+
* (public), then an operator-supplied external URL (SKIP_TUNNEL), then the LAN
|
|
2228
|
+
* address (flagged `lanOnly` — GitHub can't reach it, e.g. `--tunnel none`).
|
|
2229
|
+
* The derivation is a pure function (github-webhook.js); this just gathers the
|
|
2230
|
+
* live inputs. Surfaced to the config handler via `ctx.services.webhookPayloadUrl`.
|
|
2231
|
+
*
|
|
2232
|
+
* @returns {{ url: string|null, lanOnly: boolean, note: string|null }}
|
|
2233
|
+
*/
|
|
2234
|
+
getWebhookPayloadUrl() {
|
|
2235
|
+
return deriveWebhookPayloadUrl({
|
|
2236
|
+
tunnelUrl: this._tunnelUrl,
|
|
2237
|
+
externalUrl: this.config?.externalUrl,
|
|
2238
|
+
boundHost: this._boundHost,
|
|
2239
|
+
port: this.port,
|
|
2240
|
+
lanIp: getLanIp(),
|
|
2241
|
+
isLoopbackHost,
|
|
2242
|
+
})
|
|
2243
|
+
}
|
|
2244
|
+
|
|
1705
2245
|
start(host) {
|
|
1706
2246
|
// #5356: remember what we bound. `undefined` means the default
|
|
1707
2247
|
// all-interfaces bind — record it as 0.0.0.0 so exposure reads true.
|
|
@@ -1834,6 +2374,7 @@ export class WsServer {
|
|
|
1834
2374
|
// a still-alive but invisible WS connection.
|
|
1835
2375
|
visible: true,
|
|
1836
2376
|
_seq: 0, // monotonic sequence number for outbound messages
|
|
2377
|
+
pairingCredential: null, // stored pairing token this connection authenticated with (null = primary / none)
|
|
1837
2378
|
encryptionState: null, // { sharedKey, sendNonce, recvNonce } when active
|
|
1838
2379
|
encryptionPending: false, // true while waiting for key_exchange
|
|
1839
2380
|
postAuthQueue: null, // queued messages during key exchange
|
|
@@ -1883,6 +2424,9 @@ export class WsServer {
|
|
|
1883
2424
|
: null
|
|
1884
2425
|
|
|
1885
2426
|
ws.on('message', (raw) => {
|
|
2427
|
+
// Once a close has begun (e.g. after an auth failure) frames already in
|
|
2428
|
+
// flight must not be dispatched.
|
|
2429
|
+
if (ws.readyState !== 1) return
|
|
1886
2430
|
let msg
|
|
1887
2431
|
try {
|
|
1888
2432
|
msg = JSON.parse(raw.toString())
|
|
@@ -1925,7 +2469,7 @@ export class WsServer {
|
|
|
1925
2469
|
if (client) client.isAlive = true
|
|
1926
2470
|
if (client?.encryptionState) {
|
|
1927
2471
|
if (msg.type !== 'encrypted') {
|
|
1928
|
-
log.error(`Plaintext frame from ${client.id} after encryption established (type=${msg?.type}); closing connection`)
|
|
2472
|
+
log.error(`Plaintext frame from ${client.id} after encryption established (type=${loggableValue(msg?.type)}); closing connection`)
|
|
1929
2473
|
ws.close(1008, 'encryption required')
|
|
1930
2474
|
return
|
|
1931
2475
|
}
|
|
@@ -2000,19 +2544,33 @@ export class WsServer {
|
|
|
2000
2544
|
this._startApprovalListener()
|
|
2001
2545
|
}
|
|
2002
2546
|
|
|
2003
|
-
// Detect Claude Code Web features (non-blocking)
|
|
2547
|
+
// Detect Claude Code Web features (non-blocking). #7299: detectFeatures()
|
|
2548
|
+
// itself never rejects — every failure mode (a gate refusal, a missing
|
|
2549
|
+
// binary, a timed-out --help) degrades to remote=false/teleport=false and
|
|
2550
|
+
// is logged inside it. The `.catch` stays anyway: it hangs off the promise
|
|
2551
|
+
// `.then()` returns, so it also covers a throw inside the handler and any
|
|
2552
|
+
// rejection path a future change adds. This chain is fire-and-forget, and
|
|
2553
|
+
// an unhandled rejection takes the whole daemon down (#5369), so the catch
|
|
2554
|
+
// is worth keeping even though nothing reaches it today.
|
|
2004
2555
|
this._webTaskManager.detectFeatures().then(({ remote, teleport }) => {
|
|
2005
2556
|
if (remote || teleport) {
|
|
2006
2557
|
log.info(`Claude Code Web features detected: remote=${remote}, teleport=${teleport}`)
|
|
2007
2558
|
}
|
|
2008
2559
|
}).catch((err) => {
|
|
2009
|
-
log.warn(`
|
|
2560
|
+
log.warn(`Claude Code Web feature detection failed: ${err?.message || err} (non-critical, web features disabled)`)
|
|
2010
2561
|
})
|
|
2011
2562
|
|
|
2012
2563
|
// Forward web task events to all authenticated clients
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
|
|
2564
|
+
// A session-bound client receives a task frame only for a task in its bound
|
|
2565
|
+
// session's cwd (canClientSeeWebTask — the same rule list_web_tasks applies).
|
|
2566
|
+
// An error whose task cannot be resolved by id reaches unbound clients only.
|
|
2567
|
+
const webTaskRecipient = (task) => (client) => canClientSeeWebTask(client, task, this.sessionManager)
|
|
2568
|
+
this._webTaskManager.on('task_created', (task) => this._broadcast({ type: 'web_task_created', task }, webTaskRecipient(task)))
|
|
2569
|
+
this._webTaskManager.on('task_updated', (task) => this._broadcast({ type: 'web_task_updated', task }, webTaskRecipient(task)))
|
|
2570
|
+
this._webTaskManager.on('task_error', ({ taskId, message }) => {
|
|
2571
|
+
const task = this._webTaskManager.getTask?.(taskId) ?? null
|
|
2572
|
+
this._broadcast({ type: 'web_task_error', taskId, message }, webTaskRecipient(task))
|
|
2573
|
+
})
|
|
2016
2574
|
|
|
2017
2575
|
// Broadcast structured log entries to dashboard clients.
|
|
2018
2576
|
// Re-entrancy guard prevents infinite recursion when _broadcast() itself
|
|
@@ -2061,6 +2619,14 @@ export class WsServer {
|
|
|
2061
2619
|
pushManager: this.pushManager,
|
|
2062
2620
|
permissionSessionMap: this._permissionSessionMap,
|
|
2063
2621
|
questionSessionMap: this._questionSessionMap,
|
|
2622
|
+
// #7895 — the daemon's resolved default provider, fed to
|
|
2623
|
+
// `broadcastRosterPerRecipient`/`resolveRosterProvider` so the two
|
|
2624
|
+
// `available_models` send sites in ws-forwarding.js tag a no-session (or
|
|
2625
|
+
// legacy single-session) roster identically to `ws-history.js`'s connect
|
|
2626
|
+
// path and `createOverlayReloadBroadcaster`'s overlay-reload path — the
|
|
2627
|
+
// SAME resolution (#7932: `resolveDaemonDefaultProvider`, ./providers.js)
|
|
2628
|
+
// `billingCanaryMonitor`'s `getDefaultProvider` uses.
|
|
2629
|
+
defaultProvider: resolveDaemonDefaultProvider(this.config),
|
|
2064
2630
|
// #4788 Wave 2: hand the question-route registration through a helper so
|
|
2065
2631
|
// dispatch and routing-guard stay symmetric. When a question is
|
|
2066
2632
|
// registered for session S, every currently-connected client that's
|
|
@@ -2075,6 +2641,13 @@ export class WsServer {
|
|
|
2075
2641
|
// settings-handlers subscription guard naturally passes for legitimate
|
|
2076
2642
|
// viewers (including the "view A → switch to B → respond" flow).
|
|
2077
2643
|
registerPermissionRoute: (requestId, sessionId) => this._registerPermissionRoute(requestId, sessionId),
|
|
2644
|
+
// #7379: a session reporting `permission_expired` means the turn that
|
|
2645
|
+
// raised the prompt is gone, so the daemon's own pending entry must be
|
|
2646
|
+
// released — otherwise resendPendingPermissions hands a dead prompt, with
|
|
2647
|
+
// a live Allow button, to the next client that connects. One ctx serves
|
|
2648
|
+
// both the multi-session and legacy-CLI forwarding paths, so wiring it
|
|
2649
|
+
// here covers both by construction.
|
|
2650
|
+
releasePermission: (requestId, sessionId) => this._permissions?.releaseAbandonedPermission?.(requestId, sessionId),
|
|
2078
2651
|
broadcast: (msg, filter) => this._broadcast(msg, filter),
|
|
2079
2652
|
broadcastToSession: (sid, msg, filter) => this._broadcastToSession(sid, msg, filter),
|
|
2080
2653
|
broadcastSessionList: () => this._handlerCtx.transport.broadcastSessionList(),
|
|
@@ -2105,6 +2678,11 @@ export class WsServer {
|
|
|
2105
2678
|
}, 60_000)
|
|
2106
2679
|
|
|
2107
2680
|
log.info(`Server listening on ${host || '0.0.0.0'}:${this.port} (${this.serverMode} mode)`)
|
|
2681
|
+
// #6822: point the MCP OAuth redirect at this daemon's loopback callback so a
|
|
2682
|
+
// desktop-local browser auto-completes the flow; remote/tunneled browsers
|
|
2683
|
+
// that can't reach loopback fall back to the paste-code path. An operator
|
|
2684
|
+
// override (CHROXY_MCP_OAUTH_REDIRECT_URI) still wins inside the module.
|
|
2685
|
+
try { setMcpOAuthCallbackBase(`http://127.0.0.1:${this.port}`) } catch { /* best-effort */ }
|
|
2108
2686
|
}
|
|
2109
2687
|
|
|
2110
2688
|
/**
|
|
@@ -2122,6 +2700,8 @@ export class WsServer {
|
|
|
2122
2700
|
_replayHistory(ws, sessionId, opts) { replayHistory(this._historyCtx, ws, sessionId, opts) }
|
|
2123
2701
|
_flushPostAuthQueue(ws, queue) { flushPostAuthQueue(this._historyCtx, ws, queue) }
|
|
2124
2702
|
_sendSessionInfo(ws, sessionId) { sendSessionInfo(this._historyCtx, ws, sessionId) }
|
|
2703
|
+
_reseedActiveAgents(ws, sessionId) { reseedActiveAgents(this._historyCtx, ws, sessionId) }
|
|
2704
|
+
_resendPendingQuestions(ws, sessionId) { resendPendingQuestions(this._historyCtx, ws, sessionId) }
|
|
2125
2705
|
|
|
2126
2706
|
/** Route incoming client messages */
|
|
2127
2707
|
async _handleMessage(ws, msg) {
|
|
@@ -2145,6 +2725,20 @@ export class WsServer {
|
|
|
2145
2725
|
}
|
|
2146
2726
|
return
|
|
2147
2727
|
}
|
|
2728
|
+
|
|
2729
|
+
// A connection that authenticated with a stored pairing token is only as
|
|
2730
|
+
// good as that token: re-check it on every frame (an `auth` frame included)
|
|
2731
|
+
// rather than trusting the `authenticated` flag cached at connect time.
|
|
2732
|
+
// Removal events end the connection eagerly; this is the backstop for any
|
|
2733
|
+
// removal that did not announce itself, and it fails closed (no pairing
|
|
2734
|
+
// store => no credential). The cause is not known here, so the reason is
|
|
2735
|
+
// neutral.
|
|
2736
|
+
if (client.pairingCredential != null &&
|
|
2737
|
+
!this._pairingManager?.isSessionTokenLive(client.pairingCredential)) {
|
|
2738
|
+
this._endCredentialConnection(ws, client, 'invalid')
|
|
2739
|
+
return
|
|
2740
|
+
}
|
|
2741
|
+
|
|
2148
2742
|
if (msg.type === 'auth') return
|
|
2149
2743
|
|
|
2150
2744
|
// Key exchange for E2E encryption (delegates to ws-auth.js)
|
|
@@ -2184,12 +2778,24 @@ export class WsServer {
|
|
|
2184
2778
|
const { allowed, retryAfterMs } = this._rateLimiter.check(client.rateLimitKey)
|
|
2185
2779
|
if (!allowed) {
|
|
2186
2780
|
this._send(ws, { type: 'rate_limited', retryAfterMs, message: 'Too many messages. Please slow down.' })
|
|
2781
|
+
this._sendPreviewRefusal(ws, msg, 'Preview request was not admitted. Wait for the message limit to reset, then request a new preview')
|
|
2187
2782
|
return
|
|
2188
2783
|
}
|
|
2189
2784
|
}
|
|
2190
2785
|
|
|
2786
|
+
// A session-scoped connection's refused request gets its refusal whatever the
|
|
2787
|
+
// request's shape or the server's state (draining, no session manager): the
|
|
2788
|
+
// decision is not left to schema validation or to a handler. Applied before
|
|
2789
|
+
// both, so a malformed or unknown type is refused, not answered with a
|
|
2790
|
+
// schema error. (The dispatcher applies the same gate again.)
|
|
2791
|
+
if (isBoundClient(client) &&
|
|
2792
|
+
refuseBoundMessage(ws, client, msg, buildMessageCtx(this._handlerCtx, correlationId))) {
|
|
2793
|
+
return
|
|
2794
|
+
}
|
|
2795
|
+
|
|
2191
2796
|
// During drain, only allow permission_response and user_question_response
|
|
2192
2797
|
if (this._draining && msg.type !== 'permission_response' && msg.type !== 'user_question_response') {
|
|
2798
|
+
this._sendPreviewRefusal(ws, msg, 'Server is restarting; reconnect before requesting a preview')
|
|
2193
2799
|
if (msg.type === 'input') {
|
|
2194
2800
|
this._send(ws, { type: 'server_status', message: 'Server is restarting, please wait...' })
|
|
2195
2801
|
}
|
|
@@ -2202,6 +2808,7 @@ export class WsServer {
|
|
|
2202
2808
|
const details = parsed.error.issues.map(i => i.message).join(', ')
|
|
2203
2809
|
log.warn(`[${correlationId}] Invalid message from ${client.id}: ${details}`)
|
|
2204
2810
|
this._send(ws, { type: 'error', code: 'INVALID_MESSAGE', correlationId, details })
|
|
2811
|
+
this._sendPreviewRefusal(ws, msg, 'Invalid preview request; check the service port and reconnect to this session')
|
|
2205
2812
|
return
|
|
2206
2813
|
}
|
|
2207
2814
|
const validatedMsg = parsed.data
|
|
@@ -2209,7 +2816,7 @@ export class WsServer {
|
|
|
2209
2816
|
log.debug(`[${correlationId}] Handling ${validatedMsg.type} from ${client.id}`)
|
|
2210
2817
|
|
|
2211
2818
|
// Route based on server mode — pass correlationId in context
|
|
2212
|
-
const ctx =
|
|
2819
|
+
const ctx = buildMessageCtx(this._handlerCtx, correlationId)
|
|
2213
2820
|
try {
|
|
2214
2821
|
if (this.sessionManager) {
|
|
2215
2822
|
await handleSessionMessage(ws, client, validatedMsg, ctx)
|
|
@@ -2217,6 +2824,10 @@ export class WsServer {
|
|
|
2217
2824
|
await handleCliMessage(ws, client, validatedMsg, ctx)
|
|
2218
2825
|
}
|
|
2219
2826
|
} catch (err) {
|
|
2827
|
+
if (isAuthorityRevoked(err)) {
|
|
2828
|
+
log.info(`[${correlationId}] ${validatedMsg.type} from ${client.id} not started: connection no longer authorized`)
|
|
2829
|
+
return
|
|
2830
|
+
}
|
|
2220
2831
|
log.error(`[${correlationId}] Handler error for ${validatedMsg.type}: ${err.message}`)
|
|
2221
2832
|
this._send(ws, { type: 'server_error', correlationId, message: err.message, recoverable: true })
|
|
2222
2833
|
}
|
|
@@ -2246,6 +2857,41 @@ export class WsServer {
|
|
|
2246
2857
|
this._broadcaster._broadcast(message, filter)
|
|
2247
2858
|
}
|
|
2248
2859
|
|
|
2860
|
+
/**
|
|
2861
|
+
* #7601 — fast-path bridge: a chroxy-initiated environment stop/restart severs
|
|
2862
|
+
* every bound session's container binding, so surface CONTAINER_VANISHED on each
|
|
2863
|
+
* one right away. Reads `env.sessions` (the roster EnvironmentManager maintains)
|
|
2864
|
+
* and calls the session provider's idempotent `notifyContainerVanished()` — the
|
|
2865
|
+
* SAME surface the #7599 reactive paths and the #7601 poll use, so a stop the
|
|
2866
|
+
* poll also catches is deduped by the provider's latch. Does NOT inject a
|
|
2867
|
+
* SessionManager handle into EnvironmentManager, does NOT untag `env.sessions`,
|
|
2868
|
+
* and does NOT touch a session lacking the surface (feature-detected, never a
|
|
2869
|
+
* provider list — docker-byok gained the surface in #7600).
|
|
2870
|
+
*
|
|
2871
|
+
* @param {string} envId
|
|
2872
|
+
* @param {string} reason the emitting event, for the log line
|
|
2873
|
+
*/
|
|
2874
|
+
_surfaceContainerVanishedForEnvironment(envId, reason) {
|
|
2875
|
+
try {
|
|
2876
|
+
if (!envId || !this.environmentManager || !this.sessionManager) return
|
|
2877
|
+
const env = this.environmentManager.get?.(envId)
|
|
2878
|
+
if (!env || !Array.isArray(env.sessions) || env.sessions.length === 0) return
|
|
2879
|
+
// Copy the roster: notifyContainerVanished emits synchronously and a
|
|
2880
|
+
// downstream listener could mutate env.sessions mid-iteration.
|
|
2881
|
+
for (const sessionId of [...env.sessions]) {
|
|
2882
|
+
const entry = this.sessionManager.getSession?.(sessionId)
|
|
2883
|
+
const session = entry?.session
|
|
2884
|
+
if (session && typeof session.notifyContainerVanished === 'function') {
|
|
2885
|
+
if (session.notifyContainerVanished()) {
|
|
2886
|
+
log.info(`[${reason}] surfaced CONTAINER_VANISHED for session ${sessionId} in env ${envId}`)
|
|
2887
|
+
}
|
|
2888
|
+
}
|
|
2889
|
+
}
|
|
2890
|
+
} catch (err) {
|
|
2891
|
+
log.warn(`[${reason}] container-vanish fan-out failed for env ${envId}: ${err?.message || err}`)
|
|
2892
|
+
}
|
|
2893
|
+
}
|
|
2894
|
+
|
|
2249
2895
|
/**
|
|
2250
2896
|
* Broadcast a session-scoped message to clients viewing that session.
|
|
2251
2897
|
* Tags the message with `sessionId` so clients can route it to the correct
|
|
@@ -2253,6 +2899,11 @@ export class WsServer {
|
|
|
2253
2899
|
* matches — prevents cross-session info leakage and bandwidth waste.
|
|
2254
2900
|
* Pass a custom filter to override the default recipient selection when needed.
|
|
2255
2901
|
*/
|
|
2902
|
+
_sendPreviewRefusal(ws, msg, reason) {
|
|
2903
|
+
if (msg.type !== 'open_dev_preview' || typeof msg.requestId !== 'string' || !msg.requestId || msg.requestId.length > 128 || typeof msg.sessionId !== 'string' || !msg.sessionId || msg.sessionId.length > 256) return
|
|
2904
|
+
this._send(ws, { type: 'dev_preview_status', sessionId: msg.sessionId, requestId: msg.requestId, state: 'failed', reason })
|
|
2905
|
+
}
|
|
2906
|
+
|
|
2256
2907
|
_broadcastToSession(sessionId, message, filter) {
|
|
2257
2908
|
this._broadcaster._broadcastToSession(sessionId, message, filter)
|
|
2258
2909
|
}
|
|
@@ -2291,6 +2942,30 @@ export class WsServer {
|
|
|
2291
2942
|
)
|
|
2292
2943
|
}
|
|
2293
2944
|
|
|
2945
|
+
/**
|
|
2946
|
+
* #8331: push the daily-daemon update status to the clients allowed to act on
|
|
2947
|
+
* it: STRICT-PRIMARY and unbound (`isPrimaryToken === true && !boundSessionId`),
|
|
2948
|
+
* the same bar `daemon_update_action` enforces. Host-level (`!boundSessionId`)
|
|
2949
|
+
* is NOT enough: a paired phone holds an unbound pairing token, and the status
|
|
2950
|
+
* names the commits and subjects queued for the owner's machine.
|
|
2951
|
+
*/
|
|
2952
|
+
_broadcastDaemonUpdateStatus(status) {
|
|
2953
|
+
if (!status) return
|
|
2954
|
+
this._broadcast(
|
|
2955
|
+
{ type: 'daemon_update_status', ...status },
|
|
2956
|
+
(client) => client.isPrimaryToken === true && !client.boundSessionId,
|
|
2957
|
+
)
|
|
2958
|
+
}
|
|
2959
|
+
|
|
2960
|
+
// #6691: push a single orchestration run delta to host-level (unbound) clients
|
|
2961
|
+
// only — runs are host-wide cross-session objects; a session-bound token never
|
|
2962
|
+
// receives them. Called by the OrchestrationManager (E-4); the `delta`
|
|
2963
|
+
// already carries its own type/runId/seq (schemas/server/orchestration.ts).
|
|
2964
|
+
_broadcastOrchestrationDelta(delta) {
|
|
2965
|
+
if (!delta) return
|
|
2966
|
+
this._broadcast(delta, (client) => !client.boundSessionId)
|
|
2967
|
+
}
|
|
2968
|
+
|
|
2294
2969
|
/**
|
|
2295
2970
|
* #5510: deliver a terminal `pair_result` to the requester's still-open
|
|
2296
2971
|
* connection (if present) and drop the tracking entry. On approve the result
|
|
@@ -2515,8 +3190,8 @@ export class WsServer {
|
|
|
2515
3190
|
}
|
|
2516
3191
|
|
|
2517
3192
|
/** Get list of connected clients for auth_ok payload */
|
|
2518
|
-
_getConnectedClientList() {
|
|
2519
|
-
return this._clientManager.getConnectedList()
|
|
3193
|
+
_getConnectedClientList(forClient) {
|
|
3194
|
+
return this._clientManager.getConnectedList(forClient)
|
|
2520
3195
|
}
|
|
2521
3196
|
|
|
2522
3197
|
/** Broadcast client_joined to all OTHER authenticated clients */
|
|
@@ -2529,6 +3204,96 @@ export class WsServer {
|
|
|
2529
3204
|
this._broadcaster._broadcastClientLeft(departingClient)
|
|
2530
3205
|
}
|
|
2531
3206
|
|
|
3207
|
+
/**
|
|
3208
|
+
* True when the connection authenticated with the PRIMARY token (or auth is
|
|
3209
|
+
* disabled). Fails closed: any session binding, any recorded pairing
|
|
3210
|
+
* credential, or a primary flag that is not exactly `true` means "not primary".
|
|
3211
|
+
*/
|
|
3212
|
+
_holdsPrimaryCredential(client) {
|
|
3213
|
+
if (client.boundSessionId != null) return false
|
|
3214
|
+
if (client.pairingCredential != null) return false
|
|
3215
|
+
return client.isPrimaryToken === true || !this.authRequired
|
|
3216
|
+
}
|
|
3217
|
+
|
|
3218
|
+
/**
|
|
3219
|
+
* Delivery gate for the client sender. A connection whose stored credential is
|
|
3220
|
+
* no longer live (silent expiry between sweeps), or whose authentication was
|
|
3221
|
+
* stripped after it had authenticated (primary revoke), receives nothing but the
|
|
3222
|
+
* notices that explain it. Frames to a connection that never authenticated
|
|
3223
|
+
* (auth_ok / auth_fail / pairing / key exchange) are not gated here.
|
|
3224
|
+
*/
|
|
3225
|
+
_mayDeliverTo(client, message) {
|
|
3226
|
+
const type = message?.type
|
|
3227
|
+
if (type === 'credential_invalidated' || type === 'token_rotated') return true
|
|
3228
|
+
// The authentication flow itself: a connection whose authentication was
|
|
3229
|
+
// stripped may attempt to authenticate again and must be told the outcome.
|
|
3230
|
+
if (AUTH_FLOW_FRAME_TYPES.has(type)) return true
|
|
3231
|
+
if (type === 'error' && REVOKE_NOTICE_ERROR_CODES.has(message.code)) return true
|
|
3232
|
+
if (client.authTime != null && client.authenticated !== true) return false
|
|
3233
|
+
if (client.pairingCredential != null) {
|
|
3234
|
+
return !!this._pairingManager?.isSessionTokenLive(client.pairingCredential)
|
|
3235
|
+
}
|
|
3236
|
+
return true
|
|
3237
|
+
}
|
|
3238
|
+
|
|
3239
|
+
/**
|
|
3240
|
+
* True only while `client` is still authenticated AND the credential it
|
|
3241
|
+
* authenticated with is still valid. For code that resumes after an await:
|
|
3242
|
+
* the connection may have ended while it was suspended, and the handler still
|
|
3243
|
+
* holds the client record. A stored credential that has silently gone invalid
|
|
3244
|
+
* ends the connection here too, so the answer and the socket agree.
|
|
3245
|
+
*/
|
|
3246
|
+
_isConnectionAuthorized(client) {
|
|
3247
|
+
if (!client || client.authenticated !== true) return false
|
|
3248
|
+
if (client.pairingCredential != null &&
|
|
3249
|
+
!this._pairingManager?.isSessionTokenLive(client.pairingCredential)) {
|
|
3250
|
+
for (const [ws, c] of this.clients) {
|
|
3251
|
+
if (c === client) { this._endCredentialConnection(ws, client, 'invalid'); break }
|
|
3252
|
+
}
|
|
3253
|
+
return false
|
|
3254
|
+
}
|
|
3255
|
+
return true
|
|
3256
|
+
}
|
|
3257
|
+
|
|
3258
|
+
/**
|
|
3259
|
+
* End a connection whose credential is no longer valid. Departure runs first
|
|
3260
|
+
* (it reads client state), the client is removed so any frame still in flight
|
|
3261
|
+
* finds no connection to dispatch against, and the socket is closed with a
|
|
3262
|
+
* distinct code so the client re-pairs instead of retrying the dead token.
|
|
3263
|
+
*/
|
|
3264
|
+
_endCredentialConnection(ws, client, reason = 'revoked') {
|
|
3265
|
+
// A destroyed pairing manager means the daemon is shutting down, not that this
|
|
3266
|
+
// credential was revoked: end the connection quietly, with no notice (which would
|
|
3267
|
+
// make the client forget a token that is still valid) and no credential close code.
|
|
3268
|
+
if (this._pairingManager?.destroyed === true) {
|
|
3269
|
+
if (client.authenticated) this._handleClientDeparture(client)
|
|
3270
|
+
client.authenticated = false
|
|
3271
|
+
client.isPrimaryToken = false
|
|
3272
|
+
client.pairingCredential = null
|
|
3273
|
+
client.authToken = undefined
|
|
3274
|
+
if (client._keyExchangeTimeout) clearTimeout(client._keyExchangeTimeout)
|
|
3275
|
+
this._clientManager.removeClient(ws)
|
|
3276
|
+
try { ws.close(1001, 'server shutting down') } catch { /* already closing */ }
|
|
3277
|
+
return
|
|
3278
|
+
}
|
|
3279
|
+
// Tell the client WHY through the normal (possibly encrypted) channel first:
|
|
3280
|
+
// that frame is what lets it forget the credential. The close code that
|
|
3281
|
+
// follows only stops the connection.
|
|
3282
|
+
const known = reason === 'revoked' || reason === 'expired' || reason === 'evicted'
|
|
3283
|
+
if (ws.readyState === 1) {
|
|
3284
|
+
this._send(ws, { type: 'credential_invalidated', reason: known ? reason : 'invalid' })
|
|
3285
|
+
}
|
|
3286
|
+
if (client._keyExchangeTimeout) clearTimeout(client._keyExchangeTimeout)
|
|
3287
|
+
if (client.authenticated) this._handleClientDeparture(client)
|
|
3288
|
+
client.authenticated = false
|
|
3289
|
+
client.isPrimaryToken = false
|
|
3290
|
+
client.pairingCredential = null
|
|
3291
|
+
client.authToken = undefined
|
|
3292
|
+
this._clientManager.removeClient(ws)
|
|
3293
|
+
log.info(`Client ${client.id} ended: credential ${reason}`)
|
|
3294
|
+
try { ws.close(WS_CLOSE_CREDENTIAL_INVALID, `credential ${reason}`) } catch { /* already closing */ }
|
|
3295
|
+
}
|
|
3296
|
+
|
|
2532
3297
|
/**
|
|
2533
3298
|
* #5555.6 — one keepalive sweep over all authenticated clients.
|
|
2534
3299
|
*
|
|
@@ -2558,6 +3323,16 @@ export class WsServer {
|
|
|
2558
3323
|
try { ws.terminate() } catch {}
|
|
2559
3324
|
continue
|
|
2560
3325
|
}
|
|
3326
|
+
// A connected, responsive device is in use: slide its pairing token's
|
|
3327
|
+
// expiry so the connection does not outlive its token by simply idling.
|
|
3328
|
+
// A token that cannot be refreshed (expired, removed, or no pairing
|
|
3329
|
+
// store) ends the connection instead of leaving it authenticated.
|
|
3330
|
+
if (client.pairingCredential != null) {
|
|
3331
|
+
if (!this._pairingManager?.touchSessionToken(client.pairingCredential)) {
|
|
3332
|
+
this._endCredentialConnection(ws, client, 'invalid')
|
|
3333
|
+
continue
|
|
3334
|
+
}
|
|
3335
|
+
}
|
|
2561
3336
|
client.isAlive = false
|
|
2562
3337
|
try { ws.ping() } catch {}
|
|
2563
3338
|
}
|
|
@@ -2565,6 +3340,7 @@ export class WsServer {
|
|
|
2565
3340
|
|
|
2566
3341
|
/** Handle cleanup when an authenticated client disconnects or is terminated */
|
|
2567
3342
|
_handleClientDeparture(departingClient) {
|
|
3343
|
+
void this._devPreview.closeClient(departingClient.id)
|
|
2568
3344
|
// #5563: vacate primary for every session this client owned. Promotion
|
|
2569
3345
|
// policy is NOBODY-UNTIL-CLAIM — we clear the slot (broadcast null) rather
|
|
2570
3346
|
// than auto-promote an observer, so a backgrounded viewer is never silently
|
|
@@ -2753,12 +3529,33 @@ export class WsServer {
|
|
|
2753
3529
|
/** Send JSON to a single client (delegates to extracted ws-client-sender) */
|
|
2754
3530
|
_send(ws, message) {
|
|
2755
3531
|
const client = this.clients.get(ws)
|
|
3532
|
+
// The one outgoing choke point: a session-scoped connection is sent no
|
|
3533
|
+
// host-wide frame and has host-wide fields removed from the rest.
|
|
3534
|
+
if (client && isBoundClient(client)) {
|
|
3535
|
+
// A frame tagged with another session is not for this connection, on a
|
|
3536
|
+
// direct send as on a broadcast.
|
|
3537
|
+
if (message?.[CONVERSATION_FRAME] !== true && typeof message?.sessionId === 'string' && isBoundToOtherSession(client, message.sessionId)) return true
|
|
3538
|
+
const frame = frameForBoundClient(message)
|
|
3539
|
+
if (frame === null) return true
|
|
3540
|
+
message = frame
|
|
3541
|
+
}
|
|
2756
3542
|
// #5721: propagate the delivery boolean so callers gating crypto state on a
|
|
2757
3543
|
// frame reaching the wire (the eager handshake's auth_ok) can observe a
|
|
2758
3544
|
// swallowed send failure. Other callers ignore the return, unchanged.
|
|
2759
3545
|
return this._clientSend(ws, client, message)
|
|
2760
3546
|
}
|
|
2761
3547
|
|
|
3548
|
+
/**
|
|
3549
|
+
* How many hook-routed permission requests are parked on the daemon right now
|
|
3550
|
+
* (POST /permission held open for a human). Read-only; the idle-only
|
|
3551
|
+
* auto-deploy probe (GET /api/daemon/idle, #8324) reads it so http-routes
|
|
3552
|
+
* never reaches into the private map.
|
|
3553
|
+
* @returns {number}
|
|
3554
|
+
*/
|
|
3555
|
+
getHookPendingPermissionCount() {
|
|
3556
|
+
return this._pendingPermissions.size
|
|
3557
|
+
}
|
|
3558
|
+
|
|
2762
3559
|
/**
|
|
2763
3560
|
* Clear all pending permission requests across both subsystems.
|
|
2764
3561
|
*
|
|
@@ -2784,7 +3581,16 @@ export class WsServer {
|
|
|
2784
3581
|
}
|
|
2785
3582
|
|
|
2786
3583
|
/** Graceful shutdown */
|
|
3584
|
+
settleDevPreviews() {
|
|
3585
|
+
return this._devPreview.closeAll()
|
|
3586
|
+
}
|
|
3587
|
+
|
|
2787
3588
|
close() {
|
|
3589
|
+
if (this._daemonUpdate && this._daemonUpdateChangeHandler && typeof this._daemonUpdate.off === 'function') {
|
|
3590
|
+
this._daemonUpdate.off('change', this._daemonUpdateChangeHandler)
|
|
3591
|
+
this._daemonUpdateChangeHandler = null
|
|
3592
|
+
}
|
|
3593
|
+
try { this._daemonUpdate?.close?.() } catch { /* best effort */ }
|
|
2788
3594
|
// Remove PairingManager listeners to prevent post-shutdown broadcasts
|
|
2789
3595
|
if (this._pairingManager && this._pairingRefreshedHandler) {
|
|
2790
3596
|
this._pairingManager.off('pairing_refreshed', this._pairingRefreshedHandler)
|
|
@@ -2794,6 +3600,10 @@ export class WsServer {
|
|
|
2794
3600
|
this._pairingManager.off('pending_request_expired', this._pendingRequestExpiredHandler)
|
|
2795
3601
|
this._pendingRequestExpiredHandler = null
|
|
2796
3602
|
}
|
|
3603
|
+
if (this._pairingManager && this._sessionTokenRemovedHandler) {
|
|
3604
|
+
this._pairingManager.off('session_token_removed', this._sessionTokenRemovedHandler)
|
|
3605
|
+
this._sessionTokenRemovedHandler = null
|
|
3606
|
+
}
|
|
2797
3607
|
this._pairRequesters.clear()
|
|
2798
3608
|
|
|
2799
3609
|
// Remove TokenManager listener to prevent post-shutdown broadcasts
|
|
@@ -2821,6 +3631,26 @@ export class WsServer {
|
|
|
2821
3631
|
}
|
|
2822
3632
|
}
|
|
2823
3633
|
|
|
3634
|
+
// #7552: same reason as the SessionManager listeners above — the
|
|
3635
|
+
// EnvironmentManager outlives a WsServer instance, so a closed server must
|
|
3636
|
+
// not stay subscribed (and must not broadcast on a torn-down socket set).
|
|
3637
|
+
if (this.environmentManager && typeof this.environmentManager.off === 'function' &&
|
|
3638
|
+
this._environmentSessionsChangedHandler) {
|
|
3639
|
+
this.environmentManager.off('environment_sessions_changed', this._environmentSessionsChangedHandler)
|
|
3640
|
+
this._environmentSessionsChangedHandler = null
|
|
3641
|
+
}
|
|
3642
|
+
// #7601: symmetric detach of the stop/restart fast-path subscriptions.
|
|
3643
|
+
if (this.environmentManager && typeof this.environmentManager.off === 'function') {
|
|
3644
|
+
if (this._environmentStoppedHandler) {
|
|
3645
|
+
this.environmentManager.off('environment_stopped', this._environmentStoppedHandler)
|
|
3646
|
+
this._environmentStoppedHandler = null
|
|
3647
|
+
}
|
|
3648
|
+
if (this._environmentRestartedHandler) {
|
|
3649
|
+
this.environmentManager.off('environment_restarted', this._environmentRestartedHandler)
|
|
3650
|
+
this._environmentRestartedHandler = null
|
|
3651
|
+
}
|
|
3652
|
+
}
|
|
3653
|
+
|
|
2824
3654
|
if (this._pingInterval) {
|
|
2825
3655
|
clearInterval(this._pingInterval)
|
|
2826
3656
|
this._pingInterval = null
|
|
@@ -2838,9 +3668,9 @@ export class WsServer {
|
|
|
2838
3668
|
this._clientManager.clearAllPrimary()
|
|
2839
3669
|
this._normalizer.destroy()
|
|
2840
3670
|
|
|
2841
|
-
//
|
|
2842
|
-
//
|
|
2843
|
-
|
|
3671
|
+
// Socket teardown remains immediate; callers can await confirmed preview
|
|
3672
|
+
// child settlement before exiting the daemon.
|
|
3673
|
+
const previewSettlement = this._devPreview.closeAll()
|
|
2844
3674
|
|
|
2845
3675
|
// Clean up web task manager
|
|
2846
3676
|
this._webTaskManager.destroy()
|
|
@@ -2862,5 +3692,6 @@ export class WsServer {
|
|
|
2862
3692
|
this._approvalServer = null
|
|
2863
3693
|
removeShellApprovalInfo()
|
|
2864
3694
|
}
|
|
3695
|
+
return previewSettlement
|
|
2865
3696
|
}
|
|
2866
3697
|
}
|