@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
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
// TunnelLifecycleHandler (#5368 slice c) — extracted from server-cli.js's
|
|
2
|
+
// startCliServer.
|
|
3
|
+
//
|
|
4
|
+
// Owns the Cloudflare tunnel lifecycle: create + start (with emergency cleanup
|
|
5
|
+
// on a start throw), wire the lifecycle events, the `tunnel_recovered` re-verify
|
|
6
|
+
// + QR re-render, the `waitForTunnel` routability wait (with the warming/ready
|
|
7
|
+
// status broadcasts and emergency cleanup on failure), the success QR display,
|
|
8
|
+
// and the post-display pairing-id extension (#2599).
|
|
9
|
+
//
|
|
10
|
+
// All function deps are INJECTED rather than imported: `emergencyCleanup`,
|
|
11
|
+
// `wireTunnelEvents`, and `buildTunnel*Status` live in server-cli.js, so
|
|
12
|
+
// importing them here would be circular; `createTunnel` / `waitForTunnel` are
|
|
13
|
+
// injected so a test can drive the start-failure path (the design's key payoff:
|
|
14
|
+
// "a tunnel.start() throw calls emergencyCleanup without opening a real tunnel")
|
|
15
|
+
// and the success path without real network. Only the pure constants are
|
|
16
|
+
// imported.
|
|
17
|
+
//
|
|
18
|
+
// createAndStart() returns { ok, tunnel }: on a startup failure it runs the full
|
|
19
|
+
// emergency cleanup and returns ok:false (the caller sets process.exitCode and
|
|
20
|
+
// returns — preserving startCliServer's original early-exit), and on success it
|
|
21
|
+
// returns the live tunnel handle for shutdown to stop.
|
|
22
|
+
|
|
23
|
+
import { QUICK_TUNNEL_DNS_SETTLE_MS } from '../tunnel-check.js'
|
|
24
|
+
import { TUNNEL_STATUS_MIN_PROTOCOL_VERSION } from '../ws-server.js'
|
|
25
|
+
|
|
26
|
+
export class TunnelLifecycleHandler {
|
|
27
|
+
/**
|
|
28
|
+
* @param {{
|
|
29
|
+
* createTunnel: Function, emergencyCleanup: Function, wireTunnelEvents: Function,
|
|
30
|
+
* waitForTunnel: Function, buildTunnelWarmingStatus: Function, buildTunnelReadyStatus: Function,
|
|
31
|
+
* config: { port: number, tunnelArg: { mode: string }, tunnelConfig?: object, tunnelName?: string|null, tunnelHostname?: string|null },
|
|
32
|
+
* wsServer: object, startupDisplay: object, pairingManager: (object|null),
|
|
33
|
+
* cleanupRefs: { mdnsService?: object, bonjourInstance?: object, tokenManager?: object, sessionManager: object },
|
|
34
|
+
* logger: object,
|
|
35
|
+
* }} deps
|
|
36
|
+
*/
|
|
37
|
+
constructor({
|
|
38
|
+
createTunnel, emergencyCleanup, wireTunnelEvents, waitForTunnel,
|
|
39
|
+
buildTunnelWarmingStatus, buildTunnelReadyStatus,
|
|
40
|
+
config, wsServer, startupDisplay, pairingManager, cleanupRefs, logger,
|
|
41
|
+
}) {
|
|
42
|
+
this._createTunnel = createTunnel
|
|
43
|
+
this._emergencyCleanup = emergencyCleanup
|
|
44
|
+
this._wireTunnelEvents = wireTunnelEvents
|
|
45
|
+
this._waitForTunnel = waitForTunnel
|
|
46
|
+
this._buildTunnelWarmingStatus = buildTunnelWarmingStatus
|
|
47
|
+
this._buildTunnelReadyStatus = buildTunnelReadyStatus
|
|
48
|
+
this._config = config
|
|
49
|
+
this._wsServer = wsServer
|
|
50
|
+
this._startupDisplay = startupDisplay
|
|
51
|
+
this._pairingManager = pairingManager || null
|
|
52
|
+
this._cleanupRefs = cleanupRefs || {}
|
|
53
|
+
this._log = logger
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// The emergency-cleanup bag — everything started so far, so a startup abort
|
|
57
|
+
// leaves no orphan processes or armed timers holding the event loop alive.
|
|
58
|
+
_cleanupBag(tunnel) {
|
|
59
|
+
const { mdnsService, bonjourInstance, tokenManager, sessionManager } = this._cleanupRefs
|
|
60
|
+
return {
|
|
61
|
+
tunnel,
|
|
62
|
+
wsServer: this._wsServer,
|
|
63
|
+
mdnsService,
|
|
64
|
+
bonjourInstance,
|
|
65
|
+
tokenManager,
|
|
66
|
+
pairingManager: this._pairingManager,
|
|
67
|
+
sessionManager,
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Build + start the tunnel, wait for it to be routable, and display the QR.
|
|
73
|
+
* @returns {Promise<{ ok: boolean, tunnel?: object }>}
|
|
74
|
+
*/
|
|
75
|
+
async createAndStart() {
|
|
76
|
+
const { port, tunnelArg, tunnelConfig, tunnelName, tunnelHostname } = this._config
|
|
77
|
+
const wsServer = this._wsServer
|
|
78
|
+
const startupDisplay = this._startupDisplay
|
|
79
|
+
const pairingManager = this._pairingManager
|
|
80
|
+
const log = this._log
|
|
81
|
+
|
|
82
|
+
// #5368c (Copilot review on #5402): modeLabel is deterministic from the
|
|
83
|
+
// tunnel mode, so compute it up-front instead of after waitForTunnel (as
|
|
84
|
+
// the original did). The tunnel_recovered handler references it and can fire
|
|
85
|
+
// DURING the initial waitForTunnel after an early flap — with the late
|
|
86
|
+
// declaration that hit a TDZ ReferenceError and silently skipped the QR
|
|
87
|
+
// re-render (caught by the handler's try/catch). Same value either way; this
|
|
88
|
+
// just closes the window so a recovery-during-startup actually re-renders.
|
|
89
|
+
const modeLabel = `cloudflare:${tunnelArg.mode}`
|
|
90
|
+
|
|
91
|
+
// 4. Start the tunnel
|
|
92
|
+
const tunnel = this._createTunnel({
|
|
93
|
+
port,
|
|
94
|
+
mode: tunnelArg.mode,
|
|
95
|
+
tunnelConfig,
|
|
96
|
+
tunnelName: tunnelName || null,
|
|
97
|
+
tunnelHostname: tunnelHostname || null,
|
|
98
|
+
})
|
|
99
|
+
let wsUrl, httpUrl
|
|
100
|
+
try {
|
|
101
|
+
({ wsUrl, httpUrl } = await tunnel.start())
|
|
102
|
+
} catch (startErr) {
|
|
103
|
+
const message = `Tunnel start failed: ${startErr.message}`
|
|
104
|
+
log.error(message)
|
|
105
|
+
try { wsServer.broadcastError('tunnel', message, false) } catch {}
|
|
106
|
+
console.error(`\n ✗ ${message}\n`)
|
|
107
|
+
await this._emergencyCleanup(this._cleanupBag(tunnel))
|
|
108
|
+
return { ok: false, tunnel }
|
|
109
|
+
}
|
|
110
|
+
startupDisplay.currentWsUrl = wsUrl
|
|
111
|
+
// #5555 (sub-item 7): seed the WsServer's current public URL so the
|
|
112
|
+
// auth_bootstrap burst can carry it to (re)connecting clients.
|
|
113
|
+
wsServer.setTunnelUrl(wsUrl)
|
|
114
|
+
|
|
115
|
+
// 5. Wire up tunnel lifecycle events (before waitForTunnel to catch early failures)
|
|
116
|
+
this._wireTunnelEvents(tunnel, wsServer)
|
|
117
|
+
|
|
118
|
+
// Newest-recovery-wins guard (audit P2-11): waitForTunnel can take ~90s, so
|
|
119
|
+
// a second tunnel_recovered firing during a prior re-verify would overlap —
|
|
120
|
+
// two loops racing on `currentWsUrl` and double-broadcasting the rotated URL.
|
|
121
|
+
// Each handler claims a generation; after its (long) await it bails if a
|
|
122
|
+
// newer recovery has since superseded it.
|
|
123
|
+
let recoveryGeneration = 0
|
|
124
|
+
|
|
125
|
+
tunnel.on('tunnel_recovered', async ({ httpUrl: newHttpUrl, wsUrl: newWsUrl, attempt }) => {
|
|
126
|
+
// #5314 (WP-1.4) — async event listener: waitForTunnel THROWS on a routine
|
|
127
|
+
// DNS-settle failure, and an unhandled rejection here would hit server-cli's
|
|
128
|
+
// unhandledRejection handler → process.exit(1), crashing the whole server on
|
|
129
|
+
// a recoverable tunnel hiccup. Contain it: log and wait for the next
|
|
130
|
+
// tunnel_recovered retry.
|
|
131
|
+
const myGeneration = ++recoveryGeneration
|
|
132
|
+
try {
|
|
133
|
+
log.info(`Tunnel recovered after ${attempt} attempt(s)`)
|
|
134
|
+
|
|
135
|
+
// Re-verify the new tunnel URL
|
|
136
|
+
await this._waitForTunnel(newHttpUrl, {
|
|
137
|
+
initialDelay: tunnelArg.mode === 'quick' ? QUICK_TUNNEL_DNS_SETTLE_MS : 0,
|
|
138
|
+
})
|
|
139
|
+
|
|
140
|
+
// A newer tunnel_recovered started while we were re-verifying — let it
|
|
141
|
+
// own the URL/QR update so the two don't race or double-broadcast.
|
|
142
|
+
if (myGeneration !== recoveryGeneration) {
|
|
143
|
+
log.info(`Stale tunnel_recovered (generation ${myGeneration}, newest ${recoveryGeneration}) — superseded, skipping`)
|
|
144
|
+
return
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// Only display new QR code if URL actually changed
|
|
148
|
+
if (newWsUrl !== startupDisplay.currentWsUrl) {
|
|
149
|
+
const previousWsUrl = startupDisplay.currentWsUrl
|
|
150
|
+
startupDisplay.currentWsUrl = newWsUrl
|
|
151
|
+
if (pairingManager) pairingManager.refresh()
|
|
152
|
+
await startupDisplay.displayQr(newWsUrl, newHttpUrl, modeLabel)
|
|
153
|
+
wsServer.broadcastStatus(`Tunnel reconnected with new URL: ${newWsUrl}`)
|
|
154
|
+
// #5555 (sub-item 7): push the rotated URL to every connected client
|
|
155
|
+
// so their reconnect path dials the new endpoint instead of the dead
|
|
156
|
+
// one. Best-effort for tunnel-connected clients (their socket rode
|
|
157
|
+
// the now-dead old tunnel); LAN clients keep their socket and get it
|
|
158
|
+
// immediately. Also records the URL on the WsServer so reconnecting
|
|
159
|
+
// clients re-learn it via auth_bootstrap.
|
|
160
|
+
wsServer.broadcastTunnelUrlChanged(newWsUrl, previousWsUrl)
|
|
161
|
+
} else {
|
|
162
|
+
log.info(`Tunnel URL unchanged: ${newWsUrl}`)
|
|
163
|
+
wsServer.broadcastStatus('Tunnel connection recovered')
|
|
164
|
+
}
|
|
165
|
+
} catch (err) {
|
|
166
|
+
log.error(`tunnel_recovered handler failed (will retry on next recovery): ${err?.message || err}`)
|
|
167
|
+
}
|
|
168
|
+
})
|
|
169
|
+
|
|
170
|
+
// 6. Wait for tunnel to be fully routable (DNS propagation)
|
|
171
|
+
// UX landmine #4: waitForTunnel now throws TUNNEL_NOT_ROUTABLE
|
|
172
|
+
// instead of silently proceeding with a broken QR.
|
|
173
|
+
// #2836: phase 'tunnel_warming' is the current wire name. The
|
|
174
|
+
// previous name 'tunnel_verifying' is still accepted by the dashboard
|
|
175
|
+
// handler for backward compatibility with in-flight clients.
|
|
176
|
+
//
|
|
177
|
+
// #2849: gate on protocolVersion >= 2. v1 dashboards render unknown
|
|
178
|
+
// `server_status` payloads as chat messages because they only read
|
|
179
|
+
// `msg.message` (falls through to the legacy plain-status branch).
|
|
180
|
+
// The structured phase field is a v2 addition.
|
|
181
|
+
wsServer.broadcastMinProtocolVersion(TUNNEL_STATUS_MIN_PROTOCOL_VERSION, this._buildTunnelWarmingStatus({ tunnelMode: tunnelArg.mode, tunnelUrl: httpUrl }))
|
|
182
|
+
try {
|
|
183
|
+
await this._waitForTunnel(httpUrl, {
|
|
184
|
+
initialDelay: tunnelArg.mode === 'quick' ? QUICK_TUNNEL_DNS_SETTLE_MS : 0,
|
|
185
|
+
onAttempt: (attempt, maxAttempts) => {
|
|
186
|
+
wsServer.broadcastMinProtocolVersion(
|
|
187
|
+
TUNNEL_STATUS_MIN_PROTOCOL_VERSION,
|
|
188
|
+
this._buildTunnelWarmingStatus({
|
|
189
|
+
tunnelMode: tunnelArg.mode,
|
|
190
|
+
tunnelUrl: httpUrl,
|
|
191
|
+
attempt,
|
|
192
|
+
maxAttempts,
|
|
193
|
+
}),
|
|
194
|
+
)
|
|
195
|
+
},
|
|
196
|
+
})
|
|
197
|
+
} catch (tunnelErr) {
|
|
198
|
+
log.error(tunnelErr.message)
|
|
199
|
+
try { wsServer.broadcastError('tunnel', tunnelErr.message, false) } catch {}
|
|
200
|
+
console.error(`\n ✗ ${tunnelErr.message}\n`)
|
|
201
|
+
// Clean up everything that's been started so we don't leave
|
|
202
|
+
// orphan processes or armed timers holding the event loop alive.
|
|
203
|
+
await this._emergencyCleanup(this._cleanupBag(tunnel))
|
|
204
|
+
return { ok: false, tunnel }
|
|
205
|
+
}
|
|
206
|
+
wsServer.broadcastMinProtocolVersion(TUNNEL_STATUS_MIN_PROTOCOL_VERSION, this._buildTunnelReadyStatus({ tunnelUrl: httpUrl, tunnelMode: tunnelArg.mode }))
|
|
207
|
+
|
|
208
|
+
// 7. Generate connection info (modeLabel computed up-front; see above)
|
|
209
|
+
startupDisplay.currentTunnelMode = modeLabel
|
|
210
|
+
await startupDisplay.displayQr(wsUrl, httpUrl, modeLabel)
|
|
211
|
+
|
|
212
|
+
// Extend the pairing ID validity after first QR display to give the user
|
|
213
|
+
// time to scan. Without this, slow tunnel setup (60-80s) can consume most
|
|
214
|
+
// of the default 60s TTL, causing rotation before the user can scan (#2599).
|
|
215
|
+
if (pairingManager) pairingManager.extendCurrentId()
|
|
216
|
+
|
|
217
|
+
return { ok: true, tunnel }
|
|
218
|
+
}
|
|
219
|
+
}
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Child process entry point for supervised mode.
|
|
3
|
+
*
|
|
4
|
+
* Spawned by supervisor.js via fork(). Runs the CLI server with tunnel=none
|
|
5
|
+
* (supervisor owns the tunnel) and sends IPC messages back.
|
|
6
|
+
*
|
|
7
|
+
* IPC messages sent:
|
|
8
|
+
* { type: 'ready' } — WsServer is listening
|
|
9
|
+
* { type: 'drain_complete' } — All sessions idle, state serialized
|
|
10
|
+
*
|
|
11
|
+
* IPC messages received:
|
|
12
|
+
* { type: 'shutdown' } — Immediate graceful shutdown
|
|
13
|
+
* { type: 'drain', timeout } — Drain in-flight work, serialize state, then ack
|
|
14
|
+
*/
|
|
15
|
+
import { existsSync, readFileSync } from 'fs'
|
|
16
|
+
import { join } from 'path'
|
|
17
|
+
import { homedir } from 'os'
|
|
18
|
+
import { pathToFileURL } from 'url'
|
|
19
|
+
import { mergeConfig } from './config.js'
|
|
20
|
+
import { createLogger } from './logger.js'
|
|
21
|
+
|
|
22
|
+
const log = createLogger('child')
|
|
23
|
+
|
|
24
|
+
const CONFIG_FILE = join(homedir(), '.chroxy', 'config.json')
|
|
25
|
+
|
|
26
|
+
// Module-level references for drain handler access
|
|
27
|
+
let _sessionManager = null
|
|
28
|
+
let _wsServer = null
|
|
29
|
+
|
|
30
|
+
// Guards the flush/exit sequence so a crash arriving during an IPC shutdown
|
|
31
|
+
// (or vice-versa) doesn't double-run it.
|
|
32
|
+
let _shuttingDown = false
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Persist + tear down before the child exits. Mirrors the foreground handler in
|
|
36
|
+
* server-cli.js (#3697): broadcast the shutdown, serialize session state to disk
|
|
37
|
+
* BEFORE destroying anything (losing the user's restored state on stop/crash is
|
|
38
|
+
* worse than risking a partial write), then destroyAll() (idempotent — it
|
|
39
|
+
* serializes again and sets _destroying so late persists no-op) and close the WS.
|
|
40
|
+
*
|
|
41
|
+
* Exported (no process.exit) so it can be unit-tested with fakes. #5308 / WP-0.2.
|
|
42
|
+
*
|
|
43
|
+
* @param {object|null} sessionManager
|
|
44
|
+
* @param {object|null} wsServer
|
|
45
|
+
* @param {string} reason — broadcastShutdown reason ('shutdown' | 'crash')
|
|
46
|
+
* @param {object} [logger]
|
|
47
|
+
*/
|
|
48
|
+
export function flushAndDestroy(sessionManager, wsServer, reason, logger = log) {
|
|
49
|
+
try { if (wsServer) wsServer.broadcastShutdown(reason, 0) } catch {}
|
|
50
|
+
try {
|
|
51
|
+
if (sessionManager) sessionManager.serializeState()
|
|
52
|
+
} catch (err) {
|
|
53
|
+
logger.error(`Failed to serialize session state before ${reason}: ${err?.stack || err}`)
|
|
54
|
+
}
|
|
55
|
+
// Isolate each teardown step so one failure can't abort the rest, but log it —
|
|
56
|
+
// a throw here during a crash/shutdown is exactly when observability matters.
|
|
57
|
+
try {
|
|
58
|
+
if (sessionManager) sessionManager.destroyAll()
|
|
59
|
+
} catch (err) {
|
|
60
|
+
logger.error(`Failed to destroy sessions during ${reason}: ${err?.stack || err}`)
|
|
61
|
+
}
|
|
62
|
+
try {
|
|
63
|
+
if (wsServer) wsServer.close()
|
|
64
|
+
} catch (err) {
|
|
65
|
+
logger.error(`Failed to close WsServer during ${reason}: ${err?.stack || err}`)
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Flush state, then exit. Idempotent via _shuttingDown. The 100ms defer lets the
|
|
70
|
+
// broadcastShutdown frame + socket close flush before the process goes away.
|
|
71
|
+
function gracefulExit(code, reason) {
|
|
72
|
+
// Idempotent: the first call already armed the exit timer below, so a second
|
|
73
|
+
// path firing during the 100ms window (e.g. a crash mid-shutdown) just returns
|
|
74
|
+
// — the in-flight timer guarantees the process exits.
|
|
75
|
+
if (_shuttingDown) return
|
|
76
|
+
_shuttingDown = true
|
|
77
|
+
flushAndDestroy(_sessionManager, _wsServer, reason, log)
|
|
78
|
+
// 100ms defer lets the broadcastShutdown frame + socket close flush first.
|
|
79
|
+
setTimeout(() => process.exit(code), 100)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function main() {
|
|
83
|
+
// Load config (same as cli.js start command)
|
|
84
|
+
let fileConfig = {}
|
|
85
|
+
if (existsSync(CONFIG_FILE)) {
|
|
86
|
+
fileConfig = JSON.parse(readFileSync(CONFIG_FILE, 'utf-8'))
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const defaults = {
|
|
90
|
+
port: 8765,
|
|
91
|
+
noAuth: false,
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const config = mergeConfig({ fileConfig, defaults })
|
|
95
|
+
|
|
96
|
+
// Force tunnel=none — supervisor owns the tunnel
|
|
97
|
+
config.tunnel = 'none'
|
|
98
|
+
|
|
99
|
+
// Set environment variables for backward compatibility
|
|
100
|
+
if (config.apiToken) process.env.API_TOKEN = config.apiToken
|
|
101
|
+
if (config.port) process.env.PORT = String(config.port)
|
|
102
|
+
|
|
103
|
+
const { startCliServer } = await import('./server-cli.js')
|
|
104
|
+
const refs = await startCliServer(config)
|
|
105
|
+
|
|
106
|
+
// Capture references for drain handler
|
|
107
|
+
if (refs) {
|
|
108
|
+
_sessionManager = refs.sessionManager || null
|
|
109
|
+
_wsServer = refs.wsServer || null
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Notify supervisor that we're ready
|
|
113
|
+
if (process.send) {
|
|
114
|
+
process.send({ type: 'ready' })
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Handle drain request from supervisor.
|
|
120
|
+
* 1. Broadcast server_shutdown to connected clients (reason + ETA)
|
|
121
|
+
* 2. Set draining flag on WsServer (reject new input)
|
|
122
|
+
* 3. Wait for all sessions to idle
|
|
123
|
+
* 4. Serialize session state to disk
|
|
124
|
+
* 5. Send drain_complete back to supervisor
|
|
125
|
+
*/
|
|
126
|
+
async function handleDrain(timeout) {
|
|
127
|
+
log.info(`Drain requested (timeout: ${timeout}ms)`)
|
|
128
|
+
|
|
129
|
+
// Broadcast structured shutdown event before draining
|
|
130
|
+
// ETA: drain timeout (~30s) + ~5s for child startup
|
|
131
|
+
if (_wsServer) {
|
|
132
|
+
_wsServer.broadcastShutdown('restart', timeout + 5000)
|
|
133
|
+
_wsServer.setDraining(true)
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// Wait for busy sessions to idle
|
|
137
|
+
if (_sessionManager) {
|
|
138
|
+
const deadline = Date.now() + timeout - 2000 // Leave 2s buffer for serialization
|
|
139
|
+
while (!_sessionManager.allIdle() && Date.now() < deadline) {
|
|
140
|
+
await new Promise((r) => setTimeout(r, 500))
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
if (!_sessionManager.allIdle()) {
|
|
144
|
+
log.warn('Drain timeout reached with sessions still busy, proceeding anyway')
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// Serialize session state
|
|
148
|
+
try {
|
|
149
|
+
_sessionManager.serializeState()
|
|
150
|
+
} catch (err) {
|
|
151
|
+
log.error(`Failed to serialize state: ${err.message}`)
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// Ack drain complete
|
|
156
|
+
if (process.send) {
|
|
157
|
+
process.send({ type: 'drain_complete' })
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Only wire process-global handlers + run main() when this file is the forked
|
|
162
|
+
// entry point. When imported (e.g. unit tests of flushAndDestroy) these side
|
|
163
|
+
// effects must NOT fire — registering crash handlers or starting the server on
|
|
164
|
+
// import would corrupt the test runner. #5308 / WP-0.2.
|
|
165
|
+
const isEntryPoint = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href
|
|
166
|
+
|
|
167
|
+
if (isEntryPoint) {
|
|
168
|
+
// Listen for IPC messages from supervisor
|
|
169
|
+
if (process.send) {
|
|
170
|
+
process.on('message', async (msg) => {
|
|
171
|
+
if (msg.type === 'shutdown') {
|
|
172
|
+
// #5308 (WP-0.2) — the supervisor's stop path sends this IPC and only
|
|
173
|
+
// escalates to an OS SIGTERM at the 5s force-kill fallback, so the
|
|
174
|
+
// child's OS-signal flush handler never runs first. A bare process.exit(0)
|
|
175
|
+
// here therefore lost ALL session state on every supervised stop/restart
|
|
176
|
+
// (the #3697 data-loss class on the supervised hot path). Flush first.
|
|
177
|
+
log.info('Shutdown requested by supervisor')
|
|
178
|
+
gracefulExit(0, 'shutdown')
|
|
179
|
+
return
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
if (msg.type === 'drain') {
|
|
183
|
+
const timeout = msg.timeout || 30000
|
|
184
|
+
await handleDrain(timeout)
|
|
185
|
+
}
|
|
186
|
+
})
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// #5308 (WP-0.2) — crash handlers previously called destroyAll() (which does
|
|
190
|
+
// serialize internally) but omitted the explicit pre-destroy serializeState the
|
|
191
|
+
// foreground handler runs. gracefulExit() now serializes BEFORE destroyAll for
|
|
192
|
+
// parity with server-cli.js, isolating a serialize failure from teardown.
|
|
193
|
+
process.on('uncaughtException', (err) => {
|
|
194
|
+
log.error(`Uncaught exception: ${err?.stack || err}`)
|
|
195
|
+
gracefulExit(1, 'crash')
|
|
196
|
+
})
|
|
197
|
+
|
|
198
|
+
process.on('unhandledRejection', (err) => {
|
|
199
|
+
log.error(`Unhandled rejection: ${err?.stack || err}`)
|
|
200
|
+
gracefulExit(1, 'crash')
|
|
201
|
+
})
|
|
202
|
+
|
|
203
|
+
main().catch((err) => {
|
|
204
|
+
log.error(`Fatal error: ${err?.stack || err}`)
|
|
205
|
+
process.exit(1)
|
|
206
|
+
})
|
|
207
|
+
}
|