@loucompanion/forge-bridge 0.1.3-dev.fbe15023cdfe → 0.1.4-dev.03584818ede5
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/README.md +146 -5
- package/dist/bridge/bridge-chat-provider-command.d.ts +16 -0
- package/dist/bridge/bridge-chat-provider-command.js +137 -0
- package/dist/bridge/bridge-chat.types.d.ts +121 -0
- package/dist/bridge/bridge-chat.types.js +416 -0
- package/dist/bridge/bridge.base.d.ts +13 -1
- package/dist/bridge/bridge.service.d.ts +155 -4
- package/dist/bridge/bridge.service.js +1805 -155
- package/dist/bridge/bridge.types.d.ts +68 -1
- package/dist/bridge/dispatch-result-outbox.d.ts +35 -0
- package/dist/bridge/dispatch-result-outbox.js +87 -0
- package/dist/bridge/dispatch-result-worker.d.ts +2 -0
- package/dist/bridge/dispatch-result-worker.js +122 -0
- package/dist/bridge/internals.d.ts +2 -0
- package/dist/bridge/internals.js +1 -0
- package/dist/bridge/local-yield-flag.d.ts +6 -0
- package/dist/bridge/local-yield-flag.js +34 -0
- package/dist/bridge/readiness-result-outbox.d.ts +21 -0
- package/dist/bridge/readiness-result-outbox.js +54 -0
- package/dist/bridge/readiness-result-worker.d.ts +2 -0
- package/dist/bridge/readiness-result-worker.js +121 -0
- package/dist/bridge/runner-host-capabilities.d.ts +20 -0
- package/dist/bridge/runner-host-capabilities.js +110 -0
- package/dist/bridge/test-postgres-capability.d.ts +14 -0
- package/dist/bridge/test-postgres-capability.js +120 -0
- package/dist/cleanup/cleanup.service.d.ts +10 -0
- package/dist/cleanup/cleanup.service.js +128 -104
- package/dist/cleanup/cleanup.types.d.ts +4 -0
- package/dist/cleanup/forge-owned-paths.d.ts +9 -0
- package/dist/cleanup/forge-owned-paths.js +53 -0
- package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
- package/dist/cleanup/host-runtime-ledger.js +109 -0
- package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
- package/dist/cleanup/managed-branch-sweep.js +111 -0
- package/dist/cli/cli.help.js +22 -4
- package/dist/cli/cli.service.d.ts +30 -6
- package/dist/cli/cli.service.js +216 -31
- package/dist/cli/local-config.d.ts +5 -0
- package/dist/cli/local-config.js +30 -4
- package/dist/runtime/aspnet-runtime-prebuild.d.ts +36 -0
- package/dist/runtime/aspnet-runtime-prebuild.js +429 -0
- package/dist/runtime/attempt-database-broker.d.ts +89 -0
- package/dist/runtime/attempt-database-broker.js +390 -0
- package/dist/runtime/attempt-node-runtime-launcher.d.ts +2 -1
- package/dist/runtime/attempt-node-runtime-launcher.js +57 -18
- package/dist/runtime/attempt-path-operation.d.ts +21 -0
- package/dist/runtime/attempt-path-operation.js +94 -0
- package/dist/runtime/attempt-private-directory.d.ts +6 -0
- package/dist/runtime/attempt-private-directory.js +54 -0
- package/dist/runtime/attempt-process-supervisor.d.ts +35 -0
- package/dist/runtime/attempt-process-supervisor.js +144 -23
- package/dist/runtime/canonical-source-file.d.ts +3 -0
- package/dist/runtime/canonical-source-file.js +54 -0
- package/dist/runtime/docker-engine-probe.d.ts +90 -0
- package/dist/runtime/docker-engine-probe.js +333 -0
- package/dist/runtime/generated-output-reset.d.ts +10 -0
- package/dist/runtime/generated-output-reset.js +62 -8
- package/dist/runtime/host-database-capability-boundary.d.ts +16 -0
- package/dist/runtime/host-database-capability-boundary.js +63 -0
- package/dist/runtime/host-diagnostics.d.ts +11 -0
- package/dist/runtime/host-diagnostics.js +192 -0
- package/dist/runtime/host-execution-root.d.ts +4 -0
- package/dist/runtime/host-execution-root.js +39 -0
- package/dist/runtime/host-facts.d.ts +36 -0
- package/dist/runtime/host-facts.js +95 -0
- package/dist/runtime/host-listener-inspector.d.ts +8 -1
- package/dist/runtime/host-listener-inspector.js +121 -60
- package/dist/runtime/host-load-admission.d.ts +67 -0
- package/dist/runtime/host-load-admission.js +99 -0
- package/dist/runtime/host-load-child-environment.d.ts +27 -0
- package/dist/runtime/host-load-child-environment.js +76 -0
- package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
- package/dist/runtime/host-load-forge-cgroups.js +140 -0
- package/dist/runtime/host-load-governor-config.d.ts +52 -0
- package/dist/runtime/host-load-governor-config.js +83 -0
- package/dist/runtime/host-load-governor.d.ts +184 -0
- package/dist/runtime/host-load-governor.js +632 -0
- package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
- package/dist/runtime/host-load-ledger-lock.js +185 -0
- package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
- package/dist/runtime/host-load-runtime-settings.js +78 -0
- package/dist/runtime/host-load-sampler.d.ts +149 -0
- package/dist/runtime/host-load-sampler.js +291 -0
- package/dist/runtime/host-load-step-class.d.ts +70 -0
- package/dist/runtime/host-load-step-class.js +161 -0
- package/dist/runtime/host-load-step-reaper.d.ts +27 -0
- package/dist/runtime/host-load-step-reaper.js +95 -0
- package/dist/runtime/host-load-step-run.d.ts +73 -0
- package/dist/runtime/host-load-step-run.js +102 -0
- package/dist/runtime/host-load-test-slot.d.ts +43 -0
- package/dist/runtime/host-load-test-slot.js +81 -0
- package/dist/runtime/host-load-token-ledger.d.ts +200 -0
- package/dist/runtime/host-load-token-ledger.js +453 -0
- package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
- package/dist/runtime/host-load-windows-cpu.js +85 -0
- package/dist/runtime/host-pressure-stall.d.ts +61 -0
- package/dist/runtime/host-pressure-stall.js +168 -0
- package/dist/runtime/host-runtime-contract.d.ts +16 -1
- package/dist/runtime/host-runtime-contract.js +174 -56
- package/dist/runtime/host-runtime-lease.d.ts +163 -9
- package/dist/runtime/host-runtime-lease.js +1464 -121
- package/dist/runtime/host-runtime-promotion.d.ts +35 -3
- package/dist/runtime/host-runtime-promotion.js +107 -12
- package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
- package/dist/runtime/host-runtime-requirements-check.js +29 -0
- package/dist/runtime/host-runtime-requirements.d.ts +36 -0
- package/dist/runtime/host-runtime-requirements.js +117 -0
- package/dist/runtime/managed-command-teardown.d.ts +62 -0
- package/dist/runtime/managed-command-teardown.js +607 -0
- package/dist/runtime/memory-capacity.d.ts +70 -0
- package/dist/runtime/memory-capacity.js +123 -0
- package/dist/runtime/native-test-postgres-fallback.d.ts +25 -0
- package/dist/runtime/native-test-postgres-fallback.js +91 -0
- package/dist/runtime/node-host-runtime-adapter.d.ts +3 -0
- package/dist/runtime/node-host-runtime-adapter.js +29 -11
- package/dist/runtime/pinned-directory-process.d.ts +9 -0
- package/dist/runtime/pinned-directory-process.js +61 -0
- package/dist/runtime/pinned-source-directory.d.ts +17 -0
- package/dist/runtime/pinned-source-directory.js +94 -0
- package/dist/runtime/playwright-browser-cache.d.ts +39 -0
- package/dist/runtime/playwright-browser-cache.js +227 -0
- package/dist/runtime/playwright-host-runtime-adapter.d.ts +19 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +113 -59
- package/dist/runtime/prepared-runtime-identity.d.ts +6 -0
- package/dist/runtime/prepared-runtime-identity.js +218 -0
- package/dist/runtime/prepared-runtime-readiness.d.ts +30 -0
- package/dist/runtime/prepared-runtime-readiness.js +285 -0
- package/dist/runtime/runner-settings.d.ts +100 -0
- package/dist/runtime/runner-settings.js +214 -0
- package/dist/runtime/runtime-isolation-lease.js +4 -1
- package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
- package/dist/runtime/workspace-resource-estimator.js +174 -0
- package/dist/sandbox/host-capacity-broker.d.ts +113 -0
- package/dist/sandbox/host-capacity-broker.js +334 -0
- package/dist/sandbox/preflight.d.ts +31 -1
- package/dist/sandbox/preflight.js +237 -51
- package/dist/sandbox/repository-lock.d.ts +2 -1
- package/dist/sandbox/repository-lock.js +19 -9
- package/dist/sandbox/runtime.d.ts +16 -2
- package/dist/sandbox/runtime.js +182 -109
- package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
- package/dist/sandbox/sandbox-cgroups.js +42 -0
- package/dist/sandbox/sandbox.types.d.ts +7 -0
- package/dist/sandbox/workspace.service.js +2 -0
- package/dist/session/architect-waits.d.ts +2 -0
- package/dist/session/architect-waits.js +138 -0
- package/dist/session/managed-attempt-tools.d.ts +44 -1
- package/dist/session/managed-attempt-tools.js +816 -46
- package/dist/session/managed-build-coordinator.d.ts +5 -0
- package/dist/session/managed-build-coordinator.js +109 -0
- package/dist/session/managed-build-receipt.d.ts +21 -0
- package/dist/session/managed-build-receipt.js +337 -0
- package/dist/session/managed-command-host-load.d.ts +47 -0
- package/dist/session/managed-command-host-load.js +83 -0
- package/dist/session/managed-verification-timeouts.d.ts +8 -0
- package/dist/session/managed-verification-timeouts.js +17 -0
- package/dist/session/mcp-argument-coercion.d.ts +23 -0
- package/dist/session/mcp-argument-coercion.js +121 -0
- package/dist/session/phase-completion.artifacts.d.ts +24 -0
- package/dist/session/phase-completion.artifacts.js +319 -44
- package/dist/session/phase-completion.command-validation.d.ts +7 -0
- package/dist/session/phase-completion.command-validation.js +77 -0
- package/dist/session/phase-completion.d.ts +15 -1
- package/dist/session/phase-completion.helpers.d.ts +5 -0
- package/dist/session/phase-completion.helpers.js +43 -19
- package/dist/session/phase-completion.js +18 -3
- package/dist/session/phase-completion.prompts.js +22 -18
- package/dist/session/phase-completion.runtime.d.ts +6 -2
- package/dist/session/phase-completion.runtime.js +191 -47
- package/dist/session/phase-completion.schema-parts.d.ts +19 -0
- package/dist/session/phase-completion.schema-parts.js +188 -0
- package/dist/session/phase-completion.schemas.d.ts +3 -3
- package/dist/session/phase-completion.schemas.js +250 -226
- package/dist/session/phase-completion.validation.d.ts +3 -3
- package/dist/session/phase-completion.validation.js +135 -89
- package/dist/session/pre-publication-host-load.d.ts +27 -0
- package/dist/session/pre-publication-host-load.js +111 -0
- package/dist/session/pre-publication-pass.d.ts +61 -0
- package/dist/session/pre-publication-pass.js +148 -0
- package/dist/session/pre-publication-process.d.ts +23 -0
- package/dist/session/pre-publication-process.js +109 -0
- package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
- package/dist/session/pre-publication-skipped-tests.js +109 -0
- package/dist/session/pre-publication-step-execution.d.ts +11 -0
- package/dist/session/pre-publication-step-execution.js +49 -0
- package/dist/session/pre-publication-validation.d.ts +87 -0
- package/dist/session/pre-publication-validation.js +668 -0
- package/dist/session/provider-cli/bridge-cli.conformance-fixtures.d.ts +72 -0
- package/dist/session/provider-cli/bridge-cli.conformance-fixtures.js +462 -0
- package/dist/session/provider-cli/ci-repair-readiness.d.ts +8 -0
- package/dist/session/provider-cli/ci-repair-readiness.js +23 -3
- package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
- package/dist/session/provider-cli/claude-background-work.js +180 -0
- package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
- package/dist/session/provider-cli/pre-publication-repair.js +243 -0
- package/dist/session/provider-cli/provider-cli.artifacts.d.ts +6 -3
- package/dist/session/provider-cli/provider-cli.artifacts.js +62 -22
- package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
- package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
- package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
- package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
- package/dist/session/provider-cli/provider-cli.deterministic.js +34 -2
- package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
- package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
- package/dist/session/provider-cli/provider-cli.process.d.ts +92 -14
- package/dist/session/provider-cli/provider-cli.process.js +583 -210
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +12 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +200 -25
- package/dist/session/provider-cli/provider-cli.repair-epoch.d.ts +6 -0
- package/dist/session/provider-cli/provider-cli.repair-epoch.js +11 -0
- package/dist/session/provider-cli/provider-cli.runtime.d.ts +14 -1
- package/dist/session/provider-cli/provider-cli.runtime.js +61 -3
- package/dist/session/provider-cli/provider-cli.service.d.ts +33 -5
- package/dist/session/provider-cli/provider-cli.service.js +819 -84
- package/dist/session/provider-cli/provider-cli.types.d.ts +32 -0
- package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
- package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
- package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
- package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
- package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
- package/dist/session/provider-cli/provider-output-pipes.js +67 -0
- package/dist/session/provider-cli/provider-output-state.d.ts +18 -0
- package/dist/session/provider-cli/provider-output-state.js +376 -17
- package/dist/session/provider-cli/provider-usage.d.ts +9 -1
- package/dist/session/provider-cli/provider-usage.js +28 -5
- package/dist/session/publishable-worktree-changes.d.ts +54 -0
- package/dist/session/publishable-worktree-changes.js +193 -0
- package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
- package/dist/session/sandbox-host-capacity-gate.js +238 -0
- package/dist/session/session-redaction.js +434 -9
- package/dist/session/session.base.d.ts +9 -1
- package/dist/session/session.service.d.ts +9 -2
- package/dist/session/session.service.js +264 -27
- package/dist/session/session.types.d.ts +150 -2
- package/dist/session/session.types.js +599 -7
- package/dist/session/unreferenced-exports.d.ts +12 -0
- package/dist/session/unreferenced-exports.js +59 -0
- package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
- package/dist/session/workspace-runtime-fingerprint.js +138 -0
- package/dist/shared/format/format-bytes.d.ts +1 -0
- package/dist/shared/format/format-bytes.js +9 -0
- package/dist/shared/git/git.js +2 -1
- package/dist/shared/path/path.d.ts +1 -0
- package/dist/shared/path/path.js +18 -0
- package/dist/shared/process/dotnet-toolchain.d.ts +17 -0
- package/dist/shared/process/dotnet-toolchain.js +307 -0
- package/dist/shared/process/host-process-recovery.js +3 -2
- package/dist/shared/process/host-process-supervisor.d.ts +3 -0
- package/dist/shared/process/host-process-supervisor.js +61 -12
- package/dist/shared/process/process-tree.d.ts +52 -0
- package/dist/shared/process/process-tree.js +144 -0
- package/dist/shared/process/process.d.ts +69 -0
- package/dist/shared/process/process.js +223 -16
- package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
- package/dist/shared/process/windows-app-execution-alias.js +45 -0
- package/dist/shared/process/windows-launch.d.ts +18 -0
- package/dist/shared/process/windows-launch.js +68 -0
- package/dist/shared/provider-capabilities.d.ts +3 -0
- package/dist/shared/provider-capabilities.js +84 -0
- package/dist/shared/redaction/redaction.d.ts +1 -0
- package/dist/shared/redaction/redaction.js +39 -3
- package/dist/shared/time/monotonic.d.ts +1 -0
- package/dist/shared/time/monotonic.js +8 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/dependency-warmer.d.ts +66 -9
- package/dist/worktree/dependency-warmer.js +609 -24
- package/dist/worktree/index.d.ts +1 -1
- package/dist/worktree/story-qa-reference-hydrator.d.ts +4 -0
- package/dist/worktree/story-qa-reference-hydrator.js +253 -0
- package/dist/worktree/worktree.service.d.ts +17 -1
- package/dist/worktree/worktree.service.js +293 -21
- package/dist/worktree/worktree.types.d.ts +14 -1
- package/package.json +8 -6
- package/runtime/windows-job-supervisor.ps1 +380 -14
|
@@ -1,156 +1,178 @@
|
|
|
1
|
-
import { execFile, spawn } from "node:child_process";
|
|
1
|
+
import { execFile, execFileSync, spawn } from "node:child_process";
|
|
2
2
|
import fs from "node:fs";
|
|
3
|
-
import os from "node:os";
|
|
4
3
|
import path from "node:path";
|
|
5
|
-
import readline from "node:readline";
|
|
6
4
|
import { promisify } from "node:util";
|
|
7
5
|
import { resolveCursorAgentDirectLaunch } from "../../shared/cursor-agent/cursor-agent.launch.js";
|
|
8
6
|
import { persistHostProcessSupervisorMetadata, resolveHostProcessSupervisedLaunch, terminateHostProcessTree, } from "../../shared/process/host-process-supervisor.js";
|
|
9
|
-
import { buildWindowsLaunchCommand } from "../../shared/process/windows-launch.js";
|
|
7
|
+
import { buildWindowsLaunchCommand, chooseWindowsCommandCandidate, resolveWindowsCommandFromPath } from "../../shared/process/windows-launch.js";
|
|
8
|
+
import { buildProviderChildEnvironment } from "./provider-cli.child-environment.js";
|
|
9
|
+
import { isCodexModelsCacheSchemaFailure, quarantineIncompatibleCodexModelsCache } from "./provider-cli.codex-models-cache.js";
|
|
10
|
+
import { assertHostDatabaseCapabilityBoundary } from "../../runtime/host-database-capability-boundary.js";
|
|
11
|
+
import { ForgeFailureError } from "../session.types.js";
|
|
12
|
+
import { BackgroundWorkStopFailingRunner, ClaudeBackgroundTurnEndWatch, providerTurnEndedWithBackgroundWorkFailure } from "./claude-background-work.js";
|
|
13
|
+
import { hasNonterminalManagedCommand, isProviderTerminalFailure, isProviderTerminalSuccess, isProviderTurnActivity } from "./provider-in-flight-work.js";
|
|
14
|
+
import { OutputPipeRelease, readProcessLines, PROVIDER_OUTPUT_PIPE_RELEASE_GRACE_MS } from "./provider-output-pipes.js";
|
|
15
|
+
export { chooseWindowsCommandCandidate, resolveWindowsCommandFromPath } from "../../shared/process/windows-launch.js";
|
|
16
|
+
export { buildProviderChildEnvironment } from "./provider-cli.child-environment.js";
|
|
10
17
|
const execFileAsync = promisify(execFile);
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
"NUGET_PACKAGES",
|
|
39
|
-
"NUGET_HTTP_CACHE_PATH"
|
|
40
|
-
];
|
|
41
|
-
export function buildProviderChildEnvironment(requestEnv, options = {}) {
|
|
42
|
-
const parentEnv = options.parentEnv ?? process.env;
|
|
43
|
-
const platform = options.platform ?? process.platform;
|
|
44
|
-
const env = {};
|
|
45
|
-
for (const [key, value] of Object.entries(parentEnv)) {
|
|
46
|
-
if (typeof value === "string" && isAllowedProviderParentEnv(key, platform)) {
|
|
47
|
-
env[key] = value;
|
|
48
|
-
}
|
|
18
|
+
// Provider processes can emit many gigabytes over a long-running session. The
|
|
19
|
+
// line handlers stream that output to Forge as it arrives; the completed result
|
|
20
|
+
// only needs a bounded diagnostic tail for failure classification.
|
|
21
|
+
export const PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS = 128 * 1024;
|
|
22
|
+
const PROVIDER_TERMINAL_EXIT_GRACE_MS = 15_000;
|
|
23
|
+
// A provider that keeps starting turns after its first successful one (background-task
|
|
24
|
+
// notifications) is still stopped once this much time without supervised work in flight
|
|
25
|
+
// has passed since that first success.
|
|
26
|
+
const PROVIDER_TERMINAL_SUCCESS_CEILING_MS = 10 * 60_000;
|
|
27
|
+
// How often the end-of-turn timers re-check whether supervised work is still in flight.
|
|
28
|
+
const PROVIDER_TERMINAL_WORK_POLL_MS = 1_000;
|
|
29
|
+
/** Recovery must wrap the attempt coordinator, never its raw OS runner. Each
|
|
30
|
+
* relaunch needs a new fenced child generation and exclusive launch files. The outer
|
|
31
|
+
* layer fails any run Forge stopped because its turn ended with background work live. */
|
|
32
|
+
export function recoveringProviderProcessRunner(inner) {
|
|
33
|
+
return new BackgroundWorkStopFailingRunner(new CodexResumeRecoveringProcessRunner(new CodexModelsCacheRecoveringProcessRunner(inner)));
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Codex Desktop and an independently installed Codex CLI can briefly disagree
|
|
37
|
+
* about the shared models-cache schema during a rolling upgrade. Recover only
|
|
38
|
+
* that exact failure by quarantining the bounded cache file and retrying once;
|
|
39
|
+
* auth, config, sessions, and every other CODEX_HOME entry remain untouched.
|
|
40
|
+
*/
|
|
41
|
+
export class CodexModelsCacheRecoveringProcessRunner {
|
|
42
|
+
inner;
|
|
43
|
+
constructor(inner) {
|
|
44
|
+
this.inner = inner;
|
|
49
45
|
}
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
46
|
+
async run(request, handlers, signal) {
|
|
47
|
+
const first = await this.inner.run(request, handlers, signal);
|
|
48
|
+
if (first.exitCode === 0
|
|
49
|
+
|| signal?.aborted
|
|
50
|
+
|| !isCodexCommand(request.command)
|
|
51
|
+
|| !isCodexModelsCacheSchemaFailure(first)) {
|
|
52
|
+
return first;
|
|
56
53
|
}
|
|
54
|
+
const recovered = await quarantineIncompatibleCodexModelsCache(request.env).catch(() => false);
|
|
55
|
+
if (!recovered || signal?.aborted)
|
|
56
|
+
return first;
|
|
57
|
+
handlers?.onGenerationStart?.();
|
|
58
|
+
return await this.inner.run(request, handlers, signal);
|
|
57
59
|
}
|
|
58
|
-
if (platform === "win32") {
|
|
59
|
-
normalizeWindowsDotNetEnvironment(env, parentEnv, options.homeDir ?? os.homedir());
|
|
60
|
-
}
|
|
61
|
-
return env;
|
|
62
|
-
}
|
|
63
|
-
function isAllowedProviderParentEnv(key, platform = process.platform) {
|
|
64
|
-
return isAllowedProviderParentEnvName(key, allowedProviderParentEnvNames)
|
|
65
|
-
|| key.toUpperCase().startsWith("LC_")
|
|
66
|
-
|| (platform === "win32" && isAllowedProviderParentEnvName(key, windowsAllowedProviderParentEnvNames));
|
|
67
60
|
}
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
if (parsed.root) {
|
|
86
|
-
setEnvironmentValueIfMissing(env, "HOMEDRIVE", parsed.root.replace(/\\$/, ""));
|
|
87
|
-
setEnvironmentValueIfMissing(env, "HOMEPATH", userProfile.slice(parsed.root.length - (parsed.root.endsWith("\\") ? 1 : 0)) || "\\");
|
|
61
|
+
/**
|
|
62
|
+
* Some Codex CLI builds can start new turns but cannot resume an older thread
|
|
63
|
+
* because the backing app does not implement the paginated thread lookup RPC.
|
|
64
|
+
* Preserve the prepared worktree and prompt, then retry once as a fresh turn.
|
|
65
|
+
*/
|
|
66
|
+
export class CodexResumeRecoveringProcessRunner {
|
|
67
|
+
inner;
|
|
68
|
+
constructor(inner) {
|
|
69
|
+
this.inner = inner;
|
|
70
|
+
}
|
|
71
|
+
async run(request, handlers, signal) {
|
|
72
|
+
const first = await this.inner.run(request, handlers, signal);
|
|
73
|
+
if (first.exitCode === 0
|
|
74
|
+
|| signal?.aborted
|
|
75
|
+
|| !isCodexCommand(request.command)
|
|
76
|
+
|| !isRecoverableCodexResumeFailure(request.command, first)) {
|
|
77
|
+
return first;
|
|
88
78
|
}
|
|
79
|
+
const fallback = codexFreshTurnRequest(request);
|
|
80
|
+
if (!fallback)
|
|
81
|
+
return first;
|
|
82
|
+
handlers?.onGenerationStart?.();
|
|
83
|
+
return await this.inner.run(fallback, handlers, signal);
|
|
89
84
|
}
|
|
90
|
-
const appData = readEnvironmentValue(env, "APPDATA")
|
|
91
|
-
?? readEnvironmentValue(parentEnv, "APPDATA")
|
|
92
|
-
?? (userProfile ? path.win32.join(userProfile, "AppData", "Roaming") : undefined);
|
|
93
|
-
const localAppData = readEnvironmentValue(env, "LOCALAPPDATA")
|
|
94
|
-
?? readEnvironmentValue(parentEnv, "LOCALAPPDATA")
|
|
95
|
-
?? (userProfile ? path.win32.join(userProfile, "AppData", "Local") : undefined);
|
|
96
|
-
if (appData) {
|
|
97
|
-
setEnvironmentValueIfMissing(env, "APPDATA", appData);
|
|
98
|
-
}
|
|
99
|
-
if (localAppData) {
|
|
100
|
-
setEnvironmentValueIfMissing(env, "LOCALAPPDATA", localAppData);
|
|
101
|
-
setEnvironmentValueIfMissing(env, "NUGET_HTTP_CACHE_PATH", path.win32.join(localAppData, "NuGet", "v3-cache"));
|
|
102
|
-
}
|
|
103
|
-
setEnvironmentValueIfMissing(env, "DOTNET_NOLOGO", "1");
|
|
104
|
-
setEnvironmentValueIfMissing(env, "DOTNET_CLI_TELEMETRY_OPTOUT", "1");
|
|
105
|
-
setEnvironmentValueIfMissing(env, "DOTNET_SKIP_FIRST_TIME_EXPERIENCE", "1");
|
|
106
|
-
setEnvironmentValueIfMissing(env, "NUGET_XMLDOC_MODE", "skip");
|
|
107
85
|
}
|
|
108
|
-
function
|
|
109
|
-
const
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
const home = readEnvironmentValue(env, "HOME") ?? readEnvironmentValue(parentEnv, "HOME");
|
|
114
|
-
if (home && path.win32.isAbsolute(home)) {
|
|
115
|
-
return home;
|
|
116
|
-
}
|
|
117
|
-
const homeDrive = readEnvironmentValue(env, "HOMEDRIVE") ?? readEnvironmentValue(parentEnv, "HOMEDRIVE");
|
|
118
|
-
const homePath = readEnvironmentValue(env, "HOMEPATH") ?? readEnvironmentValue(parentEnv, "HOMEPATH");
|
|
119
|
-
if (homeDrive && homePath) {
|
|
120
|
-
return `${homeDrive}${homePath}`;
|
|
121
|
-
}
|
|
122
|
-
if (homeDir && path.win32.isAbsolute(homeDir)) {
|
|
123
|
-
return homeDir;
|
|
124
|
-
}
|
|
125
|
-
const systemDrive = readEnvironmentValue(env, "SystemDrive") ?? readEnvironmentValue(parentEnv, "SystemDrive") ?? "C:";
|
|
126
|
-
const username = readEnvironmentValue(env, "USERNAME") ?? readEnvironmentValue(parentEnv, "USERNAME");
|
|
127
|
-
return username ? path.win32.join(systemDrive, "Users", username) : undefined;
|
|
86
|
+
function isRecoverableCodexResumeFailure(command, result) {
|
|
87
|
+
const output = `${result.stderr}\n${result.stdout}`.toLowerCase();
|
|
88
|
+
return (output.includes("thread/resume failed")
|
|
89
|
+
&& output.includes("paginated_threads is not supported yet"))
|
|
90
|
+
|| isTransientCodexProviderNotFoundFailure(command, result);
|
|
128
91
|
}
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
92
|
+
/**
|
|
93
|
+
* Recognizes the exact nonzero Codex service response at the provider-process
|
|
94
|
+
* boundary. Provider stdout is deliberately excluded because it can contain
|
|
95
|
+
* arbitrary tool/command output and therefore cannot mint retry authority.
|
|
96
|
+
*/
|
|
97
|
+
export function isTransientCodexProviderNotFoundFailure(command, result) {
|
|
98
|
+
if (result.exitCode === 0 || !isCodexCommand(command))
|
|
99
|
+
return false;
|
|
100
|
+
return result.stderr
|
|
101
|
+
.split(/\r?\n/u)
|
|
102
|
+
.map(line => line.trim().toLowerCase())
|
|
103
|
+
.some(line => line === "not found: status code '404'"
|
|
104
|
+
|| line === 'not found: status code "404"');
|
|
133
105
|
}
|
|
134
|
-
function
|
|
135
|
-
|
|
136
|
-
|
|
106
|
+
function codexFreshTurnRequest(request) {
|
|
107
|
+
const args = [...request.args];
|
|
108
|
+
const resumeIndex = args.indexOf("resume");
|
|
109
|
+
if (resumeIndex < 0 || args.length < 2)
|
|
110
|
+
return null;
|
|
111
|
+
// buildProviderCliCommand always places the thread id immediately before
|
|
112
|
+
// the prompt. Remove it before moving exec-level --cd back out of the
|
|
113
|
+
// resume subcommand shape.
|
|
114
|
+
args.splice(args.length - 2, 1);
|
|
115
|
+
args.splice(resumeIndex, 1);
|
|
116
|
+
const cdIndex = args.indexOf("--cd");
|
|
117
|
+
if (cdIndex >= 0 && cdIndex + 1 < args.length) {
|
|
118
|
+
const cd = args.splice(cdIndex, 2);
|
|
119
|
+
args.splice(args.length - 1, 0, ...cd);
|
|
137
120
|
}
|
|
138
|
-
|
|
121
|
+
// The fallback starts a fresh thread, so it has no replayed turn to discount.
|
|
122
|
+
return { ...request, args, resumesProviderThread: false };
|
|
123
|
+
}
|
|
124
|
+
function isCodexCommand(command) {
|
|
125
|
+
return path.parse(command).name.toLowerCase() === "codex";
|
|
139
126
|
}
|
|
140
127
|
export class StreamingProviderProcessRunner {
|
|
128
|
+
terminalExitGraceMs;
|
|
129
|
+
terminalSuccessCeilingMs;
|
|
130
|
+
terminalWorkPollMs;
|
|
131
|
+
outputPipeReleaseGraceMs;
|
|
132
|
+
constructor(terminalExitGraceMs = PROVIDER_TERMINAL_EXIT_GRACE_MS, terminalSuccessCeilingMs = PROVIDER_TERMINAL_SUCCESS_CEILING_MS, terminalWorkPollMs = PROVIDER_TERMINAL_WORK_POLL_MS, outputPipeReleaseGraceMs = PROVIDER_OUTPUT_PIPE_RELEASE_GRACE_MS) {
|
|
133
|
+
this.terminalExitGraceMs = terminalExitGraceMs;
|
|
134
|
+
this.terminalSuccessCeilingMs = terminalSuccessCeilingMs;
|
|
135
|
+
this.terminalWorkPollMs = terminalWorkPollMs;
|
|
136
|
+
this.outputPipeReleaseGraceMs = outputPipeReleaseGraceMs;
|
|
137
|
+
}
|
|
141
138
|
async run(request, handlers = {}, signal) {
|
|
139
|
+
assertHostDatabaseCapabilityBoundary();
|
|
140
|
+
// Every child this runner launches is a new generation, including supervisor retries.
|
|
141
|
+
handlers.onGenerationStart?.();
|
|
142
142
|
const providerLaunch = await resolveProviderProcessLaunch(request.command, request.args);
|
|
143
143
|
const supervisedLaunch = resolveHostProcessSupervisedLaunch(request, providerLaunch.command, providerLaunch.args);
|
|
144
|
-
|
|
144
|
+
// An unsupervised Unix provider still gets a dedicated process group so a
|
|
145
|
+
// cancellation can stop descendants instead of only the CLI root.
|
|
146
|
+
const launch = supervisedLaunch ?? { ...providerLaunch, detached: process.platform !== "win32" };
|
|
147
|
+
const childEnvironment = buildProviderChildEnvironment(request.env);
|
|
148
|
+
// A piped prompt must reach the provider promptly (Claude Code abandons a
|
|
149
|
+
// silent stdin after ~3s), but the provider must not run before Forge has
|
|
150
|
+
// recorded its start. Off Windows, hold the launch behind a start gate in
|
|
151
|
+
// the same process: the prompt is written immediately and buffers in the
|
|
152
|
+
// pipe, and the gate execs the provider only once onStarted succeeds.
|
|
153
|
+
const startGated = process.platform !== "win32"
|
|
154
|
+
&& supervisedLaunch?.strategy !== "windows_job_object"
|
|
155
|
+
&& request.stdin !== undefined
|
|
156
|
+
&& fs.existsSync(UNIX_PROVIDER_START_GATE_SHELL)
|
|
157
|
+
&& isUnixExecutableAvailable(launch.command, childEnvironment.PATH, request.cwd);
|
|
158
|
+
const spawnLaunch = startGated
|
|
159
|
+
? buildUnixProviderStartGateLaunch(launch.command, launch.args)
|
|
160
|
+
: launch;
|
|
145
161
|
return await new Promise((resolve, reject) => {
|
|
146
162
|
const rootCreatedAt = new Date().toISOString();
|
|
147
|
-
const
|
|
163
|
+
const stdinMode = request.stdin === undefined ? "ignore" : "pipe";
|
|
164
|
+
const child = spawn(spawnLaunch.command, spawnLaunch.args, {
|
|
148
165
|
cwd: request.cwd,
|
|
149
|
-
env:
|
|
150
|
-
stdio:
|
|
166
|
+
env: childEnvironment,
|
|
167
|
+
stdio: startGated
|
|
168
|
+
? [stdinMode, "pipe", "pipe", "pipe"]
|
|
169
|
+
: [stdinMode, "pipe", "pipe"],
|
|
151
170
|
windowsHide: true,
|
|
152
171
|
detached: launch.detached,
|
|
153
172
|
});
|
|
173
|
+
const memoryObserver = supervisedLaunch
|
|
174
|
+
? new HostProcessTreeMemoryObserver(supervisedLaunch, child.pid ?? 0)
|
|
175
|
+
: null;
|
|
154
176
|
let termination = null;
|
|
155
177
|
const terminate = () => {
|
|
156
178
|
termination ??= terminateHostProcessTree(child, supervisedLaunch);
|
|
@@ -159,16 +181,36 @@ export class StreamingProviderProcessRunner {
|
|
|
159
181
|
const childStdout = child.stdout;
|
|
160
182
|
const childStderr = child.stderr;
|
|
161
183
|
if (!childStdout || !childStderr) {
|
|
162
|
-
|
|
163
|
-
reject(new
|
|
184
|
+
const pipeError = new Error("Provider process stdout/stderr streams were not piped.");
|
|
185
|
+
void terminate().then(() => reject(pipeError), terminationError => reject(new AggregateError([pipeError, terminationError], "host_process_supervisor_termination_failed: Provider launch failed and its process tree could not be proven stopped.")));
|
|
164
186
|
return;
|
|
165
187
|
}
|
|
166
|
-
|
|
167
|
-
|
|
188
|
+
const stdout = new BoundedOutputTail(PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS);
|
|
189
|
+
const stderr = new BoundedOutputTail(PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS);
|
|
190
|
+
const outputPipes = new OutputPipeRelease(child, this.outputPipeReleaseGraceMs, message => stderr.appendLine(message));
|
|
168
191
|
let settled = false;
|
|
169
192
|
let closed = false;
|
|
193
|
+
let cancellationRequested = false;
|
|
194
|
+
let cancelledBeforeClose = false;
|
|
195
|
+
let terminalTerminationStarted = false;
|
|
196
|
+
let terminalStopReason = null;
|
|
197
|
+
// Idle time (no supervised work in flight) accrued against the end-of-turn grace and
|
|
198
|
+
// the success ceiling; null while that timer is not armed.
|
|
199
|
+
let graceIdleMs = null;
|
|
200
|
+
let ceilingIdleMs = null;
|
|
201
|
+
let terminalSuccessCount = 0;
|
|
202
|
+
let replayedTurnCeilingSkipped = false;
|
|
203
|
+
let terminalWorkTimer = null;
|
|
204
|
+
let terminalWorkTickAt = 0;
|
|
205
|
+
let terminalWorkTickRunning = false;
|
|
206
|
+
let latestTurnFailed = false;
|
|
170
207
|
let readiness = null;
|
|
208
|
+
const backgroundTurnEnd = new ClaudeBackgroundTurnEndWatch(request.command, this.terminalExitGraceMs, () => finishAfterTerminalSuccess("turn_ended_with_background_work"));
|
|
171
209
|
const cleanup = () => {
|
|
210
|
+
stopTerminalWorkTimer();
|
|
211
|
+
backgroundTurnEnd.stop();
|
|
212
|
+
graceIdleMs = null;
|
|
213
|
+
ceilingIdleMs = null;
|
|
172
214
|
signal?.removeEventListener("abort", abort);
|
|
173
215
|
};
|
|
174
216
|
const fail = (error) => {
|
|
@@ -177,22 +219,45 @@ export class StreamingProviderProcessRunner {
|
|
|
177
219
|
}
|
|
178
220
|
settled = true;
|
|
179
221
|
cleanup();
|
|
180
|
-
|
|
181
|
-
|
|
222
|
+
// Do not release the caller's reservation/worktree/port ownership until
|
|
223
|
+
// descendant termination has completed (or failed with explicit proof).
|
|
224
|
+
void terminate().then(() => reject(error), terminationError => reject(new AggregateError([error, terminationError], "host_process_supervisor_termination_failed: Provider process failed and its process tree could not be proven stopped.")));
|
|
182
225
|
};
|
|
183
226
|
const abort = () => {
|
|
227
|
+
if (!closed)
|
|
228
|
+
cancelledBeforeClose = true;
|
|
229
|
+
cancellationRequested = true;
|
|
184
230
|
// Cancellation is not a launch failure when the supervised tree can be
|
|
185
231
|
// proven stopped. Let the close handler settle the command after exact
|
|
186
232
|
// termination; only a failed termination proof rejects the run.
|
|
187
233
|
void terminate().catch(fail);
|
|
188
234
|
};
|
|
189
|
-
if (signal?.aborted)
|
|
235
|
+
if (signal?.aborted)
|
|
190
236
|
abort();
|
|
191
|
-
|
|
192
|
-
else {
|
|
237
|
+
else
|
|
193
238
|
signal?.addEventListener("abort", abort, { once: true });
|
|
194
|
-
}
|
|
195
239
|
child.on("error", fail);
|
|
240
|
+
const startGrant = startGated ? child.stdio[3] : null;
|
|
241
|
+
if (startGated && !startGrant) {
|
|
242
|
+
fail(new Error("Provider start-grant stream was not piped."));
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
startGrant?.on("error", error => {
|
|
246
|
+
// A broken grant pipe means the gate already exited (terminated before
|
|
247
|
+
// its grant, or it died on its own). Its close event carries the real
|
|
248
|
+
// exit status, so an EPIPE here must not replace that result.
|
|
249
|
+
if (isBrokenPipeError(error))
|
|
250
|
+
return;
|
|
251
|
+
fail(error);
|
|
252
|
+
});
|
|
253
|
+
const grantUnixProviderStart = () => {
|
|
254
|
+
if (!startGrant)
|
|
255
|
+
return;
|
|
256
|
+
// Never release a provider whose launch was cancelled or already failed.
|
|
257
|
+
if (closed || settled || cancellationRequested || signal?.aborted)
|
|
258
|
+
return;
|
|
259
|
+
startGrant.end(UNIX_PROVIDER_START_GRANT_LINE, "utf8");
|
|
260
|
+
};
|
|
196
261
|
child.once("spawn", () => {
|
|
197
262
|
readiness = (async () => {
|
|
198
263
|
const providerReady = supervisedLaunch?.strategy === "windows_job_object"
|
|
@@ -205,6 +270,9 @@ export class StreamingProviderProcessRunner {
|
|
|
205
270
|
if (supervisedLaunch?.strategy === "windows_job_object") {
|
|
206
271
|
grantWindowsProviderStart(supervisedLaunch);
|
|
207
272
|
}
|
|
273
|
+
else if (startGated) {
|
|
274
|
+
grantUnixProviderStart();
|
|
275
|
+
}
|
|
208
276
|
})();
|
|
209
277
|
void readiness.catch(error => {
|
|
210
278
|
if (!closed && !signal?.aborted)
|
|
@@ -220,15 +288,20 @@ export class StreamingProviderProcessRunner {
|
|
|
220
288
|
return;
|
|
221
289
|
}
|
|
222
290
|
child.stdin.on("error", (error) => {
|
|
291
|
+
// A prompt still buffered when Forge stops the process (cancellation,
|
|
292
|
+
// or a refused start grant) cannot be delivered; that broken pipe is
|
|
293
|
+
// not a failure. Any other stdin error still is.
|
|
294
|
+
if ((cancellationRequested || termination) && isBrokenPipeError(error))
|
|
295
|
+
return;
|
|
223
296
|
void terminate();
|
|
224
297
|
fail(error);
|
|
225
298
|
});
|
|
226
299
|
child.stdin.end(request.stdin, "utf8");
|
|
227
300
|
};
|
|
228
301
|
if (request.stdin !== undefined) {
|
|
229
|
-
if (supervisedLaunch?.strategy === "windows_job_object") {
|
|
230
|
-
// The outer supervisor must receive stdin before it
|
|
231
|
-
//
|
|
302
|
+
if (supervisedLaunch?.strategy === "windows_job_object" || startGated) {
|
|
303
|
+
// The outer supervisor / Unix start gate must receive stdin before it
|
|
304
|
+
// can launch the provider. Its start grant fences prompt processing.
|
|
232
305
|
writeProviderInput();
|
|
233
306
|
}
|
|
234
307
|
else {
|
|
@@ -237,18 +310,113 @@ export class StreamingProviderProcessRunner {
|
|
|
237
310
|
});
|
|
238
311
|
}
|
|
239
312
|
}
|
|
313
|
+
const finishAfterTerminalSuccess = (reason) => {
|
|
314
|
+
if (closed || settled || cancellationRequested || terminalTerminationStarted)
|
|
315
|
+
return;
|
|
316
|
+
terminalTerminationStarted = true;
|
|
317
|
+
terminalStopReason = reason;
|
|
318
|
+
stopTerminalWorkTimer();
|
|
319
|
+
void terminate().catch(fail);
|
|
320
|
+
};
|
|
321
|
+
// The grace and the ceiling only count time in which no supervised work is in flight:
|
|
322
|
+
// a provider waiting on an MCP tool call or on a managed command it started is not
|
|
323
|
+
// finished, even when its turn has ended. The grace restarts once that work is done.
|
|
324
|
+
const terminalWorkTick = async () => {
|
|
325
|
+
if (terminalWorkTickRunning)
|
|
326
|
+
return;
|
|
327
|
+
terminalWorkTickRunning = true;
|
|
328
|
+
try {
|
|
329
|
+
const inFlight = await providerWorkInFlight(handlers, request.env?.FORGE_LOG_DIR);
|
|
330
|
+
const now = performance.now();
|
|
331
|
+
const elapsed = Math.max(0, now - terminalWorkTickAt);
|
|
332
|
+
terminalWorkTickAt = now;
|
|
333
|
+
if (closed || settled || terminalTerminationStarted)
|
|
334
|
+
return;
|
|
335
|
+
if (inFlight) {
|
|
336
|
+
if (graceIdleMs !== null)
|
|
337
|
+
graceIdleMs = 0;
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
if (graceIdleMs !== null)
|
|
341
|
+
graceIdleMs += elapsed;
|
|
342
|
+
if (ceilingIdleMs !== null)
|
|
343
|
+
ceilingIdleMs += elapsed;
|
|
344
|
+
if (graceIdleMs !== null && graceIdleMs >= this.terminalExitGraceMs) {
|
|
345
|
+
finishAfterTerminalSuccess("turn_exit_grace");
|
|
346
|
+
}
|
|
347
|
+
else if (ceilingIdleMs !== null && ceilingIdleMs >= this.terminalSuccessCeilingMs) {
|
|
348
|
+
finishAfterTerminalSuccess("success_ceiling");
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
finally {
|
|
352
|
+
terminalWorkTickRunning = false;
|
|
353
|
+
if (graceIdleMs === null && ceilingIdleMs === null)
|
|
354
|
+
stopTerminalWorkTimer();
|
|
355
|
+
}
|
|
356
|
+
};
|
|
357
|
+
function stopTerminalWorkTimer() {
|
|
358
|
+
if (terminalWorkTimer) {
|
|
359
|
+
clearInterval(terminalWorkTimer);
|
|
360
|
+
terminalWorkTimer = null;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
const startTerminalWorkTimer = () => {
|
|
364
|
+
if (terminalWorkTimer)
|
|
365
|
+
return;
|
|
366
|
+
terminalWorkTickAt = performance.now();
|
|
367
|
+
const intervalMs = Math.max(1, Math.min(this.terminalWorkPollMs, this.terminalExitGraceMs, this.terminalSuccessCeilingMs));
|
|
368
|
+
terminalWorkTimer = setInterval(() => { void terminalWorkTick().catch(fail); }, intervalMs);
|
|
369
|
+
terminalWorkTimer.unref?.();
|
|
370
|
+
};
|
|
371
|
+
const armTerminalExit = () => {
|
|
372
|
+
terminalSuccessCount += 1;
|
|
373
|
+
graceIdleMs = 0;
|
|
374
|
+
// Later turns may postpone the grace period, but never past this ceiling.
|
|
375
|
+
ceilingIdleMs ??= 0;
|
|
376
|
+
startTerminalWorkTimer();
|
|
377
|
+
};
|
|
240
378
|
const readers = [
|
|
241
379
|
readProcessLines(childStdout, (line) => {
|
|
242
380
|
if (request.captureOutput !== false)
|
|
243
|
-
stdout
|
|
244
|
-
|
|
381
|
+
stdout.appendLine(line);
|
|
382
|
+
const handled = handlers.onStdoutLine?.(line);
|
|
383
|
+
backgroundTurnEnd.consume(line);
|
|
384
|
+
if (!terminalTerminationStarted) {
|
|
385
|
+
if (isProviderTerminalSuccess(line)) {
|
|
386
|
+
latestTurnFailed = false;
|
|
387
|
+
armTerminalExit();
|
|
388
|
+
}
|
|
389
|
+
else if (isProviderTerminalFailure(line)) {
|
|
390
|
+
// A later turn that fails reports its failure even after an earlier success.
|
|
391
|
+
latestTurnFailed = true;
|
|
392
|
+
}
|
|
393
|
+
else if (graceIdleMs !== null && isProviderTurnActivity(line)) {
|
|
394
|
+
// A terminal event ends a turn, not necessarily the provider. Claude Code
|
|
395
|
+
// stays resident while background tasks it started are pending and begins a
|
|
396
|
+
// new turn when one reports. A provider that is working again is not finished;
|
|
397
|
+
// the grace period restarts at its next terminal event.
|
|
398
|
+
graceIdleMs = null;
|
|
399
|
+
// A resumed session can replay a queued notification turn before the
|
|
400
|
+
// prompt's own turn. The replayed turn must not consume the ceiling, or the
|
|
401
|
+
// resumed agent is stopped mid-work, but the prompt's turn still needs a
|
|
402
|
+
// watchdog: restart the ceiling from here instead of dropping it.
|
|
403
|
+
if (request.resumesProviderThread && terminalSuccessCount === 1 && !replayedTurnCeilingSkipped) {
|
|
404
|
+
replayedTurnCeilingSkipped = true;
|
|
405
|
+
ceilingIdleMs = 0;
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
return handled;
|
|
245
410
|
}),
|
|
246
411
|
readProcessLines(childStderr, (line) => {
|
|
247
412
|
if (request.captureOutput !== false)
|
|
248
|
-
stderr
|
|
413
|
+
stderr.appendLine(line);
|
|
249
414
|
return handlers.onStderrLine?.(line);
|
|
250
415
|
})
|
|
251
416
|
];
|
|
417
|
+
for (const reader of readers) {
|
|
418
|
+
void reader.catch(fail);
|
|
419
|
+
}
|
|
252
420
|
child.on("close", (code) => {
|
|
253
421
|
closed = true;
|
|
254
422
|
Promise.allSettled(readers).then(async (readerResults) => {
|
|
@@ -262,7 +430,8 @@ export class StreamingProviderProcessRunner {
|
|
|
262
430
|
return;
|
|
263
431
|
}
|
|
264
432
|
try {
|
|
265
|
-
|
|
433
|
+
memoryObserver?.sample();
|
|
434
|
+
if (supervisedLaunch?.strategy === "unix_process_group" || !supervisedLaunch) {
|
|
266
435
|
await terminate();
|
|
267
436
|
}
|
|
268
437
|
else if (termination) {
|
|
@@ -275,16 +444,206 @@ export class StreamingProviderProcessRunner {
|
|
|
275
444
|
}
|
|
276
445
|
settled = true;
|
|
277
446
|
cleanup();
|
|
447
|
+
const memory = memoryObserver?.complete();
|
|
278
448
|
resolve({
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
449
|
+
// A structured terminal-success event is the provider protocol's
|
|
450
|
+
// authoritative completion signal. If the CLI stays resident after
|
|
451
|
+
// that event, terminate the supervised tree after a short grace
|
|
452
|
+
// period and preserve the successful handoff so the existing
|
|
453
|
+
// artifact, commit, and publication gates can run.
|
|
454
|
+
// A provider stopped after a successful turn keeps that success. Whenever the
|
|
455
|
+
// most recent turn failed, the run fails, however the process ended.
|
|
456
|
+
exitCode: latestTurnFailed
|
|
457
|
+
? code && code !== 0 ? code : 1
|
|
458
|
+
: terminalTerminationStarted && !cancellationRequested ? 0 : code ?? 1,
|
|
459
|
+
stdout: stdout.toString(),
|
|
460
|
+
stderr: stderr.toString(),
|
|
461
|
+
...(memory ?? {}),
|
|
462
|
+
...(cancelledBeforeClose ? { cancelled: true } : {}),
|
|
463
|
+
...(terminalStopReason && !cancellationRequested ? { terminalStopReason } : {}),
|
|
464
|
+
...outputPipes.resultFields(),
|
|
282
465
|
});
|
|
283
466
|
}).catch(fail);
|
|
284
467
|
});
|
|
285
468
|
});
|
|
286
469
|
}
|
|
287
470
|
}
|
|
471
|
+
async function providerWorkInFlight(handlers, logDirectory) {
|
|
472
|
+
try {
|
|
473
|
+
if (handlers.isToolCallInFlight?.())
|
|
474
|
+
return true;
|
|
475
|
+
}
|
|
476
|
+
catch {
|
|
477
|
+
// A failing probe must not keep the provider open or stop it early on its own.
|
|
478
|
+
}
|
|
479
|
+
return await hasNonterminalManagedCommand(logDirectory).catch(() => false);
|
|
480
|
+
}
|
|
481
|
+
/**
|
|
482
|
+
* The typed failure for a provider run that ended without calling its required Forge
|
|
483
|
+
* completion tool. A run Forge stopped at the success ceiling or for background work is
|
|
484
|
+
* reported as such, so it is not mistaken for an agent that simply ended its turn.
|
|
485
|
+
*/
|
|
486
|
+
export function providerCompletionToolMissingFailure(message, result) {
|
|
487
|
+
if (result?.terminalStopReason === "turn_ended_with_background_work")
|
|
488
|
+
return providerTurnEndedWithBackgroundWorkFailure(message);
|
|
489
|
+
if (result?.terminalStopReason === "success_ceiling") {
|
|
490
|
+
return new ForgeFailureError("provider_terminated_at_turn_ceiling", `${message} Forge stopped the provider at its post-turn success ceiling while it was still working.`);
|
|
491
|
+
}
|
|
492
|
+
return new ForgeFailureError("provider_completion_tool_missing", message);
|
|
493
|
+
}
|
|
494
|
+
class HostProcessTreeMemoryObserver {
|
|
495
|
+
launch;
|
|
496
|
+
processGroupId;
|
|
497
|
+
peakMemoryBytes = 0;
|
|
498
|
+
sampleCount = 0;
|
|
499
|
+
observedAt = null;
|
|
500
|
+
timer;
|
|
501
|
+
constructor(launch, processGroupId) {
|
|
502
|
+
this.launch = launch;
|
|
503
|
+
this.processGroupId = processGroupId;
|
|
504
|
+
if (launch.strategy === "unix_process_group" && processGroupId > 0) {
|
|
505
|
+
this.sample();
|
|
506
|
+
this.timer = setInterval(() => this.sample(), 1_000);
|
|
507
|
+
this.timer.unref?.();
|
|
508
|
+
}
|
|
509
|
+
else {
|
|
510
|
+
this.timer = null;
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
sample() {
|
|
514
|
+
if (this.launch.strategy !== "unix_process_group" || this.processGroupId <= 0)
|
|
515
|
+
return;
|
|
516
|
+
const bytes = processGroupResidentMemoryBytes(this.processGroupId);
|
|
517
|
+
if (bytes === null)
|
|
518
|
+
return;
|
|
519
|
+
this.sampleCount += 1;
|
|
520
|
+
this.peakMemoryBytes = Math.max(this.peakMemoryBytes, bytes);
|
|
521
|
+
this.observedAt = new Date().toISOString();
|
|
522
|
+
}
|
|
523
|
+
complete() {
|
|
524
|
+
if (this.timer)
|
|
525
|
+
clearInterval(this.timer);
|
|
526
|
+
if (this.launch.strategy === "windows_job_object") {
|
|
527
|
+
return readWindowsJobMemoryTelemetry(this.launch.memoryTelemetryPath);
|
|
528
|
+
}
|
|
529
|
+
if (this.peakMemoryBytes <= 0 || this.sampleCount <= 0 || !this.observedAt)
|
|
530
|
+
return undefined;
|
|
531
|
+
return {
|
|
532
|
+
peakMemoryBytes: this.peakMemoryBytes,
|
|
533
|
+
memorySampleCount: this.sampleCount,
|
|
534
|
+
memorySource: process.platform === "linux"
|
|
535
|
+
? "linux_process_group_rss"
|
|
536
|
+
: "unix_process_group_rss",
|
|
537
|
+
memoryObservedAt: this.observedAt,
|
|
538
|
+
};
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
/** Returns aggregate resident bytes for the exact supervised Unix process group. */
|
|
542
|
+
export function processGroupResidentMemoryBytes(processGroupId, platform = process.platform, procRoot = "/proc") {
|
|
543
|
+
if (!Number.isSafeInteger(processGroupId) || processGroupId <= 0)
|
|
544
|
+
return null;
|
|
545
|
+
if (platform === "linux") {
|
|
546
|
+
let totalKilobytes = 0;
|
|
547
|
+
let matched = 0;
|
|
548
|
+
try {
|
|
549
|
+
for (const entry of fs.readdirSync(procRoot, { withFileTypes: true })) {
|
|
550
|
+
if (!entry.isDirectory() || !/^\d+$/u.test(entry.name))
|
|
551
|
+
continue;
|
|
552
|
+
try {
|
|
553
|
+
const stat = fs.readFileSync(path.join(procRoot, entry.name, "stat"), "utf8");
|
|
554
|
+
const close = stat.lastIndexOf(")");
|
|
555
|
+
const fields = close >= 0 ? stat.slice(close + 2).trim().split(/\s+/u) : [];
|
|
556
|
+
if (Number.parseInt(fields[2] ?? "", 10) !== processGroupId)
|
|
557
|
+
continue;
|
|
558
|
+
const status = fs.readFileSync(path.join(procRoot, entry.name, "status"), "utf8");
|
|
559
|
+
const rss = /^VmRSS:\s+(\d+)\s+kB$/mu.exec(status);
|
|
560
|
+
if (!rss)
|
|
561
|
+
continue;
|
|
562
|
+
totalKilobytes += Number.parseInt(rss[1], 10);
|
|
563
|
+
matched += 1;
|
|
564
|
+
}
|
|
565
|
+
catch {
|
|
566
|
+
// Processes can exit between the directory, stat, and status reads.
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
return matched > 0 ? totalKilobytes * 1024 : null;
|
|
570
|
+
}
|
|
571
|
+
catch {
|
|
572
|
+
return null;
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
if (platform !== "win32") {
|
|
576
|
+
try {
|
|
577
|
+
const output = execFileSync("ps", ["-axo", "pgid=,rss="], {
|
|
578
|
+
encoding: "utf8",
|
|
579
|
+
timeout: 5_000,
|
|
580
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
581
|
+
});
|
|
582
|
+
let totalKilobytes = 0;
|
|
583
|
+
let matched = 0;
|
|
584
|
+
for (const line of output.split(/\r?\n/u)) {
|
|
585
|
+
const fields = line.trim().split(/\s+/u);
|
|
586
|
+
if (Number.parseInt(fields[0] ?? "", 10) !== processGroupId)
|
|
587
|
+
continue;
|
|
588
|
+
const rss = Number.parseInt(fields[1] ?? "", 10);
|
|
589
|
+
if (!Number.isSafeInteger(rss) || rss < 0)
|
|
590
|
+
continue;
|
|
591
|
+
totalKilobytes += rss;
|
|
592
|
+
matched += 1;
|
|
593
|
+
}
|
|
594
|
+
return matched > 0 ? totalKilobytes * 1024 : null;
|
|
595
|
+
}
|
|
596
|
+
catch {
|
|
597
|
+
return null;
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
return null;
|
|
601
|
+
}
|
|
602
|
+
function readWindowsJobMemoryTelemetry(target) {
|
|
603
|
+
if (!target)
|
|
604
|
+
return undefined;
|
|
605
|
+
try {
|
|
606
|
+
const value = JSON.parse(fs.readFileSync(target, "utf8"));
|
|
607
|
+
const peakMemoryBytes = value.peakMemoryBytes;
|
|
608
|
+
const sampleCount = value.sampleCount;
|
|
609
|
+
const source = value.source;
|
|
610
|
+
const observedAt = value.observedAt;
|
|
611
|
+
if (!Number.isSafeInteger(peakMemoryBytes) || peakMemoryBytes <= 0
|
|
612
|
+
|| !Number.isSafeInteger(sampleCount) || sampleCount <= 0
|
|
613
|
+
|| typeof source !== "string" || source.length === 0
|
|
614
|
+
|| typeof observedAt !== "string" || !Number.isFinite(Date.parse(observedAt))) {
|
|
615
|
+
return undefined;
|
|
616
|
+
}
|
|
617
|
+
return {
|
|
618
|
+
peakMemoryBytes: peakMemoryBytes,
|
|
619
|
+
memorySampleCount: sampleCount,
|
|
620
|
+
memorySource: source,
|
|
621
|
+
memoryObservedAt: observedAt,
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
catch {
|
|
625
|
+
return undefined;
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
class BoundedOutputTail {
|
|
629
|
+
maxChars;
|
|
630
|
+
value = "";
|
|
631
|
+
constructor(maxChars) {
|
|
632
|
+
this.maxChars = maxChars;
|
|
633
|
+
}
|
|
634
|
+
appendLine(line) {
|
|
635
|
+
const chunk = `${line}\n`;
|
|
636
|
+
if (chunk.length >= this.maxChars) {
|
|
637
|
+
this.value = chunk.slice(-this.maxChars);
|
|
638
|
+
return;
|
|
639
|
+
}
|
|
640
|
+
const retainedPrefixChars = this.maxChars - chunk.length;
|
|
641
|
+
this.value = `${this.value.slice(-retainedPrefixChars)}${chunk}`;
|
|
642
|
+
}
|
|
643
|
+
toString() {
|
|
644
|
+
return this.value;
|
|
645
|
+
}
|
|
646
|
+
}
|
|
288
647
|
async function resolveProviderProcessLaunch(command, args) {
|
|
289
648
|
if (process.platform !== "win32") {
|
|
290
649
|
return { command, args };
|
|
@@ -298,9 +657,68 @@ async function resolveProviderProcessLaunch(command, args) {
|
|
|
298
657
|
return { command, args };
|
|
299
658
|
}
|
|
300
659
|
return resolveCodexNpmDirectLaunch(resolved, args)
|
|
660
|
+
?? resolveClaudeNpmDirectLaunch(resolved, args)
|
|
301
661
|
?? resolvePackageManagerDirectLaunch(resolved, args)
|
|
302
662
|
?? buildWindowsLaunchCommand(resolved, args);
|
|
303
663
|
}
|
|
664
|
+
const UNIX_PROVIDER_START_GATE_SHELL = "/bin/sh";
|
|
665
|
+
const UNIX_PROVIDER_START_GATE_NAME = "forge-provider-start-gate";
|
|
666
|
+
export const UNIX_PROVIDER_START_GRANT_LINE = "forge-provider-start-granted\n";
|
|
667
|
+
/**
|
|
668
|
+
* Blocks on fd 3 until the bridge writes the exact grant line, then replaces
|
|
669
|
+
* itself with the provider (`exec`), so the supervised root PID, process group
|
|
670
|
+
* and birth identity stay the provider's. The provider command and arguments
|
|
671
|
+
* are passed positionally and expanded only as "$@"; nothing is interpolated
|
|
672
|
+
* into the script. EOF, a read error, or any other content on fd 3 exits
|
|
673
|
+
* without running the provider. fd 3 is closed before exec so the provider and
|
|
674
|
+
* its descendants never inherit the grant channel. stdin is not touched, so
|
|
675
|
+
* the prompt stays buffered in its pipe for the provider.
|
|
676
|
+
*/
|
|
677
|
+
const UNIX_PROVIDER_START_GATE_SCRIPT = [
|
|
678
|
+
"IFS= read -r forge_start_grant <&3 || { echo \"$0: provider start was not granted\" >&2; exit 125; }",
|
|
679
|
+
`[ "$forge_start_grant" = "${UNIX_PROVIDER_START_GRANT_LINE.trim()}" ] || { echo "$0: provider start grant was invalid" >&2; exit 125; }`,
|
|
680
|
+
"exec \"$@\" 3<&-",
|
|
681
|
+
].join("\n");
|
|
682
|
+
export function buildUnixProviderStartGateLaunch(command, args) {
|
|
683
|
+
return {
|
|
684
|
+
command: UNIX_PROVIDER_START_GATE_SHELL,
|
|
685
|
+
args: ["-c", UNIX_PROVIDER_START_GATE_SCRIPT, UNIX_PROVIDER_START_GATE_NAME, command, ...args],
|
|
686
|
+
};
|
|
687
|
+
}
|
|
688
|
+
/**
|
|
689
|
+
* Mirrors the executable lookup the gate's `exec` will perform. A command that
|
|
690
|
+
* cannot be found is spawned directly instead so it keeps failing as a spawn
|
|
691
|
+
* ENOENT before any start is recorded; nothing can run in that case. The check
|
|
692
|
+
* is advisory: if the executable disappears between this lookup and the gated
|
|
693
|
+
* `exec`, the gate exits 127 with the shell's "not found" message after the
|
|
694
|
+
* start was recorded, which surfaces as an ordinary provider failure.
|
|
695
|
+
*/
|
|
696
|
+
function isUnixExecutableAvailable(command, pathValue, cwd) {
|
|
697
|
+
if (!command || command.startsWith("-"))
|
|
698
|
+
return false;
|
|
699
|
+
const candidates = command.includes("/")
|
|
700
|
+
? [path.resolve(cwd, command)]
|
|
701
|
+
: pathValue === undefined
|
|
702
|
+
? null
|
|
703
|
+
: pathValue.split(path.delimiter).map(directory => path.resolve(cwd, directory || ".", command));
|
|
704
|
+
if (candidates === null)
|
|
705
|
+
return true;
|
|
706
|
+
return candidates.some(candidate => {
|
|
707
|
+
try {
|
|
708
|
+
if (!fs.statSync(candidate).isFile())
|
|
709
|
+
return false;
|
|
710
|
+
fs.accessSync(candidate, fs.constants.X_OK);
|
|
711
|
+
return true;
|
|
712
|
+
}
|
|
713
|
+
catch {
|
|
714
|
+
return false;
|
|
715
|
+
}
|
|
716
|
+
});
|
|
717
|
+
}
|
|
718
|
+
function isBrokenPipeError(error) {
|
|
719
|
+
const code = error?.code;
|
|
720
|
+
return code === "EPIPE" || code === "ERR_STREAM_DESTROYED" || code === "ECONNRESET";
|
|
721
|
+
}
|
|
304
722
|
function grantWindowsProviderStart(launch) {
|
|
305
723
|
if (!launch.startGrantPath) {
|
|
306
724
|
throw new Error("host_process_supervisor_invalid: Windows provider start-grant path was not assigned.");
|
|
@@ -342,7 +760,7 @@ async function waitForWindowsProviderReady(launch, signal, isClosed) {
|
|
|
342
760
|
throw error;
|
|
343
761
|
}
|
|
344
762
|
if (isClosed()) {
|
|
345
|
-
throw new
|
|
763
|
+
throw new ForgeFailureError("attempt_process_supervisor_start_failed", "host_process_supervisor_start_failed: supervisor exited before the provider became ready.", "bridge");
|
|
346
764
|
}
|
|
347
765
|
if (signal?.aborted) {
|
|
348
766
|
throw signal.reason instanceof Error ? signal.reason : new Error("Provider process launch was aborted.");
|
|
@@ -361,6 +779,22 @@ export function resolveCodexNpmDirectLaunch(commandPath, args) {
|
|
|
361
779
|
? { command: process.execPath, args: [entryPoint, ...args] }
|
|
362
780
|
: null;
|
|
363
781
|
}
|
|
782
|
+
/**
|
|
783
|
+
* npm installs of Claude Code (`npm i -g @anthropic-ai/claude-code`) put a `claude.cmd` shim on
|
|
784
|
+
* PATH; launch its cli.js directly for the same Job Object reasons as Codex. The native installer
|
|
785
|
+
* ships `claude.exe`, which is preferred by PATH resolution and needs no rewrite.
|
|
786
|
+
*/
|
|
787
|
+
export function resolveClaudeNpmDirectLaunch(commandPath, args) {
|
|
788
|
+
const extension = path.extname(commandPath).toLowerCase();
|
|
789
|
+
if ((extension !== ".cmd" && extension !== ".ps1")
|
|
790
|
+
|| path.basename(commandPath, extension).toLowerCase() !== "claude") {
|
|
791
|
+
return null;
|
|
792
|
+
}
|
|
793
|
+
const entryPoint = path.join(path.dirname(commandPath), "node_modules", "@anthropic-ai", "claude-code", "cli.js");
|
|
794
|
+
return fs.existsSync(entryPoint)
|
|
795
|
+
? { command: process.execPath, args: [entryPoint, ...args] }
|
|
796
|
+
: null;
|
|
797
|
+
}
|
|
364
798
|
/**
|
|
365
799
|
* Avoids cmd.exe's nested-quote handling for package-manager shims. That
|
|
366
800
|
* quoting loses executable paths containing spaces after the command is
|
|
@@ -371,11 +805,11 @@ export function resolvePackageManagerDirectLaunch(commandPath, args) {
|
|
|
371
805
|
if (extension !== ".cmd" && extension !== ".ps1")
|
|
372
806
|
return null;
|
|
373
807
|
const packageManager = path.basename(commandPath, extension).toLowerCase();
|
|
374
|
-
if (!["npm", "npx", "pnpm", "pnpx", "yarn", "yarnpkg"].includes(packageManager))
|
|
808
|
+
if (!["corepack", "npm", "npx", "pnpm", "pnpx", "yarn", "yarnpkg"].includes(packageManager))
|
|
375
809
|
return null;
|
|
376
810
|
const root = path.dirname(commandPath);
|
|
377
811
|
const candidates = [
|
|
378
|
-
path.join(root, "node_modules", "corepack", "dist", `${packageManager}.js`),
|
|
812
|
+
path.join(root, "node_modules", "corepack", "dist", packageManager === "corepack" ? "corepack.js" : `${packageManager}.js`),
|
|
379
813
|
...(packageManager === "npm" || packageManager === "npx"
|
|
380
814
|
? [path.join(root, "node_modules", "npm", "bin", `${packageManager}-cli.js`)]
|
|
381
815
|
: []),
|
|
@@ -411,64 +845,3 @@ async function resolveWindowsCommand(command) {
|
|
|
411
845
|
return null;
|
|
412
846
|
}
|
|
413
847
|
}
|
|
414
|
-
/**
|
|
415
|
-
* Resolves Windows commands without spawning where.exe. Runtime launches can
|
|
416
|
-
* happen while the machine is under enough process pressure for where.exe to
|
|
417
|
-
* miss its timeout; returning the unresolved package-manager name in that case
|
|
418
|
-
* makes Node fall back to a shell shim that cannot survive Job Object wrapping.
|
|
419
|
-
*/
|
|
420
|
-
export function resolveWindowsCommandFromPath(command, pathValue = process.env.PATH ?? "", pathExtValue = process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD") {
|
|
421
|
-
if (!command || path.isAbsolute(command) || command.includes("/") || command.includes("\\")) {
|
|
422
|
-
return null;
|
|
423
|
-
}
|
|
424
|
-
const hasExtension = path.extname(command).length > 0;
|
|
425
|
-
const extensions = hasExtension
|
|
426
|
-
? [""]
|
|
427
|
-
: [...new Set([
|
|
428
|
-
"",
|
|
429
|
-
".exe",
|
|
430
|
-
".ps1",
|
|
431
|
-
".cmd",
|
|
432
|
-
".bat",
|
|
433
|
-
...pathExtValue.split(";").map(value => value.trim().toLowerCase()).filter(Boolean),
|
|
434
|
-
])];
|
|
435
|
-
const candidates = [];
|
|
436
|
-
for (const rawDirectory of pathValue.split(path.delimiter)) {
|
|
437
|
-
const directory = rawDirectory.trim().replace(/^"|"$/gu, "");
|
|
438
|
-
if (!directory)
|
|
439
|
-
continue;
|
|
440
|
-
for (const extension of extensions) {
|
|
441
|
-
const candidate = path.join(directory, `${command}${extension}`);
|
|
442
|
-
if (fs.existsSync(candidate))
|
|
443
|
-
candidates.push(candidate);
|
|
444
|
-
}
|
|
445
|
-
}
|
|
446
|
-
return chooseWindowsCommandCandidate(candidates);
|
|
447
|
-
}
|
|
448
|
-
export function chooseWindowsCommandCandidate(candidates) {
|
|
449
|
-
const normalized = candidates
|
|
450
|
-
.map((candidate) => candidate.trim())
|
|
451
|
-
.filter((candidate) => candidate.length > 0);
|
|
452
|
-
if (normalized.length === 0) {
|
|
453
|
-
return null;
|
|
454
|
-
}
|
|
455
|
-
const preferredExtensions = [".exe", ".ps1", ".cmd", ".bat", ""];
|
|
456
|
-
for (const extension of preferredExtensions) {
|
|
457
|
-
const candidate = normalized.find((entry) => path.extname(entry).toLowerCase() === extension);
|
|
458
|
-
if (candidate) {
|
|
459
|
-
return candidate;
|
|
460
|
-
}
|
|
461
|
-
}
|
|
462
|
-
return normalized[0];
|
|
463
|
-
}
|
|
464
|
-
async function readProcessLines(stream, onLine) {
|
|
465
|
-
const reader = readline.createInterface({ input: stream });
|
|
466
|
-
try {
|
|
467
|
-
for await (const line of reader) {
|
|
468
|
-
await onLine(line);
|
|
469
|
-
}
|
|
470
|
-
}
|
|
471
|
-
finally {
|
|
472
|
-
reader.close();
|
|
473
|
-
}
|
|
474
|
-
}
|