@chroxy/server 0.11.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 +204 -18
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +166 -11
- package/package.json +16 -12
- package/sidecar/Dockerfile +1 -1
- package/sidecar/PROTOCOL.md +9 -1
- package/sidecar/agent.js +102 -10
- package/sidecar/package-lock.json +3 -3
- package/src/acp-config.js +206 -0
- package/src/acp-session.js +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 +1203 -36
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +19 -0
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +11 -5
- package/src/bound-client-policy.js +279 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +69 -5
- package/src/built-in-tools/tool-transforms.js +1113 -13
- package/src/byok-compose-state.js +6 -9
- package/src/byok-credentials.js +2 -3
- package/src/byok-mcp-client.js +92 -7
- package/src/byok-mcp-config.js +628 -121
- package/src/byok-mcp-fleet.js +49 -7
- package/src/byok-mcp-oauth-store.js +18 -16
- package/src/byok-mcp-trust.js +3 -3
- package/src/byok-session.js +650 -175
- package/src/byok-tool-executor.js +2662 -26
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +64 -46
- package/src/claude-channel-session.js +16 -10
- package/src/claude-model-catalog.js +131 -16
- package/src/claude-model-refresh.js +385 -0
- package/src/claude-model-request.js +103 -0
- package/src/claude-stream-parser.js +53 -3
- package/src/claude-tui/diagnostic-tail.js +83 -0
- package/src/claude-tui/form-driver.js +44 -7
- package/src/claude-tui/model-error.js +41 -0
- package/src/claude-tui/pty-driver.js +211 -88
- package/src/claude-tui/sanitize-question-payload.js +109 -0
- package/src/claude-tui/usage-limit.js +239 -0
- package/src/claude-tui-session.js +3513 -287
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +4 -4
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/deploy-cmd.js +45 -10
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/init-cmd.js +15 -16
- package/src/cli/providers-cmd.js +3 -3
- package/src/cli/schedule-cmd.js +68 -39
- package/src/cli/server-cmd.js +48 -1
- package/src/cli/service-cmd.js +33 -10
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +162 -11
- package/src/cli/tokens-cmd.js +4 -5
- package/src/cli/tunnel-cmd.js +255 -24
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1066 -121
- package/src/cli.js +4 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +1454 -79
- 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 +450 -27
- package/src/config-dir-migration.js +444 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +286 -26
- 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 +7 -20
- package/src/control-room/skills-inventory.js +2 -2
- 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 +23 -19
- package/src/daemon-commit.js +92 -0
- package/src/daemon-idle-state.js +171 -0
- package/src/daemon-update-status.js +314 -0
- package/src/dashboard-build.js +70 -0
- package/src/declared-status.js +90 -0
- package/src/deepseek-credentials.js +2 -3
- package/src/dev-preview.js +169 -182
- package/src/device-preferences.js +2 -2
- package/src/diff-parser.js +87 -0
- package/src/discord-credentials.js +2 -3
- package/src/docker-byok-pool.js +3 -1
- package/src/docker-byok-session.js +678 -78
- package/src/docker-image-allowlist.js +23 -1
- package/src/docker-sdk-session.js +172 -3
- package/src/docker-session.js +284 -10
- package/src/doctor.js +767 -61
- 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 +31 -10
- package/src/environments/backends/k8s.js +49 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +118 -13
- package/src/event-normalizer.js +151 -233
- package/src/gemini-session.js +81 -5
- package/src/handler-utils.js +535 -68
- package/src/handlers/checkpoint-handlers.js +39 -4
- package/src/handlers/control-room-handlers.js +51 -11
- package/src/handlers/conversation-handlers.js +469 -56
- package/src/handlers/daemon-update-handlers.js +81 -0
- package/src/handlers/evaluator-handlers.js +14 -1
- package/src/handlers/feature-handlers.js +186 -69
- package/src/handlers/file-handlers.js +57 -13
- package/src/handlers/input-handlers.js +685 -48
- package/src/handlers/orchestration-handlers.js +3 -3
- package/src/handlers/scheduler-handlers.js +88 -14
- package/src/handlers/session-handlers.js +542 -20
- package/src/handlers/session-pr-status-handlers.js +283 -0
- package/src/handlers/session-pr-threads-handlers.js +247 -0
- package/src/handlers/settings-handlers.js +330 -42
- 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/health-proof.js +40 -0
- package/src/history-page.js +104 -0
- package/src/http-routes.js +127 -8
- package/src/ide/search.js +24 -6
- package/src/ide/symbols.js +20 -6
- package/src/input-context.js +117 -0
- package/src/instruction-policy-compiler.js +229 -0
- package/src/instruction-policy.js +250 -0
- package/src/jsonl-reader.js +289 -82
- package/src/jsonl-subprocess-session.js +92 -8
- package/src/keychain.js +1 -1
- package/src/logger.js +63 -17
- 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 +12 -4
- package/src/notifications/discord-billing-sink.js +22 -5
- package/src/notifications/discord-ci-sink.js +243 -0
- package/src/notifications/discord-webhook-client.js +71 -0
- package/src/notifications/discord-webhook-sink.js +64 -23
- package/src/notifications/expo-push-sink.js +85 -6
- package/src/notifications/ready-body.js +16 -5
- package/src/ollama-session.js +34 -2
- package/src/orchestration/build-manager.js +9 -2
- package/src/orchestration/git-ops.js +41 -7
- package/src/orchestration/orchestration-manager.js +80 -33
- package/src/orchestration/permission-gate.js +13 -1
- package/src/orchestration/run-model.js +2 -1
- package/src/orchestration/turn-driver.js +44 -20
- package/src/orphan-reaper.js +413 -0
- package/src/outgoing-policy.js +183 -0
- package/src/pairing.js +92 -13
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1357 -42
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +712 -83
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolver.js +122 -8
- package/src/permission-scope.js +43 -0
- package/src/platform.js +159 -43
- 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 +207 -4
- 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/scheduled-task-store.js +318 -26
- package/src/scheduler.js +73 -3
- package/src/sdk-session.js +2060 -187
- 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 +28 -5
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +524 -38
- package/src/server-identity.js +15 -11
- package/src/service.js +396 -25
- package/src/session-archive-limits.js +15 -0
- package/src/session-archive.js +1029 -0
- package/src/session-busy-state.js +72 -0
- package/src/session-ci-watcher.js +926 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +3491 -312
- package/src/session-message-history.js +722 -16
- package/src/session-pr-status.js +654 -0
- package/src/session-pr-threads.js +271 -0
- package/src/session-preset-trust.js +3 -3
- package/src/session-preset.js +10 -5
- package/src/session-state-persistence.js +94 -17
- package/src/session-timeout-manager.js +20 -0
- package/src/session-token-store.js +17 -8
- package/src/session-wake.js +240 -0
- package/src/shell-approval-info.js +2 -2
- package/src/shell-approval-store.js +3 -1
- package/src/skills-loader.js +7 -4
- package/src/skills-manager.js +2 -2
- package/src/skills-trust.js +95 -13
- package/src/skills-usage.js +2 -3
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +23 -11
- package/src/summarize-session.js +51 -4
- package/src/supervisor.js +22 -11
- package/src/sweep-stale-provider-dirs.js +95 -0
- package/src/thinking-level-wire.js +39 -0
- package/src/thinking-stream.js +179 -0
- package/src/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +372 -25
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +34 -31
- package/src/tunnel/index.js +9 -0
- package/src/tunnel/preview.js +64 -0
- package/src/turn-outcome.js +137 -0
- package/src/usage-normalize.js +9 -5
- package/src/user-shell-session.js +59 -5
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +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 +133 -37
- package/src/utils/deploy-control-files.js +87 -0
- package/src/utils/exec-failure-reason.js +21 -0
- package/src/utils/git-repo.js +42 -0
- package/src/utils/is-entry-point.js +137 -0
- package/src/utils/node-pty-probe.js +95 -0
- package/src/utils/node-pty-support.js +118 -0
- package/src/utils/opened-file-path.js +167 -0
- package/src/utils/path-containment.js +165 -0
- package/src/utils/permission-mode-sidecar.js +51 -0
- package/src/utils/preflight.js +360 -16
- package/src/utils/read-limiter.js +217 -0
- package/src/utils/regular-file.js +375 -0
- package/src/utils/safe-regex.js +113 -0
- package/src/utils/small-file.js +129 -0
- package/src/utils/spawn-env.js +189 -4
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-provenance.js +406 -13
- package/src/web-task-manager.js +256 -16
- package/src/worktree-gc.js +7 -2
- 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 +331 -58
- package/src/ws-file-ops/common.js +320 -14
- package/src/ws-file-ops/git.js +395 -42
- package/src/ws-file-ops/index.js +2 -0
- package/src/ws-file-ops/memory.js +137 -35
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +571 -113
- package/src/ws-forwarding.js +329 -39
- package/src/ws-handler-context.js +70 -2
- package/src/ws-history.js +940 -172
- package/src/ws-message-handlers.js +17 -1
- package/src/ws-permissions.js +307 -37
- package/src/ws-schemas.js +5 -0
- package/src/ws-server.js +643 -96
- package/sidecar/node_modules/.package-lock.json +0 -29
- package/sidecar/node_modules/ws/LICENSE +0 -20
- package/sidecar/node_modules/ws/README.md +0 -548
- package/sidecar/node_modules/ws/browser.js +0 -8
- package/sidecar/node_modules/ws/index.js +0 -22
- package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
- package/sidecar/node_modules/ws/lib/constants.js +0 -19
- package/sidecar/node_modules/ws/lib/event-target.js +0 -292
- package/sidecar/node_modules/ws/lib/extension.js +0 -203
- package/sidecar/node_modules/ws/lib/limiter.js +0 -55
- package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
- package/sidecar/node_modules/ws/lib/receiver.js +0 -706
- package/sidecar/node_modules/ws/lib/sender.js +0 -602
- package/sidecar/node_modules/ws/lib/stream.js +0 -161
- package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
- package/sidecar/node_modules/ws/lib/validation.js +0 -152
- package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
- package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
- package/sidecar/node_modules/ws/package.json +0 -70
- package/sidecar/node_modules/ws/wrapper.mjs +0 -21
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
- package/src/dashboard-next/dist/index.html +0 -13
- package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
package/src/ws-server.js
CHANGED
|
@@ -5,43 +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
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'
|
|
27
29
|
import { setMcpOAuthCallbackBase } from './byok-mcp-oauth.js'
|
|
28
30
|
import { CheckpointManager } from './checkpoint-manager.js'
|
|
29
31
|
import { DevPreviewManager } from './dev-preview.js'
|
|
32
|
+
import { broadcastEnvironmentList, isBoundClient, isBoundToOtherSession, CONVERSATION_FRAME } from './environments/authority.js'
|
|
30
33
|
import { WebTaskManager } from './web-task-manager.js'
|
|
31
34
|
import { RateLimiter, getClientIp, getRateLimitKey, LOOPBACK_ADDRESSES } from './rate-limiter.js'
|
|
32
35
|
import { isUserShellApprovalRequired } from './config.js'
|
|
33
36
|
import { writeShellApprovalInfo, removeShellApprovalInfo } from './shell-approval-info.js'
|
|
34
|
-
import { createLogger, addLogListener, removeLogListener } from './logger.js'
|
|
37
|
+
import { createLogger, addLogListener, removeLogListener, loggableValue } from './logger.js'
|
|
35
38
|
import { PermissionAuditLog } from './permission-audit.js'
|
|
36
39
|
import { WsBroadcaster } from './ws-broadcaster.js'
|
|
37
40
|
import { WsClientManager } from './ws-client-manager.js'
|
|
38
|
-
import { terminalMirrorRecipient } from './handler-utils.js'
|
|
39
|
-
import {
|
|
40
|
-
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'
|
|
41
46
|
import { isLoopbackHost } from './bind-host.js'
|
|
42
47
|
import { getLanIp } from './lan-ip.js'
|
|
43
48
|
import { deriveWebhookPayloadUrl } from './github-webhook.js'
|
|
44
49
|
import { isLocalOrLanPeer } from './connection-locality.js'
|
|
50
|
+
import { configPath } from './config-dir.js'
|
|
51
|
+
import { QuestionRouteMap } from './question-route-map.js'
|
|
45
52
|
|
|
46
53
|
const __filename = fileURLToPath(import.meta.url)
|
|
47
54
|
const __dirname = dirname(__filename)
|
|
@@ -201,6 +208,20 @@ const REVOKE_ACK_TIMEOUT_MS = 10_000
|
|
|
201
208
|
// Cloudflare / mobile-OS idle timeouts open for clients that don't initiate.
|
|
202
209
|
export const KEEPALIVE_SWEEP_MS = 15_000
|
|
203
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
|
+
|
|
204
225
|
async function checkLatestVersion(packageName) {
|
|
205
226
|
const now = Date.now()
|
|
206
227
|
if (_latestVersionCache.checkedAt > 0 && (now - _latestVersionCache.checkedAt) < VERSION_CHECK_TTL) {
|
|
@@ -266,7 +287,7 @@ function _isSecureRequest(req) {
|
|
|
266
287
|
* { type: 'cancel_queued', clientMessageId, sessionId? } — cancel ONE queued send-while-busy follow-up (#5943); server emits message_dequeued(reason: 'cancelled')
|
|
267
288
|
* { type: 'set_model', model: '...' } — change model on active session
|
|
268
289
|
* { type: 'set_permission_mode', mode: '...', confirmed? } — change permission mode (confirmed: true required for 'auto')
|
|
269
|
-
* { 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)
|
|
270
291
|
* { type: 'list_sessions' } — request session list
|
|
271
292
|
* { type: 'switch_session', sessionId } — switch to a different session
|
|
272
293
|
* { type: 'create_session', name?, cwd?, provider?, agentCommId? } — create a new session
|
|
@@ -275,6 +296,7 @@ function _isSecureRequest(req) {
|
|
|
275
296
|
* { type: 'register_push_token', token } — register push token for notifications
|
|
276
297
|
* { type: 'user_question_response', answer } — respond to AskUserQuestion prompt
|
|
277
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)
|
|
278
300
|
* { type: 'browse_files', path? } — request file/directory listing for file browser
|
|
279
301
|
* { type: 'read_file', path } — request file content for file viewer
|
|
280
302
|
* { type: 'write_file', path, content } — write file content (path validated, 5MB limit)
|
|
@@ -325,15 +347,16 @@ function _isSecureRequest(req) {
|
|
|
325
347
|
* { type: 'terminal_unsubscribe', sessionId } — #5835 opt OUT of a session's live PTY mirror
|
|
326
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
|
|
327
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)
|
|
328
|
-
* { 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)
|
|
329
351
|
* { type: 'set_permission_rules', rules, sessionId } — set per-session auto-approval rules
|
|
330
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)
|
|
331
353
|
* { type: 'submit_mcp_auth_code', server, code, sessionId?, requestId? } — #6822 submit a pasted OAuth authorization code for a remote MCP server (BYOK lane)
|
|
332
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)
|
|
333
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)
|
|
334
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)
|
|
335
|
-
* { type: 'scheduled_task_action', action, taskId?, task?, requestId? } — #6871 create/update/pause/resume/delete a scheduled task (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)
|
|
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)
|
|
336
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
|
|
337
360
|
* { type: 'set_prompt_evaluator', value: boolean, sessionId? } — toggle the per-session promptEvaluator (#3185)
|
|
338
361
|
* { type: 'set_prompt_evaluator_skip_pattern', value: string|null, sessionId? } — set the per-session evaluator skip-pattern source (#3639)
|
|
339
362
|
* { type: 'set_chroxy_context_hint', value: boolean, sessionId? } — toggle the per-session Chroxy context hint (#3805)
|
|
@@ -345,53 +368,77 @@ function _isSecureRequest(req) {
|
|
|
345
368
|
* { type: 'extension_message', ... } — opaque extension payload (passthrough, no server handling)
|
|
346
369
|
* { type: 'create_environment', name, cwd, image?, ... } — create persistent container environment
|
|
347
370
|
* { type: 'list_environments' } — list all persistent environments
|
|
348
|
-
* { 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
|
|
349
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)
|
|
350
381
|
*
|
|
351
382
|
* Server -> Client:
|
|
352
383
|
* All session-scoped messages include a `sessionId` field for background sync.
|
|
353
|
-
*
|
|
354
|
-
*
|
|
355
|
-
*
|
|
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
|
|
356
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
|
|
357
394
|
* { type: 'auth_fail', reason: '...' } — auth failed
|
|
358
395
|
* { type: 'server_mode', mode: 'cli' } — which backend mode is active
|
|
359
|
-
* { type: 'message',
|
|
360
|
-
* { type: '
|
|
361
|
-
* { type: '
|
|
362
|
-
* { 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
|
|
363
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
|
|
364
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
|
|
365
|
-
* { 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)
|
|
366
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
|
|
367
|
-
* { type: 'tool_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)
|
|
368
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)
|
|
369
|
-
* { type: 'result',
|
|
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
|
|
370
408
|
* { type: 'status', connected: true } — connection status
|
|
371
|
-
* { type: 'claude_ready' } — Claude Code ready for input
|
|
409
|
+
* { type: 'claude_ready', backgroundTasks?, scheduledWakeup? } — Claude Code ready for input
|
|
372
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
|
|
373
412
|
* { type: 'available_models', models: [...], provider?, defaultModel? } — models the active provider accepts
|
|
374
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).
|
|
375
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.
|
|
376
|
-
* { type: 'permission_request', requestId, tool, description, input, remainingMs } — permission prompt
|
|
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)
|
|
377
417
|
* { type: 'confirm_permission_mode', mode, warning } — server challenges auto mode (client must re-send with confirmed: true)
|
|
378
418
|
* { type: 'permission_mode_changed', mode: '...' } — permission mode updated
|
|
379
|
-
* { 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
|
|
380
420
|
* { type: 'session_list', sessions: [...] } — all sessions
|
|
381
|
-
* { 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.
|
|
382
|
-
* { 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.
|
|
383
422
|
* { type: 'session_destroyed', sessionId } — session removed
|
|
384
|
-
* { 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
|
|
385
|
-
* { 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? }
|
|
386
425
|
* — session in persisted state could not be restored (e.g. missing env var); history kept on disk for retry
|
|
387
426
|
* { type: 'session_persist_failed', sessionId, name|null }
|
|
388
427
|
* — a session-list mutation (create/rename/destroy) could not be flushed to disk and will be lost on restart (#5714).
|
|
389
428
|
* `name` is null on the destroy path where the entry was already removed before the flush.
|
|
390
|
-
* { type: '
|
|
391
|
-
* { type: '
|
|
392
|
-
* { 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
|
|
393
440
|
* { type: 'conversation_id', sessionId, conversationId } — SDK conversation ID for session portability
|
|
394
|
-
* { type: 'user_question', toolUseId, questions } — AskUserQuestion prompt from Claude
|
|
441
|
+
* { type: 'user_question', toolUseId, questions, historySeq?, interrupted?, superseded? } — AskUserQuestion prompt from Claude
|
|
395
442
|
* { type: 'agent_busy' } — agent started processing (per-session)
|
|
396
443
|
* { type: 'agent_idle' } — agent finished processing (per-session)
|
|
397
444
|
* { type: 'plan_started' } — Claude entered plan mode (transient)
|
|
@@ -399,11 +446,12 @@ function _isSecureRequest(req) {
|
|
|
399
446
|
* { type: 'inactivity_warning', messageId, idleMs, prefab } — soft check-in prompt, session stays alive (#3899)
|
|
400
447
|
* { type: 'multi_question_intervention', toolUseId, questionCount, reason, timestamp } — chroxy permission-hook denied a multi-question AskUserQuestion (#4653)
|
|
401
448
|
* { type: 'server_shutdown', reason, restartEtaMs } — server shutting down (reason: 'restart'|'shutdown')
|
|
402
|
-
* { type: 'server_status', message } — non-error status update (e.g., recovery)
|
|
403
|
-
* { type: 'server_error', category
|
|
404
|
-
* { 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)
|
|
405
453
|
* { type: 'file_listing', path, parentPath, entries, error } — file browser listing response
|
|
406
|
-
* { 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
|
|
407
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)
|
|
408
456
|
* { type: 'symbol_location', symbol, file, line, error } — #6475 go-to-definition result (opt-in IDE, features.ide; dashboard-only v1)
|
|
409
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)
|
|
@@ -418,14 +466,17 @@ function _isSecureRequest(req) {
|
|
|
418
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)
|
|
419
467
|
* { type: 'primary_changed', sessionId, clientId } — last-writer-wins primary changed (null on disconnect)
|
|
420
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)
|
|
421
|
-
* { type: 'pong' } — heartbeat response
|
|
469
|
+
* { type: 'pong', serverTs? } — heartbeat response
|
|
422
470
|
* { type: 'permission_expired', requestId, sessionId, message } — permission response could not be routed (expired/handled)
|
|
423
|
-
* { 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.
|
|
424
474
|
* { type: 'session_warning', sessionId, name, reason, message, remainingMs } — session about to timeout
|
|
425
475
|
* { type: 'session_timeout', sessionId, name, idleMs } — session destroyed due to idle timeout
|
|
426
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)
|
|
427
|
-
* { type: 'dev_preview', port, url, sessionId }
|
|
477
|
+
* { type: 'dev_preview', port, url, target?, exposure?, sessionId } — approved HTTP preview opened
|
|
428
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
|
|
429
480
|
* { type: 'web_task_created', task } — cloud task launched
|
|
430
481
|
* { type: 'web_task_updated', task } — cloud task status changed
|
|
431
482
|
* { type: 'web_task_error', taskId?, message, code?, boundSessionId?, boundSessionName? } — cloud task error
|
|
@@ -434,37 +485,39 @@ function _isSecureRequest(req) {
|
|
|
434
485
|
* are populated on SESSION_TOKEN_MISMATCH only;
|
|
435
486
|
* see docs/error-taxonomy.md)
|
|
436
487
|
* { type: 'web_task_list', tasks } — response to list_web_tasks
|
|
437
|
-
* { type: 'diff_result',
|
|
438
|
-
* { type: 'error', message }
|
|
439
|
-
* { type: 'file_list',
|
|
440
|
-
*
|
|
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
|
|
441
494
|
* { type: 'git_commit_result', hash, message, error } — git commit result
|
|
442
|
-
* { type: 'git_create_pr_result', url, number, branch, base, error } — in-app PR creation result (#6876; dashboard-only v1)
|
|
495
|
+
* { type: 'git_create_pr_result', url, number, branch, base, error, existingUrl? } — in-app PR creation result (#6876; dashboard-only v1)
|
|
443
496
|
* { type: 'git_stage_result', error } — git stage result
|
|
444
|
-
* { type: 'git_status_result',
|
|
497
|
+
* { type: 'git_status_result', branch, staged, unstaged, untracked, error } — git status result
|
|
445
498
|
* { type: 'git_unstage_result', error } — git unstage result
|
|
446
499
|
* { type: 'write_file_result', path, error } — write file result
|
|
447
|
-
* { type: 'append_memory_result', path, created, error
|
|
448
|
-
* { type: 'memory_stack_result', entries, memoryFile, error
|
|
449
|
-
* { type: 'log_entry', level, message, timestamp } — server log entry for dashboard
|
|
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
|
|
450
503
|
* { type: 'session_activity', sessionId, isBusy, lastCost } — session busy/idle state change
|
|
451
|
-
* { type: 'session_context', sessionId,
|
|
504
|
+
* { type: 'session_context', sessionId, gitBranch, gitDirty, gitAhead, projectName } — session context data
|
|
452
505
|
* { type: 'session_updated', sessionId, name } — session metadata updated
|
|
453
|
-
* { type: 'discovered_sessions', sessions } — discovered local Claude sessions
|
|
454
506
|
* { type: 'pair_fail', reason } — pairing failed
|
|
455
507
|
* { type: 'pairing_refreshed' } — pairing ID consumed; clients should re-fetch /qr (#2916)
|
|
456
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.
|
|
457
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.
|
|
458
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.
|
|
459
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.
|
|
460
|
-
* { type: 'rate_limited', message } — client rate-limited
|
|
461
|
-
* { type: 'agent_spawned', sessionId, agentId, parentToolId, model
|
|
462
|
-
* { 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.
|
|
463
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`)
|
|
464
|
-
* { type: 'background_work_changed', sessionId, pending } — pending background shells snapshot changed (#4307, transient; `pending: [{ shellId, command, startedAt }, …]`)
|
|
465
|
-
* { 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.
|
|
466
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? }, …]`)
|
|
467
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
|
|
468
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`)
|
|
469
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`))
|
|
470
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.
|
|
@@ -479,21 +532,24 @@ function _isSecureRequest(req) {
|
|
|
479
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.
|
|
480
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.
|
|
481
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.
|
|
482
|
-
* { 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.
|
|
483
|
-
* { 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.
|
|
484
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.
|
|
485
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.
|
|
486
|
-
* { 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.
|
|
487
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.
|
|
488
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.
|
|
489
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.
|
|
490
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`.
|
|
491
|
-
* { 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.
|
|
492
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.
|
|
493
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).
|
|
494
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.
|
|
495
|
-
* { type: 'provider_list', providers } — available providers
|
|
496
|
-
* { 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)
|
|
497
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
|
|
498
554
|
* { type: 'credential_test_result', requestId?, key, ok, error?, model?, latencyMs? } — result of a test_credential ping (#3855)
|
|
499
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`
|
|
@@ -507,19 +563,21 @@ function _isSecureRequest(req) {
|
|
|
507
563
|
* { type: 'skill_trust_grant_ok', requestId, sessionId, skillName, author } — ack for skill_trust_grant handler (#3297)
|
|
508
564
|
* { type: 'push_token_error', message } — push token registration error
|
|
509
565
|
* { type: 'cost_update', sessionId, sessionCost, totalCost, budget } — session cost update (budget-oriented; sessionId injected by _broadcastToSession)
|
|
510
|
-
* { 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)
|
|
511
567
|
* { type: 'session_cost_threshold_crossed', sessionId, costUsd, thresholdUsd } — soft "you've spent $X" warning; fires ONCE per session when cumulativeUsage.costUsd >= threshold (#4075)
|
|
512
|
-
* { type: 'budget_warning', sessionId, message,
|
|
513
|
-
* { type: 'budget_exceeded', sessionId, message,
|
|
514
|
-
* { type: '
|
|
515
|
-
* { type: '
|
|
516
|
-
* { type: '
|
|
517
|
-
* { 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)
|
|
518
576
|
* { type: 'environment_created', environmentId, name, status } — environment created
|
|
519
577
|
* { type: 'environment_list', environments: [...] } — list of all environments
|
|
520
578
|
* { type: 'environment_destroyed', environmentId } — environment destroyed
|
|
521
579
|
* { type: 'environment_info', environment: {...} } — single environment details
|
|
522
|
-
* { 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
|
|
523
581
|
* { type: 'evaluate_draft_result', requestId, verdict?, rewritten?, clarification?, reasoning?, error? } — prompt evaluator response (#3068)
|
|
524
582
|
* { type: 'prompt_evaluator_changed', sessionId, value: boolean } — per-session promptEvaluator toggle changed (#3185)
|
|
525
583
|
* { type: 'prompt_evaluator_skip_pattern_changed', sessionId, value: string|null } — per-session evaluator skip pattern changed (#3639)
|
|
@@ -531,7 +589,10 @@ function _isSecureRequest(req) {
|
|
|
531
589
|
* { type: 'orchestration_runs_snapshot', requestId?, generatedAt, runs: [RunSummary], error? } — orchestration runs-list survey (#6691, dashboard-only v1)
|
|
532
590
|
* { type: 'orchestration_run_snapshot', requestId?, generatedAt, seq, run: RunDetail|null, error? } — one run's full detail (pull-only; run:null = degraded reply) (#6691)
|
|
533
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)
|
|
534
|
-
* { type: 'scheduled_tasks', generatedAt, scheduler: { enabled, engineArmed, restartRequired, source }, schedulableProviders, defaultProvider, defaultProviderRefusal, tasks[], 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
|
|
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)
|
|
535
596
|
* { type: 'orchestration_action_ack', requestId?, action, runId, gateId? } — terminal success echo for a mutating orchestration action (#6691)
|
|
536
597
|
*
|
|
537
598
|
* Encrypted envelope (bidirectional, wraps any message above after key exchange):
|
|
@@ -574,7 +635,7 @@ function _isSecureRequest(req) {
|
|
|
574
635
|
* - A session operation failed in an expected, user-facing way → `session_error`
|
|
575
636
|
*/
|
|
576
637
|
export class WsServer {
|
|
577
|
-
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, 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 } = {}) {
|
|
578
639
|
this.port = port
|
|
579
640
|
this.apiToken = apiToken
|
|
580
641
|
this._tokenManager = tokenManager || null
|
|
@@ -643,13 +704,13 @@ export class WsServer {
|
|
|
643
704
|
? pagesRateLimiter
|
|
644
705
|
: new RateLimiter({ name: 'pages', windowMs: 60_000, maxMessages: 120, burst: 30 })
|
|
645
706
|
this.pagesStore = pagesStore || new PagesStore({
|
|
646
|
-
pagesDir:
|
|
707
|
+
pagesDir: configPath('pages'),
|
|
647
708
|
})
|
|
648
709
|
// #6277: host-local user-shell approval store. The create gate holds a spawn
|
|
649
710
|
// here when userShell.requireApproval is on; the host operator approves it
|
|
650
711
|
// out-of-band via the loopback /api/shell routes (or `chroxy shell approve`).
|
|
651
712
|
this._shellApprovalStore = new ShellApprovalStore()
|
|
652
|
-
this._clientSend = createClientSender(log)
|
|
713
|
+
this._clientSend = createClientSender(log, { mayDeliver: (client, message) => this._mayDeliverTo(client, message) })
|
|
653
714
|
// audit P1-2: when a client's active session changes, re-sync the live
|
|
654
715
|
// terminal mirror gate for BOTH the session it left and the one it joined.
|
|
655
716
|
// Without this a client opted into session A's terminal that switches to B
|
|
@@ -730,6 +791,15 @@ export class WsServer {
|
|
|
730
791
|
// would never fire in production. Cleaned up by `_sessionDestroyedHandler`
|
|
731
792
|
// so a long-running server doesn't leak entries for destroyed sessions.
|
|
732
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>
|
|
733
803
|
this._permissionSessionMap = new Map() // requestId -> sessionId (for routing responses to correct session)
|
|
734
804
|
// #5704: refcount of permission-INDUCED session subscriptions, per client.
|
|
735
805
|
// clientId -> Map<sessionId, refcount>. _registerPermissionRoute increments
|
|
@@ -746,7 +816,7 @@ export class WsServer {
|
|
|
746
816
|
this._permissionSubs = new Map() // clientId -> Map<sessionId, refcount>
|
|
747
817
|
this._hookSecrets = new Set() // per-session hook secrets registered by active CliSessions
|
|
748
818
|
this._sessionHookSecrets = new Map() // sessionId -> hookSecret (for cleanup on session_destroyed)
|
|
749
|
-
this._questionSessionMap = new
|
|
819
|
+
this._questionSessionMap = new QuestionRouteMap() // toolUseId -> sessionId (for routing question responses; remembers just-removed routes, #8470)
|
|
750
820
|
// #5563: primary-ownership now lives on the WsClientManager (sessionId →
|
|
751
821
|
// primary clientId) with explicit claim/observe/hand-off semantics, not a
|
|
752
822
|
// last-writer-wins map. `primaryClients` is no longer a server-owned Map;
|
|
@@ -777,8 +847,12 @@ export class WsServer {
|
|
|
777
847
|
this._permissions = createPermissionHandler({
|
|
778
848
|
sendFn,
|
|
779
849
|
broadcastFn,
|
|
780
|
-
|
|
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 }),
|
|
781
853
|
validateHookAuth: (req, res) => self._validateHookAuth(req, res),
|
|
854
|
+
captureBearer: (req) => captureBearer(self, req),
|
|
855
|
+
bearerStillValid: (captured) => bearerStillValid(self, captured),
|
|
782
856
|
pushManager,
|
|
783
857
|
pendingPermissions: this._pendingPermissions,
|
|
784
858
|
permissionSessionMap: this._permissionSessionMap,
|
|
@@ -845,6 +919,7 @@ export class WsServer {
|
|
|
845
919
|
self._adoptPermissionSubscription(client.id, sid)
|
|
846
920
|
self._clientManager.unsubscribe(client, sid)
|
|
847
921
|
},
|
|
922
|
+
isConnectionAuthorized: (client) => self._isConnectionAuthorized(client),
|
|
848
923
|
setActiveSession: (client, sid) => self._clientManager.setActiveSession(client, sid),
|
|
849
924
|
// #5563: explicit primary-ownership surface. `updatePrimary` is the
|
|
850
925
|
// first-input adoption path (claims if unclaimed, no-op if already
|
|
@@ -863,6 +938,18 @@ export class WsServer {
|
|
|
863
938
|
syncTerminalMirror: (sid) => self._syncTerminalMirror(sid),
|
|
864
939
|
sendSessionInfo: (ws, sid) => self._sendSessionInfo(ws, sid),
|
|
865
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),
|
|
866
953
|
get clients() { return self.clients },
|
|
867
954
|
},
|
|
868
955
|
sessions: {
|
|
@@ -938,16 +1025,28 @@ export class WsServer {
|
|
|
938
1025
|
// default) — the handlers report that as "not armed" rather than hiding
|
|
939
1026
|
// it. Late-bound so it tracks the server instance.
|
|
940
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 },
|
|
941
1035
|
},
|
|
942
1036
|
runtime: {
|
|
943
1037
|
get draining() { return self._draining },
|
|
944
1038
|
// Multi-provider data dirs (#2965): computed fresh each access so new
|
|
945
1039
|
// provider registrations are reflected without restarting the server.
|
|
946
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() },
|
|
947
1044
|
get userAgentsDirs() { return getProviderDataDirs().map(d => join(d, 'agents')) },
|
|
948
1045
|
// #3637: stable per-session auto-evaluator iteration counter (#3186).
|
|
949
1046
|
// See WsServer constructor for the lifecycle rationale.
|
|
950
1047
|
evaluatorIterations: this._evaluatorIterations,
|
|
1048
|
+
pendingEvaluatorAwaits: this._pendingEvaluatorAwaits,
|
|
1049
|
+
inputDedupRecords: this._inputDedupRecords,
|
|
951
1050
|
},
|
|
952
1051
|
}
|
|
953
1052
|
// Fail loudly if the production ctx ever drifts from the declared shape.
|
|
@@ -976,6 +1075,9 @@ export class WsServer {
|
|
|
976
1075
|
get serverMode() { return self.serverMode },
|
|
977
1076
|
serverVersion: SERVER_VERSION,
|
|
978
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() },
|
|
979
1081
|
get gitInfo() { return self._gitInfo },
|
|
980
1082
|
get encryptionEnabled() { return self._encryptionEnabled },
|
|
981
1083
|
// #5536 — identity keypair for signing the eager exchange public key.
|
|
@@ -991,9 +1093,10 @@ export class WsServer {
|
|
|
991
1093
|
protocolVersion: SERVER_PROTOCOL_VERSION,
|
|
992
1094
|
minProtocolVersion: MIN_PROTOCOL_VERSION,
|
|
993
1095
|
get webTaskManager() { return self._webTaskManager },
|
|
1096
|
+
get agentConnections() { return self.config?.agentConnections ?? [] },
|
|
994
1097
|
send: sendFn,
|
|
995
1098
|
broadcast: broadcastFn,
|
|
996
|
-
getConnectedClientList: () => self._getConnectedClientList(),
|
|
1099
|
+
getConnectedClientList: (forClient) => self._getConnectedClientList(forClient),
|
|
997
1100
|
get permissions() { return self._permissions },
|
|
998
1101
|
// #3760: effective inactivity timeout, surfaced in auth_ok so clients
|
|
999
1102
|
// render their ActivityIndicator timeout warning against the real
|
|
@@ -1018,6 +1121,13 @@ export class WsServer {
|
|
|
1018
1121
|
// `ide` capability so clients gate IDE UI. Late-bound getter so a test
|
|
1019
1122
|
// mutating self.config is seen.
|
|
1020
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 },
|
|
1021
1131
|
// #6691: whether the orchestration harness is enabled on THIS server,
|
|
1022
1132
|
// surfaced as the `orchestration` capability so the dashboard reveals the
|
|
1023
1133
|
// Runs surface. Server-wide gate, not token-scoped; fail-closed.
|
|
@@ -1038,6 +1148,8 @@ export class WsServer {
|
|
|
1038
1148
|
// surfaced in auth_ok so the dashboard can render a warning banner.
|
|
1039
1149
|
// null until start() has bound a socket.
|
|
1040
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 },
|
|
1041
1153
|
// #5821: current billing-canary snapshot, seeded into auth_ok so a
|
|
1042
1154
|
// freshly-connected client renders the billing banner immediately. null
|
|
1043
1155
|
// until a provider is wired (server-cli sets it post-construct) — live
|
|
@@ -1052,6 +1164,23 @@ export class WsServer {
|
|
|
1052
1164
|
// letting the client skip its 3-request connect-time round trip.
|
|
1053
1165
|
get fileOps() { return self._fileOps },
|
|
1054
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 },
|
|
1055
1184
|
// #5555 (sub-item 7): the current public tunnel URL (wss://), folded into
|
|
1056
1185
|
// the auth_bootstrap burst so a reconnecting client always re-learns the
|
|
1057
1186
|
// live URL — the durable recovery path when a quick-tunnel rotation
|
|
@@ -1118,12 +1247,83 @@ export class WsServer {
|
|
|
1118
1247
|
// Multi-session support: prefer sessionManager, fall back to single cliSession
|
|
1119
1248
|
this.sessionManager = sessionManager || null
|
|
1120
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
|
+
}
|
|
1121
1307
|
// #6691 (E-4): the OrchestrationManager (null when the feature is off). Its
|
|
1122
1308
|
// run_delta events are forwarded to host-level clients by server-cli via
|
|
1123
1309
|
// _broadcastOrchestrationDelta; the handlers read it off ctx.services.
|
|
1124
1310
|
this._orchestrationManager = orchestrationManager || null
|
|
1125
1311
|
// #6871: nullable by design — null whenever scheduled execution is disabled.
|
|
1126
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
|
+
}
|
|
1127
1327
|
this.defaultSessionId = defaultSessionId || null
|
|
1128
1328
|
this._checkpointManager = new CheckpointManager()
|
|
1129
1329
|
|
|
@@ -1179,6 +1379,16 @@ export class WsServer {
|
|
|
1179
1379
|
// but a long-running server with many session destroys would
|
|
1180
1380
|
// accumulate dead entries.
|
|
1181
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.
|
|
1182
1392
|
}
|
|
1183
1393
|
// #3057: audit auto-deny resolution paths (timeout / aborted / cleared).
|
|
1184
1394
|
// The WS inline response path in settings-handlers.js audits user
|
|
@@ -1234,10 +1444,14 @@ export class WsServer {
|
|
|
1234
1444
|
}
|
|
1235
1445
|
|
|
1236
1446
|
// Dev server preview tunneling
|
|
1237
|
-
this._devPreview = new DevPreviewManager()
|
|
1447
|
+
this._devPreview = new DevPreviewManager({ daemonPort: port, authRequired, getSession: id => this.sessionManager?.getSession(id),
|
|
1448
|
+
tunnelConfig: { binaryProvenance: this.sessionManager?._binaryProvenanceOptions?.() } })
|
|
1238
1449
|
|
|
1239
|
-
// Web task manager (Claude Code Web cloud delegation)
|
|
1240
|
-
|
|
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 })
|
|
1241
1455
|
|
|
1242
1456
|
// Legacy single-session mode: wrap cliSession in a minimal shim
|
|
1243
1457
|
if (!sessionManager && cliSession) {
|
|
@@ -1278,8 +1492,15 @@ export class WsServer {
|
|
|
1278
1492
|
this._draining = false
|
|
1279
1493
|
this._latestVersion = null
|
|
1280
1494
|
|
|
1281
|
-
// Background version check (non-blocking, skipped in test/CI)
|
|
1282
|
-
|
|
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') {
|
|
1283
1504
|
checkLatestVersion(packageJson.name).then((v) => { this._latestVersion = v }).catch((err) => {
|
|
1284
1505
|
log.warn(`Failed to check latest npm version: ${err.message} (non-critical, update check skipped)`)
|
|
1285
1506
|
})
|
|
@@ -1289,6 +1510,7 @@ export class WsServer {
|
|
|
1289
1510
|
// authenticated dashboard clients so they can auto-refresh the QR code (#2916).
|
|
1290
1511
|
this._pairingRefreshedHandler = null
|
|
1291
1512
|
this._pendingRequestExpiredHandler = null
|
|
1513
|
+
this._sessionTokenRemovedHandler = null
|
|
1292
1514
|
if (this._pairingManager) {
|
|
1293
1515
|
this._pairingRefreshedHandler = () => {
|
|
1294
1516
|
this._broadcast({ type: 'pairing_refreshed' })
|
|
@@ -1304,6 +1526,20 @@ export class WsServer {
|
|
|
1304
1526
|
this._broadcastPairResolved(requestId, 'expired')
|
|
1305
1527
|
}
|
|
1306
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)
|
|
1307
1543
|
}
|
|
1308
1544
|
|
|
1309
1545
|
// Wire TokenManager rotation events — broadcast new token to all clients
|
|
@@ -1499,9 +1735,15 @@ export class WsServer {
|
|
|
1499
1735
|
// Send the new token to encrypted clients (they need it for reconnection).
|
|
1500
1736
|
// Unencrypted clients (e.g. localhost dashboard) get the event without the
|
|
1501
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.
|
|
1502
1743
|
let encrypted = 0, unencrypted = 0
|
|
1503
1744
|
for (const [ws, client] of this.clients) {
|
|
1504
1745
|
if (!client.authenticated || ws.readyState !== 1) continue
|
|
1746
|
+
if (!this._holdsPrimaryCredential(client)) continue
|
|
1505
1747
|
// Carry `reason: 'scheduled'` so the wire is self-describing and
|
|
1506
1748
|
// matches the documented contract + TokenManager's event payload.
|
|
1507
1749
|
if (client.encryptionState) {
|
|
@@ -1513,7 +1755,9 @@ export class WsServer {
|
|
|
1513
1755
|
// and de-auths instead, so a compromised connection can't gain
|
|
1514
1756
|
// currency this way. Unencrypted clients get no token, so theirs
|
|
1515
1757
|
// stays stale (they must reconnect) — handled by the else branch.
|
|
1516
|
-
|
|
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
|
|
1517
1761
|
encrypted++
|
|
1518
1762
|
} else {
|
|
1519
1763
|
this._send(ws, { type: 'token_rotated', expiresAt, reason: 'scheduled' })
|
|
@@ -1555,7 +1799,7 @@ export class WsServer {
|
|
|
1555
1799
|
}
|
|
1556
1800
|
const queryToken = dashUrl.searchParams.get('token')
|
|
1557
1801
|
const token = queryToken || bearerToken || cookieVal
|
|
1558
|
-
if (!token || !this._isTokenValid(token)) {
|
|
1802
|
+
if (!token || !this._isTokenValid(token) || this._isSessionScopedToken(token)) {
|
|
1559
1803
|
res.writeHead(403, { 'Content-Type': 'text/html', ...securityHeaders })
|
|
1560
1804
|
res.end('<h1>403 Forbidden</h1><p>Invalid or missing token.</p>')
|
|
1561
1805
|
return false
|
|
@@ -1571,11 +1815,30 @@ export class WsServer {
|
|
|
1571
1815
|
return true
|
|
1572
1816
|
}
|
|
1573
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
|
+
|
|
1574
1832
|
/**
|
|
1575
1833
|
* Validate Bearer token on an HTTP request. Returns true if auth passes
|
|
1576
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.
|
|
1577
1840
|
*/
|
|
1578
|
-
_validateBearerAuth(req, res) {
|
|
1841
|
+
_validateBearerAuth(req, res, { allowScoped = false } = {}) {
|
|
1579
1842
|
if (!this.authRequired) return true
|
|
1580
1843
|
const authHeader = req.headers['authorization'] || ''
|
|
1581
1844
|
const token = authHeader.startsWith('Bearer ') ? authHeader.slice(7) : null
|
|
@@ -1584,6 +1847,11 @@ export class WsServer {
|
|
|
1584
1847
|
res.end(JSON.stringify({ error: 'unauthorized' }))
|
|
1585
1848
|
return false
|
|
1586
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
|
+
}
|
|
1587
1855
|
return true
|
|
1588
1856
|
}
|
|
1589
1857
|
|
|
@@ -1642,6 +1910,7 @@ export class WsServer {
|
|
|
1642
1910
|
tokenClass: entry.tokenClass || 'primary',
|
|
1643
1911
|
deviceName: entry.deviceName,
|
|
1644
1912
|
clientId: entry.clientId,
|
|
1913
|
+
requestId: entry.requestId || undefined,
|
|
1645
1914
|
})
|
|
1646
1915
|
}
|
|
1647
1916
|
|
|
@@ -1657,6 +1926,7 @@ export class WsServer {
|
|
|
1657
1926
|
type: 'session_error',
|
|
1658
1927
|
code: 'SHELL_APPROVAL_DENIED',
|
|
1659
1928
|
message: 'The host operator declined this shell.',
|
|
1929
|
+
...(entry.requestId ? { requestId: entry.requestId } : {}),
|
|
1660
1930
|
})
|
|
1661
1931
|
break
|
|
1662
1932
|
}
|
|
@@ -1778,7 +2048,7 @@ export class WsServer {
|
|
|
1778
2048
|
}
|
|
1779
2049
|
// No hook secrets registered — fall back to main token validation
|
|
1780
2050
|
// (handles legacy single-session setups and tests that don't register secrets)
|
|
1781
|
-
if (!this._isTokenValid(token)) {
|
|
2051
|
+
if (!this._isTokenValid(token) || this._isSessionScopedToken(token)) {
|
|
1782
2052
|
res.writeHead(403, { 'Content-Type': 'application/json' })
|
|
1783
2053
|
res.end(JSON.stringify({ error: 'unauthorized' }))
|
|
1784
2054
|
return false
|
|
@@ -2104,6 +2374,7 @@ export class WsServer {
|
|
|
2104
2374
|
// a still-alive but invisible WS connection.
|
|
2105
2375
|
visible: true,
|
|
2106
2376
|
_seq: 0, // monotonic sequence number for outbound messages
|
|
2377
|
+
pairingCredential: null, // stored pairing token this connection authenticated with (null = primary / none)
|
|
2107
2378
|
encryptionState: null, // { sharedKey, sendNonce, recvNonce } when active
|
|
2108
2379
|
encryptionPending: false, // true while waiting for key_exchange
|
|
2109
2380
|
postAuthQueue: null, // queued messages during key exchange
|
|
@@ -2153,6 +2424,9 @@ export class WsServer {
|
|
|
2153
2424
|
: null
|
|
2154
2425
|
|
|
2155
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
|
|
2156
2430
|
let msg
|
|
2157
2431
|
try {
|
|
2158
2432
|
msg = JSON.parse(raw.toString())
|
|
@@ -2195,7 +2469,7 @@ export class WsServer {
|
|
|
2195
2469
|
if (client) client.isAlive = true
|
|
2196
2470
|
if (client?.encryptionState) {
|
|
2197
2471
|
if (msg.type !== 'encrypted') {
|
|
2198
|
-
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`)
|
|
2199
2473
|
ws.close(1008, 'encryption required')
|
|
2200
2474
|
return
|
|
2201
2475
|
}
|
|
@@ -2270,19 +2544,33 @@ export class WsServer {
|
|
|
2270
2544
|
this._startApprovalListener()
|
|
2271
2545
|
}
|
|
2272
2546
|
|
|
2273
|
-
// 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.
|
|
2274
2555
|
this._webTaskManager.detectFeatures().then(({ remote, teleport }) => {
|
|
2275
2556
|
if (remote || teleport) {
|
|
2276
2557
|
log.info(`Claude Code Web features detected: remote=${remote}, teleport=${teleport}`)
|
|
2277
2558
|
}
|
|
2278
2559
|
}).catch((err) => {
|
|
2279
|
-
log.warn(`
|
|
2560
|
+
log.warn(`Claude Code Web feature detection failed: ${err?.message || err} (non-critical, web features disabled)`)
|
|
2280
2561
|
})
|
|
2281
2562
|
|
|
2282
2563
|
// Forward web task events to all authenticated clients
|
|
2283
|
-
|
|
2284
|
-
|
|
2285
|
-
|
|
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
|
+
})
|
|
2286
2574
|
|
|
2287
2575
|
// Broadcast structured log entries to dashboard clients.
|
|
2288
2576
|
// Re-entrancy guard prevents infinite recursion when _broadcast() itself
|
|
@@ -2331,6 +2619,14 @@ export class WsServer {
|
|
|
2331
2619
|
pushManager: this.pushManager,
|
|
2332
2620
|
permissionSessionMap: this._permissionSessionMap,
|
|
2333
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),
|
|
2334
2630
|
// #4788 Wave 2: hand the question-route registration through a helper so
|
|
2335
2631
|
// dispatch and routing-guard stay symmetric. When a question is
|
|
2336
2632
|
// registered for session S, every currently-connected client that's
|
|
@@ -2345,6 +2641,13 @@ export class WsServer {
|
|
|
2345
2641
|
// settings-handlers subscription guard naturally passes for legitimate
|
|
2346
2642
|
// viewers (including the "view A → switch to B → respond" flow).
|
|
2347
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),
|
|
2348
2651
|
broadcast: (msg, filter) => this._broadcast(msg, filter),
|
|
2349
2652
|
broadcastToSession: (sid, msg, filter) => this._broadcastToSession(sid, msg, filter),
|
|
2350
2653
|
broadcastSessionList: () => this._handlerCtx.transport.broadcastSessionList(),
|
|
@@ -2397,6 +2700,8 @@ export class WsServer {
|
|
|
2397
2700
|
_replayHistory(ws, sessionId, opts) { replayHistory(this._historyCtx, ws, sessionId, opts) }
|
|
2398
2701
|
_flushPostAuthQueue(ws, queue) { flushPostAuthQueue(this._historyCtx, ws, queue) }
|
|
2399
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) }
|
|
2400
2705
|
|
|
2401
2706
|
/** Route incoming client messages */
|
|
2402
2707
|
async _handleMessage(ws, msg) {
|
|
@@ -2420,6 +2725,20 @@ export class WsServer {
|
|
|
2420
2725
|
}
|
|
2421
2726
|
return
|
|
2422
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
|
+
|
|
2423
2742
|
if (msg.type === 'auth') return
|
|
2424
2743
|
|
|
2425
2744
|
// Key exchange for E2E encryption (delegates to ws-auth.js)
|
|
@@ -2459,12 +2778,24 @@ export class WsServer {
|
|
|
2459
2778
|
const { allowed, retryAfterMs } = this._rateLimiter.check(client.rateLimitKey)
|
|
2460
2779
|
if (!allowed) {
|
|
2461
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')
|
|
2462
2782
|
return
|
|
2463
2783
|
}
|
|
2464
2784
|
}
|
|
2465
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
|
+
|
|
2466
2796
|
// During drain, only allow permission_response and user_question_response
|
|
2467
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')
|
|
2468
2799
|
if (msg.type === 'input') {
|
|
2469
2800
|
this._send(ws, { type: 'server_status', message: 'Server is restarting, please wait...' })
|
|
2470
2801
|
}
|
|
@@ -2477,6 +2808,7 @@ export class WsServer {
|
|
|
2477
2808
|
const details = parsed.error.issues.map(i => i.message).join(', ')
|
|
2478
2809
|
log.warn(`[${correlationId}] Invalid message from ${client.id}: ${details}`)
|
|
2479
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')
|
|
2480
2812
|
return
|
|
2481
2813
|
}
|
|
2482
2814
|
const validatedMsg = parsed.data
|
|
@@ -2484,7 +2816,7 @@ export class WsServer {
|
|
|
2484
2816
|
log.debug(`[${correlationId}] Handling ${validatedMsg.type} from ${client.id}`)
|
|
2485
2817
|
|
|
2486
2818
|
// Route based on server mode — pass correlationId in context
|
|
2487
|
-
const ctx =
|
|
2819
|
+
const ctx = buildMessageCtx(this._handlerCtx, correlationId)
|
|
2488
2820
|
try {
|
|
2489
2821
|
if (this.sessionManager) {
|
|
2490
2822
|
await handleSessionMessage(ws, client, validatedMsg, ctx)
|
|
@@ -2492,6 +2824,10 @@ export class WsServer {
|
|
|
2492
2824
|
await handleCliMessage(ws, client, validatedMsg, ctx)
|
|
2493
2825
|
}
|
|
2494
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
|
+
}
|
|
2495
2831
|
log.error(`[${correlationId}] Handler error for ${validatedMsg.type}: ${err.message}`)
|
|
2496
2832
|
this._send(ws, { type: 'server_error', correlationId, message: err.message, recoverable: true })
|
|
2497
2833
|
}
|
|
@@ -2521,6 +2857,41 @@ export class WsServer {
|
|
|
2521
2857
|
this._broadcaster._broadcast(message, filter)
|
|
2522
2858
|
}
|
|
2523
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
|
+
|
|
2524
2895
|
/**
|
|
2525
2896
|
* Broadcast a session-scoped message to clients viewing that session.
|
|
2526
2897
|
* Tags the message with `sessionId` so clients can route it to the correct
|
|
@@ -2528,6 +2899,11 @@ export class WsServer {
|
|
|
2528
2899
|
* matches — prevents cross-session info leakage and bandwidth waste.
|
|
2529
2900
|
* Pass a custom filter to override the default recipient selection when needed.
|
|
2530
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
|
+
|
|
2531
2907
|
_broadcastToSession(sessionId, message, filter) {
|
|
2532
2908
|
this._broadcaster._broadcastToSession(sessionId, message, filter)
|
|
2533
2909
|
}
|
|
@@ -2566,6 +2942,21 @@ export class WsServer {
|
|
|
2566
2942
|
)
|
|
2567
2943
|
}
|
|
2568
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
|
+
|
|
2569
2960
|
// #6691: push a single orchestration run delta to host-level (unbound) clients
|
|
2570
2961
|
// only — runs are host-wide cross-session objects; a session-bound token never
|
|
2571
2962
|
// receives them. Called by the OrchestrationManager (E-4); the `delta`
|
|
@@ -2799,8 +3190,8 @@ export class WsServer {
|
|
|
2799
3190
|
}
|
|
2800
3191
|
|
|
2801
3192
|
/** Get list of connected clients for auth_ok payload */
|
|
2802
|
-
_getConnectedClientList() {
|
|
2803
|
-
return this._clientManager.getConnectedList()
|
|
3193
|
+
_getConnectedClientList(forClient) {
|
|
3194
|
+
return this._clientManager.getConnectedList(forClient)
|
|
2804
3195
|
}
|
|
2805
3196
|
|
|
2806
3197
|
/** Broadcast client_joined to all OTHER authenticated clients */
|
|
@@ -2813,6 +3204,96 @@ export class WsServer {
|
|
|
2813
3204
|
this._broadcaster._broadcastClientLeft(departingClient)
|
|
2814
3205
|
}
|
|
2815
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
|
+
|
|
2816
3297
|
/**
|
|
2817
3298
|
* #5555.6 — one keepalive sweep over all authenticated clients.
|
|
2818
3299
|
*
|
|
@@ -2842,6 +3323,16 @@ export class WsServer {
|
|
|
2842
3323
|
try { ws.terminate() } catch {}
|
|
2843
3324
|
continue
|
|
2844
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
|
+
}
|
|
2845
3336
|
client.isAlive = false
|
|
2846
3337
|
try { ws.ping() } catch {}
|
|
2847
3338
|
}
|
|
@@ -2849,6 +3340,7 @@ export class WsServer {
|
|
|
2849
3340
|
|
|
2850
3341
|
/** Handle cleanup when an authenticated client disconnects or is terminated */
|
|
2851
3342
|
_handleClientDeparture(departingClient) {
|
|
3343
|
+
void this._devPreview.closeClient(departingClient.id)
|
|
2852
3344
|
// #5563: vacate primary for every session this client owned. Promotion
|
|
2853
3345
|
// policy is NOBODY-UNTIL-CLAIM — we clear the slot (broadcast null) rather
|
|
2854
3346
|
// than auto-promote an observer, so a backgrounded viewer is never silently
|
|
@@ -3037,12 +3529,33 @@ export class WsServer {
|
|
|
3037
3529
|
/** Send JSON to a single client (delegates to extracted ws-client-sender) */
|
|
3038
3530
|
_send(ws, message) {
|
|
3039
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
|
+
}
|
|
3040
3542
|
// #5721: propagate the delivery boolean so callers gating crypto state on a
|
|
3041
3543
|
// frame reaching the wire (the eager handshake's auth_ok) can observe a
|
|
3042
3544
|
// swallowed send failure. Other callers ignore the return, unchanged.
|
|
3043
3545
|
return this._clientSend(ws, client, message)
|
|
3044
3546
|
}
|
|
3045
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
|
+
|
|
3046
3559
|
/**
|
|
3047
3560
|
* Clear all pending permission requests across both subsystems.
|
|
3048
3561
|
*
|
|
@@ -3068,7 +3581,16 @@ export class WsServer {
|
|
|
3068
3581
|
}
|
|
3069
3582
|
|
|
3070
3583
|
/** Graceful shutdown */
|
|
3584
|
+
settleDevPreviews() {
|
|
3585
|
+
return this._devPreview.closeAll()
|
|
3586
|
+
}
|
|
3587
|
+
|
|
3071
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 */ }
|
|
3072
3594
|
// Remove PairingManager listeners to prevent post-shutdown broadcasts
|
|
3073
3595
|
if (this._pairingManager && this._pairingRefreshedHandler) {
|
|
3074
3596
|
this._pairingManager.off('pairing_refreshed', this._pairingRefreshedHandler)
|
|
@@ -3078,6 +3600,10 @@ export class WsServer {
|
|
|
3078
3600
|
this._pairingManager.off('pending_request_expired', this._pendingRequestExpiredHandler)
|
|
3079
3601
|
this._pendingRequestExpiredHandler = null
|
|
3080
3602
|
}
|
|
3603
|
+
if (this._pairingManager && this._sessionTokenRemovedHandler) {
|
|
3604
|
+
this._pairingManager.off('session_token_removed', this._sessionTokenRemovedHandler)
|
|
3605
|
+
this._sessionTokenRemovedHandler = null
|
|
3606
|
+
}
|
|
3081
3607
|
this._pairRequesters.clear()
|
|
3082
3608
|
|
|
3083
3609
|
// Remove TokenManager listener to prevent post-shutdown broadcasts
|
|
@@ -3105,6 +3631,26 @@ export class WsServer {
|
|
|
3105
3631
|
}
|
|
3106
3632
|
}
|
|
3107
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
|
+
|
|
3108
3654
|
if (this._pingInterval) {
|
|
3109
3655
|
clearInterval(this._pingInterval)
|
|
3110
3656
|
this._pingInterval = null
|
|
@@ -3122,9 +3668,9 @@ export class WsServer {
|
|
|
3122
3668
|
this._clientManager.clearAllPrimary()
|
|
3123
3669
|
this._normalizer.destroy()
|
|
3124
3670
|
|
|
3125
|
-
//
|
|
3126
|
-
//
|
|
3127
|
-
|
|
3671
|
+
// Socket teardown remains immediate; callers can await confirmed preview
|
|
3672
|
+
// child settlement before exiting the daemon.
|
|
3673
|
+
const previewSettlement = this._devPreview.closeAll()
|
|
3128
3674
|
|
|
3129
3675
|
// Clean up web task manager
|
|
3130
3676
|
this._webTaskManager.destroy()
|
|
@@ -3146,5 +3692,6 @@ export class WsServer {
|
|
|
3146
3692
|
this._approvalServer = null
|
|
3147
3693
|
removeShellApprovalInfo()
|
|
3148
3694
|
}
|
|
3695
|
+
return previewSettlement
|
|
3149
3696
|
}
|
|
3150
3697
|
}
|