@chroxy/server 0.10.0 → 0.11.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONFIG.md +602 -19
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +416 -11
- package/package.json +20 -23
- package/sidecar/Dockerfile +1 -1
- package/sidecar/PROTOCOL.md +9 -1
- package/sidecar/agent.js +102 -10
- package/sidecar/package-lock.json +3 -3
- package/src/acp-config.js +206 -0
- package/src/acp-session.js +954 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +293 -0
- package/src/agent-control/client.js +1616 -0
- package/src/agent-control/events.js +547 -0
- package/src/agent-control/local-connection.js +275 -0
- package/src/agent-control/mcp-server.js +545 -0
- package/src/anthropic-compatible-config.js +29 -4
- package/src/anthropic-compatible-session.js +15 -6
- package/src/anthropic-openai-shim.js +0 -1
- package/src/archive-continuation.js +164 -0
- package/src/assistant-response.js +24 -0
- package/src/auth-probes.js +120 -13
- package/src/background-shell-tracker.js +27 -0
- package/src/base-session.js +1353 -41
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +24 -1
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +101 -0
- package/src/bound-client-policy.js +279 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +74 -9
- package/src/built-in-tools/tool-transforms.js +1113 -13
- package/src/byok-compose-state.js +6 -9
- package/src/byok-credentials.js +2 -3
- package/src/byok-mcp-client.js +1153 -20
- package/src/byok-mcp-config.js +1712 -8
- package/src/byok-mcp-fleet.js +416 -29
- package/src/byok-mcp-oauth-store.js +329 -0
- package/src/byok-mcp-oauth.js +635 -0
- package/src/byok-mcp-trust.js +257 -40
- package/src/byok-session.js +1400 -149
- package/src/byok-tool-executor.js +2681 -38
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +96 -51
- package/src/chroxy-host-metadata.js +122 -0
- package/src/claude-channel-session.js +16 -10
- package/src/claude-model-catalog.js +131 -16
- package/src/claude-model-refresh.js +385 -0
- package/src/claude-model-request.js +103 -0
- package/src/claude-stream-parser.js +109 -3
- package/src/claude-tui/diagnostic-tail.js +83 -0
- package/src/claude-tui/form-driver.js +44 -7
- package/src/claude-tui/model-error.js +41 -0
- package/src/claude-tui/pty-driver.js +223 -60
- package/src/claude-tui/sanitize-question-payload.js +109 -0
- package/src/claude-tui/usage-limit.js +239 -0
- package/src/claude-tui-session.js +3611 -286
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +6 -6
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/deploy-cmd.js +46 -11
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/init-cmd.js +16 -17
- package/src/cli/providers-cmd.js +6 -6
- package/src/cli/schedule-cmd.js +804 -0
- package/src/cli/server-cmd.js +64 -2
- package/src/cli/service-cmd.js +70 -27
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +168 -14
- package/src/cli/tokens-cmd.js +212 -0
- package/src/cli/tunnel-cmd.js +256 -25
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1117 -116
- package/src/cli.js +8 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +2108 -101
- package/src/codex-bundled-client.js +66 -0
- package/src/codex-model-catalog.js +548 -0
- package/src/codex-model-rejections.js +87 -0
- package/src/codex-native-resume.js +104 -0
- package/src/codex-protocol-capabilities.js +188 -0
- package/src/codex-session.js +571 -45
- package/src/config-dir-migration.js +444 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +738 -52
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +5 -9
- package/src/connection-locality.js +60 -0
- package/src/container-liveness-monitor.js +189 -0
- package/src/continuation-metadata-worker.js +17 -0
- package/src/continuations.js +114 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +23 -30
- package/src/control-room/skills-inventory.js +8 -3
- package/src/control-room/survey.js +32 -0
- package/src/conversation-scanner.js +40 -18
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +24 -22
- package/src/credential-store.js +279 -29
- package/src/daemon-commit.js +92 -0
- package/src/daemon-idle-state.js +171 -0
- package/src/daemon-update-status.js +314 -0
- package/src/dashboard-build.js +70 -0
- package/src/declared-status.js +90 -0
- package/src/deepseek-credentials.js +2 -3
- package/src/dev-preview.js +169 -182
- package/src/device-preferences.js +2 -2
- package/src/diagnostics.js +3 -0
- package/src/diff-parser.js +87 -0
- package/src/discord-credentials.js +2 -3
- package/src/docker-byok-pool.js +3 -1
- package/src/docker-byok-session.js +678 -78
- package/src/docker-image-allowlist.js +23 -1
- package/src/docker-sdk-session.js +188 -4
- package/src/docker-session.js +293 -10
- package/src/doctor.js +783 -66
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +95 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +39 -10
- package/src/environments/backends/k8s.js +58 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +137 -14
- package/src/event-normalizer.js +363 -110
- package/src/external-session-registry.js +0 -0
- package/src/gemini-session.js +100 -7
- package/src/github-webhook.js +188 -4
- package/src/handler-utils.js +563 -62
- package/src/handlers/checkpoint-handlers.js +162 -20
- package/src/handlers/control-room-handlers.js +99 -29
- package/src/handlers/conversation-handlers.js +563 -25
- package/src/handlers/credential-handlers.js +43 -2
- package/src/handlers/daemon-update-handlers.js +81 -0
- package/src/handlers/evaluator-handlers.js +14 -1
- package/src/handlers/feature-handlers.js +186 -69
- package/src/handlers/file-handlers.js +101 -13
- package/src/handlers/github-webhook-handlers.js +204 -0
- package/src/handlers/input-handlers.js +689 -48
- package/src/handlers/orchestration-handlers.js +238 -0
- package/src/handlers/scheduler-handlers.js +584 -0
- package/src/handlers/session-handlers.js +546 -16
- package/src/handlers/session-pr-status-handlers.js +283 -0
- package/src/handlers/session-pr-threads-handlers.js +247 -0
- package/src/handlers/settings-handlers.js +822 -35
- package/src/handlers/skills-handlers.js +13 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/handlers/token-handlers.js +11 -2
- package/src/health-proof.js +40 -0
- package/src/history-page.js +104 -0
- package/src/http-routes.js +286 -8
- package/src/ide/search.js +24 -6
- package/src/ide/symbols.js +20 -6
- package/src/input-context.js +117 -0
- package/src/instruction-policy-compiler.js +229 -0
- package/src/instruction-policy.js +250 -0
- package/src/jsonl-reader.js +309 -48
- package/src/jsonl-subprocess-session.js +122 -9
- package/src/keychain.js +160 -13
- package/src/logger.js +240 -31
- package/src/mailbox-route.js +11 -22
- package/src/message-wire.js +386 -0
- package/src/model-discovery.js +43 -3
- package/src/models.js +1276 -174
- package/src/notification-prefs.js +100 -10
- package/src/notifications/discord-billing-sink.js +22 -5
- package/src/notifications/discord-ci-sink.js +243 -0
- package/src/notifications/discord-webhook-client.js +71 -0
- package/src/notifications/discord-webhook-sink.js +82 -12
- package/src/notifications/expo-push-sink.js +85 -6
- package/src/notifications/ready-body.js +16 -5
- package/src/ollama-session.js +34 -2
- package/src/orchestration/build-manager.js +63 -0
- package/src/orchestration/decision-contract.js +245 -0
- package/src/orchestration/git-ops.js +381 -0
- package/src/orchestration/orchestration-manager.js +1342 -0
- package/src/orchestration/permission-gate.js +121 -0
- package/src/orchestration/role-prompts.js +136 -0
- package/src/orchestration/run-budget.js +81 -0
- package/src/orchestration/run-ledger.js +487 -0
- package/src/orchestration/run-model.js +206 -0
- package/src/orchestration/run-record.js +336 -0
- package/src/orchestration/run-report.js +194 -0
- package/src/orchestration/to-wire.js +201 -0
- package/src/orchestration/turn-driver.js +422 -0
- package/src/orphan-reaper.js +413 -0
- package/src/outgoing-policy.js +183 -0
- package/src/pairing.js +236 -12
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-audit.js +79 -3
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1770 -0
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +1175 -94
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolver.js +174 -12
- package/src/permission-rule-store.js +411 -0
- package/src/permission-scope.js +43 -0
- package/src/platform.js +483 -23
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +228 -6
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +360 -8
- package/src/roster-broadcast.js +186 -0
- package/src/schedule-parser.js +311 -0
- package/src/scheduled-task-store.js +945 -0
- package/src/scheduler.js +1099 -0
- package/src/sdk-session.js +2374 -168
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +11 -2
- package/src/server-cli/server-orchestrator.js +50 -4
- package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +760 -62
- package/src/server-identity.js +42 -14
- package/src/service.js +682 -53
- package/src/session-archive-limits.js +15 -0
- package/src/session-archive.js +1029 -0
- package/src/session-busy-state.js +72 -0
- package/src/session-ci-watcher.js +926 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +3879 -308
- package/src/session-message-history.js +749 -37
- package/src/session-pr-status.js +654 -0
- package/src/session-pr-threads.js +271 -0
- package/src/session-preset-trust.js +3 -3
- package/src/session-preset.js +10 -5
- package/src/session-state-persistence.js +94 -17
- package/src/session-timeout-manager.js +20 -0
- package/src/session-title.js +168 -0
- package/src/session-token-store.js +70 -36
- package/src/session-wake.js +240 -0
- package/src/shell-approval-info.js +2 -2
- package/src/shell-approval-store.js +3 -1
- package/src/skills-loader.js +7 -4
- package/src/skills-manager.js +2 -2
- package/src/skills-trust.js +95 -13
- package/src/skills-usage.js +22 -5
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +596 -0
- package/src/subagent-counter.js +9 -1
- package/src/summarize-session.js +51 -4
- package/src/supervisor.js +99 -38
- package/src/sweep-stale-provider-dirs.js +95 -0
- package/src/thinking-level-wire.js +39 -0
- package/src/thinking-stream.js +179 -0
- package/src/token-manager.js +39 -9
- package/src/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +413 -31
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +145 -35
- package/src/tunnel/index.js +13 -1
- package/src/tunnel/preview.js +64 -0
- package/src/tunnel-check.js +1 -1
- package/src/turn-outcome.js +137 -0
- package/src/turn-tracker.js +0 -0
- package/src/usage-normalize.js +122 -0
- package/src/user-shell-session.js +157 -37
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +741 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +597 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +25 -0
- package/src/utils/bounded-regex.js +153 -0
- package/src/utils/claude-binary.js +43 -0
- package/src/utils/claude-config-dir.js +245 -0
- package/src/utils/claude-login-command.js +16 -0
- package/src/utils/claude-native-route.js +81 -0
- package/src/utils/componentwise-resolver.js +301 -0
- package/src/utils/composite-key.js +45 -0
- package/src/utils/deploy-control-files.js +87 -0
- package/src/utils/exec-failure-reason.js +21 -0
- package/src/utils/git-repo.js +42 -0
- package/src/utils/is-entry-point.js +137 -0
- package/src/utils/iso-datetime.js +51 -0
- package/src/utils/node-pty-probe.js +95 -0
- package/src/utils/node-pty-support.js +118 -0
- package/src/utils/opened-file-path.js +167 -0
- package/src/utils/path-containment.js +165 -0
- package/src/utils/permission-mode-sidecar.js +51 -0
- package/src/utils/preflight.js +485 -29
- package/src/utils/read-limiter.js +217 -0
- package/src/utils/regular-file.js +375 -0
- package/src/utils/safe-regex.js +113 -0
- package/src/utils/small-file.js +129 -0
- package/src/utils/spawn-env.js +196 -5
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-binary.js +276 -0
- package/src/utils/verify-provenance.js +634 -0
- package/src/utils/wire-counters.js +48 -0
- package/src/web-task-manager.js +256 -16
- package/src/worktree-gc.js +11 -3
- package/src/ws-auth.js +69 -21
- package/src/ws-broadcaster.js +14 -2
- package/src/ws-client-manager.js +16 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +370 -66
- package/src/ws-file-ops/common.js +384 -11
- package/src/ws-file-ops/git.js +615 -44
- package/src/ws-file-ops/index.js +7 -0
- package/src/ws-file-ops/memory.js +460 -0
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +676 -94
- package/src/ws-forwarding.js +373 -55
- package/src/ws-handler-context.js +89 -2
- package/src/ws-history.js +1018 -177
- package/src/ws-message-handlers.js +23 -1
- package/src/ws-outbound-schemas.js +207 -0
- package/src/ws-permissions.js +589 -38
- package/src/ws-schemas.js +6 -0
- package/src/ws-server.js +936 -105
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
- package/src/dashboard-next/dist/index.html +0 -13
package/src/service.js
CHANGED
|
@@ -1,13 +1,20 @@
|
|
|
1
1
|
import { homedir, platform } from 'os'
|
|
2
|
-
import { join, dirname } from 'path'
|
|
3
|
-
import { existsSync, readFileSync, mkdirSync, unlinkSync, readdirSync, writeFileSync, chmodSync } from 'fs'
|
|
4
|
-
import { writeFileRestricted } from './platform.js'
|
|
2
|
+
import { join, dirname, resolve, win32 as pathWin32 } from 'path'
|
|
3
|
+
import { existsSync, readFileSync, mkdirSync, unlinkSync, readdirSync, writeFileSync, chmodSync, realpathSync, statSync } from 'fs'
|
|
4
|
+
import { writeFileRestricted, isWindows } from './platform.js'
|
|
5
5
|
import { execFileSync } from 'child_process'
|
|
6
6
|
import { fileURLToPath } from 'url'
|
|
7
|
+
import { configDir, configPath } from './config-dir.js'
|
|
7
8
|
|
|
8
9
|
const SERVICE_LABEL = 'com.chroxy.server'
|
|
9
|
-
|
|
10
|
+
function defaultConfigDir() {
|
|
11
|
+
return configDir()
|
|
12
|
+
}
|
|
10
13
|
const WRAPPER_NAME = 'service-wrapper.sh'
|
|
14
|
+
// Windows Task Scheduler autostart (#6647). The task name the daemon registers
|
|
15
|
+
// under, and the .cmd wrapper it runs (the Windows analogue of WRAPPER_NAME).
|
|
16
|
+
const WINDOWS_TASK_NAME = 'Chroxy'
|
|
17
|
+
const WINDOWS_WRAPPER_NAME = 'service-wrapper.cmd'
|
|
11
18
|
|
|
12
19
|
// Keychain coordinates for secrets resolved by the service wrapper at spawn
|
|
13
20
|
// time. The api-token pair mirrors keychain.js (service 'chroxy', account
|
|
@@ -37,7 +44,7 @@ function escapeXml(str) {
|
|
|
37
44
|
* @param {string} [plat] - Override platform (defaults to process.platform)
|
|
38
45
|
*/
|
|
39
46
|
export function getServicePaths(plat = platform()) {
|
|
40
|
-
const logDir =
|
|
47
|
+
const logDir = configPath('logs')
|
|
41
48
|
|
|
42
49
|
if (plat === 'darwin') {
|
|
43
50
|
return {
|
|
@@ -68,6 +75,28 @@ export function getServicePaths(plat = platform()) {
|
|
|
68
75
|
/**
|
|
69
76
|
* Generate a macOS launchd plist XML string.
|
|
70
77
|
*/
|
|
78
|
+
/**
|
|
79
|
+
* The config root to bake into a generated service definition, or null.
|
|
80
|
+
*
|
|
81
|
+
* launchd's `EnvironmentVariables` dict and systemd's `Environment=` lines are
|
|
82
|
+
* the daemon's ENTIRE environment — neither inherits the shell that ran
|
|
83
|
+
* `chroxy service install`. Since #7052 every path the installer resolves
|
|
84
|
+
* (logDir, service.json, the wrapper) follows CHROXY_CONFIG_DIR, so omitting it
|
|
85
|
+
* here would start a daemon whose logs land in the relocated root while its
|
|
86
|
+
* state goes to ~/.chroxy: the same split-brain #7052 exists to remove, moved
|
|
87
|
+
* to the service boundary, and one the operator cannot fix from their shell.
|
|
88
|
+
*
|
|
89
|
+
* Emitted only when set, so a default install produces a byte-identical
|
|
90
|
+
* definition to before. Injectable for tests.
|
|
91
|
+
*
|
|
92
|
+
* @param {object} config
|
|
93
|
+
* @returns {string|null}
|
|
94
|
+
*/
|
|
95
|
+
function serviceConfigDirEnv(config) {
|
|
96
|
+
const raw = config?.configDirEnv !== undefined ? config.configDirEnv : process.env.CHROXY_CONFIG_DIR
|
|
97
|
+
return typeof raw === 'string' && raw.trim() ? raw : null
|
|
98
|
+
}
|
|
99
|
+
|
|
71
100
|
export function generateLaunchdPlist(config) {
|
|
72
101
|
const {
|
|
73
102
|
nodePath,
|
|
@@ -76,8 +105,9 @@ export function generateLaunchdPlist(config) {
|
|
|
76
105
|
wrapperPath,
|
|
77
106
|
cwd = homedir(),
|
|
78
107
|
startAtLogin = false,
|
|
79
|
-
logDir =
|
|
108
|
+
logDir = configPath('logs'),
|
|
80
109
|
} = config
|
|
110
|
+
const configDirEnv = serviceConfigDirEnv(config)
|
|
81
111
|
|
|
82
112
|
// Bake a PATH that includes the node and claude bin dirs so the daemon's
|
|
83
113
|
// preflight finds both under launchd's bare default PATH (#5491).
|
|
@@ -116,7 +146,9 @@ ${programArgs}
|
|
|
116
146
|
<key>PATH</key>
|
|
117
147
|
<string>${escapeXml(pathValue)}</string>
|
|
118
148
|
<key>CHROXY_DAEMON</key>
|
|
119
|
-
<string>1</string
|
|
149
|
+
<string>1</string>${configDirEnv ? `
|
|
150
|
+
<key>CHROXY_CONFIG_DIR</key>
|
|
151
|
+
<string>${escapeXml(configDirEnv)}</string>` : ''}
|
|
120
152
|
</dict>
|
|
121
153
|
</dict>
|
|
122
154
|
</plist>
|
|
@@ -133,8 +165,9 @@ export function generateSystemdUnit(config) {
|
|
|
133
165
|
claudeBin,
|
|
134
166
|
wrapperPath,
|
|
135
167
|
cwd = homedir(),
|
|
136
|
-
logDir =
|
|
168
|
+
logDir = configPath('logs'),
|
|
137
169
|
} = config
|
|
170
|
+
const configDirEnv = serviceConfigDirEnv(config)
|
|
138
171
|
|
|
139
172
|
// Bake a PATH that includes the node and claude bin dirs for parity with the
|
|
140
173
|
// launchd plist (#5491).
|
|
@@ -156,7 +189,8 @@ WorkingDirectory=${cwd}
|
|
|
156
189
|
Restart=on-failure
|
|
157
190
|
RestartSec=5
|
|
158
191
|
Environment=PATH=${pathValue}
|
|
159
|
-
Environment=CHROXY_DAEMON=1
|
|
192
|
+
Environment=CHROXY_DAEMON=1${configDirEnv ? `
|
|
193
|
+
Environment=CHROXY_CONFIG_DIR=${configDirEnv}` : ''}
|
|
160
194
|
StandardOutput=file:${join(logDir, 'chroxy-stdout.log')}
|
|
161
195
|
StandardError=file:${join(logDir, 'chroxy-stderr.log')}
|
|
162
196
|
|
|
@@ -190,11 +224,81 @@ export function getWindowsAlternatives() {
|
|
|
190
224
|
]
|
|
191
225
|
}
|
|
192
226
|
|
|
227
|
+
/**
|
|
228
|
+
* Generate the Windows `.cmd` service wrapper that Task Scheduler runs (#6647).
|
|
229
|
+
*
|
|
230
|
+
* `schtasks`' basic `/Create` flags can neither set a working directory nor
|
|
231
|
+
* capture the daemon's stdout/stderr, so — mirroring the POSIX wrapper (#5491) —
|
|
232
|
+
* a small batch file sets the cwd, prepends node + claude to PATH, and runs the
|
|
233
|
+
* daemon with output redirected to the log dir.
|
|
234
|
+
*
|
|
235
|
+
* Unlike launchd/systemd there is NO keychain to resolve here, so NOTHING
|
|
236
|
+
* sensitive is written into this file or the task action: the daemon reads its
|
|
237
|
+
* config/credentials from its own store at runtime (today plaintext under
|
|
238
|
+
* `~/.chroxy`; DPAPI-encrypted per-user storage is planned in #6644, and the
|
|
239
|
+
* wrapper runs AS the user so those creds will be reachable once it lands).
|
|
240
|
+
* Keeping secrets out of the task action is an explicit #6647 goal.
|
|
241
|
+
*
|
|
242
|
+
* @param {object} config
|
|
243
|
+
* @param {string} config.nodePath - Resolved node binary path.
|
|
244
|
+
* @param {string} config.chroxyBin - Resolved chroxy CLI entry point.
|
|
245
|
+
* @param {string} [config.claudeBin] - Resolved claude binary (its dir is added to PATH).
|
|
246
|
+
* @param {string} [config.cwd] - Working directory for the daemon.
|
|
247
|
+
* @param {string} [config.logDir] - Log directory for stdout/stderr redirection.
|
|
248
|
+
* @returns {string} Windows batch (.cmd) script.
|
|
249
|
+
*/
|
|
250
|
+
export function generateWindowsServiceWrapper(config) {
|
|
251
|
+
const {
|
|
252
|
+
nodePath,
|
|
253
|
+
chroxyBin,
|
|
254
|
+
claudeBin,
|
|
255
|
+
cwd = homedir(),
|
|
256
|
+
logDir = configPath('logs'),
|
|
257
|
+
} = config
|
|
258
|
+
const configDirEnv = serviceConfigDirEnv(config)
|
|
259
|
+
|
|
260
|
+
// Use Windows path semantics regardless of host so the generated batch is
|
|
261
|
+
// correct even when this runs on a POSIX CI runner under test (#6647).
|
|
262
|
+
const pathPrepend = [pathWin32.dirname(nodePath), claudeBin ? pathWin32.dirname(claudeBin) : '']
|
|
263
|
+
.filter(Boolean)
|
|
264
|
+
.join(';')
|
|
265
|
+
const stdoutLog = pathWin32.join(logDir, 'chroxy-stdout.log')
|
|
266
|
+
const stderrLog = pathWin32.join(logDir, 'chroxy-stderr.log')
|
|
267
|
+
|
|
268
|
+
// CRLF line endings + ASCII-only (no em-dash): a .cmd is read by cmd.exe in
|
|
269
|
+
// the OEM code page, where a UTF-8 em-dash renders as garbage, and CRLF is the
|
|
270
|
+
// conventional/robust ending for a generated batch file (#6647 review).
|
|
271
|
+
// #7162: rotate oversized captures HERE, before the `>>` redirect opens a
|
|
272
|
+
// handle on them. cmd's redirect handle lacks POSIX append semantics, so
|
|
273
|
+
// the daemon cannot safely truncate these in place on Windows (a truncate
|
|
274
|
+
// under the open handle NUL-pads the gap on the next write); a rename
|
|
275
|
+
// before the handle exists is the safe equivalent. 5242880 = 5MB, matching
|
|
276
|
+
// the POSIX-side STDIO_CAPTURE_MAX_SIZE.
|
|
277
|
+
const rotateCapture = (live, old) =>
|
|
278
|
+
`if exist "${live}" for %%A in ("${live}") do if %%~zA gtr 5242880 move /y "${live}" "${old}"`
|
|
279
|
+
const lines = [
|
|
280
|
+
'@echo off',
|
|
281
|
+
'rem Chroxy service wrapper - generated by `chroxy service install` (#6647).',
|
|
282
|
+
'rem Runs the daemon under Windows Task Scheduler. Regenerated on every',
|
|
283
|
+
'rem `service install`; edits are lost.',
|
|
284
|
+
`set "PATH=${pathPrepend};%PATH%"`,
|
|
285
|
+
'set "CHROXY_DAEMON=1"',
|
|
286
|
+
...(configDirEnv ? [`set "CHROXY_CONFIG_DIR=${configDirEnv}"`] : []),
|
|
287
|
+
`cd /d "${cwd}"`,
|
|
288
|
+
rotateCapture(stdoutLog, pathWin32.join(logDir, 'chroxy-stdout.old.log')),
|
|
289
|
+
rotateCapture(stderrLog, pathWin32.join(logDir, 'chroxy-stderr.old.log')),
|
|
290
|
+
`"${nodePath}" "${chroxyBin}" start >> "${stdoutLog}" 2>> "${stderrLog}"`,
|
|
291
|
+
]
|
|
292
|
+
return lines.join('\r\n') + '\r\n'
|
|
293
|
+
}
|
|
294
|
+
|
|
193
295
|
/**
|
|
194
296
|
* Search common locations for Node 22, verify the version, and return the path.
|
|
195
297
|
* Throws with a helpful message if not found.
|
|
196
298
|
*/
|
|
197
299
|
export function resolveNode22Path() {
|
|
300
|
+
if (isWindows) return resolveWindowsNodePath()
|
|
301
|
+
|
|
198
302
|
const candidates = []
|
|
199
303
|
|
|
200
304
|
// Homebrew (Apple Silicon)
|
|
@@ -253,6 +357,38 @@ export function resolveNode22Path() {
|
|
|
253
357
|
)
|
|
254
358
|
}
|
|
255
359
|
|
|
360
|
+
/**
|
|
361
|
+
* Windows node resolution (#6647). Unlike POSIX — where the daemon is pinned to a
|
|
362
|
+
* Homebrew/nvm `node@22` — Windows has no pinning convention, so accept any Node
|
|
363
|
+
* >= 22 (the documented minimum). The installer already runs under Node, so if
|
|
364
|
+
* that interpreter satisfies the minimum, reuse its absolute path; otherwise fall
|
|
365
|
+
* back to `where node`.
|
|
366
|
+
*/
|
|
367
|
+
function resolveWindowsNodePath() {
|
|
368
|
+
const major = (v) => parseInt(String(v).replace(/^v/, '').split('.')[0], 10)
|
|
369
|
+
|
|
370
|
+
const running = process.versions?.node
|
|
371
|
+
if (running && major(running) >= 22) return process.execPath
|
|
372
|
+
|
|
373
|
+
try {
|
|
374
|
+
const out = execFileSync('where', ['node'], { encoding: 'utf-8' })
|
|
375
|
+
const first = out.split(/\r?\n/).map((s) => s.trim()).find(Boolean)
|
|
376
|
+
if (first && existsSync(first)) {
|
|
377
|
+
const version = execFileSync(first, ['--version'], { encoding: 'utf-8' }).trim()
|
|
378
|
+
if (major(version) >= 22) return first
|
|
379
|
+
}
|
|
380
|
+
} catch {
|
|
381
|
+
// `where` missing or node not on PATH — fall through to the error below.
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
throw new Error(
|
|
385
|
+
'Could not find Node.js >= 22 (the minimum supported version). Install it via:\n' +
|
|
386
|
+
' winget install OpenJS.NodeJS.LTS\n' +
|
|
387
|
+
' or nvm-windows: nvm install 22\n' +
|
|
388
|
+
'then re-run `chroxy service install`.'
|
|
389
|
+
)
|
|
390
|
+
}
|
|
391
|
+
|
|
256
392
|
/**
|
|
257
393
|
* Find the chroxy CLI entry point.
|
|
258
394
|
* First checks if we're running from the monorepo source, then falls back to `which chroxy`.
|
|
@@ -265,11 +401,13 @@ export function resolveChroxyBin() {
|
|
|
265
401
|
return monorepoCliPath
|
|
266
402
|
}
|
|
267
403
|
|
|
268
|
-
// Fall back to globally installed chroxy
|
|
404
|
+
// Fall back to globally installed chroxy (`where` on Windows, `which` on POSIX;
|
|
405
|
+
// `where` can print several lines, so take the first resolvable one — #6647).
|
|
269
406
|
try {
|
|
270
|
-
const
|
|
271
|
-
|
|
272
|
-
|
|
407
|
+
const out = execFileSync(isWindows ? 'where' : 'which', ['chroxy'], { encoding: 'utf-8' })
|
|
408
|
+
const resolved = out.split(/\r?\n/).map((s) => s.trim()).find((p) => p && existsSync(p))
|
|
409
|
+
if (resolved) {
|
|
410
|
+
return resolved
|
|
273
411
|
}
|
|
274
412
|
} catch {
|
|
275
413
|
// not found
|
|
@@ -300,9 +438,12 @@ export function resolveChroxyBin() {
|
|
|
300
438
|
*/
|
|
301
439
|
export function resolveClaudeBin(options = {}) {
|
|
302
440
|
const which = options._which || execFileSync
|
|
441
|
+
// `where` on Windows (it can print several lines — take the first resolvable
|
|
442
|
+
// one), `which` on POSIX (#6647).
|
|
303
443
|
try {
|
|
304
|
-
const
|
|
305
|
-
|
|
444
|
+
const out = which(isWindows ? 'where' : 'which', ['claude'], { encoding: 'utf-8' })
|
|
445
|
+
const resolved = String(out).split(/\r?\n/).map((s) => s.trim()).find((p) => p && existsSync(p))
|
|
446
|
+
if (resolved) {
|
|
306
447
|
return resolved
|
|
307
448
|
}
|
|
308
449
|
} catch {
|
|
@@ -366,6 +507,7 @@ export function buildServicePath({ nodePath, claudeBin }) {
|
|
|
366
507
|
*/
|
|
367
508
|
export function generateServiceWrapper(config) {
|
|
368
509
|
const { nodePath, chroxyBin, pathValue } = config
|
|
510
|
+
const configDirEnv = serviceConfigDirEnv(config)
|
|
369
511
|
|
|
370
512
|
const sh = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`
|
|
371
513
|
const keychainBlock = ({ service, account, env }) => `
|
|
@@ -383,7 +525,8 @@ fi`
|
|
|
383
525
|
set -e
|
|
384
526
|
|
|
385
527
|
export PATH=${sh(pathValue)}
|
|
386
|
-
export CHROXY_DAEMON=1
|
|
528
|
+
export CHROXY_DAEMON=1${configDirEnv ? `
|
|
529
|
+
export CHROXY_CONFIG_DIR=${sh(configDirEnv)}` : ''}
|
|
387
530
|
${keychainBlock(KEYCHAIN_API_TOKEN)}
|
|
388
531
|
${keychainBlock(KEYCHAIN_DISCORD_WEBHOOK)}
|
|
389
532
|
|
|
@@ -396,7 +539,7 @@ exec ${sh(nodePath)} ${sh(chroxyBin)} start
|
|
|
396
539
|
* @param {string} [configDir] - Override config directory (for testing)
|
|
397
540
|
* @returns {object|null}
|
|
398
541
|
*/
|
|
399
|
-
export function loadServiceState(configDir =
|
|
542
|
+
export function loadServiceState(configDir = defaultConfigDir()) {
|
|
400
543
|
const statePath = join(configDir, 'service.json')
|
|
401
544
|
if (!existsSync(statePath)) {
|
|
402
545
|
return null
|
|
@@ -413,7 +556,7 @@ export function loadServiceState(configDir = DEFAULT_CONFIG_DIR) {
|
|
|
413
556
|
* @param {object} state
|
|
414
557
|
* @param {string} [configDir] - Override config directory (for testing)
|
|
415
558
|
*/
|
|
416
|
-
export function saveServiceState(state, configDir =
|
|
559
|
+
export function saveServiceState(state, configDir = defaultConfigDir()) {
|
|
417
560
|
if (!existsSync(configDir)) {
|
|
418
561
|
mkdirSync(configDir, { recursive: true })
|
|
419
562
|
}
|
|
@@ -421,6 +564,254 @@ export function saveServiceState(state, configDir = DEFAULT_CONFIG_DIR) {
|
|
|
421
564
|
writeFileRestricted(statePath, JSON.stringify(state, null, 2))
|
|
422
565
|
}
|
|
423
566
|
|
|
567
|
+
/**
|
|
568
|
+
* Reverse the single-quote escaping `generateServiceWrapper` applies (`sh()`):
|
|
569
|
+
* split a shell line into words, honouring `'...'` and the `'\''` escape.
|
|
570
|
+
* Handles only what the wrapper emits; anything else yields null so a caller
|
|
571
|
+
* treats "cannot read it back" as a failure, never as a match.
|
|
572
|
+
*/
|
|
573
|
+
function splitShWords(line) {
|
|
574
|
+
const words = []
|
|
575
|
+
let i = 0
|
|
576
|
+
while (i < line.length) {
|
|
577
|
+
if (line[i] === ' ') { i++; continue }
|
|
578
|
+
let word = ''
|
|
579
|
+
while (i < line.length && line[i] !== ' ') {
|
|
580
|
+
if (line[i] === "'") {
|
|
581
|
+
const end = line.indexOf("'", i + 1)
|
|
582
|
+
if (end === -1) return null
|
|
583
|
+
word += line.slice(i + 1, end)
|
|
584
|
+
i = end + 1
|
|
585
|
+
} else if (line[i] === '\\' && line[i + 1] === "'") {
|
|
586
|
+
word += "'"
|
|
587
|
+
i += 2
|
|
588
|
+
} else {
|
|
589
|
+
word += line[i]
|
|
590
|
+
i++
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
words.push(word)
|
|
594
|
+
}
|
|
595
|
+
return words
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/**
|
|
599
|
+
* Read back what a POSIX service wrapper actually execs (#7161): the last
|
|
600
|
+
* `exec <node> <chroxyBin> start` line. This is the ground truth for "which
|
|
601
|
+
* working copy does launchd run" — service.json is only a record of it.
|
|
602
|
+
*
|
|
603
|
+
* @param {string} content - Wrapper script text.
|
|
604
|
+
* @returns {{ nodePath: string, chroxyBin: string } | null} null when no
|
|
605
|
+
* recognisable exec line is present (including a Windows .cmd wrapper).
|
|
606
|
+
*/
|
|
607
|
+
export function parseWrapperExecTarget(content) {
|
|
608
|
+
const lines = String(content).split(/\r?\n/)
|
|
609
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
610
|
+
if (!lines[i].startsWith('exec ')) continue
|
|
611
|
+
const words = splitShWords(lines[i].slice(5))
|
|
612
|
+
if (words && words.length === 3 && words[2] === 'start') {
|
|
613
|
+
return { nodePath: words[0], chroxyBin: words[1] }
|
|
614
|
+
}
|
|
615
|
+
return null
|
|
616
|
+
}
|
|
617
|
+
return null
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
/**
|
|
621
|
+
* Report which tree an installed service points at, from both records.
|
|
622
|
+
* `installed` is true when ANY artifact exists (state, wrapper, or the
|
|
623
|
+
* launchd/systemd file) so a deleted service.json cannot make an existing
|
|
624
|
+
* service look absent (#7161).
|
|
625
|
+
*
|
|
626
|
+
* @param {object} [options]
|
|
627
|
+
* @param {string} [options._stateDir]
|
|
628
|
+
* @param {string} [options._wrapperPath]
|
|
629
|
+
* @param {string} [options._servicePath] - launchd plist / systemd unit
|
|
630
|
+
* @returns {{ installed: boolean, hasState: boolean, recordedBin: string|null, wrapperBin: string|null,
|
|
631
|
+
* wrapperPath: string, drift: boolean }}
|
|
632
|
+
*/
|
|
633
|
+
export function inspectInstalledService(options = {}) {
|
|
634
|
+
const stateDir = options._stateDir || defaultConfigDir()
|
|
635
|
+
const state = loadServiceState(stateDir)
|
|
636
|
+
const wrapperPath = options._wrapperPath || state?.wrapperPath || join(stateDir, WRAPPER_NAME)
|
|
637
|
+
let wrapperBin = null
|
|
638
|
+
let wrapperPresent = false
|
|
639
|
+
if (existsSync(wrapperPath)) {
|
|
640
|
+
wrapperPresent = true
|
|
641
|
+
try {
|
|
642
|
+
wrapperBin = parseWrapperExecTarget(readFileSync(wrapperPath, 'utf-8'))?.chroxyBin ?? null
|
|
643
|
+
} catch {
|
|
644
|
+
wrapperBin = null
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
const recordedBin = state?.chroxyBin ?? null
|
|
648
|
+
const servicePresent = !!options._servicePath && existsSync(options._servicePath)
|
|
649
|
+
return {
|
|
650
|
+
installed: !!state || wrapperPresent || servicePresent,
|
|
651
|
+
// `chroxy service uninstall` needs service.json, so it only works when this is true.
|
|
652
|
+
hasState: !!state,
|
|
653
|
+
recordedBin,
|
|
654
|
+
wrapperBin,
|
|
655
|
+
wrapperPath,
|
|
656
|
+
// Only a disagreement between two values we could actually read counts.
|
|
657
|
+
drift: recordedBin !== null && wrapperBin !== null && recordedBin !== wrapperBin,
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/**
|
|
662
|
+
* Refuse to silently re-point an existing service at another working copy
|
|
663
|
+
* (#7161). `resolveChroxyBin()` resolves relative to the invoking file, so
|
|
664
|
+
* running `chroxy service install` from any checkout would otherwise move the
|
|
665
|
+
* launchd job to that checkout. Reinstalling needs an explicit `force`, and
|
|
666
|
+
* the message names both trees.
|
|
667
|
+
*
|
|
668
|
+
* @param {object} args
|
|
669
|
+
* @param {string} args.chroxyBin - The target this invocation would install.
|
|
670
|
+
* @param {boolean} [args.force]
|
|
671
|
+
* @param {object} [args.inspect] - Options for inspectInstalledService.
|
|
672
|
+
* @returns {{ reinstall: boolean }} reinstall=true when force overrode an existing install.
|
|
673
|
+
* @throws {Error} code SERVICE_ALREADY_INSTALLED when installed and not forced.
|
|
674
|
+
*/
|
|
675
|
+
export function assertReinstallAllowed({ chroxyBin, force = false, inspect = {} }) {
|
|
676
|
+
const found = inspectInstalledService(inspect)
|
|
677
|
+
if (!found.installed) return { reinstall: false }
|
|
678
|
+
if (force) return { reinstall: true }
|
|
679
|
+
|
|
680
|
+
const lines = ['Chroxy service is already installed.']
|
|
681
|
+
if (found.drift) {
|
|
682
|
+
lines.push(
|
|
683
|
+
'Its two records disagree:',
|
|
684
|
+
` service.json records: ${found.recordedBin}`,
|
|
685
|
+
` wrapper actually execs: ${found.wrapperBin}`,
|
|
686
|
+
)
|
|
687
|
+
}
|
|
688
|
+
const current = found.wrapperBin || found.recordedBin
|
|
689
|
+
if (current && current !== chroxyBin) {
|
|
690
|
+
lines.push(
|
|
691
|
+
'It is pinned to:',
|
|
692
|
+
` ${current}`,
|
|
693
|
+
'This install would re-point it at:',
|
|
694
|
+
` ${chroxyBin}`,
|
|
695
|
+
)
|
|
696
|
+
} else if (current) {
|
|
697
|
+
lines.push(`It is pinned to this same tree: ${current}`)
|
|
698
|
+
} else {
|
|
699
|
+
lines.push('Its target tree could not be read from service.json or the wrapper.')
|
|
700
|
+
}
|
|
701
|
+
const moves = current && current !== chroxyBin
|
|
702
|
+
lines.push(
|
|
703
|
+
moves
|
|
704
|
+
? `Re-run with --force to re-point it at ${chroxyBin} (the running daemon switches to that tree).`
|
|
705
|
+
: 'Re-run with --force to rewrite its wrapper and service definition and reload the job (same tree, nothing moves).',
|
|
706
|
+
)
|
|
707
|
+
lines.push(
|
|
708
|
+
found.hasState
|
|
709
|
+
? 'Or run "chroxy service uninstall" first to remove it.'
|
|
710
|
+
: '"chroxy service uninstall" will not work here (service.json is missing); --force is the way to recover.',
|
|
711
|
+
)
|
|
712
|
+
const err = new Error(lines.join('\n'))
|
|
713
|
+
err.code = 'SERVICE_ALREADY_INSTALLED'
|
|
714
|
+
throw err
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
/**
|
|
718
|
+
* Does a package's `main` resolve the way Node's CJS/ESM-legacy loader does?
|
|
719
|
+
* The exact file, then with .js/.json/.node appended, then as a directory
|
|
720
|
+
* holding index.js/.json/.node. Written with or without a leading "./".
|
|
721
|
+
*/
|
|
722
|
+
function resolvesAsFile(pkgDir, main) {
|
|
723
|
+
const isFile = (p) => {
|
|
724
|
+
try { return statSync(p).isFile() } catch { return false }
|
|
725
|
+
}
|
|
726
|
+
const base = resolve(pkgDir, main)
|
|
727
|
+
const exts = ['.js', '.json', '.node']
|
|
728
|
+
return isFile(base)
|
|
729
|
+
|| exts.some((e) => isFile(base + e))
|
|
730
|
+
|| exts.some((e) => isFile(join(base, 'index' + e)))
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/**
|
|
734
|
+
* Offline check that the tree `chroxyBin` lives in can actually start (#7161).
|
|
735
|
+
* KeepAlive turns one missing dependency into an infinite respawn loop under
|
|
736
|
+
* launchd, so this fails the install instead. Reads package.json and stats
|
|
737
|
+
* files only — no network, no `npm`, a few milliseconds.
|
|
738
|
+
*
|
|
739
|
+
* For each runtime `dependencies` entry it requires `node_modules/<name>/package.json`
|
|
740
|
+
* to resolve by Node's walk-up rule (hoisting is honoured), and, when that
|
|
741
|
+
* package declares a relative `main`, that file to exist (an unbuilt workspace
|
|
742
|
+
* package has a link but no `dist/`). A tree whose package.json cannot be found
|
|
743
|
+
* is a failure, never a pass: "cannot check" must not read as "nothing to check".
|
|
744
|
+
*
|
|
745
|
+
* @param {string} chroxyBin
|
|
746
|
+
* @returns {{ root: string|null, problems: string[] }}
|
|
747
|
+
*/
|
|
748
|
+
export function checkChroxyTree(chroxyBin) {
|
|
749
|
+
let real
|
|
750
|
+
try {
|
|
751
|
+
real = realpathSync(chroxyBin)
|
|
752
|
+
} catch {
|
|
753
|
+
return { root: null, problems: [`${chroxyBin} does not exist`] }
|
|
754
|
+
}
|
|
755
|
+
let root = dirname(real)
|
|
756
|
+
while (!existsSync(join(root, 'package.json'))) {
|
|
757
|
+
const parent = dirname(root)
|
|
758
|
+
if (parent === root) {
|
|
759
|
+
return { root: null, problems: [`no package.json found above ${real}, so its dependencies cannot be verified`] }
|
|
760
|
+
}
|
|
761
|
+
root = parent
|
|
762
|
+
}
|
|
763
|
+
let pkg
|
|
764
|
+
try {
|
|
765
|
+
pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf-8'))
|
|
766
|
+
} catch (err) {
|
|
767
|
+
return { root, problems: [`${join(root, 'package.json')} is unreadable: ${err.message}`] }
|
|
768
|
+
}
|
|
769
|
+
const deps = Object.keys(pkg.dependencies || {})
|
|
770
|
+
const problems = []
|
|
771
|
+
for (const name of deps) {
|
|
772
|
+
let dir = root
|
|
773
|
+
let found = null
|
|
774
|
+
for (;;) {
|
|
775
|
+
const candidate = join(dir, 'node_modules', name)
|
|
776
|
+
if (existsSync(join(candidate, 'package.json'))) { found = candidate; break }
|
|
777
|
+
const parent = dirname(dir)
|
|
778
|
+
if (parent === dir) break
|
|
779
|
+
dir = parent
|
|
780
|
+
}
|
|
781
|
+
if (!found) {
|
|
782
|
+
problems.push(`${name} is not installed`)
|
|
783
|
+
continue
|
|
784
|
+
}
|
|
785
|
+
try {
|
|
786
|
+
const main = JSON.parse(readFileSync(join(found, 'package.json'), 'utf-8')).main
|
|
787
|
+
if (typeof main === 'string' && main !== '' && !resolvesAsFile(found, main)) {
|
|
788
|
+
problems.push(`${name} is linked but its entry ${main} is missing (not built?)`)
|
|
789
|
+
}
|
|
790
|
+
} catch (err) {
|
|
791
|
+
problems.push(`${name} has an unreadable package.json: ${err.message}`)
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
return { root, problems }
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
/**
|
|
798
|
+
* Throw an actionable error when the target tree cannot start (see checkChroxyTree).
|
|
799
|
+
* @param {string} chroxyBin
|
|
800
|
+
*/
|
|
801
|
+
export function assertChroxyTreeReady(chroxyBin) {
|
|
802
|
+
const { root, problems } = checkChroxyTree(chroxyBin)
|
|
803
|
+
if (problems.length === 0) return
|
|
804
|
+
const shown = problems.slice(0, 10).map((p) => ` - ${p}`)
|
|
805
|
+
if (problems.length > 10) shown.push(` - ...and ${problems.length - 10} more`)
|
|
806
|
+
const err = new Error(
|
|
807
|
+
`The chroxy tree at ${root || chroxyBin} cannot start, so installing the service would make launchd/systemd crash-loop:\n` +
|
|
808
|
+
`${shown.join('\n')}\n` +
|
|
809
|
+
`Run "npm install" in ${root || 'that tree'} (and build any workspace packages), then re-run "chroxy service install".`
|
|
810
|
+
)
|
|
811
|
+
err.code = 'SERVICE_TREE_NOT_READY'
|
|
812
|
+
throw err
|
|
813
|
+
}
|
|
814
|
+
|
|
424
815
|
/**
|
|
425
816
|
* Write the service wrapper script to disk with 0700 perms (owner rwx only).
|
|
426
817
|
*
|
|
@@ -459,25 +850,43 @@ export function writeServiceWrapper(wrapperPath, content) {
|
|
|
459
850
|
* @param {string} [config._stateDir] - Override state directory (testing)
|
|
460
851
|
* @param {string} [config._wrapperPath] - Override wrapper script path (testing)
|
|
461
852
|
* @param {boolean} [config._skipRegister] - Skip launchctl/systemctl registration (testing)
|
|
853
|
+
* @param {boolean} [config.force] - Re-point an already-installed service (#7161).
|
|
854
|
+
* Without it an existing install is never touched.
|
|
855
|
+
* @param {(cmd: string, args: string[], opts: object) => void} [config._exec]
|
|
856
|
+
* Injectable exec for testing (defaults to execFileSync).
|
|
857
|
+
* @param {Function} [config._generateWrapper] - Override the wrapper generator (testing the read-back check)
|
|
462
858
|
* @param {string} [config._platform] - Override platform (testing)
|
|
463
859
|
*/
|
|
464
860
|
export function installService(config) {
|
|
465
861
|
const plat = config._platform || platform()
|
|
466
862
|
const paths = getServicePaths(plat)
|
|
467
863
|
|
|
864
|
+
// #7161: refuse to silently re-point an existing service at the invoking tree.
|
|
865
|
+
// Runs before anything is written so a refusal leaves the install untouched.
|
|
866
|
+
const stateDirForGuard = config._stateDir || defaultConfigDir()
|
|
867
|
+
const hadState = !!loadServiceState(stateDirForGuard)
|
|
868
|
+
const { reinstall } = assertReinstallAllowed({
|
|
869
|
+
chroxyBin: config.chroxyBin,
|
|
870
|
+
force: config.force === true,
|
|
871
|
+
inspect: {
|
|
872
|
+
_stateDir: stateDirForGuard,
|
|
873
|
+
_wrapperPath: config._wrapperPath
|
|
874
|
+
|| (plat === 'win32' ? join(stateDirForGuard, WINDOWS_WRAPPER_NAME) : undefined),
|
|
875
|
+
_servicePath: plat === 'win32'
|
|
876
|
+
? undefined
|
|
877
|
+
: config._servicePath || (plat === 'darwin' ? paths.plistPath : paths.unitPath),
|
|
878
|
+
},
|
|
879
|
+
})
|
|
880
|
+
|
|
468
881
|
if (plat === 'win32') {
|
|
469
|
-
|
|
470
|
-
return {
|
|
471
|
-
installed: false,
|
|
472
|
-
message: 'Windows does not support native service installation via chroxy. Use one of the alternatives below to run Chroxy at startup.',
|
|
473
|
-
alternatives,
|
|
474
|
-
}
|
|
882
|
+
return installWindowsService(config, paths, reinstall)
|
|
475
883
|
}
|
|
476
884
|
|
|
477
885
|
const servicePath = config._servicePath || (plat === 'darwin' ? paths.plistPath : paths.unitPath)
|
|
478
886
|
const logDir = config._logDir || paths.logDir
|
|
479
|
-
const stateDir =
|
|
887
|
+
const stateDir = stateDirForGuard
|
|
480
888
|
const wrapperPath = config._wrapperPath || join(stateDir, WRAPPER_NAME)
|
|
889
|
+
const exec = config._exec || execFileSync
|
|
481
890
|
|
|
482
891
|
// Bake the resolved binary locations into the service PATH so the daemon's
|
|
483
892
|
// preflight finds node + claude under the bare launchd/systemd PATH (#5491).
|
|
@@ -486,8 +895,12 @@ export function installService(config) {
|
|
|
486
895
|
claudeBin: config.claudeBin,
|
|
487
896
|
})
|
|
488
897
|
|
|
898
|
+
// What exists before this attempt writes anything: rollback removes only what
|
|
899
|
+
// this attempt created (#8890).
|
|
900
|
+
const preexisting = snapshotExisting([servicePath, wrapperPath])
|
|
901
|
+
|
|
489
902
|
// Write the wrapper that resolves keychain secrets at spawn time (#5491).
|
|
490
|
-
const wrapperContent = generateServiceWrapper({
|
|
903
|
+
const wrapperContent = (config._generateWrapper || generateServiceWrapper)({
|
|
491
904
|
nodePath: config.nodePath,
|
|
492
905
|
chroxyBin: config.chroxyBin,
|
|
493
906
|
pathValue,
|
|
@@ -495,6 +908,17 @@ export function installService(config) {
|
|
|
495
908
|
})
|
|
496
909
|
writeServiceWrapper(wrapperPath, wrapperContent)
|
|
497
910
|
|
|
911
|
+
// #7161: service.json must record what the wrapper ACTUALLY execs. Read it back
|
|
912
|
+
// from the file just written rather than trusting the value we passed in, so the
|
|
913
|
+
// two records cannot disagree (and a wrapper we cannot parse fails the install).
|
|
914
|
+
const execTarget = parseWrapperExecTarget(readFileSync(wrapperPath, 'utf-8'))
|
|
915
|
+
if (!execTarget || execTarget.chroxyBin !== config.chroxyBin) {
|
|
916
|
+
throw new Error(
|
|
917
|
+
`The service wrapper at ${wrapperPath} does not exec ${config.chroxyBin} ` +
|
|
918
|
+
`(read back: ${execTarget ? execTarget.chroxyBin : 'unparseable'}); refusing to record a target it does not run.`
|
|
919
|
+
)
|
|
920
|
+
}
|
|
921
|
+
|
|
498
922
|
// Generate service file content
|
|
499
923
|
const genConfig = {
|
|
500
924
|
nodePath: config.nodePath,
|
|
@@ -527,12 +951,28 @@ export function installService(config) {
|
|
|
527
951
|
// Write service file
|
|
528
952
|
writeFileRestricted(servicePath, content)
|
|
529
953
|
|
|
530
|
-
// Register with system (unless testing)
|
|
954
|
+
// Register with system (unless testing). A throw here leaves the definition and
|
|
955
|
+
// wrapper just written; a first install rolls them back (#8890).
|
|
531
956
|
if (!config._skipRegister) {
|
|
957
|
+
try {
|
|
532
958
|
if (plat === 'darwin') {
|
|
533
|
-
|
|
959
|
+
if (reinstall) {
|
|
960
|
+
// launchd refuses to bootstrap a label that is already loaded; a forced
|
|
961
|
+
// re-point must unload the old definition first. Not loaded is fine.
|
|
962
|
+
try {
|
|
963
|
+
exec('launchctl', ['bootout', `gui/${process.getuid()}/${SERVICE_LABEL}`], { stdio: 'ignore' })
|
|
964
|
+
} catch {
|
|
965
|
+
// not currently loaded
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
exec('launchctl', ['bootstrap', `gui/${process.getuid()}`, servicePath])
|
|
534
969
|
} else {
|
|
535
|
-
|
|
970
|
+
if (reinstall) exec('systemctl', ['--user', 'daemon-reload'])
|
|
971
|
+
exec('systemctl', ['--user', 'enable', '--now', 'chroxy.service'])
|
|
972
|
+
}
|
|
973
|
+
} catch (err) {
|
|
974
|
+
rollbackFreshInstall({ hadState, reinstall, preexisting }, [servicePath, wrapperPath])
|
|
975
|
+
throw err
|
|
536
976
|
}
|
|
537
977
|
}
|
|
538
978
|
|
|
@@ -542,7 +982,7 @@ export function installService(config) {
|
|
|
542
982
|
platform: plat,
|
|
543
983
|
servicePath,
|
|
544
984
|
nodePath: config.nodePath,
|
|
545
|
-
chroxyBin:
|
|
985
|
+
chroxyBin: execTarget.chroxyBin,
|
|
546
986
|
claudeBin: config.claudeBin,
|
|
547
987
|
wrapperPath,
|
|
548
988
|
cwd: genConfig.cwd,
|
|
@@ -550,16 +990,172 @@ export function installService(config) {
|
|
|
550
990
|
}, stateDir)
|
|
551
991
|
}
|
|
552
992
|
|
|
993
|
+
/** The subset of `paths` that exist right now. */
|
|
994
|
+
function snapshotExisting(paths) {
|
|
995
|
+
return new Set(paths.filter((p) => p && existsSync(p)))
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
/**
|
|
999
|
+
* Undo the files a FAILED first install left behind (#8890). The service
|
|
1000
|
+
* definition and wrapper are written before the service manager is asked to
|
|
1001
|
+
* register them, and service.json only after; so a registration that throws left
|
|
1002
|
+
* files that look like an install (and made the desktop app wait for a service
|
|
1003
|
+
* that does not exist) with no service.json for `service uninstall` to work from.
|
|
1004
|
+
*
|
|
1005
|
+
* Removes only what THIS attempt created, and never on a reinstall: a recognised
|
|
1006
|
+
* existing install (`reinstall`, which `assertReinstallAllowed` also grants from a
|
|
1007
|
+
* definition or wrapper with no service.json) may still be registered and needs
|
|
1008
|
+
* every file it had.
|
|
1009
|
+
*
|
|
1010
|
+
* @param {{ hadState: boolean, reinstall: boolean, preexisting: Set<string> }} guard
|
|
1011
|
+
* @param {string[]} paths
|
|
1012
|
+
*/
|
|
1013
|
+
function rollbackFreshInstall({ hadState, reinstall, preexisting }, paths) {
|
|
1014
|
+
if (hadState || reinstall) return
|
|
1015
|
+
for (const p of paths) {
|
|
1016
|
+
if (!p || preexisting.has(p)) continue
|
|
1017
|
+
try {
|
|
1018
|
+
if (existsSync(p)) unlinkSync(p)
|
|
1019
|
+
} catch {
|
|
1020
|
+
// best effort: the original registration error is the one to report
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
/**
|
|
1026
|
+
* Register Chroxy as a Windows autostart via Task Scheduler (#6647).
|
|
1027
|
+
*
|
|
1028
|
+
* Writes the `.cmd` wrapper, then `schtasks /Create /TN Chroxy /TR <wrapper>
|
|
1029
|
+
* /SC ONLOGON /RL HIGHEST /IT /F`:
|
|
1030
|
+
* - `/SC ONLOGON` — start when the user logs on (NOT `/SC ONSTART`).
|
|
1031
|
+
* - `/RL HIGHEST` — run with the user's highest privileges.
|
|
1032
|
+
* - `/IT` — interactive token: run only while the user is logged on,
|
|
1033
|
+
* using their session token, so NO stored password is
|
|
1034
|
+
* required (schtasks would otherwise prompt for one).
|
|
1035
|
+
* - `/F` — overwrite an existing task (idempotent reinstall).
|
|
1036
|
+
*
|
|
1037
|
+
* ONLOGON + `/IT` (vs `/SC ONSTART` with `/RU SYSTEM`) is deliberate: Chroxy is a
|
|
1038
|
+
* per-user dev daemon. Running at boot as SYSTEM would start it before anyone
|
|
1039
|
+
* logs on, as SYSTEM rather than the user — no interactive session, and (once
|
|
1040
|
+
* per-user credential encryption lands, DPAPI, #6644) no access to the user's
|
|
1041
|
+
* credentials — wrong for this workload. The trade-off (daemon starts at logon,
|
|
1042
|
+
* not boot) is documented for the user in `service-cmd.js`.
|
|
1043
|
+
*
|
|
1044
|
+
* NOTE: creating an ONLOGON task requires an elevated (Administrator) token —
|
|
1045
|
+
* a non-elevated `schtasks /Create /SC ONLOGON` fails with "Access is denied."
|
|
1046
|
+
* The catch below surfaces that stderr and tells the user to re-run elevated.
|
|
1047
|
+
*
|
|
1048
|
+
* @param {object} config - Same shape as installService's config.
|
|
1049
|
+
* @param {object} paths - getServicePaths('win32') result.
|
|
1050
|
+
* @returns {{ installed: true, platform: 'win32', taskName: string, wrapperPath: string }}
|
|
1051
|
+
*/
|
|
1052
|
+
function installWindowsService(config, paths, reinstall = false) {
|
|
1053
|
+
const stateDir = config._stateDir || defaultConfigDir()
|
|
1054
|
+
const logDir = config._logDir || paths.logDir
|
|
1055
|
+
const wrapperPath = config._wrapperPath || join(stateDir, WINDOWS_WRAPPER_NAME)
|
|
1056
|
+
const taskName = config._taskName || WINDOWS_TASK_NAME
|
|
1057
|
+
const exec = config._exec || execFileSync
|
|
1058
|
+
const cwd = config.cwd || homedir()
|
|
1059
|
+
const hadState = !!loadServiceState(stateDir)
|
|
1060
|
+
const preexisting = snapshotExisting([wrapperPath])
|
|
1061
|
+
|
|
1062
|
+
if (!existsSync(logDir)) {
|
|
1063
|
+
mkdirSync(logDir, { recursive: true })
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
// Write the wrapper Task Scheduler runs (sets cwd + PATH + log redirection).
|
|
1067
|
+
const wrapperContent = generateWindowsServiceWrapper({
|
|
1068
|
+
nodePath: config.nodePath,
|
|
1069
|
+
chroxyBin: config.chroxyBin,
|
|
1070
|
+
claudeBin: config.claudeBin,
|
|
1071
|
+
cwd,
|
|
1072
|
+
logDir,
|
|
1073
|
+
})
|
|
1074
|
+
writeServiceWrapper(wrapperPath, wrapperContent)
|
|
1075
|
+
|
|
1076
|
+
// Register the scheduled task. `/TR` is quoted so a wrapper path with spaces
|
|
1077
|
+
// runs correctly; it holds only the wrapper path — never a secret (#6647).
|
|
1078
|
+
if (!config._skipRegister) {
|
|
1079
|
+
try {
|
|
1080
|
+
exec('schtasks', [
|
|
1081
|
+
'/Create',
|
|
1082
|
+
'/TN', taskName,
|
|
1083
|
+
'/TR', `"${wrapperPath}"`,
|
|
1084
|
+
'/SC', 'ONLOGON',
|
|
1085
|
+
'/RL', 'HIGHEST',
|
|
1086
|
+
'/IT',
|
|
1087
|
+
'/F',
|
|
1088
|
+
], { stdio: 'pipe' })
|
|
1089
|
+
} catch (err) {
|
|
1090
|
+
// `schtasks` runs with piped stdio, so on failure execFileSync throws a
|
|
1091
|
+
// generic "Command failed" and drops the real reason. Surface schtasks'
|
|
1092
|
+
// stderr, and — since creating an ONLOGON task requires elevation, so a
|
|
1093
|
+
// non-elevated install fails with "Access is denied." — add the fix (#6647).
|
|
1094
|
+
rollbackFreshInstall({ hadState, reinstall, preexisting }, [wrapperPath])
|
|
1095
|
+
const detail = String(err?.stderr || '').trim()
|
|
1096
|
+
const denied = /access is denied/i.test(detail)
|
|
1097
|
+
throw new Error(
|
|
1098
|
+
`schtasks could not register the Chroxy task${detail ? `: ${detail}` : ` (${err.message})`}` +
|
|
1099
|
+
(denied
|
|
1100
|
+
? '\nRegistering a logon-triggered task requires elevation — run `chroxy service install` from an Administrator terminal.'
|
|
1101
|
+
: ''),
|
|
1102
|
+
)
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
saveServiceState({
|
|
1107
|
+
installedAt: new Date().toISOString(),
|
|
1108
|
+
platform: 'win32',
|
|
1109
|
+
taskName,
|
|
1110
|
+
// servicePath mirrors the wrapper so the generic uninstall cleanup removes it.
|
|
1111
|
+
servicePath: wrapperPath,
|
|
1112
|
+
wrapperPath,
|
|
1113
|
+
nodePath: config.nodePath,
|
|
1114
|
+
chroxyBin: config.chroxyBin,
|
|
1115
|
+
claudeBin: config.claudeBin,
|
|
1116
|
+
cwd,
|
|
1117
|
+
// ONLOGON always starts the daemon at login; there is no separate toggle.
|
|
1118
|
+
startAtLogin: true,
|
|
1119
|
+
}, stateDir)
|
|
1120
|
+
|
|
1121
|
+
return { installed: true, platform: 'win32', taskName, wrapperPath }
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
/**
|
|
1125
|
+
* Query the Windows scheduled task's registration + run state via
|
|
1126
|
+
* `schtasks /Query /TN Chroxy /V /FO LIST` (#6647). Best-effort: returns
|
|
1127
|
+
* `{ registered: false }` when the task is absent or schtasks is unavailable.
|
|
1128
|
+
*
|
|
1129
|
+
* @param {object} [options]
|
|
1130
|
+
* @param {(cmd: string, args: string[], opts: object) => string} [options._exec]
|
|
1131
|
+
* @param {string} [options._taskName]
|
|
1132
|
+
* @returns {{ registered: boolean, status: string|null }}
|
|
1133
|
+
*/
|
|
1134
|
+
export function getWindowsTaskStatus(options = {}) {
|
|
1135
|
+
const exec = options._exec || execFileSync
|
|
1136
|
+
const taskName = options._taskName || WINDOWS_TASK_NAME
|
|
1137
|
+
try {
|
|
1138
|
+
const out = String(exec('schtasks', ['/Query', '/TN', taskName, '/V', '/FO', 'LIST'], { encoding: 'utf-8' }))
|
|
1139
|
+
// The `/V /FO LIST` output has a `Status: Running|Ready|Disabled` line.
|
|
1140
|
+
const m = out.match(/^\s*Status:\s*(.+?)\s*$/mi)
|
|
1141
|
+
return { registered: true, status: m ? m[1].trim() : null }
|
|
1142
|
+
} catch {
|
|
1143
|
+
return { registered: false, status: null }
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
|
|
553
1147
|
/**
|
|
554
1148
|
* Uninstall the Chroxy system daemon.
|
|
555
1149
|
* Stops the service if running, removes the service file and state.
|
|
556
1150
|
*
|
|
557
1151
|
* @param {object} [options]
|
|
558
1152
|
* @param {string} [options._stateDir] - Override state directory (testing)
|
|
559
|
-
* @param {boolean} [options._skipUnregister] - Skip launchctl/systemctl unregistration (testing)
|
|
1153
|
+
* @param {boolean} [options._skipUnregister] - Skip launchctl/systemctl/schtasks unregistration (testing)
|
|
1154
|
+
* @param {(cmd: string, args: string[], opts: object) => void} [options._exec]
|
|
1155
|
+
* Injectable exec for testing (defaults to execFileSync).
|
|
560
1156
|
*/
|
|
561
1157
|
export function uninstallService(options = {}) {
|
|
562
|
-
const stateDir = options._stateDir ||
|
|
1158
|
+
const stateDir = options._stateDir || defaultConfigDir()
|
|
563
1159
|
const state = loadServiceState(stateDir)
|
|
564
1160
|
|
|
565
1161
|
if (!state) {
|
|
@@ -568,11 +1164,14 @@ export function uninstallService(options = {}) {
|
|
|
568
1164
|
|
|
569
1165
|
// Unregister from system (unless testing)
|
|
570
1166
|
if (!options._skipUnregister) {
|
|
1167
|
+
const exec = options._exec || execFileSync
|
|
571
1168
|
try {
|
|
572
1169
|
if (state.platform === 'darwin') {
|
|
573
|
-
|
|
1170
|
+
exec('launchctl', ['bootout', `gui/${process.getuid()}/${SERVICE_LABEL}`], { stdio: 'ignore' })
|
|
1171
|
+
} else if (state.platform === 'win32') {
|
|
1172
|
+
exec('schtasks', ['/Delete', '/TN', state.taskName || WINDOWS_TASK_NAME, '/F'], { stdio: 'ignore' })
|
|
574
1173
|
} else {
|
|
575
|
-
|
|
1174
|
+
exec('systemctl', ['--user', 'disable', '--now', 'chroxy.service'], { stdio: 'ignore' })
|
|
576
1175
|
}
|
|
577
1176
|
} catch {
|
|
578
1177
|
// Service may already be stopped/unloaded — continue cleanup
|
|
@@ -610,15 +1209,16 @@ export function uninstallService(options = {}) {
|
|
|
610
1209
|
export function startService(options = {}) {
|
|
611
1210
|
const plat = options._platform || platform()
|
|
612
1211
|
const paths = getServicePaths(plat)
|
|
613
|
-
const stateDir = options._stateDir ||
|
|
1212
|
+
const stateDir = options._stateDir || defaultConfigDir()
|
|
614
1213
|
const exec = options._exec || execFileSync
|
|
615
1214
|
|
|
616
1215
|
if (plat === 'win32') {
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
1216
|
+
// Run the registered scheduled task now (#6647).
|
|
1217
|
+
const taskName = options._taskName || WINDOWS_TASK_NAME
|
|
1218
|
+
if (!options._skipExec) {
|
|
1219
|
+
exec('schtasks', ['/Run', '/TN', taskName], { stdio: 'pipe' })
|
|
621
1220
|
}
|
|
1221
|
+
return { started: true, message: 'Service started' }
|
|
622
1222
|
}
|
|
623
1223
|
|
|
624
1224
|
if (!options._skipExec) {
|
|
@@ -702,19 +1302,22 @@ function bootstrapLaunchd(plistPath, exec) {
|
|
|
702
1302
|
export function stopService(options = {}) {
|
|
703
1303
|
const plat = options._platform || platform()
|
|
704
1304
|
const paths = getServicePaths(plat)
|
|
1305
|
+
const exec = options._exec || execFileSync
|
|
705
1306
|
|
|
706
1307
|
if (plat === 'win32') {
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
1308
|
+
// End the running scheduled task's action (#6647).
|
|
1309
|
+
const taskName = options._taskName || WINDOWS_TASK_NAME
|
|
1310
|
+
if (!options._skipExec) {
|
|
1311
|
+
exec('schtasks', ['/End', '/TN', taskName], { stdio: 'pipe' })
|
|
710
1312
|
}
|
|
1313
|
+
return { stopped: true, message: 'Service stopped' }
|
|
711
1314
|
}
|
|
712
1315
|
|
|
713
1316
|
if (!options._skipExec) {
|
|
714
1317
|
if (paths.type === 'launchd') {
|
|
715
|
-
|
|
1318
|
+
exec('launchctl', ['bootout', `gui/${process.getuid()}/${SERVICE_LABEL}`], { stdio: 'pipe' })
|
|
716
1319
|
} else {
|
|
717
|
-
|
|
1320
|
+
exec('systemctl', ['--user', 'stop', 'chroxy.service'], { stdio: 'pipe' })
|
|
718
1321
|
}
|
|
719
1322
|
}
|
|
720
1323
|
|
|
@@ -728,7 +1331,7 @@ export function stopService(options = {}) {
|
|
|
728
1331
|
* @returns {{ installed: boolean, running: boolean, pid: number|null, stale: boolean }}
|
|
729
1332
|
*/
|
|
730
1333
|
export function getServiceStatus(options = {}) {
|
|
731
|
-
const configDir = options.configDir ||
|
|
1334
|
+
const configDir = options.configDir || defaultConfigDir()
|
|
732
1335
|
const state = loadServiceState(configDir)
|
|
733
1336
|
|
|
734
1337
|
if (!state) {
|
|
@@ -778,7 +1381,7 @@ export function getServiceStatus(options = {}) {
|
|
|
778
1381
|
* @returns {Promise<object>} Full status including health, connection info, etc.
|
|
779
1382
|
*/
|
|
780
1383
|
export async function getFullServiceStatus(options = {}) {
|
|
781
|
-
const configDir = options.configDir ||
|
|
1384
|
+
const configDir = options.configDir || defaultConfigDir()
|
|
782
1385
|
const status = getServiceStatus({ configDir })
|
|
783
1386
|
const result = { ...status }
|
|
784
1387
|
|
|
@@ -819,17 +1422,43 @@ export async function getFullServiceStatus(options = {}) {
|
|
|
819
1422
|
}
|
|
820
1423
|
}
|
|
821
1424
|
|
|
822
|
-
// Read recent log lines
|
|
823
|
-
|
|
824
|
-
|
|
1425
|
+
// Read recent log lines. #7162: three files carry the daemon's recent
|
|
1426
|
+
// activity and NONE alone is sufficient — chroxy.log is written only by
|
|
1427
|
+
// the forked server child; the supervisor's lifecycle lines (crash loops,
|
|
1428
|
+
// restart backoff) exist only in the stdout capture; and the supervisor's
|
|
1429
|
+
// warn/error plus hard-crash traces land only in the stderr capture (the
|
|
1430
|
+
// supervisor process has no file log). Merge all three tails by timestamp
|
|
1431
|
+
// so a crash-looping daemon's restart lines and last error surface next to
|
|
1432
|
+
// the child's last words, and stale files lose to fresher lines naturally.
|
|
1433
|
+
const tails = []
|
|
1434
|
+
for (const name of ['chroxy.log', 'chroxy-stdout.log', 'chroxy-stderr.log']) {
|
|
1435
|
+
const logFile = join(configDir, 'logs', name)
|
|
1436
|
+
if (!existsSync(logFile)) continue
|
|
825
1437
|
try {
|
|
826
|
-
const
|
|
827
|
-
|
|
828
|
-
|
|
1438
|
+
const lines = readFileSync(logFile, 'utf-8').trimEnd().split('\n').slice(-10)
|
|
1439
|
+
let last = 0
|
|
1440
|
+
for (const text of lines) {
|
|
1441
|
+
if (!text) continue
|
|
1442
|
+
// Plain format leads with the ISO stamp; JSON mode carries "ts".
|
|
1443
|
+
// Unstamped lines (crash traces, banners) inherit the preceding
|
|
1444
|
+
// stamped line's time so multi-line output stays together.
|
|
1445
|
+
const m = /^(\d{4}-\d{2}-\d{2}T[\d:.]+Z)/.exec(text)
|
|
1446
|
+
|| /^\{"ts":"(\d{4}-[^"]+)"/.exec(text)
|
|
1447
|
+
if (m) {
|
|
1448
|
+
const parsed = Date.parse(m[1])
|
|
1449
|
+
if (!Number.isNaN(parsed)) last = parsed
|
|
1450
|
+
}
|
|
1451
|
+
tails.push({ ts: last, text })
|
|
1452
|
+
}
|
|
829
1453
|
} catch {
|
|
830
|
-
//
|
|
1454
|
+
// Unreadable candidate — surface whatever the other file has
|
|
831
1455
|
}
|
|
832
1456
|
}
|
|
1457
|
+
if (tails.length > 0) {
|
|
1458
|
+
// Array.prototype.sort is stable: equal timestamps keep push order.
|
|
1459
|
+
tails.sort((a, b) => a.ts - b.ts)
|
|
1460
|
+
result.recentLogs = tails.slice(-5).map(t => t.text)
|
|
1461
|
+
}
|
|
833
1462
|
|
|
834
1463
|
return result
|
|
835
1464
|
}
|