@chroxy/server 0.11.0 → 0.11.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONFIG.md +204 -18
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +166 -11
- package/package.json +16 -12
- package/sidecar/Dockerfile +1 -1
- package/sidecar/PROTOCOL.md +9 -1
- package/sidecar/agent.js +102 -10
- package/sidecar/package-lock.json +3 -3
- package/src/acp-config.js +206 -0
- package/src/acp-session.js +954 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +293 -0
- package/src/agent-control/client.js +1616 -0
- package/src/agent-control/events.js +547 -0
- package/src/agent-control/local-connection.js +275 -0
- package/src/agent-control/mcp-server.js +545 -0
- package/src/anthropic-compatible-config.js +29 -4
- package/src/anthropic-compatible-session.js +15 -6
- package/src/anthropic-openai-shim.js +0 -1
- package/src/archive-continuation.js +164 -0
- package/src/assistant-response.js +24 -0
- package/src/auth-probes.js +120 -13
- package/src/background-shell-tracker.js +27 -0
- package/src/base-session.js +1203 -36
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +19 -0
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +11 -5
- package/src/bound-client-policy.js +279 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +69 -5
- package/src/built-in-tools/tool-transforms.js +1113 -13
- package/src/byok-compose-state.js +6 -9
- package/src/byok-credentials.js +2 -3
- package/src/byok-mcp-client.js +92 -7
- package/src/byok-mcp-config.js +628 -121
- package/src/byok-mcp-fleet.js +49 -7
- package/src/byok-mcp-oauth-store.js +18 -16
- package/src/byok-mcp-trust.js +3 -3
- package/src/byok-session.js +650 -175
- package/src/byok-tool-executor.js +2662 -26
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +64 -46
- package/src/claude-channel-session.js +16 -10
- package/src/claude-model-catalog.js +131 -16
- package/src/claude-model-refresh.js +385 -0
- package/src/claude-model-request.js +103 -0
- package/src/claude-stream-parser.js +53 -3
- package/src/claude-tui/diagnostic-tail.js +83 -0
- package/src/claude-tui/form-driver.js +44 -7
- package/src/claude-tui/model-error.js +41 -0
- package/src/claude-tui/pty-driver.js +211 -88
- package/src/claude-tui/sanitize-question-payload.js +109 -0
- package/src/claude-tui/usage-limit.js +239 -0
- package/src/claude-tui-session.js +3513 -287
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +4 -4
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/deploy-cmd.js +45 -10
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/init-cmd.js +15 -16
- package/src/cli/providers-cmd.js +3 -3
- package/src/cli/schedule-cmd.js +68 -39
- package/src/cli/server-cmd.js +48 -1
- package/src/cli/service-cmd.js +33 -10
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +162 -11
- package/src/cli/tokens-cmd.js +4 -5
- package/src/cli/tunnel-cmd.js +255 -24
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1066 -121
- package/src/cli.js +4 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +1454 -79
- package/src/codex-bundled-client.js +66 -0
- package/src/codex-model-catalog.js +548 -0
- package/src/codex-model-rejections.js +87 -0
- package/src/codex-native-resume.js +104 -0
- package/src/codex-protocol-capabilities.js +188 -0
- package/src/codex-session.js +450 -27
- package/src/config-dir-migration.js +444 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +286 -26
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +5 -9
- package/src/connection-locality.js +60 -0
- package/src/container-liveness-monitor.js +189 -0
- package/src/continuation-metadata-worker.js +17 -0
- package/src/continuations.js +114 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +7 -20
- package/src/control-room/skills-inventory.js +2 -2
- package/src/conversation-scanner.js +40 -18
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +24 -22
- package/src/credential-store.js +23 -19
- package/src/daemon-commit.js +92 -0
- package/src/daemon-idle-state.js +171 -0
- package/src/daemon-update-status.js +314 -0
- package/src/dashboard-build.js +70 -0
- package/src/declared-status.js +90 -0
- package/src/deepseek-credentials.js +2 -3
- package/src/dev-preview.js +169 -182
- package/src/device-preferences.js +2 -2
- package/src/diff-parser.js +87 -0
- package/src/discord-credentials.js +2 -3
- package/src/docker-byok-pool.js +3 -1
- package/src/docker-byok-session.js +678 -78
- package/src/docker-image-allowlist.js +23 -1
- package/src/docker-sdk-session.js +172 -3
- package/src/docker-session.js +284 -10
- package/src/doctor.js +767 -61
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +95 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +31 -10
- package/src/environments/backends/k8s.js +49 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +118 -13
- package/src/event-normalizer.js +151 -233
- package/src/gemini-session.js +81 -5
- package/src/handler-utils.js +535 -68
- package/src/handlers/checkpoint-handlers.js +39 -4
- package/src/handlers/control-room-handlers.js +51 -11
- package/src/handlers/conversation-handlers.js +469 -56
- package/src/handlers/daemon-update-handlers.js +81 -0
- package/src/handlers/evaluator-handlers.js +14 -1
- package/src/handlers/feature-handlers.js +186 -69
- package/src/handlers/file-handlers.js +57 -13
- package/src/handlers/input-handlers.js +685 -48
- package/src/handlers/orchestration-handlers.js +3 -3
- package/src/handlers/scheduler-handlers.js +88 -14
- package/src/handlers/session-handlers.js +542 -20
- package/src/handlers/session-pr-status-handlers.js +283 -0
- package/src/handlers/session-pr-threads-handlers.js +247 -0
- package/src/handlers/settings-handlers.js +330 -42
- package/src/handlers/skills-handlers.js +13 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/health-proof.js +40 -0
- package/src/history-page.js +104 -0
- package/src/http-routes.js +127 -8
- package/src/ide/search.js +24 -6
- package/src/ide/symbols.js +20 -6
- package/src/input-context.js +117 -0
- package/src/instruction-policy-compiler.js +229 -0
- package/src/instruction-policy.js +250 -0
- package/src/jsonl-reader.js +289 -82
- package/src/jsonl-subprocess-session.js +92 -8
- package/src/keychain.js +1 -1
- package/src/logger.js +63 -17
- package/src/mailbox-route.js +11 -22
- package/src/message-wire.js +386 -0
- package/src/model-discovery.js +43 -3
- package/src/models.js +1276 -174
- package/src/notification-prefs.js +12 -4
- package/src/notifications/discord-billing-sink.js +22 -5
- package/src/notifications/discord-ci-sink.js +243 -0
- package/src/notifications/discord-webhook-client.js +71 -0
- package/src/notifications/discord-webhook-sink.js +64 -23
- package/src/notifications/expo-push-sink.js +85 -6
- package/src/notifications/ready-body.js +16 -5
- package/src/ollama-session.js +34 -2
- package/src/orchestration/build-manager.js +9 -2
- package/src/orchestration/git-ops.js +41 -7
- package/src/orchestration/orchestration-manager.js +80 -33
- package/src/orchestration/permission-gate.js +13 -1
- package/src/orchestration/run-model.js +2 -1
- package/src/orchestration/turn-driver.js +44 -20
- package/src/orphan-reaper.js +413 -0
- package/src/outgoing-policy.js +183 -0
- package/src/pairing.js +92 -13
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1357 -42
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +712 -83
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolver.js +122 -8
- package/src/permission-scope.js +43 -0
- package/src/platform.js +159 -43
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +207 -4
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +360 -8
- package/src/roster-broadcast.js +186 -0
- package/src/scheduled-task-store.js +318 -26
- package/src/scheduler.js +73 -3
- package/src/sdk-session.js +2060 -187
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +11 -2
- package/src/server-cli/server-orchestrator.js +28 -5
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +524 -38
- package/src/server-identity.js +15 -11
- package/src/service.js +396 -25
- package/src/session-archive-limits.js +15 -0
- package/src/session-archive.js +1029 -0
- package/src/session-busy-state.js +72 -0
- package/src/session-ci-watcher.js +926 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +3491 -312
- package/src/session-message-history.js +722 -16
- package/src/session-pr-status.js +654 -0
- package/src/session-pr-threads.js +271 -0
- package/src/session-preset-trust.js +3 -3
- package/src/session-preset.js +10 -5
- package/src/session-state-persistence.js +94 -17
- package/src/session-timeout-manager.js +20 -0
- package/src/session-token-store.js +17 -8
- package/src/session-wake.js +240 -0
- package/src/shell-approval-info.js +2 -2
- package/src/shell-approval-store.js +3 -1
- package/src/skills-loader.js +7 -4
- package/src/skills-manager.js +2 -2
- package/src/skills-trust.js +95 -13
- package/src/skills-usage.js +2 -3
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +23 -11
- package/src/summarize-session.js +51 -4
- package/src/supervisor.js +22 -11
- package/src/sweep-stale-provider-dirs.js +95 -0
- package/src/thinking-level-wire.js +39 -0
- package/src/thinking-stream.js +179 -0
- package/src/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +372 -25
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +34 -31
- package/src/tunnel/index.js +9 -0
- package/src/tunnel/preview.js +64 -0
- package/src/turn-outcome.js +137 -0
- package/src/usage-normalize.js +9 -5
- package/src/user-shell-session.js +59 -5
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +741 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +597 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +25 -0
- package/src/utils/bounded-regex.js +153 -0
- package/src/utils/claude-binary.js +43 -0
- package/src/utils/claude-config-dir.js +245 -0
- package/src/utils/claude-login-command.js +16 -0
- package/src/utils/claude-native-route.js +81 -0
- package/src/utils/componentwise-resolver.js +133 -37
- package/src/utils/deploy-control-files.js +87 -0
- package/src/utils/exec-failure-reason.js +21 -0
- package/src/utils/git-repo.js +42 -0
- package/src/utils/is-entry-point.js +137 -0
- package/src/utils/node-pty-probe.js +95 -0
- package/src/utils/node-pty-support.js +118 -0
- package/src/utils/opened-file-path.js +167 -0
- package/src/utils/path-containment.js +165 -0
- package/src/utils/permission-mode-sidecar.js +51 -0
- package/src/utils/preflight.js +360 -16
- package/src/utils/read-limiter.js +217 -0
- package/src/utils/regular-file.js +375 -0
- package/src/utils/safe-regex.js +113 -0
- package/src/utils/small-file.js +129 -0
- package/src/utils/spawn-env.js +189 -4
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-provenance.js +406 -13
- package/src/web-task-manager.js +256 -16
- package/src/worktree-gc.js +7 -2
- package/src/ws-auth.js +69 -21
- package/src/ws-broadcaster.js +14 -2
- package/src/ws-client-manager.js +16 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +331 -58
- package/src/ws-file-ops/common.js +320 -14
- package/src/ws-file-ops/git.js +395 -42
- package/src/ws-file-ops/index.js +2 -0
- package/src/ws-file-ops/memory.js +137 -35
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +571 -113
- package/src/ws-forwarding.js +329 -39
- package/src/ws-handler-context.js +70 -2
- package/src/ws-history.js +940 -172
- package/src/ws-message-handlers.js +17 -1
- package/src/ws-permissions.js +307 -37
- package/src/ws-schemas.js +5 -0
- package/src/ws-server.js +643 -96
- package/sidecar/node_modules/.package-lock.json +0 -29
- package/sidecar/node_modules/ws/LICENSE +0 -20
- package/sidecar/node_modules/ws/README.md +0 -548
- package/sidecar/node_modules/ws/browser.js +0 -8
- package/sidecar/node_modules/ws/index.js +0 -22
- package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
- package/sidecar/node_modules/ws/lib/constants.js +0 -19
- package/sidecar/node_modules/ws/lib/event-target.js +0 -292
- package/sidecar/node_modules/ws/lib/extension.js +0 -203
- package/sidecar/node_modules/ws/lib/limiter.js +0 -55
- package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
- package/sidecar/node_modules/ws/lib/receiver.js +0 -706
- package/sidecar/node_modules/ws/lib/sender.js +0 -602
- package/sidecar/node_modules/ws/lib/stream.js +0 -161
- package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
- package/sidecar/node_modules/ws/lib/validation.js +0 -152
- package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
- package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
- package/sidecar/node_modules/ws/package.json +0 -70
- package/sidecar/node_modules/ws/wrapper.mjs +0 -21
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
- package/src/dashboard-next/dist/index.html +0 -13
- package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The ONE copy of the parsing rules for the files the dashboard's update banner
|
|
3
|
+
* exchanges with the idle-only auto-deploy script (#8331), imported by both
|
|
4
|
+
* `daemon-update-status.js` (the daemon) and `scripts/deploy-daemon.mjs`. What counts
|
|
5
|
+
* as a valid request or postpone, how old a request may be, and what a timestamp may
|
|
6
|
+
* look like are decided here and nowhere else, so the two sides cannot drift.
|
|
7
|
+
*
|
|
8
|
+
* Next to `small-file.js`, which decides how the files are READ and WRITTEN; this
|
|
9
|
+
* module decides what a parsed value MEANS.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
const SHA = /^[0-9a-f]{40}$/i
|
|
13
|
+
const NONCE = /^[A-Za-z0-9._-]{1,64}$/
|
|
14
|
+
|
|
15
|
+
/** A request older than this is ignored: a click from an hour ago must not restart the daemon now. At least twice the 600 s launchd StartInterval, so one missed tick does not lose a click. */
|
|
16
|
+
export const REQUEST_TTL_MS = 20 * 60 * 1000
|
|
17
|
+
/** How far in the future a `requestedAt` may be (clock skew between the writer and the reader). */
|
|
18
|
+
export const REQUEST_SKEW_MS = 5 * 60 * 1000
|
|
19
|
+
/**
|
|
20
|
+
* How long an `applying` marker (written by the script when a forward deploy starts
|
|
21
|
+
* building) is believed. The build timeout is 20 minutes, so 30 covers it plus slack;
|
|
22
|
+
* past that the marker is the leftover of a crashed tick, not live work.
|
|
23
|
+
*/
|
|
24
|
+
export const APPLYING_MAX_MS = 30 * 60 * 1000
|
|
25
|
+
/** What the daemon's Postpone writes. */
|
|
26
|
+
export const POSTPONE_MS = 60 * 60 * 1000
|
|
27
|
+
/** A postpone is honoured only for at most this long from its own `requestedAt`: the hour, plus a minute of slack. */
|
|
28
|
+
export const POSTPONE_MAX_MS = POSTPONE_MS + 60 * 1000
|
|
29
|
+
|
|
30
|
+
export const isSha = (v) => typeof v === 'string' && SHA.test(v)
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* A timestamp both sides can safely use: a string that parses, with a year in
|
|
34
|
+
* 1970..9999. A year outside that range would make `toISOString()` emit the
|
|
35
|
+
* extended `+275760-…` form, which the wire schema's `datetime()` rejects and
|
|
36
|
+
* which would then fail a client's whole-frame parse.
|
|
37
|
+
*/
|
|
38
|
+
export function isIso(v) {
|
|
39
|
+
if (typeof v !== 'string' || v.length > 40) return false
|
|
40
|
+
const t = Date.parse(v)
|
|
41
|
+
if (!Number.isFinite(t)) return false
|
|
42
|
+
const year = new Date(t).getUTCFullYear()
|
|
43
|
+
return year >= 1970 && year <= 9999
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Canonical UTC ISO for a timestamp `isIso` accepted. */
|
|
47
|
+
export const canonIso = (v) => new Date(Date.parse(v)).toISOString()
|
|
48
|
+
|
|
49
|
+
/** -> a valid restart request, or null. The server writes exactly this shape. */
|
|
50
|
+
export function parseRequest(v) {
|
|
51
|
+
if (!v || typeof v !== 'object' || v.action !== 'restart-now') return null
|
|
52
|
+
if (!isSha(v.target)) return null
|
|
53
|
+
if (typeof v.force !== 'boolean') return null
|
|
54
|
+
if (!isIso(v.requestedAt)) return null
|
|
55
|
+
if (typeof v.nonce !== 'string' || !NONCE.test(v.nonce)) return null
|
|
56
|
+
return { target: v.target.toLowerCase(), force: v.force, requestedAt: canonIso(v.requestedAt), nonce: v.nonce }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** A request is fresh while it is no older than the TTL and not meaningfully from the future. */
|
|
60
|
+
export function isRequestFresh(req, nowMs) {
|
|
61
|
+
const age = nowMs - Date.parse(req.requestedAt)
|
|
62
|
+
return age <= REQUEST_TTL_MS && age >= -60 * 1000
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* -> `{ target, until }` for a postpone that is well-formed AND internally sane, else
|
|
67
|
+
* null. It needs a valid `requestedAt` that is not more than REQUEST_SKEW_MS in the
|
|
68
|
+
* future, and a hold of at most POSTPONE_MAX_MS from that timestamp, so a hand-written
|
|
69
|
+
* far-future deadline is not a postpone.
|
|
70
|
+
*/
|
|
71
|
+
export function parsePostpone(v, nowMs) {
|
|
72
|
+
if (!v || typeof v !== 'object' || !isSha(v.target) || !isIso(v.until) || !isIso(v.requestedAt)) return null
|
|
73
|
+
const asked = Date.parse(v.requestedAt)
|
|
74
|
+
if (asked - nowMs > REQUEST_SKEW_MS) return null
|
|
75
|
+
if (Date.parse(v.until) - asked > POSTPONE_MAX_MS) return null
|
|
76
|
+
return { target: v.target.toLowerCase(), until: canonIso(v.until) }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Is an `applying` marker's `applyingSince` recent enough to be live? Missing, invalid,
|
|
81
|
+
* older than APPLYING_MAX_MS, or meaningfully from the future: no.
|
|
82
|
+
*/
|
|
83
|
+
export function isApplyingFresh(applyingSince, nowMs) {
|
|
84
|
+
// A missing or unparseable value is NaN, which fails both comparisons: not fresh.
|
|
85
|
+
const age = nowMs - Date.parse(applyingSince)
|
|
86
|
+
return age <= APPLYING_MAX_MS && age >= -REQUEST_SKEW_MS
|
|
87
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Build a human-legible degradation reason from a rejected `execFile` promise.
|
|
3
|
+
*
|
|
4
|
+
* Every CLI-backed survey in the daemon degrades a failed probe to a `reason`
|
|
5
|
+
* string rather than throwing (absence is signal, never an error), and they all
|
|
6
|
+
* want the same thing out of the rejection: the CLI's own first line of stderr
|
|
7
|
+
* when it produced one, else the Error's message. This was defined privately in
|
|
8
|
+
* `control-room/integrations.js` and is now shared, so the session PR/CI survey
|
|
9
|
+
* (#7344) does not become a second copy that drifts from it.
|
|
10
|
+
*
|
|
11
|
+
* @param {unknown} err - the rejection from a promisified `execFile`.
|
|
12
|
+
* @param {string} [label] - the command being described, e.g. 'gh pr list'.
|
|
13
|
+
* @returns {string} `<label> failed: <first stderr line | error message>`
|
|
14
|
+
*/
|
|
15
|
+
export function execFailureReason(err, label = 'command') {
|
|
16
|
+
const stderr = err && typeof err === 'object' && typeof err.stderr === 'string' ? err.stderr : ''
|
|
17
|
+
const firstLine = stderr.split('\n').map(l => l.trim()).find(l => l.length > 0)
|
|
18
|
+
if (firstLine) return `${label} failed: ${firstLine}`
|
|
19
|
+
const message = err && typeof err === 'object' && typeof err.message === 'string' ? err.message : 'unknown error'
|
|
20
|
+
return `${label} failed: ${message}`
|
|
21
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { execFileSync, execFile } from 'child_process'
|
|
2
|
+
import { promisify } from 'util'
|
|
3
|
+
import { GIT } from '../git.js'
|
|
4
|
+
|
|
5
|
+
const execFileAsync = promisify(execFile)
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The one "is this directory inside a git repository?" probe. Both the
|
|
9
|
+
* worktree-create path (`SessionManager._addDetachedWorktree`) and the
|
|
10
|
+
* New Session dialog's up-front `check_git_repo` query use it, so the two
|
|
11
|
+
* agree on what a repo is (#8972). They can still disagree at the margins
|
|
12
|
+
* (timeouts, transient failures, the filesystem changing between the check and
|
|
13
|
+
* Create); the create-time refusal is the backstop.
|
|
14
|
+
*
|
|
15
|
+
* `git -C <dir> rev-parse --git-dir` succeeds for the repo root and for any
|
|
16
|
+
* subdirectory of a repo or worktree. `dir` is the argument of `-C`, so it is
|
|
17
|
+
* never parsed as an option. The argv is written out as a literal at each call
|
|
18
|
+
* so the argv-sink lint can resolve it.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/** Synchronous probe. Never throws: any failure reads as "not a repo". */
|
|
22
|
+
export function isGitRepoSync(dir) {
|
|
23
|
+
try {
|
|
24
|
+
execFileSync(GIT, ['-C', dir, 'rev-parse', '--git-dir'], {
|
|
25
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
26
|
+
encoding: 'utf-8',
|
|
27
|
+
})
|
|
28
|
+
return true
|
|
29
|
+
} catch {
|
|
30
|
+
return false
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Async probe for request handlers (does not block the event loop). */
|
|
35
|
+
export async function isGitRepo(dir) {
|
|
36
|
+
try {
|
|
37
|
+
await execFileAsync(GIT, ['-C', dir, 'rev-parse', '--git-dir'], { encoding: 'utf-8', timeout: 5000 })
|
|
38
|
+
return true
|
|
39
|
+
} catch {
|
|
40
|
+
return false
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// is-entry-point.js — "was this module run directly, or imported?"
|
|
2
|
+
//
|
|
3
|
+
// Every hand-rolled version of this check in the repo was wrong the same way,
|
|
4
|
+
// so there is one implementation per reachable scope now (#7213, after #7198).
|
|
5
|
+
// Two other copies exist and cannot import this one:
|
|
6
|
+
//
|
|
7
|
+
// scripts/lib/is-entry-point.mjs — `scripts/` is outside every workspace
|
|
8
|
+
// package and reaches into none of them
|
|
9
|
+
// packages/server/sidecar/agent.js — a standalone in-pod bundle; the
|
|
10
|
+
// Dockerfile COPYs only agent.js and its
|
|
11
|
+
// package.json, so src/ is unreachable
|
|
12
|
+
//
|
|
13
|
+
// This file and scripts/lib/is-entry-point.mjs are byte-identical from the
|
|
14
|
+
// `if (!process.argv[1])` line down. sidecar/agent.js runs the same code as an
|
|
15
|
+
// inline IIFE, so it reads `import.meta.url` directly instead of taking it as a
|
|
16
|
+
// parameter and its comments are pod-specific — everything else matches.
|
|
17
|
+
//
|
|
18
|
+
// That is not a convention anyone has to remember: the drift gate in
|
|
19
|
+
// scripts/__tests__/is-entry-point.test.mjs extracts the guard from all three
|
|
20
|
+
// files, strips comments, and fails if they diverge. Change one, change the
|
|
21
|
+
// others, and the test will tell you if you missed one (#7222).
|
|
22
|
+
//
|
|
23
|
+
// Why this is not `import.meta.main`. Node 22.18.0 shipped that as a native,
|
|
24
|
+
// symlink-correct replacement that would delete all three copies. It is
|
|
25
|
+
// unusable here: the declared floor is `"node": ">=22"`, and on Node
|
|
26
|
+
// 22.0–22.17 `import.meta.main` is plain `undefined`. A falsy guard on an
|
|
27
|
+
// older-but-supported runtime is exactly the silent exit-0 no-op this module
|
|
28
|
+
// exists to prevent, reintroduced as a version skew no CI job pinned to
|
|
29
|
+
// `node-version: 22` would ever show. Revisit when the floor moves to >=22.18.
|
|
30
|
+
//
|
|
31
|
+
// The trap: Node's ESM loader RESOLVES SYMLINKS in `import.meta.url`, but
|
|
32
|
+
// `process.argv[1]` is whatever the caller typed. Neither `resolve()` nor
|
|
33
|
+
// `pathToFileURL()` follows symlinks, so every one of these compares a
|
|
34
|
+
// realpath against a non-realpath:
|
|
35
|
+
//
|
|
36
|
+
// resolve(fileURLToPath(import.meta.url)) === resolve(process.argv[1])
|
|
37
|
+
// import.meta.url === pathToFileURL(process.argv[1]).href
|
|
38
|
+
// process.argv[1] === fileURLToPath(import.meta.url)
|
|
39
|
+
//
|
|
40
|
+
// On macOS /tmp is a symlink to /private/tmp, so running a script by a /tmp
|
|
41
|
+
// path gives 'file:///private/tmp/x.mjs' on one side and 'file:///tmp/x.mjs'
|
|
42
|
+
// on the other. The guard reads false, main() never runs, and the process
|
|
43
|
+
// exits 0 having done nothing — the failure is silence, which is why it
|
|
44
|
+
// survived in four separate files.
|
|
45
|
+
//
|
|
46
|
+
// Demonstrated:
|
|
47
|
+
// import.meta.url : file:///private/tmp/ptfu/probe.mjs
|
|
48
|
+
// pathToFileURL(argv[1]) : file:///tmp/ptfu/probe.mjs
|
|
49
|
+
// guard would be : false
|
|
50
|
+
//
|
|
51
|
+
// Usage:
|
|
52
|
+
// import { isEntryPoint } from './utils/is-entry-point.js'
|
|
53
|
+
// if (isEntryPoint(import.meta.url)) { main() }
|
|
54
|
+
|
|
55
|
+
import { realpathSync } from 'node:fs'
|
|
56
|
+
import { basename, resolve } from 'node:path'
|
|
57
|
+
import { fileURLToPath } from 'node:url'
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* True when `importMetaUrl`'s module is the script node was invoked with.
|
|
61
|
+
*
|
|
62
|
+
* Order matters. The plain (non-realpath) comparison runs FIRST and is
|
|
63
|
+
* conclusive on its own: if the two paths are already identical, this module
|
|
64
|
+
* is the entry point and no filesystem access is needed to say so. Only when
|
|
65
|
+
* they differ is realpath consulted, because the sole reason they can differ
|
|
66
|
+
* while still naming the same file is a symlink somewhere in the invocation
|
|
67
|
+
* path.
|
|
68
|
+
*
|
|
69
|
+
* That ordering is the point, not an optimisation. Reaching for realpath
|
|
70
|
+
* first and treating a failure as `false` recreates the very bug this module
|
|
71
|
+
* exists to remove: an `EACCES` on some parent directory, or a script
|
|
72
|
+
* unlinked after launch, would make a direct `node foo.js` evaluate false,
|
|
73
|
+
* `main()` would never run, and the process would exit 0 having done nothing
|
|
74
|
+
* (#7217 review). Doing the cheap comparison first means no filesystem error
|
|
75
|
+
* can reach the common case at all.
|
|
76
|
+
*
|
|
77
|
+
* The one genuinely undecidable case is left: paths that differ AND cannot be
|
|
78
|
+
* realpath'd. Whether a symlink joins them is unknowable without the
|
|
79
|
+
* filesystem call that just failed, and `false` is the only defensible answer
|
|
80
|
+
* — it is also strictly better than the pre-#7213 behaviour, which got that
|
|
81
|
+
* case wrong even when realpath would have succeeded. Undecidable does not
|
|
82
|
+
* have to mean quiet, though — that combination is what made #7198 and #7214
|
|
83
|
+
* expensive to find — so that branch warns on stderr before returning (#7226).
|
|
84
|
+
* The ordinary "this module was imported" answer stays silent; only the branch
|
|
85
|
+
* that could not tell says anything.
|
|
86
|
+
*
|
|
87
|
+
* argv[1] absent (an `-e` eval, a REPL) means there is no invoked script, so
|
|
88
|
+
* nothing can be the entry point.
|
|
89
|
+
*
|
|
90
|
+
* @param {string} importMetaUrl - the calling module's `import.meta.url`
|
|
91
|
+
* @returns {boolean}
|
|
92
|
+
*/
|
|
93
|
+
export function isEntryPoint(importMetaUrl) {
|
|
94
|
+
if (!process.argv[1]) return false
|
|
95
|
+
|
|
96
|
+
const self = fileURLToPath(importMetaUrl)
|
|
97
|
+
const invoked = resolve(process.argv[1])
|
|
98
|
+
if (self === invoked) return true
|
|
99
|
+
|
|
100
|
+
// Paths differ — a symlink is the only thing that still makes them the same
|
|
101
|
+
// file, so this is where realpath earns its keep.
|
|
102
|
+
const failures = []
|
|
103
|
+
const real = (p) => {
|
|
104
|
+
try {
|
|
105
|
+
return realpathSync(p)
|
|
106
|
+
} catch (err) {
|
|
107
|
+
failures.push({ path: p, code: err.code || err.message })
|
|
108
|
+
return null
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
const realSelf = real(self)
|
|
112
|
+
const realInvoked = real(invoked)
|
|
113
|
+
if (realSelf !== null && realInvoked !== null) return realSelf === realInvoked
|
|
114
|
+
|
|
115
|
+
// Reaching here means realpath could not answer for at least one side, so
|
|
116
|
+
// whether a symlink still joins the two paths is unknowable and `false` is
|
|
117
|
+
// the only defensible return. It is not, however, an excuse for silence —
|
|
118
|
+
// that combination is what made #7198 and #7214 expensive (#7226).
|
|
119
|
+
//
|
|
120
|
+
// An earlier version of this warned only when the errno was something other
|
|
121
|
+
// than ENOENT, on the theory that a non-existent argv[1] was a DECIDED false
|
|
122
|
+
// and warning on it would cry wolf during ordinary imports. Both halves were
|
|
123
|
+
// wrong. An ordinary import never reaches this line at all — argv[1] is the
|
|
124
|
+
// script node is running, so it exists, both realpaths succeed, and the
|
|
125
|
+
// comparison above returns. And ENOENT is not decided: argv[1] existed at
|
|
126
|
+
// exec time by construction, so ENOENT means it was REMOVED SINCE. Swap a
|
|
127
|
+
// `current -> releases-v1` symlink mid-run and you get exactly that — self
|
|
128
|
+
// resolves, invoked is ENOENT, and the module genuinely IS the entry point.
|
|
129
|
+
// The carve-out bought nothing and hid that case.
|
|
130
|
+
const why = failures.map(({ path, code }) => `${path}: ${code}`).join('; ')
|
|
131
|
+
console.warn(
|
|
132
|
+
`[is-entry-point] ${basename(self)}: cannot determine whether this module was run ` +
|
|
133
|
+
`directly — realpath failed (${why}). Assuming it was imported, so its command-line ` +
|
|
134
|
+
'behaviour did NOT run. If you invoked it directly, it did nothing.',
|
|
135
|
+
)
|
|
136
|
+
return false
|
|
137
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* node-pty-probe.js (#8151 C3) — a cached, one-shot answer to "can node-pty's
|
|
3
|
+
* native binding actually load in THIS process?", so `listProviders()` can
|
|
4
|
+
* mark `claude-tui` unavailable in an environment (the official Docker image)
|
|
5
|
+
* where it never will, rather than letting a client discover that only after
|
|
6
|
+
* a session create fails and is immediately torn down.
|
|
7
|
+
*
|
|
8
|
+
* `import('node-pty')` is a real dynamic import — it rejects, it does NOT
|
|
9
|
+
* throw synchronously. `listProviders()` is called on every dashboard/app
|
|
10
|
+
* connect (`list_providers` request + every `auth_bootstrap` burst), and
|
|
11
|
+
* awaiting a promise on every one of those calls doesn't fit
|
|
12
|
+
* `listProviders()`'s existing synchronous contract (see below) — so this
|
|
13
|
+
* module probes ONCE, at boot, and caches a plain boolean `listProviders()`
|
|
14
|
+
* can read without awaiting anything.
|
|
15
|
+
*
|
|
16
|
+
* #8151 round-2 review (S4): an earlier version of this comment justified
|
|
17
|
+
* the cache by claiming Node does NOT cache a rejected dynamic import, so a
|
|
18
|
+
* second `import('node-pty')` would repeat the full resolution/load attempt.
|
|
19
|
+
* That claim is wrong, and the correction matters because it was the stated
|
|
20
|
+
* REASON for caching, not just a background detail: Node's module graph
|
|
21
|
+
* records an evaluation failure against the resolved module record, and
|
|
22
|
+
* replays the SAME cached rejection on every subsequent `import()` of the
|
|
23
|
+
* same specifier — measured directly (a throwing stand-in module's body
|
|
24
|
+
* executes exactly once across four repeated `import()` calls in the same
|
|
25
|
+
* process, evaluation-failure or not). node-pty's real failure mode is
|
|
26
|
+
* exactly this shape: its JS entry module is found and starts evaluating,
|
|
27
|
+
* and a `require()`/native-binding load INSIDE that evaluation throws — so
|
|
28
|
+
* Node's own cache already makes a second `import('node-pty')` cheap. The
|
|
29
|
+
* reason this module still probes once and caches a boolean is simply that
|
|
30
|
+
* `listProviders()` is synchronous and cannot `await` a promise on every
|
|
31
|
+
* call — not a missing Node-level cache. node-pty's native binding also
|
|
32
|
+
* cannot appear or disappear mid-process either way (it is either built into
|
|
33
|
+
* the image at build time, or it never will be), so a process-lifetime
|
|
34
|
+
* cache — Node's or this module's — cannot go stale.
|
|
35
|
+
*
|
|
36
|
+
* `listProviders()` itself stays synchronous (existing contract, existing
|
|
37
|
+
* callers): `probeNodePtyAvailable()` is awaited ONCE at server boot
|
|
38
|
+
* (server-cli.js, before the WS server starts accepting real connections),
|
|
39
|
+
* and `listProviders()` reads the cached result synchronously via
|
|
40
|
+
* `cachedNodePtyAvailable()`, injectable per-call for tests.
|
|
41
|
+
*
|
|
42
|
+
* #8151 round-2 review (S5, nit, corrected) — node-pty ships PREBUILT
|
|
43
|
+
* native addons for win32 (`win32-x64`, `win32-arm64`) AND darwin
|
|
44
|
+
* (`darwin-x64`, `darwin-arm64`) — checked directly against the installed
|
|
45
|
+
* package's own `prebuilds/` directory — but for NEITHER does a successful
|
|
46
|
+
* `import('node-pty')` prove the binding actually WORKS: a corrupt
|
|
47
|
+
* install, or an ABI mismatch the loader doesn't surface at require()
|
|
48
|
+
* time, could still fail later, at spawn time. The probe's "available"
|
|
49
|
+
* result is a necessary, not sufficient, signal on BOTH of those
|
|
50
|
+
* platforms. Linux is the one case where it IS sufficient in practice,
|
|
51
|
+
* because node-pty ships no Linux prebuild at all (the reason this image
|
|
52
|
+
* is unsupported for claude-tui in the first place) — there, "the import
|
|
53
|
+
* resolved" means a real native build actually happened and linked, not
|
|
54
|
+
* that a vendored binary merely loaded.
|
|
55
|
+
*/
|
|
56
|
+
|
|
57
|
+
let _cached = null
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Run the probe if it hasn't run yet, and cache the result. Safe to call
|
|
61
|
+
* more than once — later calls return the cached value without re-probing.
|
|
62
|
+
*
|
|
63
|
+
* @returns {Promise<boolean>} true iff `import('node-pty')` resolves here.
|
|
64
|
+
*/
|
|
65
|
+
export async function probeNodePtyAvailable() {
|
|
66
|
+
if (_cached !== null) return _cached
|
|
67
|
+
try {
|
|
68
|
+
await import('node-pty')
|
|
69
|
+
_cached = true
|
|
70
|
+
} catch {
|
|
71
|
+
_cached = false
|
|
72
|
+
}
|
|
73
|
+
return _cached
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Synchronous read of the cached result.
|
|
78
|
+
*
|
|
79
|
+
* @returns {boolean|null} true/false once probed, `null` if
|
|
80
|
+
* `probeNodePtyAvailable()` has never been called (production always calls
|
|
81
|
+
* it once at boot; callers that might run before boot, or in a test that
|
|
82
|
+
* never probes, should treat `null` as "unknown" and decide their own
|
|
83
|
+
* fallback rather than this module guessing for them).
|
|
84
|
+
*/
|
|
85
|
+
export function cachedNodePtyAvailable() {
|
|
86
|
+
return _cached
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Test-only: reset the cache so a probe re-runs. Never called by production
|
|
91
|
+
* code — node-pty's availability cannot change mid-process (see module doc).
|
|
92
|
+
*/
|
|
93
|
+
export function resetNodePtyProbeForTest() {
|
|
94
|
+
_cached = null
|
|
95
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* node-pty-support.js (#8151) — one shared message for "node-pty failed to
|
|
3
|
+
* load", used by every provider that dynamically `import('node-pty')`s.
|
|
4
|
+
*
|
|
5
|
+
* `claude-tui-session.js` and `user-shell-session.js` both do:
|
|
6
|
+
*
|
|
7
|
+
* let ptyMod
|
|
8
|
+
* try {
|
|
9
|
+
* ptyMod = await import('node-pty')
|
|
10
|
+
* } catch (err) {
|
|
11
|
+
* // ... surface err somehow ...
|
|
12
|
+
* }
|
|
13
|
+
*
|
|
14
|
+
* node-pty is a REGULAR (non-optional) server dependency, so its JS wrapper
|
|
15
|
+
* is always present, but its native addon is not: the official Docker image
|
|
16
|
+
* runs `npm ci --ignore-scripts` (no build-essential/python3 either), which
|
|
17
|
+
* skips the node-gyp rebuild / prebuilt-binary fetch that would normally
|
|
18
|
+
* produce `build/Release/pty.node`. Importing node-pty there throws — often
|
|
19
|
+
* a bare `Cannot find module '.../build/Release/pty.node'`, which is a true
|
|
20
|
+
* statement but not an ACTIONABLE one: it doesn't say the embedded terminal
|
|
21
|
+
* and the claude-tui provider are simply unsupported in this environment, or
|
|
22
|
+
* what to use instead. Before #8151 both catch blocks reported that raw
|
|
23
|
+
* message verbatim (still not a crash — see session-manager.js's
|
|
24
|
+
* `_handleAsyncStartFailure` / claude-tui's own `error` emit — just an
|
|
25
|
+
* unhelpful one).
|
|
26
|
+
*
|
|
27
|
+
* This is deliberately NOT Docker-specific: node-pty can just as validly fail
|
|
28
|
+
* to load on a bare-metal host with no native build toolchain, or after a
|
|
29
|
+
* Node ABI bump with no matching prebuild. The message names the Docker image
|
|
30
|
+
* as the expected case (since that's the one shipped, deliberately, without a
|
|
31
|
+
* build toolchain) while staying correct for any other cause.
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
import { getErrorMessage } from './error-message.js'
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* A stable, greppable marker independent of the human-readable wording in
|
|
38
|
+
* `describeNodePtyUnavailable()` below.
|
|
39
|
+
*
|
|
40
|
+
* #8151 round-2 review (Critical 4): `scripts/docker-image-smoke.sh`'s check
|
|
41
|
+
* 3 asserts that a healthy container's logs contain NEITHER this failure
|
|
42
|
+
* signature NOR "Destroyed session" — the fingerprint of a PTY-based
|
|
43
|
+
* provider failing silently behind a healthy HTTP server. That assertion
|
|
44
|
+
* used to `grep -qF 'node-pty unavailable'`, a SUBSTRING of the prose
|
|
45
|
+
* message below — S8 reworded that prose ("node-pty unavailable" →
|
|
46
|
+
* "node-pty is unavailable here"), which silently broke the match: the
|
|
47
|
+
* negative assertion could no longer fire on a real failure, so a
|
|
48
|
+
* regression that reintroduced claude-tui as the Default provider would
|
|
49
|
+
* have passed checks 1-6 clean. A hardcoded prose fragment beside wording
|
|
50
|
+
* that's free to change is exactly the "guard whose comment describes a
|
|
51
|
+
* stronger check than its code performs" class in
|
|
52
|
+
* docs/false-safety-guards.md. This constant is the ONE literal both the
|
|
53
|
+
* message below and the smoke script's needle are built from — reworded
|
|
54
|
+
* prose can't desync the two, because there's only one string to reword.
|
|
55
|
+
*
|
|
56
|
+
* It doubles as this failure's `.code` (see `claude-tui-session.js` /
|
|
57
|
+
* `user-shell-session.js`), so a client-side error handler and a bash grep
|
|
58
|
+
* key off literally the same token.
|
|
59
|
+
*/
|
|
60
|
+
export const NODE_PTY_UNAVAILABLE_CODE = 'PTY_UNAVAILABLE'
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Build the user-visible error message for a failed `import('node-pty')`.
|
|
64
|
+
*
|
|
65
|
+
* #8151 review (S8): the ACTIONABLE sentence leads — a client showing only
|
|
66
|
+
* the first N characters of a toast still shows the fix, not just a fact.
|
|
67
|
+
* The cause is appended LAST, and only its FIRST LINE: node-pty's own
|
|
68
|
+
* "Cannot find module '.../build/Release/pty.node'" is one line, but some
|
|
69
|
+
* native-addon load failures (a segfault backtrace, an N-API ABI-mismatch
|
|
70
|
+
* dump) are many, and a multi-line cause buried in the middle of an already
|
|
71
|
+
* long message is unreadable in a one-line toast.
|
|
72
|
+
*
|
|
73
|
+
* #8151 round-2 review (S4): "reinstall it" undersold the fix — `npm rebuild
|
|
74
|
+
* node-pty` only rebuilds the native addon for the CURRENT process's already
|
|
75
|
+
* -loaded module graph; the already-running daemon must actually restart to
|
|
76
|
+
* pick up the rebuilt binding. Worded as a two-step instruction.
|
|
77
|
+
*
|
|
78
|
+
* @param {unknown} err - the caught import rejection
|
|
79
|
+
* @returns {string}
|
|
80
|
+
*/
|
|
81
|
+
export function describeNodePtyUnavailable(err) {
|
|
82
|
+
const cause = getErrorMessage(err, 'unknown error').split('\n')[0]
|
|
83
|
+
return (
|
|
84
|
+
`node-pty is unavailable here [${NODE_PTY_UNAVAILABLE_CODE}] — use the ` +
|
|
85
|
+
`claude-sdk provider instead. The embedded terminal and the claude-tui ` +
|
|
86
|
+
`provider both require a native PTY binding that failed to load. This is ` +
|
|
87
|
+
`expected inside the official chroxy Docker image, which ships without a ` +
|
|
88
|
+
`native build toolchain (node-pty has no linux prebuild). Outside ` +
|
|
89
|
+
`Docker, run \`npm rebuild node-pty\` and restart the chroxy daemon — on ` +
|
|
90
|
+
`Linux the rebuild needs python3, make and a C++ compiler. ` +
|
|
91
|
+
`Cause: ${cause}`
|
|
92
|
+
)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Build the Error to throw/latch for a failed `import('node-pty')` — the
|
|
97
|
+
* ONE catch body both providers' two import-invocation shapes (the real
|
|
98
|
+
* `await import('node-pty')` and a test's function-shaped `_ptyModOverride`
|
|
99
|
+
* override) share.
|
|
100
|
+
*
|
|
101
|
+
* #8151 round-2 review (Critical 1): before this, `claude-tui-session.js`'s
|
|
102
|
+
* `_spawnPty` and `user-shell-session.js`'s `start()` each duplicated this
|
|
103
|
+
* exact `describeNodePtyUnavailable` + `Object.assign(..., { code })`
|
|
104
|
+
* construction across TWO catch blocks per file (one per import shape) —
|
|
105
|
+
* correct duplication at the time (each catch body was too small to be
|
|
106
|
+
* worth a shared helper on its own), but it meant a future edit to one
|
|
107
|
+
* copy silently not reaching the other three. Factored out here so there
|
|
108
|
+
* is exactly one place that builds this error; the two `try`/`await
|
|
109
|
+
* import(...)` call sites stay separate (not wrapped in a shared function)
|
|
110
|
+
* so `lint-argv-sinks.mjs`'s AST recognition of the literal `ptyMod = await
|
|
111
|
+
* import('node-pty')` shape keeps seeing the real spawn sink.
|
|
112
|
+
*
|
|
113
|
+
* @param {unknown} err - the caught import rejection
|
|
114
|
+
* @returns {Error & { code: 'PTY_UNAVAILABLE' }}
|
|
115
|
+
*/
|
|
116
|
+
export function nodePtyImportFailureError(err) {
|
|
117
|
+
return Object.assign(new Error(describeNodePtyUnavailable(err)), { code: NODE_PTY_UNAVAILABLE_CODE })
|
|
118
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process'
|
|
2
|
+
import { realpath } from 'node:fs/promises'
|
|
3
|
+
import { join, posix, win32 } from 'node:path'
|
|
4
|
+
|
|
5
|
+
const PROBE_TIMEOUT_MS = 5000
|
|
6
|
+
const PROBE_OUTPUT_MAX_BYTES = 64 * 1024
|
|
7
|
+
const WINDOWS_FINAL_PATH_SCRIPT = String.raw`
|
|
8
|
+
[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
|
|
9
|
+
Add-Type -TypeDefinition @'
|
|
10
|
+
using System;
|
|
11
|
+
using System.ComponentModel;
|
|
12
|
+
using System.Runtime.InteropServices;
|
|
13
|
+
using System.Text;
|
|
14
|
+
public static class ChroxyOpenedFilePath {
|
|
15
|
+
[DllImport("kernel32.dll", SetLastError=true)]
|
|
16
|
+
public static extern IntPtr GetStdHandle(int nStdHandle);
|
|
17
|
+
[DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
|
|
18
|
+
public static extern uint GetFinalPathNameByHandle(IntPtr hFile, StringBuilder path, uint chars, uint flags);
|
|
19
|
+
public static string Read() {
|
|
20
|
+
IntPtr handle = GetStdHandle(-10);
|
|
21
|
+
if (handle == IntPtr.Zero || handle == new IntPtr(-1)) throw new Win32Exception(Marshal.GetLastWin32Error());
|
|
22
|
+
var path = new StringBuilder(32768);
|
|
23
|
+
uint length = GetFinalPathNameByHandle(handle, path, (uint)path.Capacity, 0);
|
|
24
|
+
if (length == 0) throw new Win32Exception(Marshal.GetLastWin32Error());
|
|
25
|
+
if (length >= (uint)path.Capacity) throw new InvalidOperationException("opened-file path exceeds helper bound");
|
|
26
|
+
return path.ToString();
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
'@
|
|
30
|
+
[Console]::Out.Write([ChroxyOpenedFilePath]::Read())
|
|
31
|
+
`
|
|
32
|
+
|
|
33
|
+
function probeError(message, code = 'EOPENEDPATH') {
|
|
34
|
+
return Object.assign(new Error(`opened-file identity probe: ${message}`), { code })
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function runBoundedProbe(command, args, options, spawnProcess = spawn) {
|
|
38
|
+
return new Promise((resolve, reject) => {
|
|
39
|
+
let child
|
|
40
|
+
try {
|
|
41
|
+
child = spawnProcess(command, args, options)
|
|
42
|
+
} catch (err) {
|
|
43
|
+
reject(probeError(`helper could not start (${err.code || err.message})`))
|
|
44
|
+
return
|
|
45
|
+
}
|
|
46
|
+
const stdout = []
|
|
47
|
+
const stderr = []
|
|
48
|
+
let stdoutBytes = 0
|
|
49
|
+
let stderrBytes = 0
|
|
50
|
+
let failure = null
|
|
51
|
+
let settled = false
|
|
52
|
+
let forceTimer = null
|
|
53
|
+
let timer = null
|
|
54
|
+
const finish = (err, value) => {
|
|
55
|
+
if (settled) return
|
|
56
|
+
settled = true
|
|
57
|
+
clearTimeout(timer)
|
|
58
|
+
if (forceTimer) clearTimeout(forceTimer)
|
|
59
|
+
if (err) reject(err)
|
|
60
|
+
else resolve(value)
|
|
61
|
+
}
|
|
62
|
+
const stop = (err) => {
|
|
63
|
+
if (failure) return
|
|
64
|
+
failure = err
|
|
65
|
+
try { child.kill() } catch { /* best-effort */ }
|
|
66
|
+
forceTimer = setTimeout(() => {
|
|
67
|
+
try { child.kill('SIGKILL') } catch { /* best-effort */ }
|
|
68
|
+
finish(failure)
|
|
69
|
+
}, 250)
|
|
70
|
+
forceTimer.unref?.()
|
|
71
|
+
}
|
|
72
|
+
const collect = (chunks, kind) => (chunk) => {
|
|
73
|
+
const bytes = Buffer.byteLength(chunk)
|
|
74
|
+
if (kind === 'stdout') stdoutBytes += bytes
|
|
75
|
+
else stderrBytes += bytes
|
|
76
|
+
if (stdoutBytes > PROBE_OUTPUT_MAX_BYTES || stderrBytes > PROBE_OUTPUT_MAX_BYTES) {
|
|
77
|
+
stop(probeError('helper output exceeded its bound'))
|
|
78
|
+
return
|
|
79
|
+
}
|
|
80
|
+
chunks.push(Buffer.from(chunk))
|
|
81
|
+
}
|
|
82
|
+
if (!child.stdout || !child.stderr) {
|
|
83
|
+
stop(probeError('helper pipes were unavailable'))
|
|
84
|
+
} else {
|
|
85
|
+
child.stdout.on('data', collect(stdout, 'stdout'))
|
|
86
|
+
child.stderr.on('data', collect(stderr, 'stderr'))
|
|
87
|
+
}
|
|
88
|
+
child.once('error', err => finish(probeError(`helper failed (${err.code || err.message})`)))
|
|
89
|
+
child.once('close', (code, signal) => {
|
|
90
|
+
if (failure) return finish(failure)
|
|
91
|
+
if (code !== 0 || signal) return finish(probeError(`helper exited unsuccessfully (${signal || code})`))
|
|
92
|
+
finish(null, {
|
|
93
|
+
stdout: Buffer.concat(stdout).toString('utf8'),
|
|
94
|
+
stderr: Buffer.concat(stderr).toString('utf8'),
|
|
95
|
+
})
|
|
96
|
+
})
|
|
97
|
+
timer = setTimeout(() => stop(probeError('helper timed out')), PROBE_TIMEOUT_MS)
|
|
98
|
+
timer.unref?.()
|
|
99
|
+
})
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function parseLsofOpenedFilePath(stdout, { pid, fd }) {
|
|
103
|
+
if (typeof stdout !== 'string' || Buffer.byteLength(stdout) > PROBE_OUTPUT_MAX_BYTES) {
|
|
104
|
+
throw probeError('lsof returned invalid or oversized output')
|
|
105
|
+
}
|
|
106
|
+
const fields = stdout.split(/[\0\r\n]+/).filter(Boolean)
|
|
107
|
+
if (fields.length !== 3) throw probeError('lsof returned malformed fields')
|
|
108
|
+
if (fields[0] !== `p${pid}`) throw probeError('lsof returned the wrong process')
|
|
109
|
+
if (fields[1] !== `f${fd}`) throw probeError('lsof returned the wrong descriptor')
|
|
110
|
+
if (!fields[2].startsWith('n') || fields[2].length === 1 || fields[2].includes('\0')) {
|
|
111
|
+
throw probeError('lsof returned an invalid path field')
|
|
112
|
+
}
|
|
113
|
+
const path = fields[2].slice(1)
|
|
114
|
+
if (!posix.isAbsolute(path)) throw probeError('lsof returned a non-absolute path')
|
|
115
|
+
return path
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function normalizeWindowsFinalPath(path) {
|
|
119
|
+
if (typeof path !== 'string' || !path) throw probeError('Windows helper returned an empty path')
|
|
120
|
+
let normalized = path
|
|
121
|
+
if (normalized.slice(0, 8).toLowerCase() === '\\\\?\\unc\\') normalized = `\\\\${normalized.slice(8)}`
|
|
122
|
+
else if (normalized.startsWith('\\\\?\\')) normalized = normalized.slice(4)
|
|
123
|
+
if (!win32.isAbsolute(normalized)) throw probeError('Windows helper returned a non-absolute path')
|
|
124
|
+
return win32.normalize(normalized)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export async function resolveOpenedFilePath(fd, {
|
|
128
|
+
platform = process.platform,
|
|
129
|
+
pid = process.pid,
|
|
130
|
+
realpathFile = realpath,
|
|
131
|
+
runProbe = runBoundedProbe,
|
|
132
|
+
spawnProcess = spawn,
|
|
133
|
+
systemRoot = process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows',
|
|
134
|
+
} = {}) {
|
|
135
|
+
if (!Number.isSafeInteger(fd) || fd < 0) throw probeError('descriptor must be a non-negative safe integer')
|
|
136
|
+
if (platform === 'linux') {
|
|
137
|
+
try {
|
|
138
|
+
return await realpathFile(`/proc/self/fd/${fd}`)
|
|
139
|
+
} catch (err) {
|
|
140
|
+
throw probeError(`procfs query failed (${err.code || err.message})`)
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
if (platform === 'darwin') {
|
|
144
|
+
const result = await runProbe(
|
|
145
|
+
'/usr/sbin/lsof',
|
|
146
|
+
['-a', '-p', String(pid), '-d', String(fd), '-Fpnf0'],
|
|
147
|
+
{ env: { LANG: 'en_US.UTF-8', LC_ALL: 'en_US.UTF-8' }, stdio: ['ignore', 'pipe', 'pipe'] },
|
|
148
|
+
spawnProcess,
|
|
149
|
+
)
|
|
150
|
+
return parseLsofOpenedFilePath(result.stdout, { pid, fd })
|
|
151
|
+
}
|
|
152
|
+
if (platform === 'win32') {
|
|
153
|
+
const powershell = join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe')
|
|
154
|
+
const result = await runProbe(
|
|
155
|
+
powershell,
|
|
156
|
+
['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', WINDOWS_FINAL_PATH_SCRIPT],
|
|
157
|
+
{
|
|
158
|
+
env: { SystemRoot: systemRoot, WINDIR: systemRoot, LANG: 'en_US.UTF-8' },
|
|
159
|
+
windowsHide: true,
|
|
160
|
+
stdio: [fd, 'pipe', 'pipe'],
|
|
161
|
+
},
|
|
162
|
+
spawnProcess,
|
|
163
|
+
)
|
|
164
|
+
return normalizeWindowsFinalPath(result.stdout)
|
|
165
|
+
}
|
|
166
|
+
throw probeError(`platform '${platform}' has no supported opened-file path query`, 'ENOSYS')
|
|
167
|
+
}
|