pi-lens 3.8.73 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +2614 -12
- package/README.md +50 -21
- package/dist/clients/actionable-warnings.js +73 -18
- package/dist/clients/agent-behavior-client.js +21 -4
- package/dist/clients/ast-grep-client.js +68 -16
- package/dist/clients/ast-grep-types.js +0 -1
- package/dist/clients/ast-grep-yaml-synth.js +37 -10
- package/dist/clients/atomic-write-staging.js +63 -0
- package/dist/clients/atomic-write.js +116 -16
- package/dist/clients/bash-file-access.js +193 -23
- package/dist/clients/biome-client.js +29 -25
- package/dist/clients/bootstrap.js +11 -2
- package/dist/clients/bounded-cache.js +34 -0
- package/dist/clients/bounded-pid-file-lock.js +192 -0
- package/dist/clients/bus-events-logger.js +5 -1
- package/dist/clients/bus-publish.js +10 -3
- package/dist/clients/cache/rule-cache.js +89 -6
- package/dist/clients/cache-manager.js +97 -9
- package/dist/clients/cache-observability.js +498 -0
- package/dist/clients/call-graph.js +460 -108
- package/dist/clients/cascade-logger.js +5 -1
- package/dist/clients/child-unref.js +85 -0
- package/dist/clients/codebase-model.js +52 -23
- package/dist/clients/collateral-test-role.js +40 -0
- package/dist/clients/complexity-client.js +6 -8
- package/dist/clients/console-guard-install.js +14 -0
- package/dist/clients/cooperative-budget.js +42 -0
- package/dist/clients/dead-code-client.js +2 -1
- package/dist/clients/debug-handles.js +206 -0
- package/dist/clients/debug-heap.js +167 -0
- package/dist/clients/degradation-ledger.js +153 -0
- package/dist/clients/dependency-checker.js +466 -63
- package/dist/clients/diagnostic-dispositions.js +83 -13
- package/dist/clients/diagnostics-publish.js +10 -3
- package/dist/clients/dispatch/auxiliary-lsp.js +34 -0
- package/dist/clients/dispatch/dispatcher.js +71 -13
- package/dist/clients/dispatch/fact-store.js +11 -0
- package/dist/clients/dispatch/facts/function-facts.js +37 -7
- package/dist/clients/dispatch/facts/import-facts.js +108 -119
- package/dist/clients/dispatch/facts/tree-sitter-facts.js +12 -12
- package/dist/clients/dispatch/facts/try-catch-facts.js +13 -0
- package/dist/clients/dispatch/indent-detect.js +35 -0
- package/dist/clients/dispatch/inline-suppressions.js +17 -8
- package/dist/clients/dispatch/integration.js +1094 -611
- package/dist/clients/dispatch/lazy.js +14 -0
- package/dist/clients/dispatch/plan.js +11 -1
- package/dist/clients/dispatch/rule-id-normalize.js +50 -0
- package/dist/clients/dispatch/rule-policy.js +135 -0
- package/dist/clients/dispatch/rules/async-noise.js +1 -0
- package/dist/clients/dispatch/rules/unsafe-boundary.js +7 -0
- package/dist/clients/dispatch/runners/ast-grep-napi.js +47 -6
- package/dist/clients/dispatch/runners/biome-check.js +5 -9
- package/dist/clients/dispatch/runners/detekt.js +3 -2
- package/dist/clients/dispatch/runners/hadolint.js +2 -1
- package/dist/clients/dispatch/runners/helm-lint.js +154 -0
- package/dist/clients/dispatch/runners/htmlhint.js +3 -2
- package/dist/clients/dispatch/runners/index.js +5 -1
- package/dist/clients/dispatch/runners/lsp.js +14 -6
- package/dist/clients/dispatch/runners/markdownlint.js +4 -9
- package/dist/clients/dispatch/runners/psscriptanalyzer.js +10 -1
- package/dist/clients/dispatch/runners/pyright.js +9 -5
- package/dist/clients/dispatch/runners/ruff.js +4 -8
- package/dist/clients/dispatch/runners/shellcheck.js +2 -3
- package/dist/clients/dispatch/runners/shfmt.js +2 -3
- package/dist/clients/dispatch/runners/spotbugs.js +2 -1
- package/dist/clients/dispatch/runners/taplo.js +2 -1
- package/dist/clients/dispatch/runners/terragrunt.js +163 -0
- package/dist/clients/dispatch/runners/tflint.js +37 -5
- package/dist/clients/dispatch/runners/tree-sitter.js +155 -166
- package/dist/clients/dispatch/runners/trivy-config.js +13 -7
- package/dist/clients/dispatch/runners/utils/lazy-installer.js +3 -0
- package/dist/clients/dispatch/runners/utils/runner-helpers.js +284 -34
- package/dist/clients/dispatch/runners/utils/spawn-outcome.js +22 -0
- package/dist/clients/dispatch/runners/yaml-rule-parser.js +5 -4
- package/dist/clients/disposition-publish.js +10 -3
- package/dist/clients/durable-store.js +97 -0
- package/dist/clients/event-loop-monitor.js +94 -3
- package/dist/clients/extension-log.js +139 -0
- package/dist/clients/extension-mode.js +73 -0
- package/dist/clients/feature-hints.js +53 -7
- package/dist/clients/file-kinds.js +143 -31
- package/dist/clients/file-role.js +18 -3
- package/dist/clients/file-utils.js +56 -34
- package/dist/clients/fix-worklog.js +14 -2
- package/dist/clients/format-events-publish.js +16 -3
- package/dist/clients/format-service.js +24 -8
- package/dist/clients/formatters-lazy.js +8 -0
- package/dist/clients/formatters.js +358 -61
- package/dist/clients/generated-artifacts.js +169 -15
- package/dist/clients/git-guard.js +681 -11
- package/dist/clients/git-tracked-ignore.js +4 -0
- package/dist/clients/go-client.js +2 -1
- package/dist/clients/govulncheck-client.js +8 -0
- package/dist/clients/grammar-source.js +12 -4
- package/dist/clients/gzip-stage-write.js +102 -0
- package/dist/clients/host-ports.js +31 -0
- package/dist/clients/installer/index.js +733 -213
- package/dist/clients/instance-reaper.js +142 -172
- package/dist/clients/jscpd-client.js +31 -54
- package/dist/clients/knip-client.js +78 -36
- package/dist/clients/language-policy.js +14 -2
- package/dist/clients/language-profile.js +72 -77
- package/dist/clients/latency-logger.js +28 -16
- package/dist/clients/lens-config.js +140 -166
- package/dist/clients/lens-engine.js +124 -21
- package/dist/clients/lens-events.js +27 -4
- package/dist/clients/lens-flag-registry.js +293 -0
- package/dist/clients/lens-map.js +96 -26
- package/dist/clients/live-bus-emitter.js +30 -0
- package/dist/clients/log-cleanup.js +8 -18
- package/dist/clients/lsp/cascade-tier.js +23 -3
- package/dist/clients/lsp/client.js +566 -57
- package/dist/clients/lsp/config.js +74 -10
- package/dist/clients/lsp/diagnostic-binding.js +86 -0
- package/dist/clients/lsp/edits.js +1012 -121
- package/dist/clients/lsp/index.js +1840 -803
- package/dist/clients/lsp/language.js +4 -1
- package/dist/clients/lsp/launch.js +40 -32
- package/dist/clients/lsp/path-utils.js +1 -1
- package/dist/clients/lsp/ruby-drive-dirs.js +83 -0
- package/dist/clients/lsp/server.js +279 -60
- package/dist/clients/lsp/workspace-diagnostics-cache.js +28 -4
- package/dist/clients/lsp-document-symbols.js +112 -0
- package/dist/clients/lsp-lazy.js +8 -0
- package/dist/clients/lsp-mutation.js +248 -0
- package/dist/clients/mcp/analyze.js +128 -36
- package/dist/clients/mcp/ipc.js +157 -24
- package/dist/clients/mcp/review.js +36 -3
- package/dist/clients/mcp/session.js +216 -8
- package/dist/clients/memory-sampler.js +115 -0
- package/dist/clients/metrics-client.js +2 -1
- package/dist/clients/metrics-history.js +2 -1
- package/dist/clients/module-report-lsp.js +5 -0
- package/dist/clients/module-report.js +267 -82
- package/dist/clients/ndjson-logger.js +334 -103
- package/dist/clients/opengrep-client.js +1 -1
- package/dist/clients/partial-edit-apply.js +120 -5
- package/dist/clients/path-keyed-map.js +76 -0
- package/dist/clients/path-utils.js +141 -5
- package/dist/clients/performance-report.js +327 -0
- package/dist/clients/pipeline.js +54 -13
- package/dist/clients/print-mode.js +21 -0
- package/dist/clients/project-changes.js +117 -4
- package/dist/clients/project-diagnostics/cache.js +3 -2
- package/dist/clients/project-diagnostics/extractors.js +26 -115
- package/dist/clients/project-diagnostics/fresh-fetch.js +149 -19
- package/dist/clients/project-diagnostics/runner-adapters/call-graph-impact.js +117 -0
- package/dist/clients/project-diagnostics/runner-adapters/runner-findings.js +37 -5
- package/dist/clients/project-diagnostics/scanner.js +268 -128
- package/dist/clients/project-lens-config.js +138 -34
- package/dist/clients/project-report.js +64 -25
- package/dist/clients/project-scale.js +8 -10
- package/dist/clients/project-snapshot-persist-worker.js +6 -0
- package/dist/clients/project-snapshot.js +767 -8
- package/dist/clients/project-trust.js +181 -0
- package/dist/clients/quiet-window.js +27 -5
- package/dist/clients/read-bridge.js +147 -0
- package/dist/clients/read-expansion.js +22 -12
- package/dist/clients/read-guard-logger.js +159 -1
- package/dist/clients/read-guard-tool-lines.js +150 -29
- package/dist/clients/read-guard.js +262 -3
- package/dist/clients/redact/secrets.js +449 -0
- package/dist/clients/resource-sampler.js +144 -39
- package/dist/clients/reverse-deps.js +48 -0
- package/dist/clients/review-graph/builder.js +2570 -326
- package/dist/clients/review-graph/git-identity.js +2 -1
- package/dist/clients/review-graph/import-resolvers.js +21 -10
- package/dist/clients/review-graph/persist-worker.js +10 -0
- package/dist/clients/review-graph/query.js +5 -0
- package/dist/clients/review-graph/shared-extraction-ir.js +90 -0
- package/dist/clients/review-graph/symbol-id.js +46 -0
- package/dist/clients/review-graph/tsconfig-paths.js +57 -6
- package/dist/clients/review-graph/workspace-modules.js +51 -3
- package/dist/clients/review-graph-logger.js +53 -0
- package/dist/clients/ruff-client.js +27 -44
- package/dist/clients/runtime-agent-end.js +111 -75
- package/dist/clients/runtime-context.js +36 -12
- package/dist/clients/runtime-coordinator.js +76 -8
- package/dist/clients/runtime-session.js +799 -137
- package/dist/clients/runtime-tool-call.js +117 -62
- package/dist/clients/runtime-tool-result.js +218 -23
- package/dist/clients/runtime-turn.js +284 -40
- package/dist/clients/rust-client.js +2 -1
- package/dist/clients/safe-spawn.js +873 -71
- package/dist/clients/security-scan-client.js +2 -1
- package/dist/clients/session-start-observability.js +15 -0
- package/dist/clients/session-state-store.js +5 -3
- package/dist/clients/sessionstart-logger.js +18 -0
- package/dist/clients/sg-runner.js +284 -159
- package/dist/clients/slow-fs.js +2 -1
- package/dist/clients/smells-rollup.js +224 -0
- package/dist/clients/source-filter.js +231 -43
- package/dist/clients/source-walker.js +66 -10
- package/dist/clients/startup-scan.js +15 -16
- package/dist/clients/startup-timing.js +9 -0
- package/dist/clients/test-runner-client.js +38 -8
- package/dist/clients/todo-scanner.js +30 -3
- package/dist/clients/tool-event.js +35 -0
- package/dist/clients/tool-policy.js +388 -39
- package/dist/clients/tool-render.js +155 -0
- package/dist/clients/tree-sitter-cache.js +153 -140
- package/dist/clients/tree-sitter-client.js +1722 -80
- package/dist/clients/tree-sitter-logger.js +64 -1
- package/dist/clients/tree-sitter-query-loader.js +117 -12
- package/dist/clients/tree-sitter-shared.js +48 -19
- package/dist/clients/tree-sitter-symbol-extractor.js +115 -11
- package/dist/clients/user-notify.js +51 -0
- package/dist/clients/vanished-instance-marker.js +57 -0
- package/dist/clients/warm-attach.js +33 -13
- package/dist/clients/widget-state.js +342 -49
- package/dist/clients/word-index-logger.js +44 -0
- package/dist/clients/word-index.js +612 -68
- package/dist/clients/workspace-topology.js +100 -7
- package/dist/index.js +65923 -47161
- package/dist/mcp/analyze-cli.js +185 -29
- package/dist/mcp/cli.js +110 -0
- package/dist/mcp/server.js +272 -50
- package/dist/tools/ast-grep-search.js +93 -27
- package/dist/tools/lens-diagnostics.js +247 -41
- package/dist/tools/lsp-diagnostics.js +153 -40
- package/dist/tools/lsp-navigation.js +51 -31
- package/dist/tools/module-report.js +9 -0
- package/dist/tools/symbol-search.js +21 -2
- package/docs/agent-guide.md +247 -0
- package/docs/agent-tools.md +21 -10
- package/docs/analysisall.md +192 -0
- package/docs/api-ports-inventory.md +165 -0
- package/docs/ast-grep_rules_catalog.md +5 -2
- package/docs/astplayground.md +3 -4
- package/docs/audit1.md +5 -5
- package/docs/durable-store-audit-1202.md +32 -0
- package/docs/environment-variables.md +197 -11
- package/docs/fable.md +27 -0
- package/docs/features.md +35 -5
- package/docs/globalconfig.md +101 -5
- package/docs/language-coverage.md +6 -5
- package/docs/lsp-capability-matrix.md +2 -2
- package/docs/mcp.md +54 -20
- package/docs/servercapabilities.md +7 -4
- package/docs/settings.md +192 -0
- package/docs/tools.md +18 -1
- package/docs/tree-sitter_rules_catalog.md +11 -31
- package/docs/usage.md +31 -0
- package/package.json +139 -138
- package/rules/ast-grep-rules/rule-tests/hardcoded-url-js-test.yml +1 -0
- package/rules/ast-grep-rules/rule-tests/hardcoded-url-test.yml +2 -0
- package/rules/ast-grep-rules/rule-tests/no-bare-except-test.yml +49 -0
- package/rules/ast-grep-rules/rule-tests/no-bare-host-path-in-win32-branch-test.yml +87 -0
- package/rules/ast-grep-rules/rule-tests/no-case-declarations-js-test.yml +10 -0
- package/rules/ast-grep-rules/rule-tests/no-case-declarations-test.yml +10 -0
- package/rules/ast-grep-rules/rule-tests/no-javascript-url-js-test.yml +10 -0
- package/rules/ast-grep-rules/rule-tests/no-javascript-url-test.yml +10 -0
- package/rules/ast-grep-rules/rule-tests/no-nested-links-test.yml +11 -1
- package/rules/ast-grep-rules/rule-tests/no-raw-json-store-write-test.yml +17 -0
- package/rules/ast-grep-rules/rule-tests/no-win32-isabsolute-for-qualification-test.yml +16 -0
- package/rules/ast-grep-rules/rule-tests/strict-equality-js-test.yml +3 -0
- package/rules/ast-grep-rules/rule-tests/strict-equality-test.yml +3 -0
- package/rules/ast-grep-rules/rule-tests/strict-inequality-js-test.yml +3 -0
- package/rules/ast-grep-rules/rule-tests/strict-inequality-test.yml +4 -0
- package/rules/ast-grep-rules/rules/hardcoded-url-js.yml +22 -4
- package/rules/ast-grep-rules/rules/hardcoded-url.yml +22 -4
- package/rules/ast-grep-rules/rules/no-bare-except.yml +3 -15
- package/rules/ast-grep-rules/rules/no-bare-host-path-in-win32-branch.yml +25 -0
- package/rules/ast-grep-rules/rules/no-case-declarations-js.yml +4 -3
- package/rules/ast-grep-rules/rules/no-case-declarations.yml +4 -3
- package/rules/ast-grep-rules/rules/no-console-except-error-js.yml +10 -0
- package/rules/ast-grep-rules/rules/no-console-except-error.yml +10 -0
- package/rules/ast-grep-rules/rules/no-javascript-url-js.yml +42 -6
- package/rules/ast-grep-rules/rules/no-javascript-url.yml +42 -6
- package/rules/ast-grep-rules/rules/no-nested-links.yml +7 -0
- package/rules/ast-grep-rules/rules/no-raw-json-store-write.yml +30 -0
- package/rules/ast-grep-rules/rules/no-win32-isabsolute-for-qualification.yml +23 -0
- package/rules/ast-grep-rules/rules/strict-equality-js.yml +14 -1
- package/rules/ast-grep-rules/rules/strict-equality.yml +14 -1
- package/rules/ast-grep-rules/rules/strict-inequality-js.yml +14 -1
- package/rules/ast-grep-rules/rules/strict-inequality.yml +14 -1
- package/rules/tree-sitter-queries/cpp/no-memset-sensitive-data.yml +9 -3
- package/rules/tree-sitter-queries/cpp/no-scoped-lock-without-args.yml +6 -6
- package/rules/tree-sitter-queries/css/calc-spacing.yml +8 -6
- package/rules/tree-sitter-queries/go/go-mutex-copy.yml +21 -18
- package/rules/tree-sitter-queries/go/go-shared-map-write-goroutine.yml +3 -3
- package/rules/tree-sitter-queries/java/infinite-loop-java.yml +3 -3
- package/rules/tree-sitter-queries/java/junit-call-super.yml +6 -4
- package/rules/tree-sitter-queries/java/no-double-checked-locking.yml +10 -8
- package/rules/tree-sitter-queries/java/no-field-shadowing.yml +1 -1
- package/rules/tree-sitter-queries/java/prepared-statement-valid-indices.yml +2 -3
- package/rules/tree-sitter-queries/java/resources-closed.yml +2 -2
- package/rules/tree-sitter-queries/java/springboot-default-package.yml +6 -3
- package/rules/tree-sitter-queries/java/switch-fall-through.yml +6 -4
- package/rules/tree-sitter-queries/java/switch-non-case-labels.yml +4 -3
- package/rules/tree-sitter-queries/java/tests-include-assertions.yml +6 -5
- package/rules/tree-sitter-queries/javascript/switch-case-termination-js.yml +5 -8
- package/rules/tree-sitter-queries/javascript/switch-non-case-labels.yml +3 -2
- package/rules/tree-sitter-queries/kotlin/prepared-statement-indices.yml +9 -5
- package/rules/tree-sitter-queries/php/this-in-static-context.yml +5 -5
- package/rules/tree-sitter-queries/python/exit-signature-check.yml +2 -9
- package/rules/tree-sitter-queries/python/in-operator-unsupported.yml +3 -4
- package/rules/tree-sitter-queries/python/no-super-torchscript.yml +4 -8
- package/rules/tree-sitter-queries/python/notimplemented-boolean-context.yml +1 -5
- package/rules/tree-sitter-queries/python/python-empty-except.yml +1 -1
- package/rules/tree-sitter-queries/python/return-in-init.yml +0 -2
- package/rules/tree-sitter-queries/python/yield-return-outside-function.yml +0 -3
- package/rules/tree-sitter-queries/ruby/ruby-command-injection.yml +1 -12
- package/rules/tree-sitter-queries/ruby/ruby-eval.yml +1 -1
- package/rules/tree-sitter-queries/ruby/ruby-insecure-deserialization.yml +4 -4
- package/rules/tree-sitter-queries/ruby/ruby-insecure-random.yml +4 -11
- package/rules/tree-sitter-queries/ruby/ruby-open-struct.yml +1 -1
- package/rules/tree-sitter-queries/ruby/ruby-string-eval.yml +2 -3
- package/rules/tree-sitter-queries/ruby/ruby-weak-hash.yml +4 -4
- package/rules/tree-sitter-queries/rust/rust-lock-held-across-await.yml +4 -3
- package/rules/tree-sitter-queries/tsx/no-nested-links.yml +4 -6
- package/rules/tree-sitter-queries/typescript/console-statement.yml +11 -0
- package/rules/tree-sitter-queries/typescript/duplicate-function-arg.yml +4 -9
- package/rules/tree-sitter-queries/typescript/empty-switch-case.yml +13 -9
- package/rules/tree-sitter-queries/typescript/infinite-loop.yml +2 -2
- package/rules/tree-sitter-queries/typescript/mixed-async-styles.yml +10 -1
- package/rules/tree-sitter-queries/typescript/switch-case-termination.yml +5 -8
- package/rules/tree-sitter-queries/typescript/ts-insecure-random.yml +7 -10
- package/rules/tree-sitter-queries/typescript/unsafe-regex.yml +4 -2
- package/rules/typos/_typos.toml +17 -0
- package/scripts/analyze-pi-lens-logs.mjs +55 -2
- package/skills/pi-lens-write-tree-sitter-rule/SKILL.md +5 -0
- package/dist/clients/ast-grep-parser.js +0 -86
- package/dist/clients/config-enabled-shape.js +0 -39
- package/dist/clients/lsp/interactive-install.js +0 -367
- package/dist/clients/lsp/lsp-index.js +0 -10
- package/dist/clients/lsp/server-strategies.js +0 -5
- package/dist/clients/project-metadata.js +0 -690
- package/dist/clients/source-groups.js +0 -96
- package/dist/clients/types.js +0 -11
- package/docs/env_variables.md +0 -10
- package/rules/tree-sitter-queries/abap-disabled/delete-where.yml +0 -46
- package/rules/tree-sitter-queries/cpp/no-confused-move-forward.yml +0 -59
- package/rules/tree-sitter-queries/cpp/noexcept-functions.yml +0 -58
- package/rules/tree-sitter-queries/java/mockito-initialized.yml +0 -66
- package/rules/tree-sitter-queries/java/no-wait-notify-on-thread.yml +0 -58
- package/rules/tree-sitter-queries/java/short-circuit-logic.yml +0 -57
- package/rules/tree-sitter-queries/java/spring-session-attributes-setcomplete.yml +0 -75
- package/rules/tree-sitter-queries/plsql-disabled/delete-update-where.yml +0 -56
- package/rules/tree-sitter-queries/plsql-disabled/end-loop-semicolon.yml +0 -51
- package/rules/tree-sitter-queries/plsql-disabled/fetch-bulk-collect-limit.yml +0 -47
- package/rules/tree-sitter-queries/plsql-disabled/forallsave-exceptions.yml +0 -51
- package/rules/tree-sitter-queries/plsql-disabled/nchar-nvarchar2-bytes.yml +0 -54
- package/rules/tree-sitter-queries/plsql-disabled/not-null-initialization.yml +0 -59
- package/rules/tree-sitter-queries/plsql-disabled/raise-application-error-codes.yml +0 -50
- package/rules/tree-sitter-queries/typescript-disabled/ts-path-traversal.yml +0 -71
|
@@ -13,11 +13,207 @@
|
|
|
13
13
|
* - Change: safeSpawn(cmd, args, opts)
|
|
14
14
|
* - To: await safeSpawnAsync(cmd, args, opts)
|
|
15
15
|
*/
|
|
16
|
-
import { spawn, spawnSync } from "node:child_process";
|
|
16
|
+
import { spawn, spawnSync, } from "node:child_process";
|
|
17
17
|
import * as fs from "node:fs";
|
|
18
18
|
import * as path from "node:path";
|
|
19
19
|
import { logLatency } from "./latency-logger.js";
|
|
20
|
+
import { recordDegradation } from "./degradation-ledger.js";
|
|
21
|
+
import { logExtension } from "./extension-log.js";
|
|
22
|
+
import { isFullyQualifiedWin32 } from "./path-utils.js";
|
|
20
23
|
import { startSpawnUsageSampler } from "./resource-sampler.js";
|
|
24
|
+
/** Intent-level spawn failure. `cause` retains the original OS Error/errno. */
|
|
25
|
+
export class SpawnFailureError extends Error {
|
|
26
|
+
kind;
|
|
27
|
+
cause;
|
|
28
|
+
name = "SpawnFailureError";
|
|
29
|
+
constructor(kind, message, cause) {
|
|
30
|
+
super(message, { cause });
|
|
31
|
+
this.kind = kind;
|
|
32
|
+
this.cause = cause;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export function hasSpawnFailureKind(error, kind) {
|
|
36
|
+
return (error instanceof Error &&
|
|
37
|
+
"kind" in error &&
|
|
38
|
+
error.kind === kind);
|
|
39
|
+
}
|
|
40
|
+
function toError(error) {
|
|
41
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
42
|
+
}
|
|
43
|
+
function errorCode(error) {
|
|
44
|
+
return error.code;
|
|
45
|
+
}
|
|
46
|
+
async function cwdIsUnresolvable(cwd) {
|
|
47
|
+
if (cwd === undefined)
|
|
48
|
+
return false;
|
|
49
|
+
try {
|
|
50
|
+
return !(await fs.promises.stat(cwd)).isDirectory();
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
return true;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function cwdIsUnresolvableSync(cwd) {
|
|
57
|
+
if (cwd === undefined)
|
|
58
|
+
return false;
|
|
59
|
+
try {
|
|
60
|
+
return !fs.statSync(cwd).isDirectory();
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return true;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Best-effort presence probe used ONLY to disambiguate ENOENT when the cwd is
|
|
68
|
+
* ALSO unresolvable (#1340 review): a genuinely missing tool must classify as
|
|
69
|
+
* tool-not-found even under a broken cwd, or auto-install can never repair it.
|
|
70
|
+
* Absolute commands are probed directly (with PATHEXT variants on Windows);
|
|
71
|
+
* bare names scan PATH. A relative-with-separator command under a broken cwd
|
|
72
|
+
* is genuinely ambiguous -- we err toward cwd-unresolvable there, because
|
|
73
|
+
* repairing the cwd is actionable while a reinstall loop (#1199) is not.
|
|
74
|
+
*/
|
|
75
|
+
function commandProbablyPresent(command) {
|
|
76
|
+
const exts = process.platform === "win32"
|
|
77
|
+
? ["", ...(process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)]
|
|
78
|
+
: [""];
|
|
79
|
+
const existsWithExt = (base) => {
|
|
80
|
+
for (const ext of exts) {
|
|
81
|
+
try {
|
|
82
|
+
if (fs.existsSync(base + ext))
|
|
83
|
+
return true;
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
// unreadable candidate -- keep probing
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return false;
|
|
90
|
+
};
|
|
91
|
+
if (path.isAbsolute(command))
|
|
92
|
+
return existsWithExt(command);
|
|
93
|
+
if (command.includes("/") || command.includes("\\"))
|
|
94
|
+
return "ambiguous";
|
|
95
|
+
for (const dir of (process.env.PATH ?? "").split(path.delimiter)) {
|
|
96
|
+
if (dir && existsWithExt(path.join(dir, command)))
|
|
97
|
+
return true;
|
|
98
|
+
}
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Shared errno->bucket mapping. `cwdUnresolvable` is the only async-vs-sync
|
|
103
|
+
* difference between the two public classifiers, so it arrives as a resolved
|
|
104
|
+
* flag and everything else lives once (Sonar duplication finding, #1340).
|
|
105
|
+
*/
|
|
106
|
+
function classifyWithCwdFlag(cause, options, cwdUnresolvable) {
|
|
107
|
+
const code = errorCode(cause);
|
|
108
|
+
let failure;
|
|
109
|
+
if (code === "ENOENT" &&
|
|
110
|
+
cwdUnresolvable &&
|
|
111
|
+
commandProbablyPresent(options.command) !== false) {
|
|
112
|
+
failure = new SpawnFailureError("cwd-unresolvable", `Cannot spawn ${options.command}: working directory is unresolvable (${options.cwd})`, cause);
|
|
113
|
+
}
|
|
114
|
+
else if (code === "ENOENT") {
|
|
115
|
+
failure = new SpawnFailureError("tool-not-found", `Cannot spawn ${options.command}: tool not found (${cause.message})`, cause);
|
|
116
|
+
}
|
|
117
|
+
else if (code === "EACCES" || code === "EPERM") {
|
|
118
|
+
failure = new SpawnFailureError("permission-denied", `Cannot spawn ${options.command}: permission denied`, cause);
|
|
119
|
+
}
|
|
120
|
+
else {
|
|
121
|
+
failure = new SpawnFailureError("spawn-failed", `Cannot spawn ${options.command}: ${cause.message}`, cause);
|
|
122
|
+
}
|
|
123
|
+
recordSpawnClassification(failure, options);
|
|
124
|
+
return failure;
|
|
125
|
+
}
|
|
126
|
+
const loggedSpawnClassifications = new Set();
|
|
127
|
+
const SPAWN_CLASSIFICATION_LOG_CAP = 200;
|
|
128
|
+
function recordSpawnClassification(failure, options) {
|
|
129
|
+
const pair = `${failure.kind}\0${options.command}`;
|
|
130
|
+
if (!loggedSpawnClassifications.has(pair)) {
|
|
131
|
+
if (loggedSpawnClassifications.size >= SPAWN_CLASSIFICATION_LOG_CAP) {
|
|
132
|
+
loggedSpawnClassifications.clear();
|
|
133
|
+
}
|
|
134
|
+
loggedSpawnClassifications.add(pair);
|
|
135
|
+
logExtension({
|
|
136
|
+
subsystem: "safe-spawn",
|
|
137
|
+
level: "debug",
|
|
138
|
+
message: "spawn failure classified",
|
|
139
|
+
metadata: {
|
|
140
|
+
kind: failure.kind,
|
|
141
|
+
command: options.command,
|
|
142
|
+
cwd: options.cwd,
|
|
143
|
+
},
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
if (failure.kind !== "tool-not-found") {
|
|
147
|
+
recordDegradation({
|
|
148
|
+
kind: "spawn-failure",
|
|
149
|
+
subject: options.command,
|
|
150
|
+
reason: `${failure.kind}${options.cwd ? ` in ${options.cwd}` : ""}`,
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
/** Classify a raw Node spawn error without discarding its errno-bearing Error. */
|
|
155
|
+
export async function classifySpawnFailure(error, options) {
|
|
156
|
+
const cause = toError(error);
|
|
157
|
+
const needsCwdProbe = errorCode(cause) === "ENOENT";
|
|
158
|
+
const cwdUnresolvable = needsCwdProbe && (await cwdIsUnresolvable(options.cwd));
|
|
159
|
+
return classifyWithCwdFlag(cause, options, cwdUnresolvable);
|
|
160
|
+
}
|
|
161
|
+
function classifySpawnFailureSync(error, options) {
|
|
162
|
+
const cause = toError(error);
|
|
163
|
+
const needsCwdProbe = errorCode(cause) === "ENOENT";
|
|
164
|
+
const cwdUnresolvable = needsCwdProbe && cwdIsUnresolvableSync(options.cwd);
|
|
165
|
+
return classifyWithCwdFlag(cause, options, cwdUnresolvable);
|
|
166
|
+
}
|
|
167
|
+
// Vitest reloads modules inside a reused worker. Keep this registry on the
|
|
168
|
+
// process so those module instances share one signal/exit listener set.
|
|
169
|
+
const lifetimeStateKey = Symbol.for("pi-lens.safe-spawn.lifetime-state");
|
|
170
|
+
const processWithLifetimeState = process;
|
|
171
|
+
const lifetimeState = processWithLifetimeState[lifetimeStateKey] ??
|
|
172
|
+
(processWithLifetimeState[lifetimeStateKey] = {
|
|
173
|
+
pids: new Set(),
|
|
174
|
+
installed: false,
|
|
175
|
+
});
|
|
176
|
+
function killPidTreeSync(pid) {
|
|
177
|
+
if (process.platform === "win32") {
|
|
178
|
+
try {
|
|
179
|
+
const taskkill = `${process.env.SystemRoot ?? "C:\\Windows"}\\System32\\taskkill.exe`;
|
|
180
|
+
spawnSync(taskkill, ["/F", "/T", "/PID", String(pid)], {
|
|
181
|
+
shell: false,
|
|
182
|
+
windowsHide: true,
|
|
183
|
+
stdio: "ignore",
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
// Runs from process `exit`/signal handlers — a SYNCHRONOUS spawn throw
|
|
188
|
+
// (Windows `spawn UNKNOWN`/EINVAL, the pidusage bug class, #533) would
|
|
189
|
+
// become an uncaughtException during shutdown. Best-effort tree-kill:
|
|
190
|
+
// swallow it, mirroring the already-guarded POSIX branch below.
|
|
191
|
+
}
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
try {
|
|
195
|
+
process.kill(pid, "SIGKILL");
|
|
196
|
+
}
|
|
197
|
+
catch {
|
|
198
|
+
// Child already exited.
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
function installLifetimeCleanup() {
|
|
202
|
+
if (lifetimeState.installed)
|
|
203
|
+
return;
|
|
204
|
+
lifetimeState.installed = true;
|
|
205
|
+
process.once("exit", () => {
|
|
206
|
+
for (const pid of lifetimeState.pids)
|
|
207
|
+
killPidTreeSync(pid);
|
|
208
|
+
});
|
|
209
|
+
for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {
|
|
210
|
+
process.once(signal, () => {
|
|
211
|
+
for (const pid of lifetimeState.pids)
|
|
212
|
+
killPidTreeSync(pid);
|
|
213
|
+
process.kill(process.pid, signal);
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
}
|
|
21
217
|
// ============================================================================
|
|
22
218
|
// AMBIENT TURN ABORT SIGNAL
|
|
23
219
|
// ============================================================================
|
|
@@ -78,19 +274,271 @@ export function buildWindowsShellCommand(command, args) {
|
|
|
78
274
|
return `chcp 65001 >nul 2>&1 && ${[command, ...args].map(cmdEscapeArg).join(" ")}`;
|
|
79
275
|
}
|
|
80
276
|
/**
|
|
81
|
-
*
|
|
82
|
-
*
|
|
83
|
-
*
|
|
277
|
+
* The extensions this resolver treats as executable suffixes on their own,
|
|
278
|
+
* independent of PATHEXT: `.exe`/`.com` and `.cmd`/`.bat`. An explicit suffix
|
|
279
|
+
* outside this set is not treated as a "known executable extension" unless
|
|
280
|
+
* the caller's own PATHEXT says so (#1201).
|
|
281
|
+
*
|
|
282
|
+
* This is a RESOLUTION set, not a dispatch whitelist — do not read it as "the
|
|
283
|
+
* only extensions this module can spawn". Dispatch in
|
|
284
|
+
* `safeSpawnAsync`/`safeSpawn` below routes `.cmd`/`.bat` through the cmd.exe
|
|
285
|
+
* wrapper and EVERYTHING ELSE to direct spawn, so a resolved path with any
|
|
286
|
+
* other suffix (reachable only when the caller's own PATHEXT lists it) is
|
|
287
|
+
* direct-spawned. That is deliberate and not a widening: CreateProcess does no
|
|
288
|
+
* ShellExecute file-association lookup, the default Windows PATHEXT already
|
|
289
|
+
* contains `.VBS`/`.JS`/`.WSF`/`.MSC`, and the set here is strictly narrower
|
|
290
|
+
* than the pre-#1201 behavior. Only the doc claim was ever wrong.
|
|
291
|
+
*/
|
|
292
|
+
const WINDOWS_DIRECT_RESOLVABLE_EXTS = new Set([
|
|
293
|
+
".exe",
|
|
294
|
+
".com",
|
|
295
|
+
".cmd",
|
|
296
|
+
".bat",
|
|
297
|
+
]);
|
|
298
|
+
/**
|
|
299
|
+
* Merge a parent and child environment using Windows' case-insensitive variable
|
|
300
|
+
* names. Node's JavaScript environment object can contain both `PATH` and
|
|
301
|
+
* `Path`, even though Windows treats them as one variable. Removing an older
|
|
302
|
+
* spelling before each assignment gives explicit child overrides precedence
|
|
303
|
+
* over every ambient spelling and ensures the environment passed to spawn has
|
|
304
|
+
* one unambiguous value.
|
|
305
|
+
*/
|
|
306
|
+
export function mergeWindowsEnvironment(base, overrides) {
|
|
307
|
+
const entries = new Map();
|
|
308
|
+
const assign = (source) => {
|
|
309
|
+
if (!source)
|
|
310
|
+
return;
|
|
311
|
+
for (const [key, value] of Object.entries(source)) {
|
|
312
|
+
const folded = key.toLowerCase();
|
|
313
|
+
// Delete before setting so the last explicit spelling wins while the
|
|
314
|
+
// folded map remains O(n) instead of scanning the merged object for
|
|
315
|
+
// every environment entry.
|
|
316
|
+
entries.delete(folded);
|
|
317
|
+
if (value !== undefined)
|
|
318
|
+
entries.set(folded, { key, value });
|
|
319
|
+
}
|
|
320
|
+
};
|
|
321
|
+
assign(base);
|
|
322
|
+
assign(overrides);
|
|
323
|
+
const merged = {};
|
|
324
|
+
for (const { key, value } of entries.values())
|
|
325
|
+
merged[key] = value;
|
|
326
|
+
return merged;
|
|
327
|
+
}
|
|
328
|
+
function getWindowsEnvironmentValue(env, name) {
|
|
329
|
+
let value;
|
|
330
|
+
for (const [key, entry] of Object.entries(env)) {
|
|
331
|
+
if (key.toLowerCase() === name.toLowerCase())
|
|
332
|
+
value = entry;
|
|
333
|
+
}
|
|
334
|
+
return value;
|
|
335
|
+
}
|
|
336
|
+
function driveLetter(value) {
|
|
337
|
+
const match = /^([A-Za-z]):/.exec(value);
|
|
338
|
+
return match?.[1]?.toUpperCase();
|
|
339
|
+
}
|
|
340
|
+
function isDriveAbsolute(value, drive) {
|
|
341
|
+
return (value.length >= 3 &&
|
|
342
|
+
value[0]?.toUpperCase() === drive.toUpperCase() &&
|
|
343
|
+
value[1] === ":" &&
|
|
344
|
+
(value[2] === "\\" || value[2] === "/"));
|
|
345
|
+
}
|
|
346
|
+
/** `X:\...` or `X:/...` — a drive-absolute path, for any drive letter. */
|
|
347
|
+
function isDriveAbsoluteAnyDrive(value) {
|
|
348
|
+
const drive = driveLetter(value);
|
|
349
|
+
return drive !== undefined && isDriveAbsolute(value, drive);
|
|
350
|
+
}
|
|
351
|
+
/** `\\server\share\...` — a UNC path. Two leading separators, not more. */
|
|
352
|
+
function isUncWindowsPath(value) {
|
|
353
|
+
return ((value[0] === "\\" || value[0] === "/") &&
|
|
354
|
+
(value[1] === "\\" || value[1] === "/") &&
|
|
355
|
+
value[2] !== "\\" &&
|
|
356
|
+
value[2] !== "/");
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* A path is "fully qualified" (self-contained, no ambient current-directory
|
|
360
|
+
* lookup required) only when it is drive-absolute (`X:\...`) or UNC
|
|
361
|
+
* (`\\server\share`). `path.win32.isAbsolute("\tools")` also returns `true`
|
|
362
|
+
* for a *rooted* path — one relative to the current drive's root rather than
|
|
363
|
+
* a specific drive — and treating that as fully qualified was the #1201
|
|
364
|
+
* bug: it got statSync'd against the *host* drive while a different
|
|
365
|
+
* `effectiveCwd`/`resolvedDrive` supplied the drive cmd.exe actually used to
|
|
366
|
+
* execute it, so a different file could be validated than executed.
|
|
367
|
+
*/
|
|
368
|
+
function isFullyQualifiedWindowsPath(value) {
|
|
369
|
+
return isFullyQualifiedWin32(value) && !isRootedWindowsPath(value);
|
|
370
|
+
}
|
|
371
|
+
/**
|
|
372
|
+
* `\tools` or `/tools` — rooted at the current drive's root, but naming no
|
|
373
|
+
* drive of its own (distinct from both `X:\tools` fully-qualified and
|
|
374
|
+
* `X:tools` drive-relative-to-current-directory). Windows resolves this
|
|
375
|
+
* against the root of whichever drive is "current", not the current
|
|
376
|
+
* directory on that drive.
|
|
377
|
+
*/
|
|
378
|
+
function isRootedWindowsPath(value) {
|
|
379
|
+
return ((value[0] === "\\" || value[0] === "/") &&
|
|
380
|
+
driveLetter(value) === undefined &&
|
|
381
|
+
!isUncWindowsPath(value));
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* Resolve a rooted path (`\tools`) against the ROOT of `driveSource`'s drive
|
|
385
|
+
* — not `driveSource` itself — matching Windows' own rooted-path semantics.
|
|
386
|
+
*
|
|
387
|
+
* When `driveSource` carries NO drive letter, this returns the normalized
|
|
388
|
+
* value rather than `undefined` (#1201, recurring defect shape 2). A
|
|
389
|
+
* drive-less "current drive" provenance means we are not on a drive-lettered
|
|
390
|
+
* filesystem at all — a POSIX host, or a UNC `process.cwd()` such as
|
|
391
|
+
* `\\server\share\...`, which Node permits on real Windows. In that namespace
|
|
392
|
+
* a rooted path is already as qualified as any path can be, so there is
|
|
393
|
+
* nothing to anchor and normalizing is the correct (and pre-#1201) answer.
|
|
394
|
+
* Returning `undefined` instead used to collapse the whole resolution to
|
|
395
|
+
* `null` without a single `statSync`, i.e. a false ENOENT — the exact failure
|
|
396
|
+
* signature #1199 exists to remove. This function must therefore never fail
|
|
397
|
+
* closed on the *shape* of a value that may not be a Windows path at all;
|
|
398
|
+
* the filesystem probe downstream is what decides whether it exists.
|
|
399
|
+
*/
|
|
400
|
+
function resolveRootedWindowsPath(value, driveSource) {
|
|
401
|
+
const drive = driveLetter(driveSource);
|
|
402
|
+
if (drive === undefined)
|
|
403
|
+
return path.win32.normalize(value);
|
|
404
|
+
return path.win32.normalize(path.win32.resolve(`${drive}:\\`, value));
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
* Return a validated Windows per-drive current directory. Windows exposes
|
|
408
|
+
* these as environment entries such as `=D:`; unlike ordinary environment
|
|
409
|
+
* variables they are not safe to synthesize from a drive letter. A malformed
|
|
410
|
+
* or wrong-drive value is deliberately ignored so drive-relative resolution
|
|
411
|
+
* fails closed instead of guessing a root.
|
|
412
|
+
*
|
|
413
|
+
* Node never surfaces `=X:` keys from the ambient `process.env` (verified:
|
|
414
|
+
* `Object.keys(process.env).filter(k => k.startsWith("="))` is empty), so
|
|
415
|
+
* this provenance is only ever available when a caller supplies it
|
|
416
|
+
* explicitly in an `env` override — e.g. a test, or a future integration
|
|
417
|
+
* that reads it from a lower-level Windows API. That's a real, if narrow,
|
|
418
|
+
* use: keep this path rather than deleting it, but never synthesize a value
|
|
419
|
+
* Node itself can't hand us.
|
|
420
|
+
*/
|
|
421
|
+
function getValidatedPerDriveCwd(env, drive) {
|
|
422
|
+
const value = getWindowsEnvironmentValue(env, `=${drive}:`);
|
|
423
|
+
if (value === undefined || !isDriveAbsolute(value, drive))
|
|
424
|
+
return undefined;
|
|
425
|
+
return path.win32.normalize(value);
|
|
426
|
+
}
|
|
427
|
+
function resolveEffectiveWindowsCwd(cwd, env) {
|
|
428
|
+
if (cwd === undefined) {
|
|
429
|
+
// No caller-supplied cwd: `process.cwd()` IS the effective cwd already —
|
|
430
|
+
// the real, canonical filesystem cwd of THIS process, not a string that
|
|
431
|
+
// needs (re)classifying. On a POSIX CI host it naturally carries no
|
|
432
|
+
// drive letter; that's fine, it never needs one here. Only a
|
|
433
|
+
// CALLER-SUPPLIED cwd string goes through the fully-qualified/rooted/
|
|
434
|
+
// drive-relative classification below — running `process.cwd()`'s own
|
|
435
|
+
// value through `isRootedWindowsPath` was itself a #1201 regression: a
|
|
436
|
+
// drive-less POSIX path (e.g. Linux CI's real cwd) satisfies that
|
|
437
|
+
// predicate too (single leading separator, no drive letter), which then
|
|
438
|
+
// sent it to `resolveRootedWindowsPath` looking for a drive letter on
|
|
439
|
+
// `process.cwd()` that — being the very same drive-less string — could
|
|
440
|
+
// never supply one, resolving to `undefined` (recurring defect shape
|
|
441
|
+
// 2/7: `path.win32.resolve` falls back to `process.cwd()`, which
|
|
442
|
+
// supplies a drive on Windows and none on Linux).
|
|
443
|
+
return path.win32.normalize(process.cwd());
|
|
444
|
+
}
|
|
445
|
+
const requestedDrive = driveLetter(cwd);
|
|
446
|
+
if (requestedDrive !== undefined && !isDriveAbsoluteAnyDrive(cwd)) {
|
|
447
|
+
// `D:foo` — drive-relative to that drive's own current directory.
|
|
448
|
+
const base = getValidatedPerDriveCwd(env, requestedDrive);
|
|
449
|
+
return base === undefined
|
|
450
|
+
? undefined
|
|
451
|
+
: path.win32.normalize(path.win32.resolve(base, cwd));
|
|
452
|
+
}
|
|
453
|
+
if (isFullyQualifiedWindowsPath(cwd))
|
|
454
|
+
return path.win32.normalize(cwd);
|
|
455
|
+
if (isRootedWindowsPath(cwd)) {
|
|
456
|
+
// `\tools` — rooted at the CURRENT drive's root.
|
|
457
|
+
//
|
|
458
|
+
// Note the deliberate asymmetry with `resolveWindowsPathEntry`, which
|
|
459
|
+
// anchors rooted PATH entries to `effectiveCwd`'s drive instead. Both
|
|
460
|
+
// use the SAME rule — "anchor to the best available "current drive"
|
|
461
|
+
// provenance at this point in the pipeline" — they just sit at
|
|
462
|
+
// different points. Here we are *computing* `effectiveCwd`, so it does
|
|
463
|
+
// not exist yet and the process's own cwd is the only provenance
|
|
464
|
+
// available (on real Windows it always carries a drive letter). By the
|
|
465
|
+
// time a PATH entry is resolved, `effectiveCwd` is known and is the
|
|
466
|
+
// strictly better answer, because it is the drive the child will
|
|
467
|
+
// actually run from — anchoring PATH entries to the host drive there
|
|
468
|
+
// would validate one file and execute another. Neither call can fail
|
|
469
|
+
// closed on a drive-less provenance; see `resolveRootedWindowsPath`.
|
|
470
|
+
return resolveRootedWindowsPath(cwd, process.cwd());
|
|
471
|
+
}
|
|
472
|
+
return path.win32.normalize(path.win32.resolve(process.cwd(), cwd));
|
|
473
|
+
}
|
|
474
|
+
function resolveDriveRelativeWindowsPath(value, effectiveCwd, env) {
|
|
475
|
+
const drive = driveLetter(value);
|
|
476
|
+
if (drive === undefined)
|
|
477
|
+
return undefined;
|
|
478
|
+
const cwdDrive = effectiveCwd === undefined ? undefined : driveLetter(effectiveCwd);
|
|
479
|
+
const base = cwdDrive?.toUpperCase() === drive
|
|
480
|
+
? effectiveCwd
|
|
481
|
+
: getValidatedPerDriveCwd(env, drive);
|
|
482
|
+
if (base === undefined)
|
|
483
|
+
return undefined;
|
|
484
|
+
return path.win32.normalize(path.win32.resolve(base, value));
|
|
485
|
+
}
|
|
486
|
+
function resolveWindowsPathEntry(entry, effectiveCwd, env) {
|
|
487
|
+
if (driveLetter(entry) !== undefined && !isDriveAbsoluteAnyDrive(entry)) {
|
|
488
|
+
return resolveDriveRelativeWindowsPath(entry, effectiveCwd, env);
|
|
489
|
+
}
|
|
490
|
+
if (isFullyQualifiedWindowsPath(entry))
|
|
491
|
+
return path.win32.normalize(entry);
|
|
492
|
+
if (isRootedWindowsPath(entry)) {
|
|
493
|
+
// `\tools` — rooted at the effective child cwd's drive root, not the
|
|
494
|
+
// host process's drive (#1201: a rooted PATH entry must resolve on
|
|
495
|
+
// the SAME drive the child will actually run cmd.exe/the resolved
|
|
496
|
+
// binary from). See `resolveEffectiveWindowsCwd`'s rooted branch for
|
|
497
|
+
// why that function anchors to `process.cwd()` instead — same rule,
|
|
498
|
+
// different point in the pipeline. `undefined` here means the cwd
|
|
499
|
+
// itself was unprovable, which is a genuinely different condition
|
|
500
|
+
// from "the provenance carries no drive letter".
|
|
501
|
+
return effectiveCwd === undefined
|
|
502
|
+
? undefined
|
|
503
|
+
: resolveRootedWindowsPath(entry, effectiveCwd);
|
|
504
|
+
}
|
|
505
|
+
if (effectiveCwd === undefined)
|
|
506
|
+
return undefined;
|
|
507
|
+
return path.win32.normalize(path.win32.resolve(effectiveCwd, entry));
|
|
508
|
+
}
|
|
509
|
+
/**
|
|
510
|
+
* Cached PATH + PATHEXT resolution results. The effective child environment is
|
|
511
|
+
* part of the key, not the ambient process environment: one caller's managed
|
|
512
|
+
* bin directory must never poison another caller's resolution. The key also
|
|
513
|
+
* carries the canonical child cwd and Windows `=X:` per-drive cwd entries,
|
|
514
|
+
* because both affect relative PATH and drive-relative lookup. Session-lived
|
|
515
|
+
* (matches this repo's other resolution caches, e.g.
|
|
84
516
|
* `clients/workspace-topology.ts`'s `resetWorkspaceTopology`) — cleared via
|
|
85
|
-
* `resetSafeSpawnWindowsCommandCache()`, wired into `handleSessionStart`.
|
|
517
|
+
* `resetSafeSpawnWindowsCommandCache()`, wired into `handleSessionStart`. The
|
|
518
|
+
* cache is also count-bounded with oldest-entry eviction because a long-lived
|
|
519
|
+
* process can encounter unbounded cwd/environment combinations.
|
|
86
520
|
*/
|
|
521
|
+
const WINDOWS_COMMAND_CACHE_MAX_ENTRIES = 256;
|
|
522
|
+
const WINDOWS_COMMAND_NEGATIVE_CACHE_TTL_MS = 1000;
|
|
87
523
|
const windowsCommandCache = new Map();
|
|
88
|
-
/** Reset
|
|
524
|
+
/** Reset after session replacement or a successful managed install. */
|
|
89
525
|
export function resetSafeSpawnWindowsCommandCache() {
|
|
90
526
|
windowsCommandCache.clear();
|
|
527
|
+
loggedSpawnClassifications.clear();
|
|
528
|
+
}
|
|
529
|
+
function cacheWindowsCommandResult(key, resolved) {
|
|
530
|
+
if (windowsCommandCache.size >= WINDOWS_COMMAND_CACHE_MAX_ENTRIES) {
|
|
531
|
+
// Resolution entries are session-scoped and cheap to recompute. Evict the
|
|
532
|
+
// oldest insertion first so a long-lived process cannot retain every cwd /
|
|
533
|
+
// environment it has ever touched.
|
|
534
|
+
const oldest = windowsCommandCache.keys().next().value;
|
|
535
|
+
if (oldest !== undefined)
|
|
536
|
+
windowsCommandCache.delete(oldest);
|
|
537
|
+
}
|
|
538
|
+
windowsCommandCache.set(key, { resolved, checkedAt: Date.now() });
|
|
91
539
|
}
|
|
92
|
-
function getPathExts() {
|
|
93
|
-
const raw =
|
|
540
|
+
function getPathExts(env) {
|
|
541
|
+
const raw = getWindowsEnvironmentValue(env, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD";
|
|
94
542
|
return raw
|
|
95
543
|
.split(";")
|
|
96
544
|
.map((ext) => ext.trim().toLowerCase())
|
|
@@ -104,48 +552,145 @@ function statIsFile(candidate) {
|
|
|
104
552
|
return false;
|
|
105
553
|
}
|
|
106
554
|
}
|
|
107
|
-
function resolveWindowsCommandUncached(command,
|
|
108
|
-
const pathExts = getPathExts();
|
|
109
|
-
const existingExt = path.extname(command).toLowerCase();
|
|
110
|
-
const
|
|
555
|
+
function resolveWindowsCommandUncached(command, effectiveCwd, env) {
|
|
556
|
+
const pathExts = getPathExts(env);
|
|
557
|
+
const existingExt = path.win32.extname(command).toLowerCase();
|
|
558
|
+
const hasExplicitExt = existingExt.length > 0;
|
|
559
|
+
// A suffix is "known executable" when it's one of the four extensions this
|
|
560
|
+
// resolver actually knows how to run (direct .exe/.com, or the
|
|
561
|
+
// cmd.exe-wrapped .cmd/.bat) OR it's explicitly listed in the caller's own
|
|
562
|
+
// PATHEXT. Anything else with a dot is NOT necessarily "an extension" — a
|
|
563
|
+
// versioned interpreter (`python3.11`, `node-v20.1`) has an `extname()` of
|
|
564
|
+
// `.11`/`.1` that is part of the basename, not a suffix to match exactly
|
|
565
|
+
// (#1201).
|
|
566
|
+
const isKnownExecutableExt = (ext) => WINDOWS_DIRECT_RESOLVABLE_EXTS.has(ext) || pathExts.includes(ext);
|
|
111
567
|
const tryBase = (base) => {
|
|
112
|
-
|
|
113
|
-
|
|
568
|
+
// Additive, not exclusive: an explicit, known-executable suffix is
|
|
569
|
+
// tried as an exact candidate FIRST (this also lets a caller ask for
|
|
570
|
+
// `foo.cmd` even when the current PATHEXT doesn't happen to list
|
|
571
|
+
// `.CMD`). Whenever the suffix ISN'T a PATHEXT entry — no extension at
|
|
572
|
+
// all, or a versioned/unknown one like `.11` — the PATHEXT-append loop
|
|
573
|
+
// ALSO runs against the full base, so `python3.11` still finds
|
|
574
|
+
// `python3.11.exe`. An unknown suffix (e.g. `foo.txt`) never gets an
|
|
575
|
+
// exact-match short-circuit: that would let an arbitrary
|
|
576
|
+
// non-executable file resolve as "spawnable" and reach the
|
|
577
|
+
// direct-spawn branch downstream.
|
|
578
|
+
if (hasExplicitExt &&
|
|
579
|
+
isKnownExecutableExt(existingExt) &&
|
|
580
|
+
statIsFile(base)) {
|
|
581
|
+
return { resolvedPath: base, ext: existingExt };
|
|
114
582
|
}
|
|
115
|
-
|
|
116
|
-
const
|
|
117
|
-
|
|
118
|
-
|
|
583
|
+
if (!hasExplicitExt || !pathExts.includes(existingExt)) {
|
|
584
|
+
for (const ext of pathExts) {
|
|
585
|
+
const candidate = base + ext;
|
|
586
|
+
if (statIsFile(candidate))
|
|
587
|
+
return { resolvedPath: candidate, ext };
|
|
588
|
+
}
|
|
119
589
|
}
|
|
120
590
|
return null;
|
|
121
591
|
};
|
|
122
592
|
const hasPathSep = /[\\/]/.test(command);
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
593
|
+
// `D:tool.exe` is drive-relative on Windows, not a bare PATH command. It
|
|
594
|
+
// uses the effective cwd only when that cwd is on D:. For another drive we
|
|
595
|
+
// require an explicit, validated `=D:` provenance entry; otherwise this
|
|
596
|
+
// resolver fails closed rather than guessing `D:\\` or searching PATH.
|
|
597
|
+
const hasDrivePrefix = driveLetter(command) !== undefined;
|
|
598
|
+
if (hasPathSep || hasDrivePrefix || isFullyQualifiedWindowsPath(command)) {
|
|
599
|
+
let base;
|
|
600
|
+
if (isFullyQualifiedWindowsPath(command)) {
|
|
601
|
+
base = path.win32.normalize(command);
|
|
602
|
+
}
|
|
603
|
+
else if (hasDrivePrefix) {
|
|
604
|
+
base = resolveDriveRelativeWindowsPath(command, effectiveCwd, env);
|
|
605
|
+
}
|
|
606
|
+
else if (isRootedWindowsPath(command)) {
|
|
607
|
+
base =
|
|
608
|
+
effectiveCwd === undefined
|
|
609
|
+
? undefined
|
|
610
|
+
: resolveRootedWindowsPath(command, effectiveCwd);
|
|
611
|
+
}
|
|
612
|
+
else if (effectiveCwd !== undefined) {
|
|
613
|
+
base = path.win32.normalize(path.win32.resolve(effectiveCwd, command));
|
|
614
|
+
}
|
|
615
|
+
return base === undefined ? null : tryBase(base);
|
|
128
616
|
}
|
|
129
|
-
|
|
617
|
+
// A bare command (no path separator) is a plain PATH search. Absolute PATH
|
|
618
|
+
// entries don't need `effectiveCwd` at all, so an unresolvable cwd must
|
|
619
|
+
// only skip the relative entries (handled per-entry in
|
|
620
|
+
// resolveWindowsPathEntry below), not abort the whole search (#1201: a bad
|
|
621
|
+
// cwd shouldn't make an otherwise-resolvable command look "not installed").
|
|
622
|
+
const pathValue = getWindowsEnvironmentValue(env, "PATH") ?? "";
|
|
623
|
+
const pathDirs = pathValue.split(path.win32.delimiter);
|
|
130
624
|
for (const dir of pathDirs) {
|
|
131
625
|
if (!dir)
|
|
132
626
|
continue;
|
|
133
|
-
const
|
|
627
|
+
const resolvedDir = resolveWindowsPathEntry(dir, effectiveCwd, env);
|
|
628
|
+
if (resolvedDir === undefined)
|
|
629
|
+
continue;
|
|
630
|
+
const found = tryBase(path.win32.join(resolvedDir, command));
|
|
134
631
|
if (found)
|
|
135
632
|
return found;
|
|
136
633
|
}
|
|
137
634
|
return null;
|
|
138
635
|
}
|
|
139
|
-
/**
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
636
|
+
/**
|
|
637
|
+
* Resolve a Windows command using the exact environment that will be passed to
|
|
638
|
+
* the child. Exported as a small platform-independent test/diagnostic seam;
|
|
639
|
+
* callers should pass a Windows-shaped environment and do not need to mutate
|
|
640
|
+
* `process.env` to exercise resolution. Drive-relative commands (`D:tool.exe`)
|
|
641
|
+
* use a same-drive effective cwd, or a validated absolute `=D:` entry for a
|
|
642
|
+
* different drive; without that provenance they fail closed and never search
|
|
643
|
+
* PATH. Relative PATH entries use the canonical effective child cwd.
|
|
644
|
+
*/
|
|
645
|
+
export function resolveWindowsCommandForEnvironment(command, cwd, env) {
|
|
646
|
+
const effectiveCwd = resolveEffectiveWindowsCwd(cwd, env);
|
|
647
|
+
const pathValue = getWindowsEnvironmentValue(env, "PATH");
|
|
648
|
+
const pathExtValue = getWindowsEnvironmentValue(env, "PATHEXT");
|
|
649
|
+
const perDriveCwds = Object.entries(env)
|
|
650
|
+
.flatMap(([key, value]) => /^=[A-Za-z]:$/.test(key)
|
|
651
|
+
? [[key.toLowerCase(), value]]
|
|
652
|
+
: [])
|
|
653
|
+
.sort(([left], [right]) => left.localeCompare(right));
|
|
654
|
+
// Keep presence separate from value: absent PATHEXT means the Windows
|
|
655
|
+
// default extension list, while PATHEXT="" means no implicit extensions.
|
|
656
|
+
// The per-drive snapshot is equally important: it is provenance for
|
|
657
|
+
// drive-relative commands and PATH entries, not ambient decoration.
|
|
658
|
+
const cacheKey = JSON.stringify([
|
|
659
|
+
"win32",
|
|
660
|
+
command,
|
|
661
|
+
pathValue === undefined ? ["absent"] : ["present", pathValue],
|
|
662
|
+
pathExtValue === undefined ? ["absent"] : ["present", pathExtValue],
|
|
663
|
+
effectiveCwd === undefined ? ["unresolved"] : ["resolved", effectiveCwd],
|
|
664
|
+
perDriveCwds,
|
|
665
|
+
]);
|
|
666
|
+
const cached = windowsCommandCache.get(cacheKey);
|
|
667
|
+
if (cached) {
|
|
668
|
+
// Positive entries are revalidated on every hit so an executable deleted
|
|
669
|
+
// or replaced mid-session cannot remain spawnable through stale cache
|
|
670
|
+
// state. Negative entries are short-lived to discover external installs;
|
|
671
|
+
// pi-lens-managed installs also reset the cache immediately on success.
|
|
672
|
+
if (cached.resolved && statIsFile(cached.resolved.resolvedPath)) {
|
|
673
|
+
return cached.resolved;
|
|
674
|
+
}
|
|
675
|
+
if (!cached.resolved &&
|
|
676
|
+
Date.now() - cached.checkedAt <= WINDOWS_COMMAND_NEGATIVE_CACHE_TTL_MS) {
|
|
677
|
+
return null;
|
|
678
|
+
}
|
|
679
|
+
windowsCommandCache.delete(cacheKey);
|
|
144
680
|
}
|
|
145
|
-
const resolved = resolveWindowsCommandUncached(command,
|
|
146
|
-
|
|
681
|
+
const resolved = resolveWindowsCommandUncached(command, effectiveCwd, env);
|
|
682
|
+
cacheWindowsCommandResult(cacheKey, resolved);
|
|
147
683
|
return resolved;
|
|
148
684
|
}
|
|
685
|
+
/** Cached `where`-equivalent for the effective child environment. */
|
|
686
|
+
function resolveWindowsCommand(command, cwd, env) {
|
|
687
|
+
return resolveWindowsCommandForEnvironment(command, cwd, env);
|
|
688
|
+
}
|
|
689
|
+
function getSpawnEnvironment(overrides) {
|
|
690
|
+
return process.platform === "win32"
|
|
691
|
+
? mergeWindowsEnvironment(process.env, overrides)
|
|
692
|
+
: { ...process.env, ...overrides };
|
|
693
|
+
}
|
|
149
694
|
/**
|
|
150
695
|
* Characters that make a cmd.exe `/c` command line unsound to build from
|
|
151
696
|
* caller-tainted input: `%`/`!` expand even inside double quotes and cannot
|
|
@@ -165,10 +710,8 @@ function findCmdUnsafeValue(command, args) {
|
|
|
165
710
|
}
|
|
166
711
|
function synthesizeEnoentError(command) {
|
|
167
712
|
// Shaped like Node's native `spawn <cmd> ENOENT` error (message/code/
|
|
168
|
-
// syscall/path) so
|
|
169
|
-
//
|
|
170
|
-
// keep working now that Windows resolution happens before spawn instead
|
|
171
|
-
// of inside cmd.exe.
|
|
713
|
+
// syscall/path) so the typed classifier retains the same diagnostic cause
|
|
714
|
+
// now that Windows resolution happens before spawn instead of inside cmd.exe.
|
|
172
715
|
const err = new Error(`spawn ${command} ENOENT`);
|
|
173
716
|
err.code = "ENOENT";
|
|
174
717
|
err.syscall = "spawn";
|
|
@@ -201,11 +744,22 @@ function ensureUtf8ConsoleCodePageOnce() {
|
|
|
201
744
|
});
|
|
202
745
|
}
|
|
203
746
|
catch {
|
|
204
|
-
// Best-effort: worst case is non-ASCII tool output
|
|
747
|
+
// Best-effort: worst case is non-ASCII tool output decoded incorrectly, not a
|
|
205
748
|
// spawn failure — never let this block the real spawn.
|
|
206
749
|
}
|
|
207
750
|
}
|
|
208
|
-
/**
|
|
751
|
+
/**
|
|
752
|
+
* Test-only seam: clear the one-shot `chcp` memoization.
|
|
753
|
+
*
|
|
754
|
+
* No test observes it today — the memoized work only runs inside a real
|
|
755
|
+
* Windows direct spawn, so exercising it would mean a Windows-only test, and
|
|
756
|
+
* the state it guards is a console code page, not behavior any assertion
|
|
757
|
+
* depends on. This is kept purely so a future Windows-only test (or a second
|
|
758
|
+
* caller of `ensureUtf8ConsoleCodePageOnce`) can reset process-lifetime state
|
|
759
|
+
* without reaching into the module; it was dropped once as unrelated scope
|
|
760
|
+
* creep in an earlier #1199 revision and restored on review. Do not read the
|
|
761
|
+
* export as evidence of existing coverage (#1201).
|
|
762
|
+
*/
|
|
209
763
|
export function resetUtf8ConsoleCodePageStateForTests() {
|
|
210
764
|
utf8ConsoleCodePageApplied = false;
|
|
211
765
|
}
|
|
@@ -225,7 +779,15 @@ export function resetUtf8ConsoleCodePageStateForTests() {
|
|
|
225
779
|
* if (result.error) console.error("Failed:", result.error);
|
|
226
780
|
*/
|
|
227
781
|
export async function safeSpawnAsync(command, args, options) {
|
|
228
|
-
const
|
|
782
|
+
const configuredTimeout = options?.timeout !== undefined &&
|
|
783
|
+
Number.isFinite(options.timeout) &&
|
|
784
|
+
options.timeout >= 0
|
|
785
|
+
? options.timeout
|
|
786
|
+
: 30000;
|
|
787
|
+
const deadlineRemaining = options?.deadlineAt !== undefined && Number.isFinite(options.deadlineAt)
|
|
788
|
+
? options.deadlineAt - Date.now()
|
|
789
|
+
: Number.POSITIVE_INFINITY;
|
|
790
|
+
const timeout = Math.max(0, Math.min(configuredTimeout, deadlineRemaining));
|
|
229
791
|
// Fall back to the current turn's ambient signal (set from ctx.signal) so an
|
|
230
792
|
// Esc/abort mid-turn cancels dispatches that didn't thread a signal of their
|
|
231
793
|
// own — unless the caller opts out (installs, which must run to completion).
|
|
@@ -234,18 +796,72 @@ export async function safeSpawnAsync(command, args, options) {
|
|
|
234
796
|
return new Promise((resolve) => {
|
|
235
797
|
// Check for early abort
|
|
236
798
|
if (abortSignal?.aborted) {
|
|
799
|
+
const cause = new Error("Spawn aborted before start");
|
|
800
|
+
resolve({
|
|
801
|
+
stdout: "",
|
|
802
|
+
stderr: "",
|
|
803
|
+
status: null,
|
|
804
|
+
error: cause,
|
|
805
|
+
failure: "aborted",
|
|
806
|
+
spawnFailure: new SpawnFailureError("killed", cause.message, cause),
|
|
807
|
+
});
|
|
808
|
+
return;
|
|
809
|
+
}
|
|
810
|
+
if (timeout <= 0) {
|
|
811
|
+
const cause = new Error(`Process timed out after ${timeout}ms`);
|
|
237
812
|
resolve({
|
|
238
813
|
stdout: "",
|
|
239
814
|
stderr: "",
|
|
240
815
|
status: null,
|
|
241
|
-
error:
|
|
816
|
+
error: cause,
|
|
817
|
+
failure: "timeout",
|
|
818
|
+
spawnFailure: new SpawnFailureError("timeout", cause.message, cause),
|
|
242
819
|
});
|
|
243
820
|
return;
|
|
244
821
|
}
|
|
245
822
|
let stdout = "";
|
|
246
823
|
let stderr = "";
|
|
247
824
|
let timedOut = false;
|
|
825
|
+
let aborted = false;
|
|
248
826
|
let killed = false;
|
|
827
|
+
let outputTruncated = false;
|
|
828
|
+
let spawnErrored = false;
|
|
829
|
+
// #1109: the non-Windows SIGTERM→SIGKILL escalation timer (armed in
|
|
830
|
+
// killTree below). Stored per-call (never shared) so the close/error
|
|
831
|
+
// handlers can clear it if the child exits before it fires — same
|
|
832
|
+
// uncleared-race-timeout class as the LSP client-wait leak (#1097):
|
|
833
|
+
// a ref'd 1s timer that outlives the child it was escalating against
|
|
834
|
+
// would keep a one-shot `pi --print` process alive for up to 1s.
|
|
835
|
+
let escalationTimer;
|
|
836
|
+
// #1114: `child.killed` is set by Node the moment `kill()` successfully
|
|
837
|
+
// SENDS a signal, not when the child actually dies — so gating the
|
|
838
|
+
// escalation on `!child.killed` right after a successful `SIGTERM` send
|
|
839
|
+
// is always false and the SIGKILL branch is unreachable. Track observed
|
|
840
|
+
// death via the close/error handlers instead (set synchronously, before
|
|
841
|
+
// any `await`, so a timer firing during the close handler's `await
|
|
842
|
+
// killPromise` still observes the flag correctly).
|
|
843
|
+
let closed = false;
|
|
844
|
+
const maxOutputBytes = options?.maxOutputBytes !== undefined &&
|
|
845
|
+
Number.isFinite(options.maxOutputBytes) &&
|
|
846
|
+
options.maxOutputBytes > 0
|
|
847
|
+
? Math.floor(options.maxOutputBytes)
|
|
848
|
+
: undefined;
|
|
849
|
+
const appendOutput = (current, chunk) => {
|
|
850
|
+
const text = typeof chunk === "string" ? chunk : chunk.toString();
|
|
851
|
+
if (maxOutputBytes === undefined)
|
|
852
|
+
return current + text;
|
|
853
|
+
const used = Buffer.byteLength(stdout) + Buffer.byteLength(stderr);
|
|
854
|
+
const remaining = maxOutputBytes - used;
|
|
855
|
+
if (remaining <= 0) {
|
|
856
|
+
outputTruncated = true;
|
|
857
|
+
return current;
|
|
858
|
+
}
|
|
859
|
+
const bytes = Buffer.byteLength(text);
|
|
860
|
+
if (bytes <= remaining)
|
|
861
|
+
return current + text;
|
|
862
|
+
outputTruncated = true;
|
|
863
|
+
return current + Buffer.from(text).subarray(0, remaining).toString();
|
|
864
|
+
};
|
|
249
865
|
// Spawn the process (non-blocking). Keeping Node's `shell` option false
|
|
250
866
|
// is important on every path here: shell:true concatenates tainted
|
|
251
867
|
// arguments into a command line before spawning (CodeQL #17 / CWE-78).
|
|
@@ -263,12 +879,36 @@ export async function safeSpawnAsync(command, args, options) {
|
|
|
263
879
|
// - unresolvable → synthesize an ENOENT-shaped error instead of
|
|
264
880
|
// letting cmd.exe report "not recognized" from inside a shell.
|
|
265
881
|
const isWindows = process.platform === "win32";
|
|
882
|
+
const spawnEnv = getSpawnEnvironment(options?.env);
|
|
883
|
+
// The cwd handed to the CHILD process doesn't need OUR validation —
|
|
884
|
+
// Windows resolves it natively, exactly as it did before #817 ever
|
|
885
|
+
// touched this file. A drive-relative cwd (`D:work`) without a
|
|
886
|
+
// validated `=D:` env entry can't be canonicalized by us (Node never
|
|
887
|
+
// surfaces `=X:` keys from the ambient environment — see
|
|
888
|
+
// `getValidatedPerDriveCwd`'s doc comment), but that is a gap in OUR
|
|
889
|
+
// provenance, not evidence the cwd itself is bad. Fall back to the raw
|
|
890
|
+
// value instead of failing the whole spawn before ever attempting it
|
|
891
|
+
// (#1201) — command resolution just below still fails closed for any
|
|
892
|
+
// relative PATH entry that would need this cwd to be canonical.
|
|
893
|
+
// No `?? process.cwd()` third arm: `resolveEffectiveWindowsCwd(undefined,
|
|
894
|
+
// env)` always returns a string, so the only way to reach `undefined`
|
|
895
|
+
// here is a DEFINED-but-unprovable `options.cwd`, which `?? options?.cwd`
|
|
896
|
+
// already covers. A `process.cwd()` arm would be unreachable, and it
|
|
897
|
+
// would read like a live silent-wrong-directory hazard (#1201).
|
|
898
|
+
const spawnCwd = isWindows
|
|
899
|
+
? (resolveEffectiveWindowsCwd(options?.cwd, spawnEnv) ?? options?.cwd)
|
|
900
|
+
: options?.cwd;
|
|
266
901
|
let spawnCmd = command;
|
|
267
902
|
let spawnArgs = args;
|
|
268
903
|
let windowsVerbatimArguments = false;
|
|
269
904
|
let resolutionError;
|
|
270
905
|
if (isWindows) {
|
|
271
|
-
|
|
906
|
+
// Pass the ORIGINAL (unresolved) cwd here, not `spawnCwd` above — this
|
|
907
|
+
// seam intentionally fails closed on unprovable drive-relative
|
|
908
|
+
// provenance (matches `resolveWindowsCommandForEnvironment`'s
|
|
909
|
+
// documented contract and its dedicated test coverage), independent
|
|
910
|
+
// of the passthrough fallback the actual child cwd gets above.
|
|
911
|
+
const resolved = resolveWindowsCommand(command, options?.cwd, spawnEnv);
|
|
272
912
|
if (!resolved) {
|
|
273
913
|
resolutionError = synthesizeEnoentError(command);
|
|
274
914
|
}
|
|
@@ -309,16 +949,52 @@ export async function safeSpawnAsync(command, args, options) {
|
|
|
309
949
|
}
|
|
310
950
|
}
|
|
311
951
|
if (resolutionError) {
|
|
312
|
-
|
|
952
|
+
void classifySpawnFailure(resolutionError, {
|
|
953
|
+
command,
|
|
954
|
+
cwd: options?.cwd,
|
|
955
|
+
}).then((spawnFailure) => resolve({
|
|
956
|
+
stdout: "",
|
|
957
|
+
stderr: "",
|
|
958
|
+
status: null,
|
|
959
|
+
error: resolutionError,
|
|
960
|
+
failure: "spawn",
|
|
961
|
+
spawnFailure,
|
|
962
|
+
}));
|
|
313
963
|
return;
|
|
314
964
|
}
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
965
|
+
let child;
|
|
966
|
+
try {
|
|
967
|
+
child = spawn(spawnCmd, spawnArgs, {
|
|
968
|
+
cwd: spawnCwd,
|
|
969
|
+
env: spawnEnv,
|
|
970
|
+
windowsHide: true,
|
|
971
|
+
shell: false,
|
|
972
|
+
windowsVerbatimArguments,
|
|
973
|
+
});
|
|
974
|
+
}
|
|
975
|
+
catch (err) {
|
|
976
|
+
// A SYNCHRONOUS spawn throw (Windows `spawn UNKNOWN`/EINVAL — the
|
|
977
|
+
// pidusage bug class, #533) must NOT reject this Promise: every caller
|
|
978
|
+
// relies on safeSpawnAsync never rejecting (they inspect result.error),
|
|
979
|
+
// and many invoke it fire-and-forget in best-effort/background paths, so
|
|
980
|
+
// a rejection here could surface as an unhandledRejection that crashes
|
|
981
|
+
// the host. Resolve the failure gracefully instead — same contract as an
|
|
982
|
+
// asynchronously-emitted `'error'` event (handled below).
|
|
983
|
+
const cause = toError(err);
|
|
984
|
+
void classifySpawnFailure(cause, { command, cwd: options?.cwd }).then((spawnFailure) => resolve({
|
|
985
|
+
stdout: "",
|
|
986
|
+
stderr: "",
|
|
987
|
+
status: null,
|
|
988
|
+
error: cause,
|
|
989
|
+
failure: "spawn",
|
|
990
|
+
spawnFailure,
|
|
991
|
+
}));
|
|
992
|
+
return;
|
|
993
|
+
}
|
|
994
|
+
if (options?.lifetimeCoupled && child.pid) {
|
|
995
|
+
installLifetimeCleanup();
|
|
996
|
+
lifetimeState.pids.add(child.pid);
|
|
997
|
+
}
|
|
322
998
|
// #620: bracket this spawn's lifetime with a short-interval CPU/RSS poll
|
|
323
999
|
// (started right here, stopped in the "close" handler below) so transient
|
|
324
1000
|
// analyzer children (jscpd, knip, madge, gitleaks, etc.) — which live too
|
|
@@ -338,13 +1014,21 @@ export async function safeSpawnAsync(command, args, options) {
|
|
|
338
1014
|
// On Windows, shell:true means child.pid is cmd.exe — child.kill() only
|
|
339
1015
|
// kills the wrapper, leaving the actual subprocess (e.g. knip/npx) alive
|
|
340
1016
|
// as an orphan. Use taskkill /F /T to kill the full process tree instead.
|
|
341
|
-
const killTree = () => {
|
|
1017
|
+
const killTree = async () => {
|
|
342
1018
|
if (isWindows && child.pid && child.pid > 0) {
|
|
343
1019
|
const taskkill = `${process.env.SystemRoot ?? "C:\\Windows"}\\System32\\taskkill.exe`;
|
|
344
1020
|
try {
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
1021
|
+
await new Promise((done) => {
|
|
1022
|
+
const killer = spawn(taskkill, ["/F", "/T", "/PID", String(child.pid)], {
|
|
1023
|
+
shell: false,
|
|
1024
|
+
windowsHide: true,
|
|
1025
|
+
stdio: "ignore",
|
|
1026
|
+
});
|
|
1027
|
+
killer.once("close", () => done());
|
|
1028
|
+
killer.once("error", () => {
|
|
1029
|
+
child.kill("SIGKILL");
|
|
1030
|
+
done();
|
|
1031
|
+
});
|
|
348
1032
|
});
|
|
349
1033
|
}
|
|
350
1034
|
catch {
|
|
@@ -353,31 +1037,48 @@ export async function safeSpawnAsync(command, args, options) {
|
|
|
353
1037
|
}
|
|
354
1038
|
else {
|
|
355
1039
|
child.kill("SIGTERM");
|
|
356
|
-
setTimeout(() => {
|
|
357
|
-
if (!
|
|
1040
|
+
escalationTimer = setTimeout(() => {
|
|
1041
|
+
if (!closed)
|
|
358
1042
|
child.kill("SIGKILL");
|
|
359
1043
|
}, 1000);
|
|
360
1044
|
}
|
|
361
1045
|
};
|
|
362
1046
|
// Handle abort signal
|
|
363
1047
|
const onAbort = () => {
|
|
1048
|
+
aborted = true;
|
|
364
1049
|
if (!killed && !child.killed) {
|
|
365
1050
|
killed = true;
|
|
366
|
-
killTree();
|
|
1051
|
+
void killTree();
|
|
367
1052
|
}
|
|
368
1053
|
};
|
|
369
1054
|
abortSignal?.addEventListener("abort", onAbort, { once: true });
|
|
1055
|
+
// Output-cap kills are awaited by the close handler below, just like
|
|
1056
|
+
// timeout/abort kills. This keeps a noisy CLI from continuing in the
|
|
1057
|
+
// background after its retained output has been bounded.
|
|
1058
|
+
let killPromise;
|
|
1059
|
+
const stopForOutputLimit = () => {
|
|
1060
|
+
if (outputTruncated && !killed && !child.killed) {
|
|
1061
|
+
killed = true;
|
|
1062
|
+
killPromise = killTree();
|
|
1063
|
+
}
|
|
1064
|
+
};
|
|
370
1065
|
// Collect output
|
|
371
1066
|
child.stdout?.setEncoding("utf-8");
|
|
372
1067
|
child.stderr?.setEncoding("utf-8");
|
|
373
|
-
child.stdout?.on("data", (data) =>
|
|
374
|
-
|
|
1068
|
+
child.stdout?.on("data", (data) => {
|
|
1069
|
+
stdout = appendOutput(stdout, data);
|
|
1070
|
+
stopForOutputLimit();
|
|
1071
|
+
});
|
|
1072
|
+
child.stderr?.on("data", (data) => {
|
|
1073
|
+
stderr = appendOutput(stderr, data);
|
|
1074
|
+
stopForOutputLimit();
|
|
1075
|
+
});
|
|
375
1076
|
// Timeout handling - KILL the process, don't just abandon it
|
|
376
1077
|
const timeoutId = setTimeout(() => {
|
|
377
1078
|
timedOut = true;
|
|
378
1079
|
if (!killed && !child.killed) {
|
|
379
1080
|
killed = true;
|
|
380
|
-
killTree();
|
|
1081
|
+
killPromise = killTree();
|
|
381
1082
|
}
|
|
382
1083
|
}, timeout);
|
|
383
1084
|
// #620: stop the poll and log peak/average CPU%+RSS for this invocation
|
|
@@ -405,37 +1106,100 @@ export async function safeSpawnAsync(command, args, options) {
|
|
|
405
1106
|
return summary;
|
|
406
1107
|
};
|
|
407
1108
|
// Process completion
|
|
408
|
-
child.on("close", (code, signal) => {
|
|
1109
|
+
child.on("close", async (code, signal) => {
|
|
1110
|
+
if (spawnErrored)
|
|
1111
|
+
return;
|
|
1112
|
+
closed = true;
|
|
409
1113
|
clearTimeout(timeoutId);
|
|
410
1114
|
abortSignal?.removeEventListener("abort", onAbort);
|
|
1115
|
+
if (child.pid)
|
|
1116
|
+
lifetimeState.pids.delete(child.pid);
|
|
1117
|
+
await killPromise;
|
|
1118
|
+
// #1109: the child has exited — if killTree armed the non-Windows
|
|
1119
|
+
// SIGTERM→SIGKILL escalation timer and it hasn't fired yet, clear it
|
|
1120
|
+
// so it doesn't linger as a ref'd handle after this promise resolves.
|
|
1121
|
+
if (escalationTimer)
|
|
1122
|
+
clearTimeout(escalationTimer);
|
|
411
1123
|
const resourceUsage = finishResourceUsage();
|
|
1124
|
+
const outputInfo = outputTruncated ? { outputTruncated: true } : {};
|
|
412
1125
|
if (timedOut) {
|
|
1126
|
+
const cause = new Error(`Process timed out after ${timeout}ms (killed with ${signal || "SIGTERM"})`);
|
|
1127
|
+
resolve({
|
|
1128
|
+
stdout,
|
|
1129
|
+
stderr,
|
|
1130
|
+
status: null,
|
|
1131
|
+
error: cause,
|
|
1132
|
+
failure: "timeout",
|
|
1133
|
+
spawnFailure: new SpawnFailureError("timeout", cause.message, cause),
|
|
1134
|
+
...outputInfo,
|
|
1135
|
+
resourceUsage,
|
|
1136
|
+
});
|
|
1137
|
+
}
|
|
1138
|
+
else if (aborted) {
|
|
1139
|
+
const cause = new Error("Spawn aborted");
|
|
413
1140
|
resolve({
|
|
414
1141
|
stdout,
|
|
415
1142
|
stderr,
|
|
416
1143
|
status: null,
|
|
417
|
-
error:
|
|
1144
|
+
error: cause,
|
|
1145
|
+
failure: "aborted",
|
|
1146
|
+
spawnFailure: new SpawnFailureError("killed", cause.message, cause),
|
|
1147
|
+
...outputInfo,
|
|
418
1148
|
resourceUsage,
|
|
419
1149
|
});
|
|
420
1150
|
}
|
|
421
1151
|
else if (signal) {
|
|
1152
|
+
const cause = new Error(`Process killed by signal: ${signal}`);
|
|
422
1153
|
resolve({
|
|
423
1154
|
stdout,
|
|
424
1155
|
stderr,
|
|
425
1156
|
status: null,
|
|
426
|
-
error:
|
|
1157
|
+
error: cause,
|
|
1158
|
+
failure: "signal",
|
|
1159
|
+
spawnFailure: new SpawnFailureError("killed", cause.message, cause),
|
|
1160
|
+
...outputInfo,
|
|
427
1161
|
resourceUsage,
|
|
428
1162
|
});
|
|
429
1163
|
}
|
|
430
1164
|
else {
|
|
431
|
-
resolve({ stdout, stderr, status: code, resourceUsage });
|
|
1165
|
+
resolve({ stdout, stderr, status: code, ...outputInfo, resourceUsage });
|
|
432
1166
|
}
|
|
433
1167
|
});
|
|
434
1168
|
child.on("error", (err) => {
|
|
1169
|
+
spawnErrored = true;
|
|
1170
|
+
closed = true;
|
|
435
1171
|
clearTimeout(timeoutId);
|
|
436
1172
|
abortSignal?.removeEventListener("abort", onAbort);
|
|
1173
|
+
if (escalationTimer)
|
|
1174
|
+
clearTimeout(escalationTimer);
|
|
1175
|
+
if (child.pid)
|
|
1176
|
+
lifetimeState.pids.delete(child.pid);
|
|
437
1177
|
const resourceUsage = finishResourceUsage();
|
|
438
|
-
|
|
1178
|
+
let failure = "spawn";
|
|
1179
|
+
if (aborted)
|
|
1180
|
+
failure = "aborted";
|
|
1181
|
+
else if (timedOut)
|
|
1182
|
+
failure = "timeout";
|
|
1183
|
+
const controlFailure = aborted
|
|
1184
|
+
? new SpawnFailureError("killed", err.message, err)
|
|
1185
|
+
: timedOut
|
|
1186
|
+
? new SpawnFailureError("timeout", err.message, err)
|
|
1187
|
+
: undefined;
|
|
1188
|
+
const finish = (spawnFailure) => resolve({
|
|
1189
|
+
stdout,
|
|
1190
|
+
stderr,
|
|
1191
|
+
status: null,
|
|
1192
|
+
error: err,
|
|
1193
|
+
failure,
|
|
1194
|
+
spawnFailure,
|
|
1195
|
+
...(outputTruncated ? { outputTruncated: true } : {}),
|
|
1196
|
+
resourceUsage,
|
|
1197
|
+
});
|
|
1198
|
+
if (controlFailure)
|
|
1199
|
+
finish(controlFailure);
|
|
1200
|
+
else {
|
|
1201
|
+
void classifySpawnFailure(err, { command, cwd: options?.cwd }).then(finish);
|
|
1202
|
+
}
|
|
439
1203
|
});
|
|
440
1204
|
});
|
|
441
1205
|
}
|
|
@@ -504,14 +1268,29 @@ export async function findCommandAsync(command) {
|
|
|
504
1268
|
* No `shell: true` anywhere.
|
|
505
1269
|
*/
|
|
506
1270
|
export function safeSpawn(command, args, options) {
|
|
1271
|
+
const spawnEnv = getSpawnEnvironment(options?.env);
|
|
507
1272
|
if (process.platform === "win32") {
|
|
508
|
-
|
|
1273
|
+
// See the matching comment in safeSpawnAsync: the child's cwd doesn't
|
|
1274
|
+
// need OUR validation (Windows resolves it natively), so an unprovable
|
|
1275
|
+
// drive-relative cwd falls back to the raw value instead of failing the
|
|
1276
|
+
// whole spawn before ever attempting it (#1201). Command resolution
|
|
1277
|
+
// below intentionally still uses the ORIGINAL raw cwd and fails closed
|
|
1278
|
+
// for PATH entries that would need it to be canonical.
|
|
1279
|
+
// See safeSpawnAsync for why there is no `?? process.cwd()` third arm.
|
|
1280
|
+
const spawnCwd = resolveEffectiveWindowsCwd(options?.cwd, spawnEnv) ?? options?.cwd;
|
|
1281
|
+
const resolved = resolveWindowsCommand(command, options?.cwd, spawnEnv);
|
|
509
1282
|
if (!resolved) {
|
|
1283
|
+
const error = synthesizeEnoentError(command);
|
|
510
1284
|
return {
|
|
511
1285
|
stdout: "",
|
|
512
1286
|
stderr: "",
|
|
513
1287
|
status: null,
|
|
514
|
-
error
|
|
1288
|
+
error,
|
|
1289
|
+
failure: "spawn",
|
|
1290
|
+
spawnFailure: classifySpawnFailureSync(error, {
|
|
1291
|
+
command,
|
|
1292
|
+
cwd: options?.cwd,
|
|
1293
|
+
}),
|
|
515
1294
|
};
|
|
516
1295
|
}
|
|
517
1296
|
let spawnCmd;
|
|
@@ -523,15 +1302,21 @@ export function safeSpawn(command, args, options) {
|
|
|
523
1302
|
// extensionless) `command` string — plus every arg.
|
|
524
1303
|
const unsafeValue = findCmdUnsafeValue(resolved.resolvedPath, args);
|
|
525
1304
|
if (unsafeValue !== undefined) {
|
|
1305
|
+
const error = new Error(`Refusing to spawn "${resolved.resolvedPath}" via cmd.exe: ` +
|
|
1306
|
+
`${JSON.stringify(unsafeValue)} contains a character ("` +
|
|
1307
|
+
`, %, !, or CR/LF) that cannot be safely escaped on a ` +
|
|
1308
|
+
`cmd.exe /c command line (CWE-78, #817). Rename/quote the ` +
|
|
1309
|
+
"value or invoke the tool without going through cmd.exe.");
|
|
526
1310
|
return {
|
|
527
1311
|
stdout: "",
|
|
528
1312
|
stderr: "",
|
|
529
1313
|
status: null,
|
|
530
|
-
error
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
1314
|
+
error,
|
|
1315
|
+
failure: "spawn",
|
|
1316
|
+
spawnFailure: classifySpawnFailureSync(error, {
|
|
1317
|
+
command,
|
|
1318
|
+
cwd: options?.cwd,
|
|
1319
|
+
}),
|
|
535
1320
|
};
|
|
536
1321
|
}
|
|
537
1322
|
spawnCmd = `${process.env.SystemRoot ?? "C:\\Windows"}\\System32\\cmd.exe`;
|
|
@@ -550,29 +1335,46 @@ export function safeSpawn(command, args, options) {
|
|
|
550
1335
|
}
|
|
551
1336
|
const result = spawnSync(spawnCmd, spawnArgs, {
|
|
552
1337
|
...options,
|
|
1338
|
+
cwd: spawnCwd,
|
|
1339
|
+
env: spawnEnv,
|
|
553
1340
|
encoding: "utf-8",
|
|
554
1341
|
shell: false,
|
|
555
1342
|
windowsHide: true,
|
|
556
1343
|
windowsVerbatimArguments,
|
|
557
1344
|
});
|
|
1345
|
+
const spawnFailure = result.error
|
|
1346
|
+
? classifySpawnFailureSync(result.error, { command, cwd: options?.cwd })
|
|
1347
|
+
: undefined;
|
|
558
1348
|
return {
|
|
559
1349
|
stdout: result.stdout?.toString() || "",
|
|
560
1350
|
stderr: result.stderr?.toString() || "",
|
|
561
1351
|
status: result.status,
|
|
562
1352
|
error: result.error,
|
|
1353
|
+
...(spawnFailure ? { failure: "spawn", spawnFailure } : {}),
|
|
563
1354
|
};
|
|
564
1355
|
}
|
|
565
1356
|
const result = spawnSync(command, args, {
|
|
566
1357
|
...options,
|
|
1358
|
+
// Explicit override, not just the spread above: `options.env` alone
|
|
1359
|
+
// would otherwise reach the child as a full replacement (no
|
|
1360
|
+
// process.env merge, no PATH) instead of the merged environment the
|
|
1361
|
+
// resolver/Windows branch above both use (#1201) — the module's
|
|
1362
|
+
// "resolver and child receive the same merged environment" invariant
|
|
1363
|
+
// must hold on every platform, not just Windows.
|
|
1364
|
+
env: spawnEnv,
|
|
567
1365
|
encoding: "utf-8",
|
|
568
1366
|
shell: false,
|
|
569
1367
|
windowsHide: true,
|
|
570
1368
|
});
|
|
1369
|
+
const spawnFailure = result.error
|
|
1370
|
+
? classifySpawnFailureSync(result.error, { command, cwd: options?.cwd })
|
|
1371
|
+
: undefined;
|
|
571
1372
|
return {
|
|
572
1373
|
stdout: result.stdout?.toString() || "",
|
|
573
1374
|
stderr: result.stderr?.toString() || "",
|
|
574
1375
|
status: result.status,
|
|
575
1376
|
error: result.error,
|
|
1377
|
+
...(spawnFailure ? { failure: "spawn", spawnFailure } : {}),
|
|
576
1378
|
};
|
|
577
1379
|
}
|
|
578
1380
|
/**
|