@chroxy/server 0.11.0 → 0.11.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONFIG.md +206 -18
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +166 -11
- package/package.json +16 -12
- package/sidecar/Dockerfile +1 -1
- package/sidecar/PROTOCOL.md +9 -1
- package/sidecar/agent.js +102 -10
- package/sidecar/package-lock.json +3 -3
- package/src/acp-config.js +206 -0
- package/src/acp-session.js +958 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +304 -0
- package/src/agent-control/client.js +1645 -0
- package/src/agent-control/events.js +551 -0
- package/src/agent-control/local-connection.js +293 -0
- package/src/agent-control/mcp-server.js +547 -0
- package/src/anthropic-compatible-config.js +30 -4
- package/src/anthropic-compatible-session.js +15 -6
- package/src/anthropic-gemini-shim.js +444 -0
- package/src/anthropic-gemini-translate.js +1030 -0
- package/src/anthropic-openai-shim.js +0 -1
- package/src/archive-continuation.js +164 -0
- package/src/assistant-response.js +24 -0
- package/src/auth-probes.js +120 -13
- package/src/background-shell-tracker.js +27 -0
- package/src/base-session.js +1520 -36
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +19 -0
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +11 -5
- package/src/bound-client-policy.js +291 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +69 -5
- package/src/built-in-tools/tool-transforms.js +1113 -13
- package/src/byok-compose-state.js +6 -9
- package/src/byok-credentials.js +2 -3
- package/src/byok-mcp-client.js +92 -7
- package/src/byok-mcp-config.js +633 -122
- package/src/byok-mcp-fleet.js +49 -7
- package/src/byok-mcp-oauth-store.js +18 -16
- package/src/byok-mcp-trust.js +37 -23
- package/src/byok-session.js +707 -179
- package/src/byok-tool-executor.js +2742 -26
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +64 -46
- package/src/claude-channel-session.js +16 -10
- package/src/claude-model-catalog.js +131 -16
- package/src/claude-model-refresh.js +385 -0
- package/src/claude-model-request.js +103 -0
- package/src/claude-setting-sources.js +74 -0
- package/src/claude-stream-parser.js +53 -3
- package/src/claude-tui/diagnostic-tail.js +83 -0
- package/src/claude-tui/form-driver.js +44 -7
- package/src/claude-tui/model-error.js +41 -0
- package/src/claude-tui/pty-driver.js +215 -88
- package/src/claude-tui/sanitize-question-payload.js +109 -0
- package/src/claude-tui/usage-limit.js +239 -0
- package/src/claude-tui-session.js +3563 -284
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-cmd.js +236 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +4 -4
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/connection-state.js +54 -0
- package/src/cli/deploy-cmd.js +45 -10
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/freshness-cmd.js +53 -0
- package/src/cli/init-cmd.js +15 -16
- package/src/cli/pages-cmd.js +6 -4
- package/src/cli/pair-code-cmd.js +7 -6
- package/src/cli/pair-discord-cmd.js +7 -6
- package/src/cli/providers-cmd.js +3 -3
- package/src/cli/schedule-cmd.js +91 -40
- package/src/cli/server-cmd.js +54 -1
- package/src/cli/service-cmd.js +33 -10
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +162 -11
- package/src/cli/shell-cmd.js +7 -4
- package/src/cli/status-cmd.js +19 -5
- package/src/cli/tokens-cmd.js +4 -5
- package/src/cli/tunnel-cmd.js +255 -24
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1250 -126
- package/src/cli.js +8 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +1517 -81
- package/src/codex-bundled-client.js +66 -0
- package/src/codex-error-text.js +114 -0
- package/src/codex-model-catalog.js +548 -0
- package/src/codex-model-rejections.js +87 -0
- package/src/codex-native-resume.js +104 -0
- package/src/codex-protocol-capabilities.js +188 -0
- package/src/codex-session.js +450 -27
- package/src/config-dir-migration.js +449 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +306 -26
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +78 -23
- package/src/connection-locality.js +60 -0
- package/src/container-liveness-monitor.js +189 -0
- package/src/continuation-metadata-worker.js +17 -0
- package/src/continuations.js +227 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +7 -20
- package/src/control-room/skills-inventory.js +2 -2
- package/src/conversation-scanner.js +42 -39
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +28 -39
- package/src/credential-store.js +23 -19
- package/src/daemon-commit.js +92 -0
- package/src/daemon-idle-state.js +171 -0
- package/src/daemon-update-status.js +314 -0
- package/src/dashboard-build.js +70 -0
- package/src/declared-status.js +90 -0
- package/src/deepseek-credentials.js +2 -3
- package/src/dev-preview.js +170 -182
- package/src/device-preferences.js +2 -2
- package/src/diff-parser.js +87 -0
- package/src/discord-credentials.js +2 -3
- package/src/docker-byok-pool.js +3 -1
- package/src/docker-byok-session.js +678 -78
- package/src/docker-image-allowlist.js +23 -1
- package/src/docker-sdk-session.js +172 -3
- package/src/docker-session.js +294 -11
- package/src/doctor.js +781 -64
- package/src/durable-write.js +35 -0
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +101 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +31 -10
- package/src/environments/backends/k8s.js +49 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +118 -13
- package/src/event-normalizer.js +186 -235
- package/src/folder-trust-wire.js +137 -0
- package/src/folder-trust-worker.js +17 -0
- package/src/folder-trust.js +1572 -0
- package/src/freshness/activity-meter.js +101 -0
- package/src/freshness/adapter.js +199 -0
- package/src/freshness/checks.js +239 -0
- package/src/freshness/config.js +98 -0
- package/src/freshness/core.js +185 -0
- package/src/freshness/derive.js +680 -0
- package/src/freshness/exchange.js +305 -0
- package/src/freshness/file-ledger.js +400 -0
- package/src/freshness/grade.js +81 -0
- package/src/freshness/hash.js +45 -0
- package/src/freshness/inbox.js +163 -0
- package/src/freshness/index.js +20 -0
- package/src/freshness/investigation.js +474 -0
- package/src/freshness/keys.js +177 -0
- package/src/freshness/ledger.js +122 -0
- package/src/freshness/outbox.js +131 -0
- package/src/freshness/policy.js +599 -0
- package/src/freshness/queue.js +843 -0
- package/src/freshness/read-errors.js +23 -0
- package/src/freshness/render.js +153 -0
- package/src/freshness/runtime.js +113 -0
- package/src/freshness/session-registry-adapter.js +161 -0
- package/src/freshness/state-file-adapter.js +167 -0
- package/src/freshness-runner/build-info.js +139 -0
- package/src/freshness-runner/cli.js +105 -0
- package/src/freshness-runner/run-tick.js +109 -0
- package/src/freshness-runner/stamp.js +57 -0
- package/src/freshness-sources/claude-transcript-adapter.js +211 -0
- package/src/freshness-sources/codex-transcript-adapter.js +33 -0
- package/src/freshness-sources/index.js +8 -0
- package/src/gemini-byok-session.js +292 -0
- package/src/gemini-credentials.js +67 -0
- package/src/gemini-key-safety.js +246 -0
- package/src/gemini-models.js +386 -0
- package/src/gemini-session.js +81 -5
- package/src/handler-utils.js +540 -80
- package/src/handlers/checkpoint-handlers.js +47 -4
- package/src/handlers/control-room-handlers.js +51 -11
- package/src/handlers/conversation-handlers.js +469 -56
- package/src/handlers/daemon-update-handlers.js +81 -0
- package/src/handlers/evaluator-handlers.js +14 -1
- package/src/handlers/feature-handlers.js +186 -69
- package/src/handlers/file-handlers.js +57 -13
- package/src/handlers/folder-trust-handlers.js +90 -0
- package/src/handlers/input-handlers.js +714 -48
- package/src/handlers/orchestration-handlers.js +3 -3
- package/src/handlers/principal-admin-handlers.js +229 -0
- package/src/handlers/principal-handlers.js +262 -0
- package/src/handlers/scheduler-handlers.js +92 -18
- package/src/handlers/session-handlers.js +551 -20
- package/src/handlers/session-pr-status-handlers.js +283 -0
- package/src/handlers/session-pr-threads-handlers.js +247 -0
- package/src/handlers/settings-handlers.js +372 -50
- package/src/handlers/skills-handlers.js +20 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/health-proof.js +40 -0
- package/src/history-page.js +112 -0
- package/src/http-routes.js +127 -8
- package/src/ide/search.js +24 -6
- package/src/ide/symbols.js +20 -6
- package/src/input-context.js +117 -0
- package/src/instruction-policy-compiler.js +229 -0
- package/src/instruction-policy.js +250 -0
- package/src/jsonl-reader.js +378 -91
- package/src/jsonl-subprocess-session.js +96 -9
- package/src/keychain.js +1 -1
- package/src/logger.js +166 -30
- package/src/mailbox-route.js +113 -22
- package/src/message-wire.js +386 -0
- package/src/model-discovery.js +43 -3
- package/src/models.js +1276 -174
- package/src/notification-prefs.js +27 -4
- package/src/notifications/discord-billing-sink.js +22 -5
- package/src/notifications/discord-ci-sink.js +243 -0
- package/src/notifications/discord-webhook-client.js +71 -0
- package/src/notifications/discord-webhook-sink.js +64 -23
- package/src/notifications/expo-push-sink.js +85 -6
- package/src/notifications/ready-body.js +16 -5
- package/src/ollama-session.js +34 -2
- package/src/orchestration/build-manager.js +9 -2
- package/src/orchestration/git-ops.js +41 -7
- package/src/orchestration/orchestration-manager.js +112 -36
- package/src/orchestration/permission-gate.js +17 -2
- package/src/orchestration/run-model.js +2 -1
- package/src/orchestration/run-record.js +11 -0
- package/src/orchestration/turn-driver.js +185 -43
- package/src/orphan-reaper.js +470 -0
- package/src/outgoing-policy.js +189 -0
- package/src/pairing.js +92 -13
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1410 -43
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +737 -89
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolved-by.js +89 -0
- package/src/permission-resolver.js +126 -8
- package/src/permission-scope.js +43 -0
- package/src/platform.js +315 -47
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/principal-audit.js +189 -0
- package/src/principal-binding.js +25 -0
- package/src/principal-brakes.js +21 -0
- package/src/principal-effect.js +101 -0
- package/src/principal-journal.js +905 -0
- package/src/principal-kill-switch.js +183 -0
- package/src/principal-label.js +5 -0
- package/src/principal-pending-permissions.js +177 -0
- package/src/principal-policy.js +1094 -0
- package/src/principal-sessions-snapshot.js +208 -0
- package/src/principal-store.js +488 -0
- package/src/principal-subscriptions.js +283 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +209 -4
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +531 -20
- package/src/roster-broadcast.js +186 -0
- package/src/scheduled-task-store.js +330 -26
- package/src/scheduler.js +368 -11
- package/src/sdk-session.js +2114 -188
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +17 -3
- package/src/server-cli/server-orchestrator.js +28 -5
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +553 -38
- package/src/server-identity.js +15 -11
- package/src/service.js +396 -25
- package/src/session-archive-limits.js +15 -0
- package/src/session-archive.js +1029 -0
- package/src/session-busy-state.js +72 -0
- package/src/session-ci-watcher.js +1099 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +4062 -312
- package/src/session-message-history.js +841 -16
- package/src/session-name-allocator.js +685 -0
- package/src/session-pr-status.js +654 -0
- package/src/session-pr-threads.js +271 -0
- package/src/session-preset-trust.js +3 -3
- package/src/session-preset.js +10 -5
- package/src/session-state-persistence.js +94 -17
- package/src/session-timeout-manager.js +20 -0
- package/src/session-token-store.js +17 -8
- package/src/session-wake.js +240 -0
- package/src/shell-approval-info.js +2 -2
- package/src/shell-approval-store.js +3 -1
- package/src/skills-loader.js +7 -4
- package/src/skills-manager.js +2 -2
- package/src/skills-trust.js +95 -13
- package/src/skills-usage.js +2 -3
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +100 -29
- package/src/summarize-session.js +53 -4
- package/src/supervisor.js +22 -11
- package/src/sweep-stale-provider-dirs.js +95 -0
- package/src/thinking-level-wire.js +39 -0
- package/src/thinking-stream.js +179 -0
- package/src/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +372 -25
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +34 -31
- package/src/tunnel/index.js +9 -0
- package/src/tunnel/preview.js +64 -0
- package/src/turn-outcome.js +140 -0
- package/src/usage-normalize.js +9 -5
- package/src/user-shell-session.js +59 -5
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +770 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +639 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +29 -0
- package/src/utils/bounded-regex.js +162 -0
- package/src/utils/claude-binary.js +43 -0
- package/src/utils/claude-config-dir.js +245 -0
- package/src/utils/claude-login-command.js +16 -0
- package/src/utils/claude-native-route.js +81 -0
- package/src/utils/componentwise-resolver.js +133 -37
- package/src/utils/deploy-control-files.js +87 -0
- package/src/utils/exec-failure-reason.js +21 -0
- package/src/utils/git-repo.js +42 -0
- package/src/utils/is-entry-point.js +137 -0
- package/src/utils/node-pty-probe.js +95 -0
- package/src/utils/node-pty-support.js +118 -0
- package/src/utils/opened-file-path.js +167 -0
- package/src/utils/path-containment.js +165 -0
- package/src/utils/permission-mode-sidecar.js +51 -0
- package/src/utils/pid-liveness.js +47 -0
- package/src/utils/preflight.js +360 -16
- package/src/utils/read-limiter.js +217 -0
- package/src/utils/regular-file.js +375 -0
- package/src/utils/safe-regex.js +113 -0
- package/src/utils/small-file.js +129 -0
- package/src/utils/spawn-env.js +189 -4
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-provenance.js +406 -13
- package/src/web-task-manager.js +297 -16
- package/src/worktree-gc.js +202 -6
- package/src/ws-auth.js +163 -31
- package/src/ws-broadcaster.js +49 -5
- package/src/ws-client-manager.js +24 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +363 -58
- package/src/ws-file-ops/common.js +320 -14
- package/src/ws-file-ops/git.js +395 -42
- package/src/ws-file-ops/index.js +2 -0
- package/src/ws-file-ops/memory.js +137 -35
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +571 -113
- package/src/ws-forwarding.js +349 -39
- package/src/ws-handler-context.js +88 -2
- package/src/ws-history.js +1010 -175
- package/src/ws-message-handlers.js +25 -1
- package/src/ws-permissions.js +307 -37
- package/src/ws-schemas.js +5 -0
- package/src/ws-server.js +885 -98
- package/sidecar/node_modules/.package-lock.json +0 -29
- package/sidecar/node_modules/ws/LICENSE +0 -20
- package/sidecar/node_modules/ws/README.md +0 -548
- package/sidecar/node_modules/ws/browser.js +0 -8
- package/sidecar/node_modules/ws/index.js +0 -22
- package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
- package/sidecar/node_modules/ws/lib/constants.js +0 -19
- package/sidecar/node_modules/ws/lib/event-target.js +0 -292
- package/sidecar/node_modules/ws/lib/extension.js +0 -203
- package/sidecar/node_modules/ws/lib/limiter.js +0 -55
- package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
- package/sidecar/node_modules/ws/lib/receiver.js +0 -706
- package/sidecar/node_modules/ws/lib/sender.js +0 -602
- package/sidecar/node_modules/ws/lib/stream.js +0 -161
- package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
- package/sidecar/node_modules/ws/lib/validation.js +0 -152
- package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
- package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
- package/sidecar/node_modules/ws/package.json +0 -70
- package/sidecar/node_modules/ws/wrapper.mjs +0 -21
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
- package/src/dashboard-next/dist/index.html +0 -13
- package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
package/src/server-cli.js
CHANGED
|
@@ -1,10 +1,21 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
SessionManager,
|
|
3
|
+
ProviderBinaryNotFoundError,
|
|
4
|
+
ProviderBinaryQuarantinedError,
|
|
5
|
+
ProviderBinaryProvenanceError,
|
|
6
|
+
ProviderBinaryUnsupportedError,
|
|
7
|
+
ProviderBinaryVersionError,
|
|
8
|
+
ProviderCredentialMissingError,
|
|
9
|
+
} from './session-manager.js'
|
|
2
10
|
import { DEFAULT_RESULT_TIMEOUT_MS, DEFAULT_HARD_TIMEOUT_MS, DEFAULT_STREAM_STALL_TIMEOUT_MS } from './base-session.js'
|
|
3
11
|
import { DEFAULT_TOOL_CALL_TIMEOUT_MS } from './byok-mcp-client.js'
|
|
4
12
|
import { formatIdleDuration } from './session-timeout-manager.js'
|
|
5
13
|
import { isOperatorTimeoutInRange } from './duration.js'
|
|
6
14
|
import { WsServer } from './ws-server.js'
|
|
7
15
|
import { BillingCanaryMonitor } from './billing-canary-monitor.js'
|
|
16
|
+
import { buildSessionCiWatcher } from './session-ci-watcher.js'
|
|
17
|
+
import { DaemonUpdateStatus } from './daemon-update-status.js'
|
|
18
|
+
import { computeDaemonIdleState } from './daemon-idle-state.js'
|
|
8
19
|
import { resolvePublicIp } from './get-public-ip.js'
|
|
9
20
|
import { createTunnel, parseTunnelArg } from './tunnel/index.js'
|
|
10
21
|
// #5368 slice (c): QUICK_TUNNEL_DNS_SETTLE_MS + TUNNEL_STATUS_MIN_PROTOCOL_VERSION
|
|
@@ -14,6 +25,8 @@ import { waitForTunnel } from './tunnel-check.js'
|
|
|
14
25
|
import { PushManager, settlePush } from './push.js'
|
|
15
26
|
import { ensureIngestSecret } from './event-ingest.js'
|
|
16
27
|
import { getChroxyHostEnv } from './chroxy-host-metadata.js'
|
|
28
|
+
import { boundedRegex } from './utils/bounded-regex.js'
|
|
29
|
+
import { probeNodePtyAvailable } from './utils/node-pty-probe.js'
|
|
17
30
|
import { PushNotificationHandler } from './server-cli/push-notification-handler.js'
|
|
18
31
|
import { StartupDisplay } from './server-cli/startup-display.js'
|
|
19
32
|
import { TunnelLifecycleHandler } from './server-cli/tunnel-lifecycle-handler.js'
|
|
@@ -23,6 +36,9 @@ import { readFileSync, existsSync } from 'fs'
|
|
|
23
36
|
import { fileURLToPath } from 'url'
|
|
24
37
|
import { dirname, join, relative, sep } from 'path'
|
|
25
38
|
import { createLogger, setJsonMode, initFileLogging, setConsoleQuiet } from './logger.js'
|
|
39
|
+
import { configDir, configPath } from './config-dir.js'
|
|
40
|
+
import { defaultCwdAdvisory } from './handler-utils.js'
|
|
41
|
+
import { detectStrandedState, missingTokenAdvice, startupStrandedWarning } from './config-dir-migration.js'
|
|
26
42
|
|
|
27
43
|
const log = createLogger('cli')
|
|
28
44
|
// #5368 slice (b): QRCode + writeConnectionInfo moved to startup-display.js with
|
|
@@ -36,23 +52,30 @@ import { resolveBindHost, isLoopbackHost, formatHostForUrl, maybeWarnNonLoopback
|
|
|
36
52
|
import { writeFileRestricted } from './platform.js'
|
|
37
53
|
import { getToken, setToken, migrateToken, isKeychainAvailable } from './keychain.js'
|
|
38
54
|
import { maybeEncryptCredentialsAtRest } from './credential-store.js'
|
|
39
|
-
import { registerDockerProvider, resolveProviderLabel, DEFAULT_PROVIDER } from './providers.js'
|
|
55
|
+
import { registerDockerProvider, resolveProviderLabel, DEFAULT_PROVIDER, resolveDaemonDefaultProvider } from './providers.js'
|
|
40
56
|
import { registerAnthropicCompatibleProviders } from './anthropic-compatible-session.js'
|
|
41
57
|
import { registerOpenAiCompatibleProviders } from './openai-compatible-session.js'
|
|
58
|
+
import { registerAcpProviders } from './acp-session.js'
|
|
42
59
|
import { getSharedPool, isPoolEnabled } from './docker-byok-pool.js'
|
|
43
60
|
import { getSharedPoolStats } from './docker-byok-pool-stats.js'
|
|
44
|
-
import { getRegistryForProvider, watchModelsOverlay } from './models.js'
|
|
61
|
+
import { getRegistryForProvider, watchModelsOverlay, setInUseModelsProvider } from './models.js'
|
|
62
|
+
import { clientActiveProvider, overlayBroadcastReachesProvider, broadcastRosterPerRecipient } from './roster-broadcast.js'
|
|
45
63
|
// Imported from a dedicated constants module rather than environment-manager.js
|
|
46
64
|
// so we don't eagerly pull in DockerBackend when environments are disabled —
|
|
47
65
|
// environment-manager.js itself remains behind the dynamic import below
|
|
48
66
|
// (`if (config?.environments?.enabled)`).
|
|
49
67
|
import { UNREACHABLE_STATUSES } from './environment-statuses.js'
|
|
50
|
-
import { resolveSkipPermissions, buildEnvironmentBackend, isUserShellEnabled, getAllowAnyModelProviders, isSemanticTitlesEnabled, resolveSemanticTitleModel, resolveSemanticTitleTimeoutMs, resolveBinaryProvenanceMode, isBinarySignatureGateEnabled } from './config.js'
|
|
68
|
+
import { resolveSkipPermissions, buildEnvironmentBackend, isUserShellEnabled, getAllowAnyModelProviders, isSemanticTitlesEnabled, resolveSemanticTitleModel, resolveSemanticTitleTimeoutMs, resolveBinaryProvenanceMode, isBinarySignatureGateEnabled, applyCodexBinaryConfig, resolveSessionNaming } from './config.js'
|
|
69
|
+
import { sweepStaleProviderDirs } from './sweep-stale-provider-dirs.js'
|
|
51
70
|
import { buildOrchestrationManager } from './orchestration/build-manager.js'
|
|
52
71
|
import { buildSchedulerEngine } from './scheduler.js'
|
|
53
72
|
import { parseDuration } from './duration.js'
|
|
54
73
|
import { createSessionTokenStore } from './session-token-store.js'
|
|
74
|
+
import { createPrincipalStore } from './principal-store.js'
|
|
75
|
+
import { createPrincipalBrakes } from './principal-brakes.js'
|
|
76
|
+
import { PrincipalJournal } from './principal-journal.js'
|
|
55
77
|
import { StatusLineManager } from './statusline.js'
|
|
78
|
+
import { warnIfClaudeConfigDirUnusable } from './utils/claude-config-dir.js'
|
|
56
79
|
|
|
57
80
|
const __filename = fileURLToPath(import.meta.url)
|
|
58
81
|
const __dirname = dirname(__filename)
|
|
@@ -233,6 +256,155 @@ export function buildServerBanner({ version, provider }) {
|
|
|
233
256
|
return `Chroxy Server v${version} (${modeStr})`
|
|
234
257
|
}
|
|
235
258
|
|
|
259
|
+
/**
|
|
260
|
+
* #7722 — build the `available_models` broadcasts for one models-overlay
|
|
261
|
+
* hot-reload (`watchModelsOverlay`'s `onReload`).
|
|
262
|
+
*
|
|
263
|
+
* The reload re-folds the default (Claude) registry AND every per-provider
|
|
264
|
+
* registry the overlay touches (#6377), so it produces ONE roster per affected
|
|
265
|
+
* registry — not one. Broadcasting only the Claude roster (and labelling it
|
|
266
|
+
* `claude-sdk`, as this did before) had two failures on a live codex session: a
|
|
267
|
+
* `provider: "codex"` overlay row never reached the codex client at all, and —
|
|
268
|
+
* on the pre-#7728 clients this was written against — the claude-sdk tag flipped
|
|
269
|
+
* the dashboard's `modelsMatchProvider` false, which HID the model picker until
|
|
270
|
+
* the client reconnected. That second failure is gone: `modelsMatchProvider` was
|
|
271
|
+
* deleted with the single `availableModels` slot, and a client now keys each
|
|
272
|
+
* roster by its sender. The FIRST one is still live and is what this function
|
|
273
|
+
* exists for — a roster that is never sent cannot be read from any slot.
|
|
274
|
+
*
|
|
275
|
+
* The wire shape is unchanged — each entry is the same provider-tagged
|
|
276
|
+
* `available_models` message every other sender emits.
|
|
277
|
+
*
|
|
278
|
+
* This builds the SET; it does not decide recipients.
|
|
279
|
+
* `overlayBroadcastReachesProvider` below is the recipient rule, and
|
|
280
|
+
* `createOverlayReloadBroadcaster` is what applies it. Until #7728 that routing
|
|
281
|
+
* was load-bearing for CORRECTNESS: every client kept ONE `availableModels`
|
|
282
|
+
* slot, replaced unconditionally on every message, so sending the whole set to
|
|
283
|
+
* everyone was last-write-wins and a Claude client on a daemon that also has a
|
|
284
|
+
* codex row ended up tagged `codex` and lost the very picker this issue is
|
|
285
|
+
* about. Clients now key each roster by the provider that sent it
|
|
286
|
+
* (`mergeModelsByProvider`, store-core/src/models-by-provider.ts), so the
|
|
287
|
+
* routing is defence in depth and bandwidth rather than the only thing standing
|
|
288
|
+
* between a codex session and a Claude roster.
|
|
289
|
+
*
|
|
290
|
+
* Exported so tests can assert the broadcast set without executing
|
|
291
|
+
* `startCliServer()` end-to-end.
|
|
292
|
+
*
|
|
293
|
+
* @param {{ models?: object[], defaultModelId?: string|null, providers?: {provider: string, models: object[], defaultModelId: string|null}[] }} reload
|
|
294
|
+
* @returns {{ type: 'available_models', models: object[], defaultModel: string|null, provider: string }[]}
|
|
295
|
+
*/
|
|
296
|
+
export function buildOverlayReloadBroadcasts({ models, defaultModelId, providers } = {}) {
|
|
297
|
+
const out = [{
|
|
298
|
+
type: 'available_models',
|
|
299
|
+
models: models || [],
|
|
300
|
+
defaultModel: defaultModelId ?? null,
|
|
301
|
+
provider: 'claude-sdk',
|
|
302
|
+
}]
|
|
303
|
+
for (const entry of providers || []) {
|
|
304
|
+
if (!entry || typeof entry.provider !== 'string' || entry.provider.length === 0) continue
|
|
305
|
+
out.push({
|
|
306
|
+
type: 'available_models',
|
|
307
|
+
models: entry.models || [],
|
|
308
|
+
defaultModel: entry.defaultModelId ?? null,
|
|
309
|
+
provider: entry.provider,
|
|
310
|
+
})
|
|
311
|
+
}
|
|
312
|
+
return out
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// #7895 — `overlayBroadcastReachesProvider` and `clientActiveProvider` moved to
|
|
316
|
+
// `./roster-broadcast.js` so `ws-forwarding.js`'s two `available_models` send
|
|
317
|
+
// sites can share them (and the per-recipient tagging loop below) instead of a
|
|
318
|
+
// third hand-rolled copy. Re-exported here so every existing importer of this
|
|
319
|
+
// module — notably `models-overlay-reload-broadcast.test.js` — is unaffected.
|
|
320
|
+
export { overlayBroadcastReachesProvider, clientActiveProvider }
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* #7722 — build the `watchModelsOverlay({ onReload })` callback: turn one reload
|
|
324
|
+
* into its broadcast set and send each entry ONLY to the clients that registry
|
|
325
|
+
* is the roster for (`overlayBroadcastReachesProvider`).
|
|
326
|
+
*
|
|
327
|
+
* #7756 — the DEFAULT (Claude) entry additionally gets RE-TAGGED per recipient
|
|
328
|
+
* instead of sent verbatim. `claude-sdk`, `claude-cli` and `claude-tui` share
|
|
329
|
+
* this one registry, so `overlayBroadcastReachesProvider` correctly decides all
|
|
330
|
+
* three should receive it — but since #7728 the client keys each roster by the
|
|
331
|
+
* EXACT tag it arrived under (`modelsByProvider`,
|
|
332
|
+
* store-core/src/models-by-provider.ts), so a single `claude-sdk` literal
|
|
333
|
+
* never refreshes a `claude-cli`/`claude-tui` client's OWN bucket even though
|
|
334
|
+
* routing already decided it should. Each recipient is instead served the same roster
|
|
335
|
+
* tagged with the name `resolveRosterProvider` would give IT on a fresh
|
|
336
|
+
* connect (`ws-history.js`'s own resolution), so a reload and a reconnect agree
|
|
337
|
+
* on what a session's roster is called — no reconnect-vs-reload skew.
|
|
338
|
+
*
|
|
339
|
+
* The concrete tag set is derived from the provider REGISTRY
|
|
340
|
+
* (`getRegisteredProviderNames` + `isClaudeProvider`, #5858's single source of
|
|
341
|
+
* truth), never a hand-maintained name literal — the exact defect class #5855
|
|
342
|
+
* fixed for `isClaudeProvider` itself. That includes `claude-byok`
|
|
343
|
+
* (`static claudeFamily = true`, byok-session.js) — see the paragraph below
|
|
344
|
+
* for why an earlier revision of this fix excluded it and why that was wrong.
|
|
345
|
+
*
|
|
346
|
+
* A residual broadcast (still tagged with the reload's own literal) covers
|
|
347
|
+
* whatever does not resolve to a known tag — an unregistered/custom provider
|
|
348
|
+
* name, or one whose own registry build throws — preserving the pre-#7756
|
|
349
|
+
* fail-open delivery for that edge case (`overlayBroadcastReachesProvider`'s
|
|
350
|
+
* own try/catch) rather than silently dropping it. That roster was already
|
|
351
|
+
* "delivered and discarded" for such a client before this fix (its own bucket
|
|
352
|
+
* key never matched `claude-sdk` either), so nothing regresses; #7756 is about
|
|
353
|
+
* the KNOWN Claude-family names landing in the wrong bucket, not this edge
|
|
354
|
+
* case.
|
|
355
|
+
*
|
|
356
|
+
* `claude-byok` MUST be in `knownTags`, not the residual: `ws-history.js`'s
|
|
357
|
+
* post-auth connect path (`resolveRosterProvider(entry.provider, ...)` at
|
|
358
|
+
* `ws-history.js:928`) tags a byok client's roster `'claude-byok'` exactly,
|
|
359
|
+
* same registry as claude-sdk/cli/tui. A prior revision of this fix instead
|
|
360
|
+
* excluded `claude-byok` from `knownTags` and explicitly skipped it in the
|
|
361
|
+
* residual, reasoning that connect never refreshed a byok client's own
|
|
362
|
+
* bucket either — but that reasoning rested on a stale reading of #7756
|
|
363
|
+
* (`static claudeFamily = false`) that does not match this class. Excluding
|
|
364
|
+
* it here reproduces the EXACT #7756 bug for a fourth provider: the roster is
|
|
365
|
+
* delivered (via the residual, tagged with the reload's own literal) and
|
|
366
|
+
* discarded, because a byok client's bucket key is `'claude-byok'`, not
|
|
367
|
+
* whatever the residual's literal happens to be. Folding it into the same
|
|
368
|
+
* per-tag treatment as claude-cli/claude-tui is what keeps a reload and a
|
|
369
|
+
* reconnect agreeing on a byok session's roster tag, exactly as they do for
|
|
370
|
+
* the other three.
|
|
371
|
+
*
|
|
372
|
+
* A factory rather than an inline closure so the wiring is a single named
|
|
373
|
+
* reference at the call site AND the behaviour is directly executable in a test
|
|
374
|
+
* — the previous inline closure lived inside `startCliServer()`, which no test
|
|
375
|
+
* can run, so the only available check was a source grep over its body.
|
|
376
|
+
*
|
|
377
|
+
* #7895 — the per-message tagging loop itself (the `tagIsDefault` branch, the
|
|
378
|
+
* known-tags set, the residual fallback) now lives in
|
|
379
|
+
* `broadcastRosterPerRecipient` (`./roster-broadcast.js`), shared with
|
|
380
|
+
* `ws-forwarding.js`'s two `available_models` send sites. This function keeps
|
|
381
|
+
* only what's specific to the overlay-reload wiring: the per-message reload
|
|
382
|
+
* log line and adapting `wsServer._broadcast` to the shared `(msg, filter)`
|
|
383
|
+
* broadcast shape.
|
|
384
|
+
*
|
|
385
|
+
* @param {{ wsServer: { _broadcast: Function }, sessionManager: object, logger?: object, defaultProvider?: string|null }} deps
|
|
386
|
+
* `defaultProvider` is this daemon's resolved default (`config.provider ||
|
|
387
|
+
* DEFAULT_PROVIDER`) — the same value `ws-history.js` feeds
|
|
388
|
+
* `resolveRosterProvider` from `billingCanary.defaultProvider`. Omitted (as
|
|
389
|
+
* every existing caller/test does), `resolveRosterProvider` falls back to
|
|
390
|
+
* `DEFAULT_PROVIDER` itself, which is a true statement only when the daemon
|
|
391
|
+
* was not started with an explicit `--provider` override.
|
|
392
|
+
* @returns {(reload: object) => void}
|
|
393
|
+
*/
|
|
394
|
+
export function createOverlayReloadBroadcaster({ wsServer, sessionManager, logger = log, defaultProvider = null }) {
|
|
395
|
+
return (reload) => {
|
|
396
|
+
for (const message of buildOverlayReloadBroadcasts(reload)) {
|
|
397
|
+
logger.info(`Models overlay reloaded (${message.provider}): ${message.models.map((m) => m.id).join(', ')}`)
|
|
398
|
+
broadcastRosterPerRecipient({
|
|
399
|
+
broadcast: (msg, filter) => wsServer._broadcast(msg, filter),
|
|
400
|
+
sessionManager,
|
|
401
|
+
defaultProvider,
|
|
402
|
+
message,
|
|
403
|
+
})
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
|
|
236
408
|
/**
|
|
237
409
|
* Run `environmentManager.reconnect()` and log a startup summary (#3464).
|
|
238
410
|
*
|
|
@@ -406,6 +578,99 @@ export function resolveStartupTimeouts(config = {}, log = { warn: () => {} }) {
|
|
|
406
578
|
}
|
|
407
579
|
}
|
|
408
580
|
|
|
581
|
+
/**
|
|
582
|
+
* Resolve runtime-skill policy once for both SessionManager construction and
|
|
583
|
+
* startup diagnostics (#7834). Keeping the effective values beside their
|
|
584
|
+
* diagnostic source prevents startup from reporting a policy that was not
|
|
585
|
+
* actually forwarded to provider sessions.
|
|
586
|
+
*
|
|
587
|
+
* Omitted values preserve the documented permissive/no-trust defaults.
|
|
588
|
+
* An explicitly malformed allowlist throws before SessionManager construction:
|
|
589
|
+
* `null` is the loader's permissive sentinel, so falling back to it would fail
|
|
590
|
+
* open on the supervised child's independent config re-read. Unknown trust
|
|
591
|
+
* modes remain disabled and are called out as rejected in diagnostics.
|
|
592
|
+
*
|
|
593
|
+
* @param {object} config merged daemon config
|
|
594
|
+
* @returns {{
|
|
595
|
+
* sessionManagerOptions: {
|
|
596
|
+
* maxSkillBytes: number|null,
|
|
597
|
+
* maxTotalSkillBytes: number|null,
|
|
598
|
+
* providerSkillAllowlist: object|null,
|
|
599
|
+
* trustMismatchMode: 'warn'|'block'|null,
|
|
600
|
+
* },
|
|
601
|
+
* diagnostics: {
|
|
602
|
+
* allowlist: { effective: 'configured'|'disabled', source: 'config'|'default'|'rejected config', providerCount: number },
|
|
603
|
+
* trust: { effective: 'warn'|'block'|'disabled', source: 'config'|'default'|'rejected config' },
|
|
604
|
+
* },
|
|
605
|
+
* }}
|
|
606
|
+
*/
|
|
607
|
+
export function resolveStartupSkillPolicy(config = {}) {
|
|
608
|
+
const hasAllowlist = Object.prototype.hasOwnProperty.call(config, 'providerSkillAllowlist')
|
|
609
|
+
const allowlist = config.providerSkillAllowlist
|
|
610
|
+
const allowlistIsValid = allowlist !== null
|
|
611
|
+
&& typeof allowlist === 'object'
|
|
612
|
+
&& !Array.isArray(allowlist)
|
|
613
|
+
if (hasAllowlist && !allowlistIsValid) {
|
|
614
|
+
const error = new TypeError('Runtime skills: allowlist=rejected (source: config; expected object)')
|
|
615
|
+
error.code = 'INVALID_PROVIDER_SKILL_ALLOWLIST'
|
|
616
|
+
throw error
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
const hasTrustMode = Object.prototype.hasOwnProperty.call(config, 'trustMismatchMode')
|
|
620
|
+
const trustMode = config.trustMismatchMode
|
|
621
|
+
const trustModeIsValid = trustMode === 'warn' || trustMode === 'block'
|
|
622
|
+
|
|
623
|
+
return {
|
|
624
|
+
sessionManagerOptions: {
|
|
625
|
+
// Keep byte budgets in this builder too: all runtime-skill startup
|
|
626
|
+
// options now cross the daemon boundary through one production seam.
|
|
627
|
+
maxSkillBytes: Number.isFinite(config.maxSkillBytes) ? config.maxSkillBytes : null,
|
|
628
|
+
maxTotalSkillBytes: Number.isFinite(config.maxTotalSkillBytes) ? config.maxTotalSkillBytes : null,
|
|
629
|
+
providerSkillAllowlist: allowlistIsValid ? allowlist : null,
|
|
630
|
+
trustMismatchMode: trustModeIsValid ? trustMode : null,
|
|
631
|
+
},
|
|
632
|
+
diagnostics: {
|
|
633
|
+
allowlist: {
|
|
634
|
+
effective: allowlistIsValid ? 'configured' : 'disabled',
|
|
635
|
+
source: allowlistIsValid ? 'config' : 'default',
|
|
636
|
+
providerCount: allowlistIsValid ? Object.keys(allowlist).length : 0,
|
|
637
|
+
},
|
|
638
|
+
trust: {
|
|
639
|
+
effective: trustModeIsValid ? trustMode : 'disabled',
|
|
640
|
+
source: trustModeIsValid ? 'config' : (hasTrustMode ? 'rejected config' : 'default'),
|
|
641
|
+
},
|
|
642
|
+
},
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/** Format the content-free operator diagnostic for resolved skill policy. */
|
|
647
|
+
export function formatStartupSkillPolicyDiagnostic(diagnostics) {
|
|
648
|
+
const allowlist = diagnostics?.allowlist || { effective: 'disabled', source: 'default', providerCount: 0 }
|
|
649
|
+
const trust = diagnostics?.trust || { effective: 'disabled', source: 'default' }
|
|
650
|
+
const providers = allowlist.effective === 'configured'
|
|
651
|
+
? `, providers: ${allowlist.providerCount}`
|
|
652
|
+
: ''
|
|
653
|
+
return `Runtime skills: allowlist=${allowlist.effective} (source: ${allowlist.source}${providers}); trust=${trust.effective} (source: ${trust.source})`
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
/**
|
|
657
|
+
* Construct the daemon SessionManager with its resolved runtime-skill policy.
|
|
658
|
+
* Tests use this same production factory so removing the final constructor
|
|
659
|
+
* forwarding cannot leave a resolver-only test green (#7834).
|
|
660
|
+
*
|
|
661
|
+
* @param {object} config merged daemon config
|
|
662
|
+
* @param {object} sessionManagerOptions remaining daemon constructor options
|
|
663
|
+
* @returns {{ sessionManager: SessionManager, startupSkillPolicy: object }}
|
|
664
|
+
*/
|
|
665
|
+
export function createDaemonSessionManager(config, sessionManagerOptions) {
|
|
666
|
+
const startupSkillPolicy = resolveStartupSkillPolicy(config)
|
|
667
|
+
const sessionManager = new SessionManager({
|
|
668
|
+
...sessionManagerOptions,
|
|
669
|
+
...startupSkillPolicy.sessionManagerOptions,
|
|
670
|
+
})
|
|
671
|
+
return { sessionManager, startupSkillPolicy }
|
|
672
|
+
}
|
|
673
|
+
|
|
409
674
|
export function initFileLoggingFromConfig(config = {}) {
|
|
410
675
|
if (process.env.CHROXY_NO_FILE_LOGGING === '1') {
|
|
411
676
|
return { enabled: false, level: 'info', logDir: null }
|
|
@@ -506,11 +771,12 @@ export async function emergencyCleanup({
|
|
|
506
771
|
// String(err?.message || err) so a non-Error throw (e.g. a Symbol) can't make
|
|
507
772
|
// the log-formatting itself throw and break this best-effort teardown chain.
|
|
508
773
|
try { if (tunnel) await tunnel.stop() } catch (err) { logger?.warn?.(`emergencyCleanup: tunnel.stop failed: ${String(err?.message || err)}`) }
|
|
509
|
-
try { wsServer?.close() } catch (err) { logger?.warn?.(`emergencyCleanup: wsServer.close failed: ${String(err?.message || err)}`) }
|
|
774
|
+
try { await wsServer?.close() } catch (err) { logger?.warn?.(`emergencyCleanup: wsServer.close failed: ${String(err?.message || err)}`) }
|
|
510
775
|
try { mdnsService?.stop?.() } catch {}
|
|
511
776
|
try { bonjourInstance?.destroy?.() } catch {}
|
|
512
777
|
try { tokenManager?.destroy() } catch {}
|
|
513
778
|
try { pairingManager?.destroy() } catch {}
|
|
779
|
+
try { boundedRegex.close() } catch {}
|
|
514
780
|
try { sessionManager?.destroyAll() } catch (err) { logger?.warn?.(`emergencyCleanup: destroyAll failed: ${String(err?.message || err)}`) }
|
|
515
781
|
}
|
|
516
782
|
|
|
@@ -534,6 +800,7 @@ export function emergencyCleanupSync({ kind, tunnel, wsServer, sessionManager, l
|
|
|
534
800
|
try { sessionManager?.serializeState() } catch (serializeErr) {
|
|
535
801
|
logger?.warn?.(`Failed to serialize state during ${kind}: ${String(serializeErr?.stack || serializeErr)}`)
|
|
536
802
|
}
|
|
803
|
+
try { boundedRegex.close() } catch {}
|
|
537
804
|
try { sessionManager?.destroyAll() } catch {}
|
|
538
805
|
try { wsServer?.close() } catch {}
|
|
539
806
|
// NO await — see the invariant above.
|
|
@@ -541,7 +808,75 @@ export function emergencyCleanupSync({ kind, tunnel, wsServer, sessionManager, l
|
|
|
541
808
|
try { removeConnectionInfo() } catch {}
|
|
542
809
|
}
|
|
543
810
|
|
|
811
|
+
// #8029: the set of typed errors `runProviderPreflight` (via
|
|
812
|
+
// SessionManager#createSession) throws for a provider that isn't usable —
|
|
813
|
+
// binary missing/quarantined/unsupported/wrong-provenance/wrong-version, or
|
|
814
|
+
// missing credentials. Kept as an explicit instanceof list (not a
|
|
815
|
+
// duck-typed `err.code` check) and exposed through `isProviderPreflightError`
|
|
816
|
+
// below, so a test can prove the startup
|
|
817
|
+
// default-session guard below only swallows THIS class of failure and lets
|
|
818
|
+
// anything else — a bug, an out-of-memory error, a corrupted state file —
|
|
819
|
+
// still crash loudly instead of being silently absorbed by a broadened net.
|
|
820
|
+
const PROVIDER_PREFLIGHT_ERROR_CLASSES = [
|
|
821
|
+
ProviderBinaryNotFoundError,
|
|
822
|
+
ProviderBinaryQuarantinedError,
|
|
823
|
+
ProviderBinaryProvenanceError,
|
|
824
|
+
ProviderBinaryUnsupportedError,
|
|
825
|
+
ProviderBinaryVersionError,
|
|
826
|
+
ProviderCredentialMissingError,
|
|
827
|
+
]
|
|
828
|
+
|
|
829
|
+
export function isProviderPreflightError(err) {
|
|
830
|
+
return PROVIDER_PREFLIGHT_ERROR_CLASSES.some((ErrorClass) => err instanceof ErrorClass)
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
/**
|
|
834
|
+
* Create the startup default session, or return the already-restored one.
|
|
835
|
+
* Extracted (like `createDaemonSessionManager` above) so the #8029 preflight
|
|
836
|
+
* guard is unit-testable without driving the rest of `startCliServer`'s
|
|
837
|
+
* WS-server/tunnel/push-manager setup.
|
|
838
|
+
*
|
|
839
|
+
* `createSession` runs `runProviderPreflight` for the configured default
|
|
840
|
+
* provider, which throws a typed error (binary missing/quarantined/
|
|
841
|
+
* unsupported/wrong-provenance/wrong-version, or missing credentials) when
|
|
842
|
+
* the provider isn't usable. Without `--skip-checks`, `chroxy start`'s
|
|
843
|
+
* doctor pass (server-cmd.js) catches the same class of failure first and
|
|
844
|
+
* refuses with a readable one-line message before any server state exists.
|
|
845
|
+
* `--skip-checks` reaches this point instead. `restoreState()` (called just
|
|
846
|
+
* before this) already keeps the daemon running when a RESTORED session fails
|
|
847
|
+
* to come back (it catches any restore failure, broader than this guard), so
|
|
848
|
+
* one broken provider does not take the whole process down. This does the
|
|
849
|
+
* same, more narrowly, for the startup default session: log the same readable message and
|
|
850
|
+
* keep starting with no default session, rather than letting an uncaught
|
|
851
|
+
* exception kill a daemon that (a) may serve other, working providers per
|
|
852
|
+
* session and (b) is often the only way to reach this machine remotely to
|
|
853
|
+
* fix the credential/binary problem in the first place.
|
|
854
|
+
*
|
|
855
|
+
* The returned `defaultSessionId` may be `null` — `ws-server.js` already
|
|
856
|
+
* coalesces that (`this.defaultSessionId = defaultSessionId || null`) and
|
|
857
|
+
* every client (dashboard's WelcomeScreen, the app's "No active sessions"
|
|
858
|
+
* states) already renders a clean zero-session state.
|
|
859
|
+
*
|
|
860
|
+
* Anything NOT one of the typed preflight errors is an unexpected failure
|
|
861
|
+
* and must still surface (uncaught), same as before this guard existed.
|
|
862
|
+
*
|
|
863
|
+
* @param {{ sessionManager: SessionManager, defaultSessionId: string|null, logger?: { warn: Function } }} args
|
|
864
|
+
* @returns {string|null}
|
|
865
|
+
*/
|
|
866
|
+
export function createDefaultSessionIfNeeded({ sessionManager, defaultSessionId, logger = log }) {
|
|
867
|
+
if (defaultSessionId) return defaultSessionId
|
|
868
|
+
try {
|
|
869
|
+
return sessionManager.createSession({ name: 'Default' })
|
|
870
|
+
} catch (err) {
|
|
871
|
+
if (!isProviderPreflightError(err)) throw err
|
|
872
|
+
logger.warn(`✗ default session [${err.code}]: ${err.message}`)
|
|
873
|
+
logger.warn('Starting with no default session — fix the provider (see the message above) and create a session from the app or dashboard, or restart once resolved.')
|
|
874
|
+
return null
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
|
|
544
878
|
export async function startCliServer(config) {
|
|
879
|
+
applyCodexBinaryConfig(config)
|
|
545
880
|
// Enable JSON log format if configured
|
|
546
881
|
if (config.logFormat === 'json') {
|
|
547
882
|
setJsonMode(true)
|
|
@@ -549,6 +884,9 @@ export async function startCliServer(config) {
|
|
|
549
884
|
|
|
550
885
|
const fileLogging = initFileLoggingFromConfig(config)
|
|
551
886
|
|
|
887
|
+
// #8270: say so once at startup when the claude data-dir override is unusable.
|
|
888
|
+
warnIfClaudeConfigDirUnusable()
|
|
889
|
+
|
|
552
890
|
// #7162: under a service manager (CHROXY_DAEMON=1) the console streams are
|
|
553
891
|
// captured to files nothing rotates (launchd StandardOutPath et al); the
|
|
554
892
|
// logger's console mirror is how the stdout capture reached 32MB in a
|
|
@@ -570,6 +908,40 @@ export async function startCliServer(config) {
|
|
|
570
908
|
// $CHROXY_HOST_VERSION / _GIT_SHA / _CHANNEL to confirm the exact running build.
|
|
571
909
|
Object.assign(process.env, getChroxyHostEnv())
|
|
572
910
|
|
|
911
|
+
// #8151 (C3) — probe once, before the WS server can accept any real
|
|
912
|
+
// connection, so the very first `list_providers` / `auth_bootstrap` a
|
|
913
|
+
// client sees already reflects reality (claude-tui greyed out when
|
|
914
|
+
// node-pty can't load here, e.g. the official Docker image). Cheap either
|
|
915
|
+
// way (a failed resolution is a fast ENOENT-class failure) and cached for
|
|
916
|
+
// the rest of the process by node-pty-probe.js.
|
|
917
|
+
await probeNodePtyAvailable()
|
|
918
|
+
|
|
919
|
+
// #7240 — state stranded at ~/.chroxy by a CHROXY_CONFIG_DIR relocation.
|
|
920
|
+
//
|
|
921
|
+
// This runs HERE, near the top of startCliServer, and the placement is the
|
|
922
|
+
// point. #7052 logs the resolved root, but that line sits ~500 lines further
|
|
923
|
+
// down — past the `No API token configured` exit below. In the sharpest
|
|
924
|
+
// failure (stranded config.json on a keychain-less host) the daemon exits
|
|
925
|
+
// before it ever says which root it opened, so the operator sees a token
|
|
926
|
+
// error with no hint that a relocation caused it. Warning first is what makes
|
|
927
|
+
// the diagnosis reachable.
|
|
928
|
+
//
|
|
929
|
+
// Detection only — the copy is opt-in via `chroxy config-dir migrate`.
|
|
930
|
+
// Best-effort, like maybeEncryptCredentialsAtRest: never blocks boot.
|
|
931
|
+
//
|
|
932
|
+
// #7244 — an operator running a deliberate second root can acknowledge the
|
|
933
|
+
// CURRENT set with `chroxy config-dir ack`. Only the warning is filtered:
|
|
934
|
+
// `strandedState` stays the raw detection, so the missing-token exit below
|
|
935
|
+
// still names an unmoved config.json even when it was acknowledged. An entry
|
|
936
|
+
// that appears after the acknowledgement is not in the snapshot and warns.
|
|
937
|
+
let strandedState = null
|
|
938
|
+
try {
|
|
939
|
+
strandedState = detectStrandedState()
|
|
940
|
+
for (const line of startupStrandedWarning(strandedState)) log.warn(line)
|
|
941
|
+
} catch (err) {
|
|
942
|
+
log.warn(`Stranded config-dir state check failed: ${err.message}`)
|
|
943
|
+
}
|
|
944
|
+
|
|
573
945
|
const PORT = config.port || parseInt(process.env.PORT || '8765', 10)
|
|
574
946
|
const NO_AUTH = !!config.noAuth
|
|
575
947
|
|
|
@@ -578,7 +950,7 @@ export async function startCliServer(config) {
|
|
|
578
950
|
|
|
579
951
|
// Migrate plaintext token to keychain and remove from config file
|
|
580
952
|
if (!NO_AUTH && config.apiToken && isKeychainAvailable()) {
|
|
581
|
-
const configFile =
|
|
953
|
+
const configFile = configPath('config.json')
|
|
582
954
|
const { migrated } = migrateToken(config)
|
|
583
955
|
// Remove plaintext token from config file (whether newly migrated or already in keychain)
|
|
584
956
|
const keychainToken = getToken()
|
|
@@ -601,7 +973,12 @@ export async function startCliServer(config) {
|
|
|
601
973
|
}
|
|
602
974
|
|
|
603
975
|
if (!NO_AUTH && !API_TOKEN) {
|
|
604
|
-
|
|
976
|
+
// #7240 — when config.json is sitting at ~/.chroxy and the daemon is reading
|
|
977
|
+
// a relocated root, `chroxy init` is the WRONG advice: it mints a brand new
|
|
978
|
+
// token and forces every paired device to re-pair. Name the real cause.
|
|
979
|
+
// The wording lives in missingTokenAdvice so a test can pin it; an
|
|
980
|
+
// acknowledgement (#7244) does not change it.
|
|
981
|
+
for (const line of missingTokenAdvice(strandedState)) console.error(line) // intentional user-facing output
|
|
605
982
|
process.exit(1)
|
|
606
983
|
}
|
|
607
984
|
|
|
@@ -614,7 +991,12 @@ export async function startCliServer(config) {
|
|
|
614
991
|
log.warn(`Credentials at-rest encryption check failed: ${err.message}`)
|
|
615
992
|
}
|
|
616
993
|
|
|
617
|
-
|
|
994
|
+
// #8189: pass the daemon's actually-resolved default through the shared
|
|
995
|
+
// helper rather than the raw `config.provider` field — `buildServerBanner`
|
|
996
|
+
// itself still floors to DEFAULT_PROVIDER internally (its own unit tests
|
|
997
|
+
// call it directly with no provider at all), so this is belt-and-suspenders
|
|
998
|
+
// against the two ever drifting apart, not a behavior change today.
|
|
999
|
+
const banner = buildServerBanner({ version: SERVER_VERSION, provider: resolveDaemonDefaultProvider(config) })
|
|
618
1000
|
const pad = Math.max(0, 38 - banner.length)
|
|
619
1001
|
const left = Math.floor(pad / 2)
|
|
620
1002
|
const right = pad - left
|
|
@@ -654,8 +1036,13 @@ export async function startCliServer(config) {
|
|
|
654
1036
|
// talks chat-completions via the Anthropic↔OpenAI shim. Registered right
|
|
655
1037
|
// after the Anthropic-compatible block (collision-checked against it).
|
|
656
1038
|
registerOpenAiCompatibleProviders(config)
|
|
1039
|
+
// #7319: register config-driven ACP (Agent Client Protocol) agents from
|
|
1040
|
+
// `providers.acp` — one registered provider per configured agent, spawned
|
|
1041
|
+
// over stdio. Permissions ship denied-by-default (#7320 wires the real
|
|
1042
|
+
// bridge). Collision-checked against every provider registered above.
|
|
1043
|
+
registerAcpProviders(config)
|
|
657
1044
|
|
|
658
|
-
const providerType = config
|
|
1045
|
+
const providerType = resolveDaemonDefaultProvider(config)
|
|
659
1046
|
|
|
660
1047
|
// Warm the models registry from disk cache so the picker is populated before
|
|
661
1048
|
// any SDK session fires supportedModels(). Routed through the ACTIVE provider's
|
|
@@ -753,14 +1140,40 @@ export async function startCliServer(config) {
|
|
|
753
1140
|
// a single warning here at boot (not three on each tunable).
|
|
754
1141
|
const startupTimeouts = resolveStartupTimeouts(config, log)
|
|
755
1142
|
|
|
1143
|
+
// #7601: wire the proactive container-liveness poll's inspect seam. A dedicated
|
|
1144
|
+
// DockerBackend (a stateless docker-CLI wrapper — same shape server-cli already
|
|
1145
|
+
// constructs for the compose sweep above) inspects each live containerized
|
|
1146
|
+
// session's container; `inspectContainerLiveness` classifies a rejection so a
|
|
1147
|
+
// Docker-daemon outage can't false-surface a vanish across every session at
|
|
1148
|
+
// once. Safe to wire unconditionally: the poll is a no-op when no containerized
|
|
1149
|
+
// session exists, and docker-cli/docker-sdk sessions can be created even with
|
|
1150
|
+
// the container-environments feature off.
|
|
1151
|
+
const { DockerBackend: LivenessDockerBackend } = await import('./environments/backends/docker.js')
|
|
1152
|
+
const { inspectContainerLiveness } = await import('./docker-session.js')
|
|
1153
|
+
const livenessBackend = new LivenessDockerBackend()
|
|
1154
|
+
const containerInspect = (containerId) =>
|
|
1155
|
+
inspectContainerLiveness((cid) => livenessBackend.getEnvironmentStatus(cid), containerId)
|
|
1156
|
+
|
|
756
1157
|
// 1. Create session manager
|
|
757
|
-
|
|
1158
|
+
// (#8967 — registered right after construction below, so a live Claude model
|
|
1159
|
+
// refresh keeps a row a running session is still on instead of dropping it.)
|
|
1160
|
+
const { sessionManager, startupSkillPolicy } = createDaemonSessionManager(config, {
|
|
758
1161
|
maxSessions: config.maxSessions || 5,
|
|
759
1162
|
port: PORT,
|
|
760
1163
|
apiToken: API_TOKEN,
|
|
761
1164
|
defaultCwd: config.cwd || (isWithinHome(process.cwd()) ? process.cwd() : homedir()),
|
|
762
1165
|
defaultModel: config.model || null,
|
|
763
1166
|
defaultPermissionMode: 'approve',
|
|
1167
|
+
// #7552: so a session created with an `environmentId` is TAGGED onto that
|
|
1168
|
+
// environment for its lifetime (and untagged on teardown). Null when
|
|
1169
|
+
// container environments are off — the block above only constructs one when
|
|
1170
|
+
// the feature is enabled — and every use inside SessionManager is
|
|
1171
|
+
// optional-chained. Ordering matters and already holds: the manager is
|
|
1172
|
+
// constructed AND `reconnect()`ed (which clears every stale session tag from
|
|
1173
|
+
// the previous process) above, before this line runs.
|
|
1174
|
+
environmentManager,
|
|
1175
|
+
// #7601: the proactive container-liveness poll inspect seam (see above).
|
|
1176
|
+
containerInspect,
|
|
764
1177
|
// #5859 (audit P1-7): reclaim orphaned chroxy session worktrees at boot when
|
|
765
1178
|
// the operator opted into worktree auto-reaping. Clean-tree-guarded.
|
|
766
1179
|
sweepOrphanWorktrees: config.worktreeGc?.autoReap === true,
|
|
@@ -776,6 +1189,8 @@ export async function startCliServer(config) {
|
|
|
776
1189
|
// operator set userShell.enabled:true in the config file. Enforced in
|
|
777
1190
|
// SessionManager.createSession so it covers every spawn path.
|
|
778
1191
|
userShellEnabled: isUserShellEnabled(config),
|
|
1192
|
+
// Unnamed sessions are named "<project> <n>" unless the operator sets sessionNaming: 'legacy'.
|
|
1193
|
+
sessionNaming: resolveSessionNaming(config),
|
|
779
1194
|
// #6378: providers opted into unrestricted model validation (serve any
|
|
780
1195
|
// API-valid model id without a release). Empty Set unless the operator set
|
|
781
1196
|
// config.providers.allowAnyModel.
|
|
@@ -787,6 +1202,7 @@ export async function startCliServer(config) {
|
|
|
787
1202
|
binaryProvenanceMode: resolveBinaryProvenanceMode(config),
|
|
788
1203
|
binarySignatureGate: isBinarySignatureGateEnabled(config),
|
|
789
1204
|
providerType,
|
|
1205
|
+
agentConnections: config.agentConnections || [],
|
|
790
1206
|
maxToolInput: config.maxToolInput || null,
|
|
791
1207
|
transforms: config.transforms || [],
|
|
792
1208
|
sessionTimeout: config.sessionTimeout || null,
|
|
@@ -794,6 +1210,9 @@ export async function startCliServer(config) {
|
|
|
794
1210
|
costBudget: config.costBudget || null,
|
|
795
1211
|
// #5665: monthly programmatic-credit budget meter config.
|
|
796
1212
|
billing: config.billing || null,
|
|
1213
|
+
// Session archive retention (`sessionArchive` config block); the archive
|
|
1214
|
+
// directory itself sits next to the session-state file.
|
|
1215
|
+
sessionArchive: config.sessionArchive || null,
|
|
797
1216
|
maxMessages: config.maxMessages || config.maxHistory || null,
|
|
798
1217
|
// #6764: opt-in semantic session titles. Off unless the operator set
|
|
799
1218
|
// features.semanticTitles:true (or CHROXY_SEMANTIC_TITLES=1). The title model
|
|
@@ -836,10 +1255,10 @@ export async function startCliServer(config) {
|
|
|
836
1255
|
// over-24h operator value falls back to null here so byok-mcp-client
|
|
837
1256
|
// applies its default (and the operator gets a warn log).
|
|
838
1257
|
mcpToolCallTimeoutMs: startupTimeouts.mcpToolCallTimeoutMs,
|
|
839
|
-
// Skills size budgets (#3202). null = use loader defaults (32KB / 256KB).
|
|
840
|
-
maxSkillBytes: Number.isFinite(config.maxSkillBytes) ? config.maxSkillBytes : null,
|
|
841
|
-
maxTotalSkillBytes: Number.isFinite(config.maxTotalSkillBytes) ? config.maxTotalSkillBytes : null,
|
|
842
1258
|
})
|
|
1259
|
+
// #8303: a blank New Session cwd inherits this without the explicit-cwd check.
|
|
1260
|
+
const defaultCwdWarning = defaultCwdAdvisory(sessionManager.defaultCwd, config)
|
|
1261
|
+
if (defaultCwdWarning) log.warn(defaultCwdWarning)
|
|
843
1262
|
|
|
844
1263
|
// #3749 / #3899: surface the effective inactivity timeouts at startup so
|
|
845
1264
|
// operators can verify their config overrides took effect.
|
|
@@ -852,6 +1271,9 @@ export async function startCliServer(config) {
|
|
|
852
1271
|
? 'disabled'
|
|
853
1272
|
: `${formatIdleDuration(effectiveStreamStallTimeoutMs)} (${effectiveStreamStallTimeoutMs}ms)`
|
|
854
1273
|
log.info(`Inactivity soft-warning: ${formatIdleDuration(effectiveResultTimeoutMs)} (${effectiveResultTimeoutMs}ms); hard-cap: ${formatIdleDuration(effectiveHardTimeoutMs)} (${effectiveHardTimeoutMs}ms); stream-stall: ${stallLabel}`)
|
|
1274
|
+
log.info(formatStartupSkillPolicyDiagnostic(startupSkillPolicy.diagnostics))
|
|
1275
|
+
|
|
1276
|
+
setInUseModelsProvider(() => sessionManager.listSessions().map((s) => s.model).filter(Boolean))
|
|
855
1277
|
|
|
856
1278
|
// 2. Try restoring session state from a previous instance
|
|
857
1279
|
let defaultSessionId
|
|
@@ -861,9 +1283,7 @@ export async function startCliServer(config) {
|
|
|
861
1283
|
}
|
|
862
1284
|
|
|
863
1285
|
// 3. Create default session if no restore
|
|
864
|
-
|
|
865
|
-
defaultSessionId = sessionManager.createSession({ name: 'Default' })
|
|
866
|
-
}
|
|
1286
|
+
defaultSessionId = createDefaultSessionIfNeeded({ sessionManager, defaultSessionId, logger: log })
|
|
867
1287
|
|
|
868
1288
|
let wsServer
|
|
869
1289
|
|
|
@@ -935,6 +1355,11 @@ export async function startCliServer(config) {
|
|
|
935
1355
|
// (and all timers are .unref()'d, so they never block process exit anyway).
|
|
936
1356
|
statusLineManager.stopSession(sessionId)
|
|
937
1357
|
})
|
|
1358
|
+
// A session whose folder is no longer trusted stops showing the status line that
|
|
1359
|
+
// came from the folder's own settings (Stop trusting, or an edit that revoked it).
|
|
1360
|
+
sessionManager.on('folder_trust_lost', ({ sessionId }) => {
|
|
1361
|
+
statusLineManager.clearProjectOutput(sessionId)
|
|
1362
|
+
})
|
|
938
1363
|
// Turn-boundary refresh for immediacy (mirrors Claude Code's "new assistant
|
|
939
1364
|
// message" trigger); the periodic loop in StatusLineManager covers the rest.
|
|
940
1365
|
sessionManager.on('session_event', ({ sessionId, event }) => {
|
|
@@ -951,10 +1376,10 @@ export async function startCliServer(config) {
|
|
|
951
1376
|
|
|
952
1377
|
// 3. Create push notification manager, token manager, and WebSocket server
|
|
953
1378
|
const pushManager = new PushManager({
|
|
954
|
-
storagePath:
|
|
1379
|
+
storagePath: configPath('push-tokens.json'),
|
|
955
1380
|
// #4541: notification preferences persistence. Co-located in
|
|
956
1381
|
// ~/.chroxy alongside push-tokens.json so cleanup is one step.
|
|
957
|
-
prefsPath:
|
|
1382
|
+
prefsPath: configPath('notification-prefs.json'),
|
|
958
1383
|
// #5413 Phase 2: Discord status-embed sink. Off by default — only
|
|
959
1384
|
// active when a webhook URL resolves from CHROXY_DISCORD_WEBHOOK_URL
|
|
960
1385
|
// or ~/.chroxy/credentials.json (0600). Non-secret knobs (bot name,
|
|
@@ -963,10 +1388,10 @@ export async function startCliServer(config) {
|
|
|
963
1388
|
// (message ids, current state) persists alongside the other
|
|
964
1389
|
// notification state in ~/.chroxy.
|
|
965
1390
|
discord: {
|
|
966
|
-
statePath:
|
|
1391
|
+
statePath: configPath('discord-webhook-state.json'),
|
|
967
1392
|
// #5828: the billing-alert sink keeps its own state file, separate from
|
|
968
1393
|
// the per-project status store above.
|
|
969
|
-
billingStatePath:
|
|
1394
|
+
billingStatePath: configPath('discord-billing-state.json'),
|
|
970
1395
|
...(config.notifications?.discord || {}),
|
|
971
1396
|
},
|
|
972
1397
|
})
|
|
@@ -990,7 +1415,7 @@ export async function startCliServer(config) {
|
|
|
990
1415
|
})
|
|
991
1416
|
pushNotificationHandler.start()
|
|
992
1417
|
|
|
993
|
-
const configFile =
|
|
1418
|
+
const configFile = configPath('config.json')
|
|
994
1419
|
const tokenManager = NO_AUTH ? null : new TokenManager({
|
|
995
1420
|
token: API_TOKEN,
|
|
996
1421
|
tokenExpiry: config.tokenExpiry || null,
|
|
@@ -1090,7 +1515,13 @@ export async function startCliServer(config) {
|
|
|
1090
1515
|
)
|
|
1091
1516
|
// #6598 — persist paired tokens across restarts (encrypted at rest). Honour a
|
|
1092
1517
|
// CHROXY_CONFIG_DIR override so it sits next to config.json / credentials.json.
|
|
1093
|
-
const chroxyDir =
|
|
1518
|
+
const chroxyDir = configDir()
|
|
1519
|
+
// #7052 — state the resolved root once at startup. Every persistent path the
|
|
1520
|
+
// daemon touches now hangs off it, so when an operator relocates the dir and
|
|
1521
|
+
// finds empty trust stores or a missing token, this line is the one thing
|
|
1522
|
+
// that tells them WHICH root the daemon actually opened. Logged
|
|
1523
|
+
// unconditionally: knowing it is `~/.chroxy` is exactly as useful.
|
|
1524
|
+
log.info(`Config/state root: ${chroxyDir}${process.env.CHROXY_CONFIG_DIR ? ' (from CHROXY_CONFIG_DIR)' : ''}`)
|
|
1094
1525
|
const pairingManager = NO_AUTH ? null : new PairingManager({
|
|
1095
1526
|
ttlMs: 60_000,
|
|
1096
1527
|
autoRefresh: true,
|
|
@@ -1109,6 +1540,48 @@ export async function startCliServer(config) {
|
|
|
1109
1540
|
// no timers and spawns nothing.
|
|
1110
1541
|
const schedulerEngine = buildSchedulerEngine({ sessionManager, config, logger: log })
|
|
1111
1542
|
|
|
1543
|
+
// #7424 (step 3 of #7344): watch the PR each session opened and announce a CI
|
|
1544
|
+
// run the moment it SETTLES, to both audiences — a `ci_complete` push for the
|
|
1545
|
+
// user's phone, and one typed line into the session's own prompt so the agent
|
|
1546
|
+
// learns it without spending a turn (and a full cached-context re-read)
|
|
1547
|
+
// polling `gh pr checks`.
|
|
1548
|
+
//
|
|
1549
|
+
// ON by default; `sessionCi.watch: false` returns null here. Everything
|
|
1550
|
+
// decidable lives in buildSessionCiWatcher so it is unit-tested rather than
|
|
1551
|
+
// source-grepped.
|
|
1552
|
+
//
|
|
1553
|
+
// Built BEFORE the WsServer (#7427) because the ws handler ctx carries it: the
|
|
1554
|
+
// dashboard's on-demand `session_pr_status_request` survey hands its snapshot
|
|
1555
|
+
// to `observe()`, which ARMS the watch without waiting on the sweep's
|
|
1556
|
+
// five-minute discovery pass.
|
|
1557
|
+
const sessionCiWatcher = buildSessionCiWatcher({ config, sessionManager, pushManager, logger: log })
|
|
1558
|
+
sessionCiWatcher?.start()
|
|
1559
|
+
|
|
1560
|
+
// #8331: the daily-daemon "update ready" banner. Watches the files the idle-only
|
|
1561
|
+
// auto-deploy script leaves in the config dir and answers the dashboard's
|
|
1562
|
+
// Restart now / Postpone. The idle verdict is the SAME function
|
|
1563
|
+
// GET /api/daemon/idle answers from, so the confirm dialog and the script's own
|
|
1564
|
+
// gate cannot disagree. Harmless on a daemon with no deploy script: with no
|
|
1565
|
+
// files there is nothing to report and nothing to act on.
|
|
1566
|
+
const daemonUpdate = new DaemonUpdateStatus({
|
|
1567
|
+
dir: chroxyDir,
|
|
1568
|
+
getIdleState: () => computeDaemonIdleState({
|
|
1569
|
+
sessionManager,
|
|
1570
|
+
getHookPendingPermissionCount: () => wsServer.getHookPendingPermissionCount(),
|
|
1571
|
+
}),
|
|
1572
|
+
})
|
|
1573
|
+
daemonUpdate.start()
|
|
1574
|
+
|
|
1575
|
+
// The brakes (kill switch + file-backed audit requirement) ride on the store's state().
|
|
1576
|
+
const principalStore = createPrincipalStore()
|
|
1577
|
+
principalStore.attachBrakes(createPrincipalBrakes())
|
|
1578
|
+
const principalJournal = new PrincipalJournal({
|
|
1579
|
+
dir: configPath('principal-journal'),
|
|
1580
|
+
enabled: () => principalStore.hasEntries(),
|
|
1581
|
+
})
|
|
1582
|
+
// A journal whose session no longer exists is dead weight: drop it at boot.
|
|
1583
|
+
try { principalJournal.prune((id) => sessionManager.getSession(id) != null) } catch (err) { log.warn(`principal journal prune failed: ${err?.message || err}`) }
|
|
1584
|
+
|
|
1112
1585
|
wsServer = new WsServer({
|
|
1113
1586
|
port: PORT,
|
|
1114
1587
|
apiToken: API_TOKEN,
|
|
@@ -1117,6 +1590,11 @@ export async function startCliServer(config) {
|
|
|
1117
1590
|
// #6871: nullable — null whenever the scheduled-execution gate is closed (the
|
|
1118
1591
|
// default). The scheduled-tasks handlers report that as "not armed".
|
|
1119
1592
|
schedulerEngine,
|
|
1593
|
+
// #7427: nullable — null when `sessionCi.watch` is off. Handed to handlers
|
|
1594
|
+
// only; server-cli owns its start() above and ServerOrchestrator its stop().
|
|
1595
|
+
sessionCiWatcher,
|
|
1596
|
+
// #8331: closed by wsServer.close().
|
|
1597
|
+
daemonUpdate,
|
|
1120
1598
|
defaultSessionId,
|
|
1121
1599
|
authRequired: !NO_AUTH,
|
|
1122
1600
|
pushManager,
|
|
@@ -1128,6 +1606,15 @@ export async function startCliServer(config) {
|
|
|
1128
1606
|
localhostBypass: !config.encryptLocalhost,
|
|
1129
1607
|
tokenManager,
|
|
1130
1608
|
pairingManager,
|
|
1609
|
+
// #9116: the agent-principal store. Hash-only, 0600, read through the trusted-file
|
|
1610
|
+
// read; an absent store is empty and an untrusted one invalidates every principal.
|
|
1611
|
+
// Nothing can mint a token yet (landing order: S11 first), so on a real install this
|
|
1612
|
+
// is empty.
|
|
1613
|
+
principalStore,
|
|
1614
|
+
// #9118: the normalized event journal behind the principal read path. It records only
|
|
1615
|
+
// while the principal store has an entry, so a daemon with no principals journals
|
|
1616
|
+
// nothing (and writes nothing). 0600 sidecar files in <config dir>/principal-journal.
|
|
1617
|
+
principalJournal,
|
|
1131
1618
|
// #5536 — the identity keypair the WsServer uses to sign each connection's
|
|
1132
1619
|
// ephemeral exchange public key (both eager and discrete paths). Null when
|
|
1133
1620
|
// pinning is unavailable (no-auth / no-encrypt / keychain failure).
|
|
@@ -1167,13 +1654,24 @@ export async function startCliServer(config) {
|
|
|
1167
1654
|
// #5932: hot-reload the ~/.chroxy/models.json overlay on edit — surfacing a
|
|
1168
1655
|
// new model id (or a label/contextWindow/pricing override) is "a config entry,
|
|
1169
1656
|
// not a code change", so it must not require a daemon restart. On a successful
|
|
1170
|
-
// reload, re-broadcast `available_models` for
|
|
1171
|
-
//
|
|
1657
|
+
// reload, re-broadcast `available_models` for every registry the overlay
|
|
1658
|
+
// CHANGED — the default (Claude) one plus each provider-tagged slice (#7722)
|
|
1659
|
+
// — routed so each client only ever receives the roster for the provider its
|
|
1660
|
+
// active session runs on, RE-TAGGED per recipient for the default registry
|
|
1661
|
+
// (#7756) so a claude-cli/claude-tui/claude-byok client's own bucket
|
|
1662
|
+
// refreshes too. A malformed save is ignored (last-good kept).
|
|
1663
|
+
//
|
|
1664
|
+
// #7756: `defaultProvider` mirrors `billingCanaryMonitor`'s own
|
|
1665
|
+
// `getDefaultProvider` below (`resolveDaemonDefaultProvider(config)`) — the
|
|
1666
|
+
// same resolution `ws-history.js` feeds `resolveRosterProvider` via
|
|
1667
|
+
// `billingCanary.defaultProvider` — so a no-session client's roster is
|
|
1668
|
+
// tagged identically whether it arrives on connect or on a reload.
|
|
1172
1669
|
const modelsOverlayWatcher = watchModelsOverlay({
|
|
1173
|
-
onReload: ({
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1670
|
+
onReload: createOverlayReloadBroadcaster({
|
|
1671
|
+
wsServer,
|
|
1672
|
+
sessionManager,
|
|
1673
|
+
defaultProvider: resolveDaemonDefaultProvider(config),
|
|
1674
|
+
}),
|
|
1177
1675
|
})
|
|
1178
1676
|
|
|
1179
1677
|
// #5821 (live wiring): the billing canary. Recomputes the daemon's billing
|
|
@@ -1193,8 +1691,8 @@ export async function startCliServer(config) {
|
|
|
1193
1691
|
const egressCheckEnabled = config.billing?.egressCheck === true
|
|
1194
1692
|
const billingCanaryMonitor = new BillingCanaryMonitor({
|
|
1195
1693
|
getSessions: () => sessionManager.listSessions(),
|
|
1196
|
-
getDefaultProvider: () => config
|
|
1197
|
-
getApiKeyAuth: () => (config
|
|
1694
|
+
getDefaultProvider: () => resolveDaemonDefaultProvider(config),
|
|
1695
|
+
getApiKeyAuth: () => resolveDaemonDefaultProvider(config) === 'claude-sdk' && Boolean(process.env.ANTHROPIC_API_KEY),
|
|
1198
1696
|
broadcast: (msg) => { try { wsServer?.broadcast(msg) } catch { /* best-effort */ } },
|
|
1199
1697
|
logger: log,
|
|
1200
1698
|
resolveEgressIp: egressCheckEnabled ? () => resolvePublicIp() : undefined,
|
|
@@ -1245,6 +1743,10 @@ export async function startCliServer(config) {
|
|
|
1245
1743
|
// Wire session timeout to WsServer viewer checks
|
|
1246
1744
|
sessionManager.setActiveViewersFn((sid) => wsServer.hasActiveViewersForSession(sid))
|
|
1247
1745
|
sessionManager.startSessionTimeouts()
|
|
1746
|
+
// #7601: begin the proactive container-liveness poll (no-op when no
|
|
1747
|
+
// containerInspect seam was wired). Surfaces CONTAINER_VANISHED on an idle
|
|
1748
|
+
// containerized session whose container was stopped/removed externally.
|
|
1749
|
+
sessionManager.startContainerLiveness()
|
|
1248
1750
|
|
|
1249
1751
|
// Advertise via mDNS/Bonjour for local network discovery. Suppressed on a
|
|
1250
1752
|
// loopback bind and when auth is off — see maybeAdvertiseMdns (#5280).
|
|
@@ -1384,14 +1886,25 @@ export async function startCliServer(config) {
|
|
|
1384
1886
|
.catch((err) => log.warn(`worktree auto-reaper failed: ${(err && err.message) || err}`))
|
|
1385
1887
|
}
|
|
1386
1888
|
|
|
1387
|
-
// #
|
|
1388
|
-
//
|
|
1389
|
-
//
|
|
1390
|
-
//
|
|
1391
|
-
//
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1889
|
+
// #7606: orphaned-child reaper — sends SIGKILL to processes a dead session
|
|
1890
|
+
// left behind, reparented to pid 1 inside chroxy's own worktree root (ppid 1
|
|
1891
|
+
// + this uid + cwd under the root + older than minAgeMs). Default ON; the
|
|
1892
|
+
// sweep is a no-op on Windows. Same lazy-import / getter-at-shutdown shape
|
|
1893
|
+
// as the worktree reaper above.
|
|
1894
|
+
let orphanReapTimer = null
|
|
1895
|
+
if (config.orphanReap?.enabled !== false) {
|
|
1896
|
+
import('./orphan-reaper.js')
|
|
1897
|
+
.then(({ startPeriodicOrphanReap }) => { orphanReapTimer = startPeriodicOrphanReap(config, log) })
|
|
1898
|
+
.catch((err) => log.warn(`orphan-reaper failed: ${(err && err.message) || err}`))
|
|
1899
|
+
}
|
|
1900
|
+
|
|
1901
|
+
// #7374 — every provider's stale per-session dirs (claude-tui, claude-cli,
|
|
1902
|
+
// codex app-server, docker-byok — #8047). The body lives in its own module
|
|
1903
|
+
// so the sweep is covered by tests that RUN it; this block used to be
|
|
1904
|
+
// inline and was pinned only by a source grep, which stayed green with the
|
|
1905
|
+
// whole thing behind a false condition. Fire-and-forget: the function never
|
|
1906
|
+
// rejects, and a sweep must never affect startup.
|
|
1907
|
+
sweepStaleProviderDirs(log)
|
|
1395
1908
|
|
|
1396
1909
|
console.log('\nPress Ctrl+C to stop.\n')
|
|
1397
1910
|
|
|
@@ -1418,10 +1931,12 @@ export async function startCliServer(config) {
|
|
|
1418
1931
|
pairingManager,
|
|
1419
1932
|
pushManager,
|
|
1420
1933
|
billingCanaryMonitor,
|
|
1934
|
+
sessionCiWatcher,
|
|
1421
1935
|
orchestrationManager,
|
|
1422
1936
|
schedulerEngine,
|
|
1423
1937
|
modelsOverlayWatcher,
|
|
1424
1938
|
getWorktreeReapTimer: () => worktreeReapTimer,
|
|
1939
|
+
getOrphanReapTimer: () => orphanReapTimer,
|
|
1425
1940
|
emergencyCleanupSync,
|
|
1426
1941
|
removeConnectionInfo,
|
|
1427
1942
|
isPoolEnabled,
|