@chroxy/server 0.10.0
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 +695 -0
- package/README.md +105 -0
- package/hooks/permission-hook.sh +285 -0
- package/package.json +69 -0
- package/scripts/fix-node-pty-helper.js +44 -0
- package/sidecar/Dockerfile +40 -0
- package/sidecar/PROTOCOL.md +691 -0
- package/sidecar/agent.js +1290 -0
- package/sidecar/package-lock.json +43 -0
- package/sidecar/package.json +17 -0
- package/src/activity-registry.js +491 -0
- package/src/anthropic-compatible-config.js +534 -0
- package/src/anthropic-compatible-session.js +579 -0
- package/src/anthropic-openai-shim.js +109 -0
- package/src/anthropic-openai-translate.js +377 -0
- package/src/auth-probes.js +296 -0
- package/src/background-shell-tracker.js +320 -0
- package/src/background-shells.js +125 -0
- package/src/base-session.js +1518 -0
- package/src/billing-budget.js +191 -0
- package/src/billing-canary-monitor.js +203 -0
- package/src/billing-class.js +149 -0
- package/src/bind-host.js +82 -0
- package/src/built-in-tools/bash-exec.js +167 -0
- package/src/built-in-tools/file-ops.js +198 -0
- package/src/built-in-tools/tool-transforms.js +179 -0
- package/src/builtin-commands.js +107 -0
- package/src/byok-compose-state-shared.js +31 -0
- package/src/byok-compose-state.js +234 -0
- package/src/byok-credentials.js +127 -0
- package/src/byok-event-translator.js +136 -0
- package/src/byok-mcp-client.js +404 -0
- package/src/byok-mcp-config.js +159 -0
- package/src/byok-mcp-fleet.js +214 -0
- package/src/byok-mcp-trust.js +175 -0
- package/src/byok-session.js +2019 -0
- package/src/byok-subagent-profiles.js +101 -0
- package/src/byok-tool-executor.js +813 -0
- package/src/byok-tools.js +271 -0
- package/src/channels/PACKAGING.md +181 -0
- package/src/channels/README.md +99 -0
- package/src/channels/chroxy-channel-server.js +248 -0
- package/src/checkpoint-manager.js +515 -0
- package/src/child-stream-guard.js +38 -0
- package/src/claude-channel-session.js +185 -0
- package/src/claude-model-catalog.js +266 -0
- package/src/claude-stream-parser.js +106 -0
- package/src/claude-tui/form-driver.js +874 -0
- package/src/claude-tui/pty-driver.js +520 -0
- package/src/claude-tui/tested-cli-version.js +22 -0
- package/src/claude-tui-attachments.js +342 -0
- package/src/claude-tui-session.js +4029 -0
- package/src/cli/config-cmd.js +34 -0
- package/src/cli/credentials-cmd.js +59 -0
- package/src/cli/deploy-cmd.js +167 -0
- package/src/cli/doctor-cmd.js +52 -0
- package/src/cli/identity-cmd.js +82 -0
- package/src/cli/init-cmd.js +209 -0
- package/src/cli/pages-cmd.js +167 -0
- package/src/cli/pair-code-cmd.js +108 -0
- package/src/cli/pair-discord-cmd.js +100 -0
- package/src/cli/providers-cmd.js +168 -0
- package/src/cli/server-cmd.js +94 -0
- package/src/cli/service-cmd.js +237 -0
- package/src/cli/session-cmd.js +143 -0
- package/src/cli/shared.js +194 -0
- package/src/cli/shell-cmd.js +130 -0
- package/src/cli/status-cmd.js +204 -0
- package/src/cli/tunnel-cmd.js +101 -0
- package/src/cli/update-cmd.js +45 -0
- package/src/cli/worktree-gc-cmd.js +195 -0
- package/src/cli-session.js +1820 -0
- package/src/cli.js +60 -0
- package/src/codex-app-server-client.js +156 -0
- package/src/codex-app-server-session.js +572 -0
- package/src/codex-session.js +604 -0
- package/src/config.js +1757 -0
- package/src/connection-info.js +42 -0
- package/src/connection-locality.js +55 -0
- package/src/content-blocks.js +42 -0
- package/src/control-room/byok-pool.js +130 -0
- package/src/control-room/constants.js +26 -0
- package/src/control-room/containers.js +258 -0
- package/src/control-room/emulators.js +279 -0
- package/src/control-room/handler-factory.js +142 -0
- package/src/control-room/host-prune.js +387 -0
- package/src/control-room/integrations.js +929 -0
- package/src/control-room/repo-runtime-config.js +239 -0
- package/src/control-room/repo-set.js +162 -0
- package/src/control-room/runners.js +479 -0
- package/src/control-room/simulators.js +223 -0
- package/src/control-room/skills-inventory.js +303 -0
- package/src/control-room/survey.js +685 -0
- package/src/control-room/wsl.js +182 -0
- package/src/conversation-scanner.js +270 -0
- package/src/conversation-scope.js +52 -0
- package/src/conversation-search.js +216 -0
- package/src/cost-budget-manager.js +190 -0
- package/src/credential-cipher.js +179 -0
- package/src/credential-store.js +786 -0
- package/src/credential-test.js +145 -0
- package/src/credentials-file.js +58 -0
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
- package/src/dashboard-next/dist/index.html +13 -0
- package/src/deepseek-credentials.js +58 -0
- package/src/deepseek-session.js +192 -0
- package/src/detect-thinking-keyword.js +67 -0
- package/src/dev-preview.js +227 -0
- package/src/devcontainer-config.js +269 -0
- package/src/device-preferences.js +267 -0
- package/src/diagnostics.js +187 -0
- package/src/diff-parser.js +157 -0
- package/src/discord-credentials.js +188 -0
- package/src/discord-pair-delivery.js +113 -0
- package/src/docker-byok-pool-stats.js +221 -0
- package/src/docker-byok-pool.js +841 -0
- package/src/docker-byok-session.js +2172 -0
- package/src/docker-image-allowlist.js +99 -0
- package/src/docker-sdk-session.js +396 -0
- package/src/docker-session.js +382 -0
- package/src/doctor-billing.js +179 -0
- package/src/doctor.js +667 -0
- package/src/duration.js +77 -0
- package/src/environment-manager.js +753 -0
- package/src/environment-statuses.js +20 -0
- package/src/environments/backends/docker.js +931 -0
- package/src/environments/backends/k8s.js +3030 -0
- package/src/environments/backends/rancher.js +326 -0
- package/src/environments/backends/types.js +332 -0
- package/src/event-ingest.js +546 -0
- package/src/event-normalizer.js +1083 -0
- package/src/external-session-registry.js +0 -0
- package/src/file-store.js +52 -0
- package/src/gemini-session.js +498 -0
- package/src/get-public-ip.js +52 -0
- package/src/git.js +15 -0
- package/src/github-webhook.js +256 -0
- package/src/handler-utils.js +663 -0
- package/src/handlers/checkpoint-handlers.js +202 -0
- package/src/handlers/control-room-handlers.js +1945 -0
- package/src/handlers/conversation-handlers.js +201 -0
- package/src/handlers/credential-handlers.js +247 -0
- package/src/handlers/evaluator-handlers.js +94 -0
- package/src/handlers/feature-handlers.js +332 -0
- package/src/handlers/file-handlers.js +142 -0
- package/src/handlers/ide-handlers.js +238 -0
- package/src/handlers/input-handlers.js +1048 -0
- package/src/handlers/pairing-handlers.js +94 -0
- package/src/handlers/repo-handlers.js +295 -0
- package/src/handlers/session-handlers.js +660 -0
- package/src/handlers/settings-handlers.js +818 -0
- package/src/handlers/skills-handlers.js +682 -0
- package/src/handlers/summarize-handlers.js +172 -0
- package/src/handlers/token-handlers.js +57 -0
- package/src/http-oversize.js +51 -0
- package/src/http-routes.js +1158 -0
- package/src/ide/search.js +268 -0
- package/src/ide/symbols.js +423 -0
- package/src/ip-utils.js +85 -0
- package/src/json-state-file.js +169 -0
- package/src/jsonl-reader.js +187 -0
- package/src/jsonl-subprocess-session.js +441 -0
- package/src/keychain.js +458 -0
- package/src/lan-ip.js +38 -0
- package/src/logger.js +388 -0
- package/src/mailbox-route.js +252 -0
- package/src/mcp-tools.js +46 -0
- package/src/message-transform.js +102 -0
- package/src/metrics.js +67 -0
- package/src/model-discovery.js +288 -0
- package/src/models.js +1426 -0
- package/src/notification-prefs.js +544 -0
- package/src/notifications/discord-billing-sink.js +323 -0
- package/src/notifications/discord-webhook-client.js +187 -0
- package/src/notifications/discord-webhook-sink.js +768 -0
- package/src/notifications/expo-push-sink.js +414 -0
- package/src/notifications/ready-body.js +177 -0
- package/src/notifications/sink-registry.js +98 -0
- package/src/notifications/sink.js +82 -0
- package/src/ollama-session.js +221 -0
- package/src/ollama-tags.js +238 -0
- package/src/openai-compatible-session.js +118 -0
- package/src/pages-store.js +255 -0
- package/src/pairing.js +836 -0
- package/src/path-hash-trust-ledger.js +311 -0
- package/src/per-session-settings.js +366 -0
- package/src/permission-audit.js +120 -0
- package/src/permission-hook.js +257 -0
- package/src/permission-manager.js +829 -0
- package/src/permission-resolver.js +144 -0
- package/src/platform.js +139 -0
- package/src/prompt-evaluator.js +386 -0
- package/src/providers.js +436 -0
- package/src/push.js +565 -0
- package/src/rate-limiter.js +433 -0
- package/src/redaction.js +206 -0
- package/src/sdk-session.js +1773 -0
- package/src/semver.js +92 -0
- package/src/server-cli/push-notification-handler.js +240 -0
- package/src/server-cli/server-orchestrator.js +168 -0
- package/src/server-cli/startup-display.js +146 -0
- package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
- package/src/server-cli-child.js +207 -0
- package/src/server-cli.js +1223 -0
- package/src/server-identity.js +383 -0
- package/src/service.js +835 -0
- package/src/session-context.js +49 -0
- package/src/session-lock.js +60 -0
- package/src/session-manager.js +3257 -0
- package/src/session-message-history.js +511 -0
- package/src/session-preset-trust.js +78 -0
- package/src/session-preset.js +458 -0
- package/src/session-state-persistence.js +307 -0
- package/src/session-timeout-manager.js +166 -0
- package/src/session-token-store.js +83 -0
- package/src/shell-approval-info.js +45 -0
- package/src/shell-approval-store.js +163 -0
- package/src/shell-audit.js +63 -0
- package/src/skills-budget.js +181 -0
- package/src/skills-content-validator.js +106 -0
- package/src/skills-frontmatter.js +422 -0
- package/src/skills-loader.js +1893 -0
- package/src/skills-manager.js +256 -0
- package/src/skills-trust.js +532 -0
- package/src/skills-usage.js +335 -0
- package/src/snapshots-store.js +345 -0
- package/src/ssrf-guard.js +130 -0
- package/src/subagent-counter.js +149 -0
- package/src/summarize-session.js +268 -0
- package/src/supervisor.js +929 -0
- package/src/test-client.js +131 -0
- package/src/token-compare.js +28 -0
- package/src/token-manager.js +220 -0
- package/src/tool-result.js +87 -0
- package/src/transcript-tasks.js +334 -0
- package/src/tunnel/base.js +294 -0
- package/src/tunnel/cloudflare.js +281 -0
- package/src/tunnel/index.js +54 -0
- package/src/tunnel-check.js +84 -0
- package/src/turn-tracker.js +0 -0
- package/src/user-shell-registry.js +218 -0
- package/src/user-shell-session.js +411 -0
- package/src/utils/check-dependencies.js +70 -0
- package/src/utils/concurrency.js +24 -0
- package/src/utils/context-window-learn.js +148 -0
- package/src/utils/error-message.js +25 -0
- package/src/utils/format-bytes.js +35 -0
- package/src/utils/preflight.js +143 -0
- package/src/utils/resolve-binary.js +91 -0
- package/src/utils/respawn-rate-limiter.js +59 -0
- package/src/utils/sleep.js +58 -0
- package/src/utils/spawn-env.js +193 -0
- package/src/utils/validation-patterns.js +23 -0
- package/src/utils/win-spawn.js +98 -0
- package/src/version-check.js +16 -0
- package/src/web-task-manager.js +383 -0
- package/src/worktree-gc.js +418 -0
- package/src/worktree-reaper.js +168 -0
- package/src/ws-auth.js +645 -0
- package/src/ws-broadcaster.js +385 -0
- package/src/ws-client-manager.js +476 -0
- package/src/ws-client-sender.js +115 -0
- package/src/ws-file-ops/browser.js +594 -0
- package/src/ws-file-ops/common.js +163 -0
- package/src/ws-file-ops/git.js +298 -0
- package/src/ws-file-ops/index.js +52 -0
- package/src/ws-file-ops/reader.js +595 -0
- package/src/ws-forwarding.js +543 -0
- package/src/ws-handler-context.js +196 -0
- package/src/ws-history.js +1251 -0
- package/src/ws-message-handlers.js +165 -0
- package/src/ws-permissions.js +676 -0
- package/src/ws-schemas.js +119 -0
- package/src/ws-server.js +2866 -0
package/src/semver.js
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lightweight semver comparison utilities.
|
|
3
|
+
*
|
|
4
|
+
* Parses versions in the form MAJOR.MINOR.PATCH[-prerelease][+build].
|
|
5
|
+
* No external dependencies — uses only string/number operations.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const SEMVER_RE = /^(\d+)\.(\d+)\.(\d+)(?:-([a-zA-Z0-9.]+))?(?:\+[a-zA-Z0-9.]+)?$/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Parse a version string into its components.
|
|
12
|
+
* Returns null if the string is not valid semver.
|
|
13
|
+
*/
|
|
14
|
+
export function parseSemver(str) {
|
|
15
|
+
const cleaned = str.replace(/^v/, '')
|
|
16
|
+
const m = SEMVER_RE.exec(cleaned)
|
|
17
|
+
if (!m) return null
|
|
18
|
+
return {
|
|
19
|
+
major: Number(m[1]),
|
|
20
|
+
minor: Number(m[2]),
|
|
21
|
+
patch: Number(m[3]),
|
|
22
|
+
prerelease: m[4] || null,
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Compare two pre-release strings per semver spec.
|
|
28
|
+
* Returns -1 | 0 | 1.
|
|
29
|
+
*
|
|
30
|
+
* Rules:
|
|
31
|
+
* - No pre-release > any pre-release (1.0.0 > 1.0.0-alpha)
|
|
32
|
+
* - Numeric identifiers compared as integers
|
|
33
|
+
* - String identifiers compared lexically
|
|
34
|
+
* - Numeric < string when types differ
|
|
35
|
+
* - Longer tuple has higher precedence if all preceding ids are equal
|
|
36
|
+
*/
|
|
37
|
+
function comparePre(a, b) {
|
|
38
|
+
if (a === null && b === null) return 0
|
|
39
|
+
// No pre-release is higher precedence than any pre-release
|
|
40
|
+
if (a === null) return 1
|
|
41
|
+
if (b === null) return -1
|
|
42
|
+
|
|
43
|
+
const partsA = a.split('.')
|
|
44
|
+
const partsB = b.split('.')
|
|
45
|
+
const len = Math.max(partsA.length, partsB.length)
|
|
46
|
+
|
|
47
|
+
for (let i = 0; i < len; i++) {
|
|
48
|
+
if (i >= partsA.length) return -1
|
|
49
|
+
if (i >= partsB.length) return 1
|
|
50
|
+
|
|
51
|
+
const numA = /^\d+$/.test(partsA[i]) ? Number(partsA[i]) : null
|
|
52
|
+
const numB = /^\d+$/.test(partsB[i]) ? Number(partsB[i]) : null
|
|
53
|
+
|
|
54
|
+
if (numA !== null && numB !== null) {
|
|
55
|
+
if (numA < numB) return -1
|
|
56
|
+
if (numA > numB) return 1
|
|
57
|
+
} else if (numA !== null) {
|
|
58
|
+
return -1 // numeric < string
|
|
59
|
+
} else if (numB !== null) {
|
|
60
|
+
return 1
|
|
61
|
+
} else {
|
|
62
|
+
if (partsA[i] < partsB[i]) return -1
|
|
63
|
+
if (partsA[i] > partsB[i]) return 1
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return 0
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Compare two semver version strings.
|
|
71
|
+
* Returns -1 if a < b, 0 if a === b, 1 if a > b.
|
|
72
|
+
* Throws if either string is not valid semver.
|
|
73
|
+
*/
|
|
74
|
+
export function compareSemver(a, b) {
|
|
75
|
+
const pa = parseSemver(a)
|
|
76
|
+
const pb = parseSemver(b)
|
|
77
|
+
if (!pa) throw new Error(`Invalid semver: ${a}`)
|
|
78
|
+
if (!pb) throw new Error(`Invalid semver: ${b}`)
|
|
79
|
+
|
|
80
|
+
if (pa.major !== pb.major) return pa.major > pb.major ? 1 : -1
|
|
81
|
+
if (pa.minor !== pb.minor) return pa.minor > pb.minor ? 1 : -1
|
|
82
|
+
if (pa.patch !== pb.patch) return pa.patch > pb.patch ? 1 : -1
|
|
83
|
+
|
|
84
|
+
return comparePre(pa.prerelease, pb.prerelease)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Returns true if version `a` is newer than version `b`.
|
|
89
|
+
*/
|
|
90
|
+
export function isNewer(a, b) {
|
|
91
|
+
return compareSemver(a, b) > 0
|
|
92
|
+
}
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
// PushNotificationHandler (#5368 slice a) — extracted from server-cli.js's
|
|
2
|
+
// startCliServer god function.
|
|
3
|
+
//
|
|
4
|
+
// Owns the entire `session_event` → push-notification path, including the
|
|
5
|
+
// per-session idle-push dedupe (#3866) and the four separately-fixed races it
|
|
6
|
+
// relocates verbatim:
|
|
7
|
+
// - #3866 — per-session dedupe Set so a duplicate `result` can't double-fire
|
|
8
|
+
// the idle push.
|
|
9
|
+
// - #3870 — latch the dedupe SYNCHRONOUSLY before `send()` returns its
|
|
10
|
+
// promise, so a second `result` in the same tick can't pass the gate twice.
|
|
11
|
+
// - #3871 — the `session_event` listener is registered BEFORE wsServer
|
|
12
|
+
// exists, so a `result` from a restoreState-resurrected session can fire
|
|
13
|
+
// while wsServer is still undefined; read it through `getWsServer()` and
|
|
14
|
+
// guard the undefined case rather than capturing it at construction.
|
|
15
|
+
// - #3872 — reset the dedupe on `tool_start` too (not just `stream_start`),
|
|
16
|
+
// because Codex tool-only turns emit `tool_start` without a `stream_start`.
|
|
17
|
+
//
|
|
18
|
+
// Constructor-injection seams (sessionManager / pushManager / getWsServer /
|
|
19
|
+
// logger) make this unit-testable with fakes — the biggest coverage win of the
|
|
20
|
+
// split, since the inline version was impossible to exercise in isolation.
|
|
21
|
+
|
|
22
|
+
import {
|
|
23
|
+
composeReadyNotificationBody,
|
|
24
|
+
readBackgroundTaskSnapshot,
|
|
25
|
+
} from '../notifications/ready-body.js'
|
|
26
|
+
|
|
27
|
+
export class PushNotificationHandler {
|
|
28
|
+
/**
|
|
29
|
+
* @param {{
|
|
30
|
+
* sessionManager: import('events').EventEmitter & { getSession: Function },
|
|
31
|
+
* pushManager: { hasConfiguredSinks: () => boolean, send: Function },
|
|
32
|
+
* getWsServer: () => ({ authenticatedClientCount: number, hasActiveViewersForSession: Function } | undefined),
|
|
33
|
+
* logger: { info: Function, warn: Function, error: Function, debug: Function },
|
|
34
|
+
* }} deps
|
|
35
|
+
* `getWsServer` is a getter (not the instance) because the handler is wired
|
|
36
|
+
* before wsServer is constructed (#3871).
|
|
37
|
+
*/
|
|
38
|
+
constructor({ sessionManager, pushManager, getWsServer, logger }) {
|
|
39
|
+
this._sessionManager = sessionManager
|
|
40
|
+
this._pushManager = pushManager
|
|
41
|
+
this._getWsServer = typeof getWsServer === 'function' ? getWsServer : () => undefined
|
|
42
|
+
this._log = logger
|
|
43
|
+
|
|
44
|
+
// #3866 — explicit per-session dedupe for the idle push. Each entry pins
|
|
45
|
+
// "we already sent an idle push for the current active→idle cycle of this
|
|
46
|
+
// session" so a duplicate `result` event (or a race where the gate flips
|
|
47
|
+
// mid-turn) can't produce two OS-level notifications. Cleared when the
|
|
48
|
+
// session next emits `stream_start`/`tool_start` (next busy cycle) or is
|
|
49
|
+
// destroyed.
|
|
50
|
+
this._idleNotifiedSessions = new Set()
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Attach the listeners. Call once, after pushManager exists and before
|
|
55
|
+
* wsServer is constructed (so an early restoreState event still routes here —
|
|
56
|
+
* the wsServer-undefined branch handles it, #3871).
|
|
57
|
+
*/
|
|
58
|
+
start() {
|
|
59
|
+
this._sessionManager.on('session_event', (e) => this._onSessionEvent(e))
|
|
60
|
+
// The dedupe must clear when a session goes away so a future session that
|
|
61
|
+
// reuses the id can't be wrongly suppressed (the rest of session_destroyed
|
|
62
|
+
// logging stays in server-cli.js).
|
|
63
|
+
this._sessionManager.on('session_destroyed', ({ sessionId }) => {
|
|
64
|
+
this._idleNotifiedSessions.delete(sessionId)
|
|
65
|
+
})
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
_onSessionEvent({ sessionId, event, data }) {
|
|
69
|
+
const log = this._log
|
|
70
|
+
const pushManager = this._pushManager
|
|
71
|
+
const sessionManager = this._sessionManager
|
|
72
|
+
const wsServer = this._getWsServer()
|
|
73
|
+
|
|
74
|
+
// #5413 Phase 2: gate on "any sink configured" rather than the
|
|
75
|
+
// Expo-only `hasTokens` — a Discord-only setup must not have its
|
|
76
|
+
// notifications suppressed here, upstream of the pipeline. The
|
|
77
|
+
// `hasTokens` fallback keeps legacy fakes/PushManager doubles working.
|
|
78
|
+
const hasSinks = typeof pushManager.hasConfiguredSinks === 'function'
|
|
79
|
+
? pushManager.hasConfiguredSinks()
|
|
80
|
+
: pushManager.hasTokens
|
|
81
|
+
|
|
82
|
+
if (event === 'ready') {
|
|
83
|
+
log.info(`Session ${sessionId} ready: ${data.sessionId} (model: ${data.model})`)
|
|
84
|
+
} else if (event === 'error') {
|
|
85
|
+
log.error(`Session ${sessionId} error: ${data.message}`)
|
|
86
|
+
// Error is already broadcast as { type: 'message', messageType: 'error' } through
|
|
87
|
+
// the forwarding path (ws-forwarding.js → EventNormalizer). Don't also broadcastError()
|
|
88
|
+
// here — that produces a duplicate server_error message on every client.
|
|
89
|
+
// Activity update: error (immediate)
|
|
90
|
+
if (hasSinks) {
|
|
91
|
+
const sessionName = sessionManager.getSession(sessionId)?.name
|
|
92
|
+
pushManager.send('activity_error', 'Session error', data.message, {
|
|
93
|
+
sessionId,
|
|
94
|
+
sessionName,
|
|
95
|
+
state: 'error',
|
|
96
|
+
detail: data.message,
|
|
97
|
+
})
|
|
98
|
+
}
|
|
99
|
+
} else if (event === 'result' && data.cost != null) {
|
|
100
|
+
log.info(`Session ${sessionId} query: $${data.cost.toFixed(4)} in ${data.duration}ms`)
|
|
101
|
+
// Note: this arm used to ALSO fire an 'idle' push here ("Claude is waiting")
|
|
102
|
+
// for the same unattended-completion case that the activity_update push below
|
|
103
|
+
// already covers. Because the two pushes used different rate-limit buckets
|
|
104
|
+
// (idle=60s, activity_update=10s) they never deduped each other, so every
|
|
105
|
+
// unattended completion produced two OS-level notifications on the phone.
|
|
106
|
+
// Removed in favor of the single activity_update fire below.
|
|
107
|
+
} else if (event === 'result') {
|
|
108
|
+
// result without cost (e.g. Gemini providers) — log duration if available
|
|
109
|
+
if (data.duration != null) {
|
|
110
|
+
log.info(`Session ${sessionId} query completed in ${data.duration}ms`)
|
|
111
|
+
}
|
|
112
|
+
} else if (event === 'budget_warning') {
|
|
113
|
+
log.warn(`Budget warning: ${data.message}`)
|
|
114
|
+
} else if (event === 'budget_exceeded') {
|
|
115
|
+
log.warn(`Budget exceeded: ${data.message}`)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// Reset the idle-push dedupe at the start of each busy cycle (#3866).
|
|
119
|
+
// Different providers emit different "session became busy" signals:
|
|
120
|
+
// - SDK / Claude CLI turns typically fire stream_start first
|
|
121
|
+
// - Codex tool-only turns can fire tool_start without any stream_start
|
|
122
|
+
// (see codex-session.js _processJsonlLine — `item.type === 'tool_call'`
|
|
123
|
+
// emits tool_start unconditionally)
|
|
124
|
+
// Without clearing on tool_start, a Codex turn that runs a tool and
|
|
125
|
+
// returns no streamed text would leave the dedupe latched, and the
|
|
126
|
+
// *next* turn's result would be wrongly suppressed as "already
|
|
127
|
+
// notified" (#3872, Copilot review).
|
|
128
|
+
if (event === 'stream_start' || event === 'tool_start') {
|
|
129
|
+
this._idleNotifiedSessions.delete(sessionId)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Push notifications for actionable events only (#2612)
|
|
133
|
+
// Intermediate events (stream_start, tool_start) no longer trigger pushes.
|
|
134
|
+
if (!hasSinks && (event === 'result' || event === 'permission_request' || event === 'user_question')) {
|
|
135
|
+
// #3866 diagnostic — silently dropping a push because no delivery
|
|
136
|
+
// channel is configured (no push token ever registered, no Discord
|
|
137
|
+
// webhook) is the most common "I'm getting nothing" failure mode.
|
|
138
|
+
// Surface it at debug so operators can confirm registration happened
|
|
139
|
+
// on their last connect.
|
|
140
|
+
log.debug(`Push suppressed for ${event} on ${sessionId}: no configured notification sinks`)
|
|
141
|
+
}
|
|
142
|
+
if (hasSinks) {
|
|
143
|
+
if (event === 'result') {
|
|
144
|
+
// Session idle push (#3866). Gate on noActiveViewers so the user
|
|
145
|
+
// isn't pinged while actively chatting with this session. The
|
|
146
|
+
// per-session dedupe Set prevents a duplicate `result` from
|
|
147
|
+
// firing twice for the same active→idle transition.
|
|
148
|
+
if (wsServer) {
|
|
149
|
+
const noClients = wsServer.authenticatedClientCount === 0
|
|
150
|
+
const noActiveViewers = !noClients && !wsServer.hasActiveViewersForSession(sessionId)
|
|
151
|
+
const allowed = noClients || noActiveViewers
|
|
152
|
+
const alreadyNotified = this._idleNotifiedSessions.has(sessionId)
|
|
153
|
+
if (allowed && !alreadyNotified) {
|
|
154
|
+
const session = sessionManager.getSession(sessionId)
|
|
155
|
+
const sessionName = session?.name
|
|
156
|
+
// #5438 — enrich the idle body with the #5436 background-task
|
|
157
|
+
// snapshot ("still watching: <task>" / "resumes at HH:MM").
|
|
158
|
+
// Absent snapshot (session type doesn't expose one, or the
|
|
159
|
+
// transcript scan degraded) = no information → body unchanged.
|
|
160
|
+
// The body rides the pipeline to every sink, so the Expo push
|
|
161
|
+
// and the Discord status embed both pick this up.
|
|
162
|
+
const body = composeReadyNotificationBody(readBackgroundTaskSnapshot(session))
|
|
163
|
+
// #3870: latch SYNCHRONOUSLY before send() returns its promise
|
|
164
|
+
// so a second `result` arriving in the same tick can't double-
|
|
165
|
+
// fire (passes the !alreadyNotified gate twice). `send()` now
|
|
166
|
+
// returns a Promise<boolean> — `false` means Expo hard-failed
|
|
167
|
+
// (non-2xx or network throw, both caught inside _sendToTokenSet
|
|
168
|
+
// and surfaced via this return value, NOT via rejection since
|
|
169
|
+
// _sendToTokenSet swallows the throw). On hard failure, log at
|
|
170
|
+
// warn and RELEASE the latch so the next active→idle cycle gets
|
|
171
|
+
// a fresh chance — without this the user was silently dropped
|
|
172
|
+
// *and* permanently latched until the session went busy again.
|
|
173
|
+
this._idleNotifiedSessions.add(sessionId)
|
|
174
|
+
Promise.resolve(
|
|
175
|
+
pushManager.send('activity_update', 'Session idle', body, {
|
|
176
|
+
sessionId,
|
|
177
|
+
sessionName,
|
|
178
|
+
state: 'idle',
|
|
179
|
+
...(data.duration != null && { elapsed: data.duration }),
|
|
180
|
+
})
|
|
181
|
+
).then(ok => {
|
|
182
|
+
if (ok === false) {
|
|
183
|
+
log.warn(`Idle push send failed for ${sessionId} (Expo hard failure)`)
|
|
184
|
+
this._idleNotifiedSessions.delete(sessionId)
|
|
185
|
+
}
|
|
186
|
+
}).catch(err => {
|
|
187
|
+
// Defensive — _sendToTokenSet should never throw, but if a
|
|
188
|
+
// future refactor lets one escape, treat it as hard failure.
|
|
189
|
+
log.warn(`Idle push send failed for ${sessionId}: ${err?.message || err}`)
|
|
190
|
+
this._idleNotifiedSessions.delete(sessionId)
|
|
191
|
+
})
|
|
192
|
+
} else if (!allowed) {
|
|
193
|
+
// Diagnostic for #3866: surface why a push was suppressed so we
|
|
194
|
+
// can tell registration failures apart from "user is viewing".
|
|
195
|
+
log.debug(`Idle push suppressed for ${sessionId}: active viewers present`)
|
|
196
|
+
} else if (alreadyNotified) {
|
|
197
|
+
log.debug(`Idle push suppressed for ${sessionId}: already notified this turn`)
|
|
198
|
+
}
|
|
199
|
+
} else {
|
|
200
|
+
// #3871: session_event listener is registered BEFORE wsServer is
|
|
201
|
+
// constructed, so a result event from a restoreState-resurrected
|
|
202
|
+
// session can fire while wsServer is still undefined. Surface that
|
|
203
|
+
// here at debug so it's not silently dropped — same diagnostic
|
|
204
|
+
// discipline as the no-tokens / active-viewers / already-notified
|
|
205
|
+
// branches above (#3866).
|
|
206
|
+
log.debug(`Idle push suppressed for ${sessionId}: wsServer not yet initialized`)
|
|
207
|
+
}
|
|
208
|
+
} else if (event === 'permission_request') {
|
|
209
|
+
const sessionName = sessionManager.getSession(sessionId)?.name
|
|
210
|
+
pushManager.send('activity_waiting', 'Waiting for approval', `Permission needed: ${data.tool}`, {
|
|
211
|
+
sessionId,
|
|
212
|
+
sessionName,
|
|
213
|
+
state: 'waiting',
|
|
214
|
+
detail: data.tool,
|
|
215
|
+
})
|
|
216
|
+
} else if (event === 'user_question') {
|
|
217
|
+
const sessionName = sessionManager.getSession(sessionId)?.name
|
|
218
|
+
pushManager.send('activity_waiting', 'Input needed', 'Claude has a question', {
|
|
219
|
+
sessionId,
|
|
220
|
+
sessionName,
|
|
221
|
+
state: 'waiting',
|
|
222
|
+
})
|
|
223
|
+
} else if (event === 'inactivity_warning') {
|
|
224
|
+
// #3899: soft inactivity warning replaces the pre-#3899 kill-on-
|
|
225
|
+
// timeout behaviour. Push regardless of active-viewer state — a
|
|
226
|
+
// viewer with the dashboard open but AFK still benefits from the
|
|
227
|
+
// device-level nudge. (The transient UI chip in the dashboard
|
|
228
|
+
// covers the actively-watching case.)
|
|
229
|
+
const sessionName = sessionManager.getSession(sessionId)?.name
|
|
230
|
+
pushManager.send('inactivity_warning', 'Agent quiet for a while', 'Tap to check in', {
|
|
231
|
+
sessionId,
|
|
232
|
+
sessionName,
|
|
233
|
+
state: 'idle_warning',
|
|
234
|
+
prefab: data.prefab,
|
|
235
|
+
idleMs: data.idleMs,
|
|
236
|
+
})
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// ServerOrchestrator (#5368 slice d) — extracted from server-cli.js's
|
|
2
|
+
// startCliServer.
|
|
3
|
+
//
|
|
4
|
+
// Owns the process lifecycle: the `shuttingDown` latch, the graceful
|
|
5
|
+
// `shutdown(signal)` teardown sequence, and the SIGINT / SIGTERM / SIGHUP /
|
|
6
|
+
// uncaughtException / unhandledRejection registrations (the last two via the
|
|
7
|
+
// #5369 `onFatal` factory that calls `emergencyCleanupSync`). This is the
|
|
8
|
+
// silent-failure-prone surface — a missed teardown step orphans processes / hangs
|
|
9
|
+
// exit, and a broken crash handler suppresses Node's default crash-exit — so the
|
|
10
|
+
// sequence is moved verbatim.
|
|
11
|
+
//
|
|
12
|
+
// Two injection details matter:
|
|
13
|
+
// - `getWorktreeReapTimer` is a GETTER, not a value: the timer is assigned
|
|
14
|
+
// inside an async `import().then()` in startCliServer, so it may still be
|
|
15
|
+
// null when this orchestrator is constructed. The original shutdown closure
|
|
16
|
+
// read it at shutdown time — reproduce that with a lazy getter so a
|
|
17
|
+
// late-resolved timer still gets cleared.
|
|
18
|
+
// - `emergencyCleanupSync` is injected because it lives in server-cli.js
|
|
19
|
+
// (importing it here would be circular). `exit` / `exitDelayMs` are injected
|
|
20
|
+
// so tests can drive shutdown + onFatal without killing the test process.
|
|
21
|
+
|
|
22
|
+
import { removeConnectionInfo as defaultRemoveConnectionInfo } from '../connection-info.js'
|
|
23
|
+
import { getSharedPool as defaultGetSharedPool, isPoolEnabled as defaultIsPoolEnabled } from '../docker-byok-pool.js'
|
|
24
|
+
|
|
25
|
+
export class ServerOrchestrator {
|
|
26
|
+
constructor({
|
|
27
|
+
wsServer,
|
|
28
|
+
sessionManager,
|
|
29
|
+
tunnel,
|
|
30
|
+
mdnsService,
|
|
31
|
+
bonjourInstance,
|
|
32
|
+
tokenManager,
|
|
33
|
+
pairingManager,
|
|
34
|
+
pushManager = null,
|
|
35
|
+
billingCanaryMonitor = null,
|
|
36
|
+
modelsOverlayWatcher = null,
|
|
37
|
+
getWorktreeReapTimer,
|
|
38
|
+
emergencyCleanupSync,
|
|
39
|
+
removeConnectionInfo = defaultRemoveConnectionInfo,
|
|
40
|
+
isPoolEnabled = defaultIsPoolEnabled,
|
|
41
|
+
getSharedPool = defaultGetSharedPool,
|
|
42
|
+
logger,
|
|
43
|
+
exit = (code) => process.exit(code),
|
|
44
|
+
exitDelayMs = 100,
|
|
45
|
+
}) {
|
|
46
|
+
this._wsServer = wsServer
|
|
47
|
+
this._sessionManager = sessionManager
|
|
48
|
+
this._tunnel = tunnel
|
|
49
|
+
this._mdnsService = mdnsService
|
|
50
|
+
this._bonjourInstance = bonjourInstance
|
|
51
|
+
this._tokenManager = tokenManager
|
|
52
|
+
this._pairingManager = pairingManager
|
|
53
|
+
this._pushManager = pushManager
|
|
54
|
+
this._billingCanaryMonitor = billingCanaryMonitor
|
|
55
|
+
// #5932: the models.json overlay fs-watcher handle (or null when watching
|
|
56
|
+
// couldn't be established). Closed on shutdown so the watch doesn't outlive
|
|
57
|
+
// the daemon.
|
|
58
|
+
this._modelsOverlayWatcher = modelsOverlayWatcher || null
|
|
59
|
+
this._getWorktreeReapTimer = typeof getWorktreeReapTimer === 'function' ? getWorktreeReapTimer : () => null
|
|
60
|
+
this._emergencyCleanupSync = emergencyCleanupSync
|
|
61
|
+
this._removeConnectionInfo = removeConnectionInfo
|
|
62
|
+
this._isPoolEnabled = isPoolEnabled
|
|
63
|
+
this._getSharedPool = getSharedPool
|
|
64
|
+
this._log = logger
|
|
65
|
+
this._exit = exit
|
|
66
|
+
this._exitDelayMs = exitDelayMs
|
|
67
|
+
|
|
68
|
+
// Idempotent: a second SIGINT/SIGTERM (or a crash arriving mid-shutdown)
|
|
69
|
+
// returns immediately. Without this, the second call ran serializeState()
|
|
70
|
+
// against an already-empty `_sessions` Map and wrote 0 sessions to disk,
|
|
71
|
+
// erasing the user's restored state across upgrade/quit cycles (#3697).
|
|
72
|
+
this._shuttingDown = false
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async shutdown(signal) {
|
|
76
|
+
const log = this._log
|
|
77
|
+
if (this._shuttingDown) {
|
|
78
|
+
log.info(`[${signal}] Shutdown already in progress, ignoring duplicate signal`)
|
|
79
|
+
return
|
|
80
|
+
}
|
|
81
|
+
this._shuttingDown = true
|
|
82
|
+
log.info(`[${signal}] Shutting down...`)
|
|
83
|
+
// Notify connected clients (ETA 0 = not coming back unless supervised)
|
|
84
|
+
this._wsServer.broadcastShutdown('shutdown', 0)
|
|
85
|
+
if (this._mdnsService) {
|
|
86
|
+
try { this._mdnsService.stop?.() } catch {}
|
|
87
|
+
}
|
|
88
|
+
if (this._bonjourInstance) {
|
|
89
|
+
try { this._bonjourInstance.destroy?.() } catch {}
|
|
90
|
+
}
|
|
91
|
+
if (this._tokenManager) this._tokenManager.destroy()
|
|
92
|
+
if (this._pairingManager) this._pairingManager.destroy()
|
|
93
|
+
// #5413: stop the Discord sink's heartbeat. It's unref'd so it wouldn't
|
|
94
|
+
// block exit, but clearing it avoids a refresh PATCH racing shutdown.
|
|
95
|
+
if (this._pushManager) {
|
|
96
|
+
try { this._pushManager.destroy?.() } catch {}
|
|
97
|
+
}
|
|
98
|
+
// #5326 (WP-5.4): stop the periodic worktree reaper. It's unref'd so it
|
|
99
|
+
// wouldn't block exit, but clearing it avoids a sweep racing shutdown.
|
|
100
|
+
const worktreeReapTimer = this._getWorktreeReapTimer()
|
|
101
|
+
if (worktreeReapTimer) clearInterval(worktreeReapTimer)
|
|
102
|
+
// #5932: stop watching ~/.chroxy/models.json so the fs-watch doesn't outlive
|
|
103
|
+
// the daemon. Best-effort — close() never throws but guard anyway.
|
|
104
|
+
if (this._modelsOverlayWatcher) {
|
|
105
|
+
try { this._modelsOverlayWatcher.close?.() } catch {}
|
|
106
|
+
}
|
|
107
|
+
// #5821: stop the billing-canary recompute timer. It's unref'd so it
|
|
108
|
+
// wouldn't block exit, but clearing it avoids a recompute racing shutdown.
|
|
109
|
+
if (this._billingCanaryMonitor) {
|
|
110
|
+
try { this._billingCanaryMonitor.stop() } catch {}
|
|
111
|
+
}
|
|
112
|
+
// Persist sessions before destroying (enables restore on restart)
|
|
113
|
+
try { this._sessionManager.serializeState() } catch (err) {
|
|
114
|
+
log.error(`Failed to serialize session state: ${err?.message || err}`)
|
|
115
|
+
}
|
|
116
|
+
this._sessionManager.destroyAll()
|
|
117
|
+
// #5042: drain the docker-byok across-session pool so the `sleep
|
|
118
|
+
// infinity` containers it holds don't outlive the server. Default-OFF
|
|
119
|
+
// (`isPoolEnabled` returns false unless `CHROXY_DOCKER_BYOK_POOL=1`),
|
|
120
|
+
// so this is a no-op for the common path. When the flag is on, the
|
|
121
|
+
// pool's `docker rm -f` calls run in parallel and we let them settle
|
|
122
|
+
// before `process.exit(0)` strands them.
|
|
123
|
+
if (this._isPoolEnabled(process.env)) {
|
|
124
|
+
try {
|
|
125
|
+
const pool = this._getSharedPool(process.env)
|
|
126
|
+
if (pool) await pool.shutdown()
|
|
127
|
+
} catch (err) {
|
|
128
|
+
log.error(`Failed to drain docker-byok pool: ${err?.message || err}`)
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
this._wsServer.close()
|
|
132
|
+
if (this._tunnel) await this._tunnel.stop()
|
|
133
|
+
this._removeConnectionInfo()
|
|
134
|
+
this._exit(0)
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// #5369: uncaughtException and unhandledRejection share an identical body —
|
|
138
|
+
// one handler taking a `kind` log label. The "during shutdown" branch still
|
|
139
|
+
// just logs + schedules exit (otherwise installing these handlers would
|
|
140
|
+
// suppress Node's default crash-exit and a stuck shutdown — e.g. a hung
|
|
141
|
+
// tunnel.stop() — could leave the process alive forever).
|
|
142
|
+
_onFatal(kind, err) {
|
|
143
|
+
const log = this._log
|
|
144
|
+
if (this._shuttingDown) {
|
|
145
|
+
log.error(`${kind} during shutdown: ${err?.stack || err}`)
|
|
146
|
+
setTimeout(() => this._exit(1), this._exitDelayMs)
|
|
147
|
+
return
|
|
148
|
+
}
|
|
149
|
+
this._shuttingDown = true
|
|
150
|
+
log.error(`${kind}: ${err?.stack || err}`)
|
|
151
|
+
this._emergencyCleanupSync({ kind, tunnel: this._tunnel, wsServer: this._wsServer, sessionManager: this._sessionManager })
|
|
152
|
+
setTimeout(() => this._exit(1), this._exitDelayMs)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Register the signal + crash handlers on `process`. */
|
|
156
|
+
install() {
|
|
157
|
+
process.on('SIGINT', () => { this.shutdown('SIGINT').catch(() => this._exit(1)) })
|
|
158
|
+
process.on('SIGTERM', () => { this.shutdown('SIGTERM').catch(() => this._exit(1)) })
|
|
159
|
+
// #5336: a PTY-owning daemon receives SIGHUP when its controlling terminal
|
|
160
|
+
// closes. Node's default SIGHUP action is to terminate the process, which
|
|
161
|
+
// skips the shutdown() state flush — so the user's session state is lost on
|
|
162
|
+
// terminal close. Chroxy has no config-reload semantics, so route SIGHUP
|
|
163
|
+
// through the same graceful shutdown as SIGINT/SIGTERM.
|
|
164
|
+
process.on('SIGHUP', () => { this.shutdown('SIGHUP').catch(() => this._exit(1)) })
|
|
165
|
+
process.on('uncaughtException', this._onFatal.bind(this, 'Uncaught exception'))
|
|
166
|
+
process.on('unhandledRejection', this._onFatal.bind(this, 'Unhandled rejection'))
|
|
167
|
+
}
|
|
168
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
// StartupDisplay (#5368 slice b) — extracted from server-cli.js's startCliServer.
|
|
2
|
+
//
|
|
3
|
+
// Owns the CLI headless-mode connection display: the QR render + manual
|
|
4
|
+
// connect block + `writeConnectionInfo` side-car (displayQr), the
|
|
5
|
+
// ephemeral-pairing-URL builder (buildPairingUrl), the current-URL/mode display
|
|
6
|
+
// state shared across modes (tunnel / external / LAN), and the QR re-render
|
|
7
|
+
// listeners that fire when the pairing id auto-refreshes or the API token
|
|
8
|
+
// rotates.
|
|
9
|
+
//
|
|
10
|
+
// The tunnel-lifecycle code (still inline in startCliServer; slice c) drives
|
|
11
|
+
// this object: it sets `currentWsUrl` / `currentTunnelMode` and calls
|
|
12
|
+
// `displayQr()` at each mode's success point. displayQr deliberately does NOT
|
|
13
|
+
// mutate the current-URL state — the call sites do, because the tunnel path
|
|
14
|
+
// must set `currentWsUrl` EARLY (before the first displayQr) so a
|
|
15
|
+
// `tunnel_recovered` event arriving mid-startup has a value to diff against.
|
|
16
|
+
//
|
|
17
|
+
// Constructor-injection seams (pairingManager / tokenManager / apiToken /
|
|
18
|
+
// showToken / logger) make the QR/connection-info rendering unit-testable with
|
|
19
|
+
// fakes + captured console output — impossible while it was a closure inside the
|
|
20
|
+
// god function.
|
|
21
|
+
|
|
22
|
+
import QRCode from 'qrcode'
|
|
23
|
+
import { writeConnectionInfo as defaultWriteConnectionInfo } from '../connection-info.js'
|
|
24
|
+
|
|
25
|
+
// #2339: small display helper, also inlined in supervisor.js + covered by
|
|
26
|
+
// mask-token.test.js. Moved here with displayQr (its only server-cli caller).
|
|
27
|
+
export function maskToken(token) {
|
|
28
|
+
if (!token) return ''
|
|
29
|
+
if (token.length <= 8) return token
|
|
30
|
+
return `${token.slice(0, 4)}...${token.slice(-4)}`
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export class StartupDisplay {
|
|
34
|
+
/**
|
|
35
|
+
* @param {{
|
|
36
|
+
* pairingManager: ({ setWsUrl: Function, currentPairingUrl: string, refresh: Function, on: Function } | null),
|
|
37
|
+
* tokenManager: ({ on: Function } | null),
|
|
38
|
+
* apiToken: string,
|
|
39
|
+
* showToken: boolean,
|
|
40
|
+
* logger: { info: Function },
|
|
41
|
+
* writeConnectionInfo?: Function,
|
|
42
|
+
* }} deps
|
|
43
|
+
* `writeConnectionInfo` is an optional injection seam (defaults to the real
|
|
44
|
+
* side-car writer) so tests can capture it without touching ~/.chroxy.
|
|
45
|
+
*/
|
|
46
|
+
constructor({ pairingManager, tokenManager, apiToken, showToken, logger, writeConnectionInfo }) {
|
|
47
|
+
this._pairingManager = pairingManager || null
|
|
48
|
+
this._tokenManager = tokenManager || null
|
|
49
|
+
this._apiToken = apiToken
|
|
50
|
+
this._showToken = !!showToken
|
|
51
|
+
this._log = logger
|
|
52
|
+
this._writeConnectionInfo = writeConnectionInfo || defaultWriteConnectionInfo
|
|
53
|
+
|
|
54
|
+
// Current WebSocket URL + mode label, tracked across all modes (tunnel,
|
|
55
|
+
// external, LAN). Set by the mode branches in startCliServer and read by the
|
|
56
|
+
// re-render listeners below.
|
|
57
|
+
this._currentWsUrl = null
|
|
58
|
+
this._currentTunnelMode = 'none'
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
get currentWsUrl() { return this._currentWsUrl }
|
|
62
|
+
set currentWsUrl(v) { this._currentWsUrl = v }
|
|
63
|
+
get currentTunnelMode() { return this._currentTunnelMode }
|
|
64
|
+
set currentTunnelMode(v) { this._currentTunnelMode = v }
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Build the QR connection URL using the ephemeral pairing id (never the
|
|
68
|
+
* permanent token). Returns null when pairing is disabled (no-auth).
|
|
69
|
+
*/
|
|
70
|
+
buildPairingUrl(wsUrlStr) {
|
|
71
|
+
if (!this._pairingManager) return null
|
|
72
|
+
this._pairingManager.setWsUrl(wsUrlStr)
|
|
73
|
+
return this._pairingManager.currentPairingUrl
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Render the QR code + manual-connect block to the console and write the
|
|
78
|
+
* connection-info side-car. Pure presentation: does NOT mutate
|
|
79
|
+
* currentWsUrl/currentTunnelMode (the caller sets those — see class header).
|
|
80
|
+
*/
|
|
81
|
+
async displayQr(wsUrlStr, httpUrlStr, modeLabel) {
|
|
82
|
+
const pairingUrl = this.buildPairingUrl(wsUrlStr)
|
|
83
|
+
if (pairingUrl) {
|
|
84
|
+
console.log(`\n[✓] Server ready! (CLI headless mode, ${modeLabel})\n`)
|
|
85
|
+
console.log('📱 Scan this QR code with the Chroxy app:\n')
|
|
86
|
+
const qrText = await QRCode.toString(pairingUrl, { type: 'terminal', small: true })
|
|
87
|
+
process.stdout.write(qrText)
|
|
88
|
+
const displayToken = this._showToken ? this._apiToken : maskToken(this._apiToken)
|
|
89
|
+
console.log(`\nOr connect manually:`)
|
|
90
|
+
console.log(` URL: ${wsUrlStr}`)
|
|
91
|
+
console.log(` Token: ${displayToken}`)
|
|
92
|
+
if (httpUrlStr) {
|
|
93
|
+
if (this._showToken) {
|
|
94
|
+
console.log(` Dashboard: ${httpUrlStr}/dashboard?token=${this._apiToken}`)
|
|
95
|
+
} else {
|
|
96
|
+
console.log(` Dashboard: ${httpUrlStr}/dashboard (use --show-token to see full URL)`)
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
this._writeConnectionInfo({
|
|
102
|
+
wsUrl: wsUrlStr,
|
|
103
|
+
httpUrl: httpUrlStr,
|
|
104
|
+
apiToken: this._apiToken,
|
|
105
|
+
connectionUrl: pairingUrl || `chroxy://${wsUrlStr.replace(/^wss?:\/\//, '')}?token=${this._apiToken}`,
|
|
106
|
+
tunnelMode: modeLabel,
|
|
107
|
+
startedAt: new Date().toISOString(),
|
|
108
|
+
pid: process.pid,
|
|
109
|
+
})
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Wire the QR re-render listeners: redraw the terminal QR when the pairing id
|
|
114
|
+
* auto-refreshes (keeps it scannable) and when the API token rotates. Call
|
|
115
|
+
* once after the mode branches have set the initial currentWsUrl.
|
|
116
|
+
*/
|
|
117
|
+
wireReRenderListeners() {
|
|
118
|
+
// Re-render QR code when pairing auto-refreshes (keeps terminal QR scannable)
|
|
119
|
+
if (this._pairingManager) {
|
|
120
|
+
this._pairingManager.on('pairing_refreshed', async () => {
|
|
121
|
+
if (!this._currentWsUrl) return
|
|
122
|
+
const httpBase = this._currentWsUrl.replace(/^wss:\/\//, 'https://').replace(/^ws:\/\//, 'http://')
|
|
123
|
+
await this.displayQr(this._currentWsUrl, httpBase, this._currentTunnelMode)
|
|
124
|
+
this._log.info('QR code refreshed with new pairing ID.')
|
|
125
|
+
})
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Regenerate QR code and update connection info when token rotates
|
|
129
|
+
if (this._tokenManager) {
|
|
130
|
+
this._tokenManager.on('token_rotated', async () => {
|
|
131
|
+
if (!this._currentWsUrl) return // no-auth or localhost-only — no QR to update
|
|
132
|
+
|
|
133
|
+
// Refresh pairing ID when token rotates (old session tokens remain valid).
|
|
134
|
+
// The pairing_refreshed listener handles QR re-render; only call displayQr
|
|
135
|
+
// directly when pairingManager is absent (no pairing_refreshed will fire).
|
|
136
|
+
if (this._pairingManager) {
|
|
137
|
+
this._pairingManager.refresh()
|
|
138
|
+
} else {
|
|
139
|
+
const httpBase = this._currentWsUrl.replace(/^wss:\/\//, 'https://').replace(/^ws:\/\//, 'http://')
|
|
140
|
+
await this.displayQr(this._currentWsUrl, httpBase, this._currentTunnelMode)
|
|
141
|
+
}
|
|
142
|
+
this._log.info('API token rotated. QR code updated.')
|
|
143
|
+
})
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|