@loucompanion/forge-bridge 0.1.4-dev.fb770705136a → 0.2.1-dev.15efe2d7309f
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 -3
- package/dist/bridge/bridge-chat-giphy-look.d.ts +48 -0
- package/dist/bridge/bridge-chat-giphy-look.js +55 -0
- package/dist/bridge/bridge-chat-provider-command.d.ts +40 -0
- package/dist/bridge/bridge-chat-provider-command.js +230 -0
- package/dist/bridge/bridge-chat.types.d.ts +20 -0
- package/dist/bridge/bridge-chat.types.js +28 -1
- package/dist/bridge/bridge-state-file.d.ts +161 -0
- package/dist/bridge/bridge-state-file.js +376 -0
- package/dist/bridge/bridge-state-io.d.ts +11 -0
- package/dist/bridge/bridge-state-io.js +50 -0
- package/dist/bridge/bridge-state-lock.d.ts +11 -0
- package/dist/bridge/bridge-state-lock.js +102 -0
- package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
- package/dist/bridge/bridge-state-unpublished.js +111 -0
- package/dist/bridge/bridge.base.d.ts +9 -0
- package/dist/bridge/bridge.service.d.ts +92 -14
- package/dist/bridge/bridge.service.js +446 -380
- package/dist/bridge/bridge.types.d.ts +21 -0
- package/dist/bridge/in-flight-registry.d.ts +62 -0
- package/dist/bridge/in-flight-registry.js +207 -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 +5 -1
- package/dist/bridge/readiness-result-outbox.js +20 -0
- package/dist/bridge/runner-host-capabilities.d.ts +5 -0
- package/dist/bridge/runner-host-capabilities.js +31 -1
- package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
- package/dist/bridge/sandbox-resource-accounting.js +150 -0
- package/dist/bridge/test-postgres-capability.d.ts +14 -0
- package/dist/bridge/test-postgres-capability.js +120 -0
- package/dist/bridge/windows-bash-resolution.d.ts +31 -0
- package/dist/bridge/windows-bash-resolution.js +153 -0
- package/dist/cleanup/cleanup-wip.d.ts +12 -0
- package/dist/cleanup/cleanup-wip.js +66 -0
- package/dist/cleanup/cleanup.service.d.ts +20 -1
- package/dist/cleanup/cleanup.service.js +150 -169
- package/dist/cleanup/cleanup.types.d.ts +6 -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 +7 -0
- package/dist/cleanup/host-runtime-ledger.js +130 -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 +74 -12
- package/dist/cli/cli.service.d.ts +19 -10
- package/dist/cli/cli.service.js +152 -187
- package/dist/cli/idle-status.d.ts +84 -0
- package/dist/cli/idle-status.js +181 -0
- package/dist/cli/local-config.d.ts +6 -0
- package/dist/cli/local-config.js +32 -4
- package/dist/cli/provider-cli-detection.d.ts +10 -0
- package/dist/cli/provider-cli-detection.js +160 -0
- package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
- package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
- package/dist/runtime/attempt-database-broker.d.ts +1 -1
- package/dist/runtime/attempt-node-runtime-launcher.d.ts +36 -0
- package/dist/runtime/attempt-node-runtime-launcher.js +169 -0
- package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
- package/dist/runtime/attempt-process-supervisor.js +12 -6
- package/dist/runtime/docker-engine-probe.d.ts +5 -0
- package/dist/runtime/docker-engine-probe.js +7 -0
- package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
- package/dist/runtime/dotnet-build-outputs.js +402 -0
- package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
- package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
- package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
- package/dist/runtime/ephemeral-test-postgres.js +303 -0
- package/dist/runtime/host-facts.d.ts +2 -1
- package/dist/runtime/host-listener-inspector.d.ts +26 -0
- package/dist/runtime/host-listener-inspector.js +84 -3
- package/dist/runtime/host-load-admission.d.ts +72 -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 +61 -0
- package/dist/runtime/host-load-governor-config.js +86 -0
- package/dist/runtime/host-load-governor.d.ts +193 -0
- package/dist/runtime/host-load-governor.js +662 -0
- package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
- package/dist/runtime/host-load-ledger-lock.js +187 -0
- package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
- package/dist/runtime/host-load-runtime-settings.js +80 -0
- package/dist/runtime/host-load-sampler.d.ts +75 -2
- package/dist/runtime/host-load-sampler.js +142 -8
- 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 +88 -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 +21 -1
- package/dist/runtime/host-pressure-stall.js +48 -1
- package/dist/runtime/host-runtime-contract.d.ts +15 -0
- package/dist/runtime/host-runtime-contract.js +39 -6
- package/dist/runtime/host-runtime-lease.d.ts +101 -6
- package/dist/runtime/host-runtime-lease.js +408 -294
- package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
- package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
- package/dist/runtime/host-runtime-promotion.d.ts +101 -2
- package/dist/runtime/host-runtime-promotion.js +355 -14
- 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.js +5 -16
- package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
- package/dist/runtime/native-test-postgres-fallback.js +60 -8
- package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
- package/dist/runtime/prepared-runtime-identity.d.ts +4 -0
- package/dist/runtime/prepared-runtime-identity.js +130 -9
- package/dist/runtime/prepared-runtime-readiness.d.ts +23 -1
- package/dist/runtime/prepared-runtime-readiness.js +89 -18
- package/dist/runtime/runner-settings.d.ts +104 -0
- package/dist/runtime/runner-settings.js +236 -0
- package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
- package/dist/runtime/supervised-runtime-build-guard.js +112 -0
- package/dist/sandbox/host-capacity-broker.d.ts +115 -0
- package/dist/sandbox/host-capacity-broker.js +336 -0
- package/dist/sandbox/managed-branch.d.ts +13 -0
- package/dist/sandbox/managed-branch.js +90 -0
- package/dist/sandbox/provider-auth/codex.js +11 -11
- package/dist/sandbox/runtime.d.ts +10 -1
- package/dist/sandbox/runtime.js +47 -8
- package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
- package/dist/sandbox/sandbox-cgroups.js +42 -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 +2 -7
- package/dist/session/managed-attempt-tools.js +207 -121
- package/dist/session/managed-build-coordinator.d.ts +16 -0
- package/dist/session/managed-build-coordinator.js +10 -0
- package/dist/session/managed-build-receipt.d.ts +5 -0
- package/dist/session/managed-build-receipt.js +8 -3
- package/dist/session/managed-command-host-load.d.ts +47 -0
- package/dist/session/managed-command-host-load.js +83 -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 +7 -0
- package/dist/session/phase-completion.artifacts.js +96 -26
- 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 +12 -0
- package/dist/session/phase-completion.helpers.js +13 -12
- package/dist/session/phase-completion.js +5 -0
- package/dist/session/phase-completion.mcp-args.d.ts +9 -0
- package/dist/session/phase-completion.mcp-args.js +156 -0
- package/dist/session/phase-completion.prompts.js +6 -1
- package/dist/session/phase-completion.runtime.d.ts +5 -11
- package/dist/session/phase-completion.runtime.js +91 -215
- 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 +208 -231
- package/dist/session/phase-completion.validation.d.ts +2 -3
- package/dist/session/phase-completion.validation.js +49 -93
- 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-native-postgres.d.ts +30 -0
- package/dist/session/pre-publication-native-postgres.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 +3 -0
- package/dist/session/pre-publication-process.js +31 -19
- package/dist/session/pre-publication-step-execution.d.ts +12 -0
- package/dist/session/pre-publication-step-execution.js +50 -0
- package/dist/session/pre-publication-validation.d.ts +37 -21
- package/dist/session/pre-publication-validation.js +221 -182
- package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
- package/dist/session/provider-cli/claude-background-work.js +181 -0
- package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
- package/dist/session/provider-cli/host-build-lock.js +30 -0
- package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
- package/dist/session/provider-cli/pre-publication-repair.js +277 -0
- package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
- package/dist/session/provider-cli/provider-cli.child-environment.js +75 -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.merge-integrity.d.ts +6 -3
- package/dist/session/provider-cli/provider-cli.merge-integrity.js +29 -10
- package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
- package/dist/session/provider-cli/provider-cli.process.js +41 -432
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +15 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +109 -32
- package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
- package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
- package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
- package/dist/session/provider-cli/provider-cli.service.js +106 -181
- package/dist/session/provider-cli/provider-cli.types.d.ts +35 -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-cli.windows-launch.d.ts +23 -0
- package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
- package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
- package/dist/session/provider-cli/provider-in-flight-work.js +45 -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 +2 -0
- package/dist/session/provider-cli/provider-output-state.js +6 -0
- package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
- package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
- package/dist/session/qa-sidecar-validation.d.ts +6 -0
- package/dist/session/qa-sidecar-validation.js +28 -0
- package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
- package/dist/session/sandbox-host-capacity-gate.js +257 -0
- package/dist/session/session-host-project.d.ts +22 -0
- package/dist/session/session-host-project.js +98 -0
- package/dist/session/session-redaction.js +31 -181
- package/dist/session/session.base.d.ts +9 -1
- package/dist/session/session.service.d.ts +15 -2
- package/dist/session/session.service.js +246 -138
- package/dist/session/session.types.d.ts +4 -0
- package/dist/session/session.types.js +7 -7
- package/dist/session/sidecar-json-shape.d.ts +31 -0
- package/dist/session/sidecar-json-shape.js +217 -0
- package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
- package/dist/session/workspace-runtime-fingerprint.js +138 -0
- package/dist/shared/fs/file-identity.d.ts +10 -0
- package/dist/shared/fs/file-identity.js +15 -0
- package/dist/shared/fs/replace-file.d.ts +7 -0
- package/dist/shared/fs/replace-file.js +33 -0
- package/dist/shared/process/host-process-recovery.d.ts +14 -3
- package/dist/shared/process/host-process-recovery.js +23 -3
- package/dist/shared/process/host-process-supervisor.d.ts +14 -1
- package/dist/shared/process/host-process-supervisor.js +67 -15
- 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 +67 -0
- package/dist/shared/process/process.js +213 -11
- 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.js +14 -7
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/dependency-warmer.d.ts +25 -0
- package/dist/worktree/dependency-warmer.js +46 -10
- package/dist/worktree/orphan-relink.d.ts +19 -0
- package/dist/worktree/orphan-relink.js +106 -0
- package/dist/worktree/wip-git.d.ts +58 -0
- package/dist/worktree/wip-git.js +182 -0
- package/dist/worktree/wip-refs.d.ts +85 -0
- package/dist/worktree/wip-refs.js +169 -0
- package/dist/worktree/wip-restore.d.ts +51 -0
- package/dist/worktree/wip-restore.js +324 -0
- package/dist/worktree/wip-snapshot.d.ts +53 -0
- package/dist/worktree/wip-snapshot.js +270 -0
- package/dist/worktree/worktree-inputs.d.ts +8 -0
- package/dist/worktree/worktree-inputs.js +134 -0
- package/dist/worktree/worktree-origin-sync.d.ts +35 -0
- package/dist/worktree/worktree-origin-sync.js +128 -0
- package/dist/worktree/worktree-wip-events.d.ts +20 -0
- package/dist/worktree/worktree-wip-events.js +148 -0
- package/dist/worktree/worktree-wip.d.ts +57 -0
- package/dist/worktree/worktree-wip.js +200 -0
- package/dist/worktree/worktree.base.d.ts +7 -1
- package/dist/worktree/worktree.service.d.ts +36 -5
- package/dist/worktree/worktree.service.js +127 -155
- package/dist/worktree/worktree.types.d.ts +47 -0
- package/package.json +2 -2
- package/runtime/windows-listener-owner.ps1 +12 -1
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { replaceFile } from "../shared/fs/replace-file.js";
|
|
5
|
+
import { attemptProcessSupervisorLedgerPath } from "./attempt-process-supervisor.js";
|
|
6
|
+
import { canonicalExistingPath, fileSystemProjectFiles, findDotnetOutputCollisions, hostPathPlatform, isDotnetExecutable, parseDotnetOutputCommand, } from "./dotnet-build-outputs.js";
|
|
7
|
+
const activeChildStatuses = new Set(["starting", "running", "stopping"]);
|
|
8
|
+
export function supervisedRuntimeDescriptorPath(logDirectory, childName) {
|
|
9
|
+
return path.join(logDirectory, `${childName}.runtime.json`);
|
|
10
|
+
}
|
|
11
|
+
export async function writeSupervisedRuntimeDescriptor(logDirectory, descriptor) {
|
|
12
|
+
const target = supervisedRuntimeDescriptorPath(logDirectory, descriptor.childName);
|
|
13
|
+
const temporary = `${target}.${randomUUID()}.tmp`;
|
|
14
|
+
await fs.writeFile(temporary, `${JSON.stringify({ schemaVersion: 1, ...descriptor })}\n`, { encoding: "utf8", mode: 0o600 });
|
|
15
|
+
try {
|
|
16
|
+
await replaceFile(temporary, target);
|
|
17
|
+
}
|
|
18
|
+
finally {
|
|
19
|
+
await fs.rm(temporary, { force: true }).catch(() => undefined);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Finds the first running supervised runtime of this attempt whose build output the command
|
|
24
|
+
* would write. Only the project graph and output directory decide a collision: a build of an
|
|
25
|
+
* unrelated project, into another output, or a test run without a build never matches.
|
|
26
|
+
*/
|
|
27
|
+
export async function findSupervisedRuntimeCollision(check) {
|
|
28
|
+
const platform = check.platform ?? hostPathPlatform();
|
|
29
|
+
const files = check.files ?? fileSystemProjectFiles;
|
|
30
|
+
const writer = await buildingCommand(check, platform);
|
|
31
|
+
if (!writer)
|
|
32
|
+
return null;
|
|
33
|
+
const ledger = await readJson(attemptProcessSupervisorLedgerPath(check.logDirectory));
|
|
34
|
+
for (const child of ledger?.children ?? []) {
|
|
35
|
+
if (!child.name.startsWith("project-") || !activeChildStatuses.has(child.status))
|
|
36
|
+
continue;
|
|
37
|
+
const descriptor = await readJson(supervisedRuntimeDescriptorPath(check.logDirectory, child.name));
|
|
38
|
+
if (descriptor?.schemaVersion !== 1 || !Array.isArray(descriptor.args))
|
|
39
|
+
continue;
|
|
40
|
+
const holder = parseDotnetOutputCommand(descriptor.command, descriptor.args, await canonicalPath(descriptor.cwd), { platform, holder: true });
|
|
41
|
+
if (!holder)
|
|
42
|
+
continue;
|
|
43
|
+
const [collision] = await findDotnetOutputCollisions(writer, holder, files, platform);
|
|
44
|
+
if (!collision)
|
|
45
|
+
continue;
|
|
46
|
+
const metadata = await readJson(child.metadataPath);
|
|
47
|
+
const pid = [metadata?.providerPid, metadata?.rootPid].find(value => Number.isSafeInteger(value) && value > 0);
|
|
48
|
+
// A default output's framework folder is the wildcard `*` until the project names it.
|
|
49
|
+
const framework = await projectTargetFramework(collision.project, files);
|
|
50
|
+
const outputDirectory = framework ? collision.outputDirectory.replace(/(?<=[\\/])\*(?=[\\/]|$)/u, framework) : collision.outputDirectory;
|
|
51
|
+
return {
|
|
52
|
+
childName: child.name,
|
|
53
|
+
role: descriptor.role,
|
|
54
|
+
pid: pid ?? null,
|
|
55
|
+
project: collision.project,
|
|
56
|
+
outputDirectory,
|
|
57
|
+
lockedPath: lockedOutputPath(collision.project, outputDirectory, await runtimeProject(holder, files), platform),
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
/** A single-targeted project's TargetFramework, which names the default output's framework folder. */
|
|
63
|
+
async function projectTargetFramework(project, files) {
|
|
64
|
+
const content = await files.read(project);
|
|
65
|
+
return content?.match(/<TargetFramework>\s*([^<;\s]+)\s*<\/TargetFramework>/u)?.[1]?.toLowerCase() ?? null;
|
|
66
|
+
}
|
|
67
|
+
async function buildingCommand(check, platform) {
|
|
68
|
+
const parsed = parseDotnetOutputCommand(check.command, check.args, await canonicalPath(check.cwd), { platform });
|
|
69
|
+
if (parsed || isDotnetExecutable(check.command, platform) || !check.buildsWorktreeSolution)
|
|
70
|
+
return parsed;
|
|
71
|
+
// The verification scripts build the worktree's solution with its default output.
|
|
72
|
+
return parseDotnetOutputCommand("dotnet", ["build"], await canonicalPath(check.worktreePath), { platform });
|
|
73
|
+
}
|
|
74
|
+
/** Both sides compare canonical paths: a junction, symlink, or 8.3 alias must not hide a collision. */
|
|
75
|
+
async function canonicalPath(directory) {
|
|
76
|
+
return await canonicalExistingPath(directory);
|
|
77
|
+
}
|
|
78
|
+
/** The project the runtime runs, at its real location like the collision's project. */
|
|
79
|
+
async function runtimeProject(holder, files) {
|
|
80
|
+
const target = holder.targets[0];
|
|
81
|
+
return target === undefined || !files.canonical ? target : await files.canonical(target);
|
|
82
|
+
}
|
|
83
|
+
/** The runtime's own executable when the colliding project is the one it runs, otherwise that project's assembly. */
|
|
84
|
+
function lockedOutputPath(project, outputDirectory, runtimeProject, platform) {
|
|
85
|
+
const p = platform === "win32" ? path.win32 : path.posix;
|
|
86
|
+
const name = p.basename(project).replace(/\.(?:cs|fs|vb)proj$/iu, "");
|
|
87
|
+
const isRuntimeProject = runtimeProject !== undefined
|
|
88
|
+
&& (platform === "win32" ? runtimeProject.toLowerCase() === project.toLowerCase() : runtimeProject === project);
|
|
89
|
+
const fileName = isRuntimeProject ? `${name}${platform === "win32" ? ".exe" : ""}` : `${name}.dll`;
|
|
90
|
+
return p.join(outputDirectory, fileName);
|
|
91
|
+
}
|
|
92
|
+
export function supervisedRuntimeCollisionMessage(collision) {
|
|
93
|
+
return `managed_command_runtime_output_collision: this command would build ${collision.project} into ${collision.outputDirectory}, `
|
|
94
|
+
+ `the output the attempt's running supervised runtime ${collision.childName} (role ${collision.role}, PID ${collision.pid ?? "unknown"}) `
|
|
95
|
+
+ `executes from; ${collision.lockedPath} is in use. Forge refused it before launch, because the build would fail on the locked file `
|
|
96
|
+
+ "(MSB3027 on Windows) or replace files under the running runtime. Build into a different output directory: the runtime runs from its "
|
|
97
|
+
+ "own output, so the project's default output is free. Forge rebuilds and restarts the runtime from the current source when validation needs it.";
|
|
98
|
+
}
|
|
99
|
+
/** Fails fast, naming the runtime, instead of letting the build hit the runtime's locked files. */
|
|
100
|
+
export async function assertBuildSparesSupervisedRuntimes(check) {
|
|
101
|
+
const collision = await findSupervisedRuntimeCollision(check);
|
|
102
|
+
if (collision)
|
|
103
|
+
throw new Error(supervisedRuntimeCollisionMessage(collision));
|
|
104
|
+
}
|
|
105
|
+
async function readJson(file) {
|
|
106
|
+
try {
|
|
107
|
+
return JSON.parse(await fs.readFile(file, "utf8"));
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import type { HostLoadStepGate } from "../runtime/host-load-governor.js";
|
|
2
|
+
import type { HostLoadStepProcess } from "../runtime/host-load-step-reaper.js";
|
|
3
|
+
import type { HostLoadTokenPriority } from "../runtime/host-load-token-ledger.js";
|
|
4
|
+
export declare const sandboxHostCapacityBrokerEnvironment = "FORGE_HOST_LOAD_BROKER";
|
|
5
|
+
export declare const sandboxHostCapacityBrokerProtocol = "stdout-v1";
|
|
6
|
+
export declare const sandboxHostCapacityLineType = "forge_host_capacity";
|
|
7
|
+
export declare const sandboxHostCapacityResponseRoot = "/run/forge/host-capacity";
|
|
8
|
+
/** Owner of authentic replies inside the container: root, via `docker exec --user 0`. */
|
|
9
|
+
export declare const sandboxHostCapacityResponseOwnerUid = 0;
|
|
10
|
+
export declare const sandboxHostCapacityMaxWaitEnvironment = "FORGE_HOST_LOAD_BROKER_MAX_WAIT_MS";
|
|
11
|
+
export interface SandboxHostCapacityRequest {
|
|
12
|
+
readonly action: "acquire" | "release" | "retain";
|
|
13
|
+
readonly requestId: string;
|
|
14
|
+
readonly stepClass: string;
|
|
15
|
+
readonly label: string;
|
|
16
|
+
}
|
|
17
|
+
export interface SandboxHostCapacityResponse {
|
|
18
|
+
readonly requestId: string;
|
|
19
|
+
/** Rises with every reply the broker sends; the container keeps only the newest. */
|
|
20
|
+
readonly sequence: number;
|
|
21
|
+
readonly status: "waiting" | "admitted" | "failed" | "fenced";
|
|
22
|
+
readonly waitMs?: number;
|
|
23
|
+
readonly reason?: string;
|
|
24
|
+
readonly detail?: string;
|
|
25
|
+
readonly code?: string;
|
|
26
|
+
readonly message?: string;
|
|
27
|
+
}
|
|
28
|
+
export type SandboxHostCapacityDelivery = (response: SandboxHostCapacityResponse) => Promise<void>;
|
|
29
|
+
/** Parses one stdout line; null when it is not a well-formed broker request. */
|
|
30
|
+
export declare function parseSandboxHostCapacityRequest(line: string): SandboxHostCapacityRequest | null;
|
|
31
|
+
export interface SandboxHostCapacityBrokerOptions {
|
|
32
|
+
/** Requests (acquire or release) one sandbox may hold or start at once. */
|
|
33
|
+
readonly maximumOutstanding?: number;
|
|
34
|
+
/** Request lines allowed in a burst, and their sustained rate. */
|
|
35
|
+
readonly burst?: number;
|
|
36
|
+
readonly refillPerSecond?: number;
|
|
37
|
+
/** The sandbox's process tree (its container's init), recorded on each brokered token. */
|
|
38
|
+
readonly stepProcess?: () => Promise<HostLoadStepProcess | null>;
|
|
39
|
+
/** Delay before retrying a failed delivery; doubles up to a few seconds. */
|
|
40
|
+
readonly retryMs?: number;
|
|
41
|
+
readonly now?: () => number;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* One sandbox's brokered tokens. The sandbox never chooses the cost or the
|
|
45
|
+
* attempt. Replies for one request go out one at a time, newest state only,
|
|
46
|
+
* each with a rising sequence the container-side writer uses to refuse an
|
|
47
|
+
* older reply; a failed delivery is retried until a newer state replaces it
|
|
48
|
+
* or the broker closes. A sandbox that floods requests or exceeds its
|
|
49
|
+
* outstanding limit stops the broker and fails its attempt.
|
|
50
|
+
*/
|
|
51
|
+
export declare class SandboxHostCapacityBroker {
|
|
52
|
+
private readonly gate;
|
|
53
|
+
private readonly dispatchAttemptId;
|
|
54
|
+
private readonly priority;
|
|
55
|
+
private readonly deliver;
|
|
56
|
+
private readonly options;
|
|
57
|
+
private readonly tokens;
|
|
58
|
+
private readonly deliveries;
|
|
59
|
+
private readonly work;
|
|
60
|
+
private readonly maximumOutstanding;
|
|
61
|
+
private readonly burst;
|
|
62
|
+
private readonly refillPerSecond;
|
|
63
|
+
private readonly retryMs;
|
|
64
|
+
private readonly now;
|
|
65
|
+
private sequence;
|
|
66
|
+
private allowance;
|
|
67
|
+
private allowanceAtMs;
|
|
68
|
+
private closed;
|
|
69
|
+
private abuse;
|
|
70
|
+
constructor(gate: HostLoadStepGate, dispatchAttemptId: string, priority: HostLoadTokenPriority, deliver: SandboxHostCapacityDelivery, options?: SandboxHostCapacityBrokerOptions);
|
|
71
|
+
/**
|
|
72
|
+
* True when the line was a broker request; such a line is never a runner
|
|
73
|
+
* event. Throws sandbox_host_capacity_abuse once the sandbox breaks its
|
|
74
|
+
* limits: its tokens are returned and the attempt fails with that reason.
|
|
75
|
+
*/
|
|
76
|
+
handleLine(line: string): boolean;
|
|
77
|
+
/** The sandbox exited: cancel its waits and return every token it holds. */
|
|
78
|
+
close(): Promise<void>;
|
|
79
|
+
/** Requests waiting or admitted, for diagnostics and tests. */
|
|
80
|
+
outstanding(): number;
|
|
81
|
+
private stop;
|
|
82
|
+
private takeAllowance;
|
|
83
|
+
private track;
|
|
84
|
+
private acquire;
|
|
85
|
+
/**
|
|
86
|
+
* The sandbox's step ended but part of its tree may still run: the host token is
|
|
87
|
+
* kept, marked retained (so the attempt's own next step does not wait for it),
|
|
88
|
+
* until the sandbox releases the request or exits.
|
|
89
|
+
*/
|
|
90
|
+
private retain;
|
|
91
|
+
private release;
|
|
92
|
+
/** Queues the newest state for a request; at most one delivery per request is in flight. */
|
|
93
|
+
private respond;
|
|
94
|
+
private pump;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Adds the broker variables to a worker `docker create` command, just before
|
|
98
|
+
* its image: the protocol, and the host's maximum queue wait so the
|
|
99
|
+
* container's own fail-safe never fires before the host answers.
|
|
100
|
+
*/
|
|
101
|
+
export declare function withSandboxHostCapacityBroker(createArgs: readonly string[], image: string, maxWaitMs: number): string[];
|
|
102
|
+
/** `docker exec` arguments that write one reply into the container as root. */
|
|
103
|
+
export declare function sandboxHostCapacityDeliveryExecArgs(container: string): string[];
|
|
104
|
+
/**
|
|
105
|
+
* The `node -e` script that writes one response file inside the container, run
|
|
106
|
+
* as root. It keeps the newest reply: one with a lower or equal sequence than
|
|
107
|
+
* the file already holds is dropped, so a late delivery can never replace a
|
|
108
|
+
* newer state. Replies are world-readable but owned by the writer (root, via
|
|
109
|
+
* `docker exec --user 0`). The directory must already be owned by that same uid
|
|
110
|
+
* and writable by no one else, i.e. the root-owned reply mount; it is never
|
|
111
|
+
* created here, where it could turn out to be the sandbox's own directory. A
|
|
112
|
+
* runtime without POSIX user ids (Windows) cannot prove that, so the script
|
|
113
|
+
* writes nothing there (exit 3), as for any directory it cannot trust.
|
|
114
|
+
*/
|
|
115
|
+
export declare const sandboxHostCapacityResponseScript: string;
|
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
import { hostLoadStepCostForClass } from "../runtime/host-load-step-class.js";
|
|
2
|
+
import { takesHostTestSlot } from "../runtime/host-load-test-slot.js";
|
|
3
|
+
import { ForgeFailureError } from "../session/session.types.js";
|
|
4
|
+
// Host side of Docker-sandbox admission (decision 0013). The validator inside a
|
|
5
|
+
// container cannot reach the host ledger, so it asks the bridge over the
|
|
6
|
+
// channels the sandbox already has: a request line on the worker's stdout
|
|
7
|
+
// (which the bridge parses anyway) and a response file the bridge writes with
|
|
8
|
+
// `docker exec`. The bridge's own governor holds the token, renews it, and
|
|
9
|
+
// returns it when the sandbox releases it or exits, so Docker steps share the
|
|
10
|
+
// host budget.
|
|
11
|
+
//
|
|
12
|
+
// Replies are unforgeable from inside the sandbox. They live on their own tmpfs
|
|
13
|
+
// owned by root with mode 0755, mounted only for brokered workers, and are
|
|
14
|
+
// written by `docker exec --user 0`. The workload runs as uid 10001 with every
|
|
15
|
+
// capability dropped and no-new-privileges, so it can neither write there nor
|
|
16
|
+
// create any root-owned file anywhere, and a mount point cannot be renamed
|
|
17
|
+
// away. The validator accepts only a regular, root-owned, single-link reply
|
|
18
|
+
// that no one else can write (sandbox-host-capacity-gate.ts).
|
|
19
|
+
export const sandboxHostCapacityBrokerEnvironment = "FORGE_HOST_LOAD_BROKER";
|
|
20
|
+
export const sandboxHostCapacityBrokerProtocol = "stdout-v1";
|
|
21
|
+
export const sandboxHostCapacityLineType = "forge_host_capacity";
|
|
22
|
+
export const sandboxHostCapacityResponseRoot = "/run/forge/host-capacity";
|
|
23
|
+
/** Owner of authentic replies inside the container: root, via `docker exec --user 0`. */
|
|
24
|
+
export const sandboxHostCapacityResponseOwnerUid = 0;
|
|
25
|
+
export const sandboxHostCapacityMaxWaitEnvironment = "FORGE_HOST_LOAD_BROKER_MAX_WAIT_MS";
|
|
26
|
+
const requestIdPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
|
|
27
|
+
const stepClassPattern = /^[a-z0-9][a-z0-9._-]{0,63}$/u;
|
|
28
|
+
/** A sandbox validates one step at a time; a small bound stops a runaway from hoarding tokens. */
|
|
29
|
+
const defaultMaximumOutstanding = 2;
|
|
30
|
+
/** A validation run sends two lines per step; this leaves room for reruns and caps docker exec churn. */
|
|
31
|
+
const defaultBurst = 40;
|
|
32
|
+
const defaultRefillPerSecond = 2;
|
|
33
|
+
function codeOf(error) {
|
|
34
|
+
const code = error?.code;
|
|
35
|
+
return typeof code === "string" ? code : null;
|
|
36
|
+
}
|
|
37
|
+
function hasCode(error, code) {
|
|
38
|
+
return codeOf(error) === code;
|
|
39
|
+
}
|
|
40
|
+
/** Parses one stdout line; null when it is not a well-formed broker request. */
|
|
41
|
+
export function parseSandboxHostCapacityRequest(line) {
|
|
42
|
+
const trimmed = line.trim();
|
|
43
|
+
if (!trimmed.startsWith("{") || !trimmed.includes(sandboxHostCapacityLineType) || trimmed.length > 4096)
|
|
44
|
+
return null;
|
|
45
|
+
let value;
|
|
46
|
+
try {
|
|
47
|
+
value = JSON.parse(trimmed);
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
if (!value || value.type !== sandboxHostCapacityLineType || value.version !== 1)
|
|
53
|
+
return null;
|
|
54
|
+
if (value.action !== "acquire" && value.action !== "release" && value.action !== "retain")
|
|
55
|
+
return null;
|
|
56
|
+
if (typeof value.requestId !== "string" || !requestIdPattern.test(value.requestId))
|
|
57
|
+
return null;
|
|
58
|
+
const claimed = typeof value.stepClass === "string" && stepClassPattern.test(value.stepClass) ? value.stepClass : "generic";
|
|
59
|
+
// A sandbox brokers only validation steps; it cannot claim a class that skips the host test slot.
|
|
60
|
+
const stepClass = takesHostTestSlot(claimed) ? claimed : "generic";
|
|
61
|
+
// Diagnostics only, but never control characters or markup from the sandbox.
|
|
62
|
+
const label = typeof value.label === "string" ? value.label.replace(/[^\w .:/@+-]/gu, "_").slice(0, 128) : "";
|
|
63
|
+
return { action: value.action, requestId: value.requestId, stepClass, label };
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* One sandbox's brokered tokens. The sandbox never chooses the cost or the
|
|
67
|
+
* attempt. Replies for one request go out one at a time, newest state only,
|
|
68
|
+
* each with a rising sequence the container-side writer uses to refuse an
|
|
69
|
+
* older reply; a failed delivery is retried until a newer state replaces it
|
|
70
|
+
* or the broker closes. A sandbox that floods requests or exceeds its
|
|
71
|
+
* outstanding limit stops the broker and fails its attempt.
|
|
72
|
+
*/
|
|
73
|
+
export class SandboxHostCapacityBroker {
|
|
74
|
+
gate;
|
|
75
|
+
dispatchAttemptId;
|
|
76
|
+
priority;
|
|
77
|
+
deliver;
|
|
78
|
+
options;
|
|
79
|
+
tokens = new Map();
|
|
80
|
+
deliveries = new Map();
|
|
81
|
+
work = new Set();
|
|
82
|
+
maximumOutstanding;
|
|
83
|
+
burst;
|
|
84
|
+
refillPerSecond;
|
|
85
|
+
retryMs;
|
|
86
|
+
now;
|
|
87
|
+
sequence = 0;
|
|
88
|
+
allowance;
|
|
89
|
+
allowanceAtMs;
|
|
90
|
+
closed = false;
|
|
91
|
+
abuse = null;
|
|
92
|
+
constructor(gate, dispatchAttemptId, priority, deliver, options = {}) {
|
|
93
|
+
this.gate = gate;
|
|
94
|
+
this.dispatchAttemptId = dispatchAttemptId;
|
|
95
|
+
this.priority = priority;
|
|
96
|
+
this.deliver = deliver;
|
|
97
|
+
this.options = options;
|
|
98
|
+
this.maximumOutstanding = options.maximumOutstanding ?? defaultMaximumOutstanding;
|
|
99
|
+
this.burst = options.burst ?? defaultBurst;
|
|
100
|
+
this.refillPerSecond = options.refillPerSecond ?? defaultRefillPerSecond;
|
|
101
|
+
this.retryMs = options.retryMs ?? 250;
|
|
102
|
+
this.now = options.now ?? Date.now;
|
|
103
|
+
this.allowance = this.burst;
|
|
104
|
+
this.allowanceAtMs = this.now();
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* True when the line was a broker request; such a line is never a runner
|
|
108
|
+
* event. Throws sandbox_host_capacity_abuse once the sandbox breaks its
|
|
109
|
+
* limits: its tokens are returned and the attempt fails with that reason.
|
|
110
|
+
*/
|
|
111
|
+
handleLine(line) {
|
|
112
|
+
if (this.abuse)
|
|
113
|
+
throw this.abuse;
|
|
114
|
+
const request = parseSandboxHostCapacityRequest(line);
|
|
115
|
+
if (!request)
|
|
116
|
+
return false;
|
|
117
|
+
if (!this.takeAllowance()) {
|
|
118
|
+
this.stop(`more than ${this.burst} host capacity requests in a burst (sustained limit ${this.refillPerSecond}/s)`);
|
|
119
|
+
}
|
|
120
|
+
if (request.action === "acquire" && !this.tokens.has(request.requestId) && this.tokens.size >= this.maximumOutstanding) {
|
|
121
|
+
this.stop(`more than ${this.maximumOutstanding} host capacity requests outstanding at once`);
|
|
122
|
+
}
|
|
123
|
+
this.track(request.action === "acquire" ? this.acquire(request)
|
|
124
|
+
: request.action === "retain" ? Promise.resolve(this.retain(request.requestId)) : this.release(request.requestId));
|
|
125
|
+
return true;
|
|
126
|
+
}
|
|
127
|
+
/** The sandbox exited: cancel its waits and return every token it holds. */
|
|
128
|
+
async close() {
|
|
129
|
+
this.closed = true;
|
|
130
|
+
await Promise.allSettled([...this.tokens.keys()].map(requestId => this.release(requestId)));
|
|
131
|
+
await Promise.allSettled([...this.work]);
|
|
132
|
+
}
|
|
133
|
+
/** Requests waiting or admitted, for diagnostics and tests. */
|
|
134
|
+
outstanding() {
|
|
135
|
+
return this.tokens.size;
|
|
136
|
+
}
|
|
137
|
+
stop(reason) {
|
|
138
|
+
this.abuse = new ForgeFailureError("sandbox_host_capacity_abuse", `sandbox_host_capacity_abuse: the sandbox sent ${reason}; Forge returned its host capacity and stopped the attempt.`, "sandbox");
|
|
139
|
+
void this.close();
|
|
140
|
+
throw this.abuse;
|
|
141
|
+
}
|
|
142
|
+
takeAllowance() {
|
|
143
|
+
const nowMs = this.now();
|
|
144
|
+
this.allowance = Math.min(this.burst, this.allowance + ((nowMs - this.allowanceAtMs) / 1000) * this.refillPerSecond);
|
|
145
|
+
this.allowanceAtMs = nowMs;
|
|
146
|
+
if (this.allowance < 1)
|
|
147
|
+
return false;
|
|
148
|
+
this.allowance -= 1;
|
|
149
|
+
return true;
|
|
150
|
+
}
|
|
151
|
+
track(task) {
|
|
152
|
+
const tracked = task.catch(() => undefined);
|
|
153
|
+
this.work.add(tracked);
|
|
154
|
+
void tracked.finally(() => this.work.delete(tracked));
|
|
155
|
+
}
|
|
156
|
+
async acquire(request) {
|
|
157
|
+
if (this.closed || this.tokens.has(request.requestId))
|
|
158
|
+
return;
|
|
159
|
+
const entry = { controller: new AbortController(), admission: null, released: false, retained: false };
|
|
160
|
+
this.tokens.set(request.requestId, entry);
|
|
161
|
+
let admission;
|
|
162
|
+
try {
|
|
163
|
+
admission = await this.gate.acquire({
|
|
164
|
+
stepClass: request.stepClass,
|
|
165
|
+
label: `sandbox ${request.label || request.stepClass}`,
|
|
166
|
+
// The host decides the cost from the class; the sandbox cannot claim a cheaper one.
|
|
167
|
+
cost: hostLoadStepCostForClass(request.stepClass),
|
|
168
|
+
dispatchAttemptId: this.dispatchAttemptId,
|
|
169
|
+
priority: this.priority,
|
|
170
|
+
}, {
|
|
171
|
+
signal: entry.controller.signal,
|
|
172
|
+
// Sequenced when called, so it can never overtake the admission that follows.
|
|
173
|
+
onWaiting: decision => this.respond({
|
|
174
|
+
requestId: request.requestId, status: "waiting", reason: decision.reason, detail: decision.detail,
|
|
175
|
+
}),
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
catch (error) {
|
|
179
|
+
this.tokens.delete(request.requestId);
|
|
180
|
+
if (entry.released)
|
|
181
|
+
return;
|
|
182
|
+
const failure = error;
|
|
183
|
+
void this.respond({
|
|
184
|
+
requestId: request.requestId,
|
|
185
|
+
status: "failed",
|
|
186
|
+
code: typeof failure.code === "string" ? failure.code : "host_capacity_broker_failed",
|
|
187
|
+
message: typeof failure.message === "string" ? failure.message : String(error),
|
|
188
|
+
...(typeof failure.waitMs === "number" ? { waitMs: Math.round(failure.waitMs) } : {}),
|
|
189
|
+
});
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
if (entry.released) {
|
|
193
|
+
await admission.release().catch(() => undefined);
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
entry.admission = admission;
|
|
197
|
+
// A reclaim after a bridge crash then stops the sandbox before reusing its capacity.
|
|
198
|
+
// Without a known process (lookup failed) the token has no tree and, on a crash,
|
|
199
|
+
// stays degraded with its cost; a failed recording is terminal, not ignored.
|
|
200
|
+
let attachFailure = null;
|
|
201
|
+
if (!admission.fenced.aborted) {
|
|
202
|
+
const stepProcess = await this.options.stepProcess?.().catch(() => null);
|
|
203
|
+
if (stepProcess)
|
|
204
|
+
attachFailure = await admission.attachProcess(stepProcess).then(() => null, (error) => error);
|
|
205
|
+
}
|
|
206
|
+
if (entry.released)
|
|
207
|
+
return;
|
|
208
|
+
if (admission.fenced.aborted || attachFailure !== null) {
|
|
209
|
+
// Lost before the sandbox was told it may start: it never runs this step, so
|
|
210
|
+
// it gets a terminal answer instead of "admitted", and the token goes back now.
|
|
211
|
+
const reason = admission.fenced.aborted ? admission.fenced.reason : attachFailure;
|
|
212
|
+
const fenced = admission.fenced.aborted || hasCode(reason, "host_capacity_token_fenced");
|
|
213
|
+
entry.released = true;
|
|
214
|
+
this.tokens.delete(request.requestId);
|
|
215
|
+
void this.respond({
|
|
216
|
+
requestId: request.requestId,
|
|
217
|
+
status: fenced ? "fenced" : "failed",
|
|
218
|
+
code: fenced ? "host_capacity_token_fenced" : codeOf(reason) ?? "host_capacity_broker_failed",
|
|
219
|
+
message: reason instanceof Error ? reason.message : String(reason),
|
|
220
|
+
});
|
|
221
|
+
await admission.release().catch(() => undefined);
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
// Registered synchronously after the check above, so no fence can slip between them.
|
|
225
|
+
admission.fenced.addEventListener("abort", () => {
|
|
226
|
+
// Retention stops the step's reservation on purpose; the sandbox already knows.
|
|
227
|
+
if (entry.retained)
|
|
228
|
+
return;
|
|
229
|
+
void this.respond({
|
|
230
|
+
requestId: request.requestId,
|
|
231
|
+
status: "fenced",
|
|
232
|
+
code: "host_capacity_token_fenced",
|
|
233
|
+
message: admission.fenced.reason instanceof Error ? admission.fenced.reason.message : "host_capacity_token_fenced",
|
|
234
|
+
});
|
|
235
|
+
}, { once: true });
|
|
236
|
+
void this.respond({
|
|
237
|
+
requestId: request.requestId, status: "admitted", waitMs: Math.round(admission.waitMs), reason: admission.decision.reason,
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* The sandbox's step ended but part of its tree may still run: the host token is
|
|
242
|
+
* kept, marked retained (so the attempt's own next step does not wait for it),
|
|
243
|
+
* until the sandbox releases the request or exits.
|
|
244
|
+
*/
|
|
245
|
+
retain(requestId) {
|
|
246
|
+
const entry = this.tokens.get(requestId);
|
|
247
|
+
if (!entry?.admission || entry.released || entry.retained)
|
|
248
|
+
return;
|
|
249
|
+
entry.retained = true;
|
|
250
|
+
entry.admission.retainUntilStopped(async () => entry.released, new Error("The sandbox step's processes could not be proven stopped; its host capacity is kept until the sandbox releases it."));
|
|
251
|
+
}
|
|
252
|
+
async release(requestId) {
|
|
253
|
+
const entry = this.tokens.get(requestId);
|
|
254
|
+
if (!entry || entry.released)
|
|
255
|
+
return;
|
|
256
|
+
entry.released = true;
|
|
257
|
+
this.tokens.delete(requestId);
|
|
258
|
+
this.deliveries.delete(requestId);
|
|
259
|
+
entry.controller.abort(new Error("The sandbox released its host capacity request."));
|
|
260
|
+
await entry.admission?.release().catch(() => undefined);
|
|
261
|
+
}
|
|
262
|
+
/** Queues the newest state for a request; at most one delivery per request is in flight. */
|
|
263
|
+
respond(response) {
|
|
264
|
+
// A container that already exited cannot read the answer; the token is released on close.
|
|
265
|
+
if (this.closed)
|
|
266
|
+
return Promise.resolve();
|
|
267
|
+
this.sequence += 1;
|
|
268
|
+
const state = this.deliveries.get(response.requestId) ?? { latest: null, delivering: false };
|
|
269
|
+
this.deliveries.set(response.requestId, state);
|
|
270
|
+
state.latest = { ...response, sequence: this.sequence };
|
|
271
|
+
if (state.delivering)
|
|
272
|
+
return Promise.resolve();
|
|
273
|
+
state.delivering = true;
|
|
274
|
+
const pump = this.pump(response.requestId, state);
|
|
275
|
+
this.track(pump);
|
|
276
|
+
return pump;
|
|
277
|
+
}
|
|
278
|
+
async pump(requestId, state) {
|
|
279
|
+
// The reply chain for one request; ends when its newest state landed or the broker closed.
|
|
280
|
+
let delayMs = this.retryMs;
|
|
281
|
+
try {
|
|
282
|
+
while (state.latest && !this.closed) {
|
|
283
|
+
const next = state.latest;
|
|
284
|
+
try {
|
|
285
|
+
await this.deliver(next);
|
|
286
|
+
if (state.latest === next)
|
|
287
|
+
state.latest = null;
|
|
288
|
+
delayMs = this.retryMs;
|
|
289
|
+
}
|
|
290
|
+
catch {
|
|
291
|
+
// Redeliver the newest state (this one, unless a newer one arrived meanwhile).
|
|
292
|
+
await new Promise(resolve => setTimeout(resolve, delayMs));
|
|
293
|
+
delayMs = Math.min(delayMs * 2, 4_000);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
finally {
|
|
298
|
+
state.delivering = false;
|
|
299
|
+
if (!this.tokens.has(requestId) && this.deliveries.get(requestId) === state)
|
|
300
|
+
this.deliveries.delete(requestId);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Adds the broker variables to a worker `docker create` command, just before
|
|
306
|
+
* its image: the protocol, and the host's maximum queue wait so the
|
|
307
|
+
* container's own fail-safe never fires before the host answers.
|
|
308
|
+
*/
|
|
309
|
+
export function withSandboxHostCapacityBroker(createArgs, image, maxWaitMs) {
|
|
310
|
+
const imageIndex = createArgs.lastIndexOf(image);
|
|
311
|
+
if (imageIndex < 0)
|
|
312
|
+
throw new Error("sandbox_host_capacity_broker_invalid: the worker image is missing from its create command.");
|
|
313
|
+
const args = [...createArgs];
|
|
314
|
+
args.splice(imageIndex, 0,
|
|
315
|
+
// Root-owned and not writable by the sandbox user: only the bridge's replies land here.
|
|
316
|
+
"--tmpfs", `${sandboxHostCapacityResponseRoot}:rw,nosuid,nodev,noexec,size=4m,uid=0,gid=0,mode=0755`, "--env", `${sandboxHostCapacityBrokerEnvironment}=${sandboxHostCapacityBrokerProtocol}`, "--env", `${sandboxHostCapacityMaxWaitEnvironment}=${Math.round(maxWaitMs)}`);
|
|
317
|
+
return args;
|
|
318
|
+
}
|
|
319
|
+
/** `docker exec` arguments that write one reply into the container as root. */
|
|
320
|
+
export function sandboxHostCapacityDeliveryExecArgs(container) {
|
|
321
|
+
return ["exec", "--interactive", "--user", "0", container, "node", "-e", sandboxHostCapacityResponseScript];
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* The `node -e` script that writes one response file inside the container, run
|
|
325
|
+
* as root. It keeps the newest reply: one with a lower or equal sequence than
|
|
326
|
+
* the file already holds is dropped, so a late delivery can never replace a
|
|
327
|
+
* newer state. Replies are world-readable but owned by the writer (root, via
|
|
328
|
+
* `docker exec --user 0`). The directory must already be owned by that same uid
|
|
329
|
+
* and writable by no one else, i.e. the root-owned reply mount; it is never
|
|
330
|
+
* created here, where it could turn out to be the sandbox's own directory. A
|
|
331
|
+
* runtime without POSIX user ids (Windows) cannot prove that, so the script
|
|
332
|
+
* writes nothing there (exit 3), as for any directory it cannot trust.
|
|
333
|
+
*/
|
|
334
|
+
export const sandboxHostCapacityResponseScript = "let s='';process.stdin.setEncoding('utf8');process.stdin.on('data',c=>s+=c);process.stdin.on('end',()=>{const f=require('fs'),r=JSON.parse(s),d='"
|
|
335
|
+
+ sandboxHostCapacityResponseRoot
|
|
336
|
+
+ "';if(!/^[0-9a-f-]{36}$/.test(r.requestId)||!Number.isSafeInteger(r.sequence))process.exit(2);if(typeof process.getuid!=='function')process.exit(3);const st=f.lstatSync(d);if(!st.isDirectory()||st.uid!==process.getuid()||(st.mode&0o022))process.exit(3);const p=d+'/'+r.requestId+'.json',t=p+'.'+process.pid+'.tmp';let o=-1;try{o=JSON.parse(f.readFileSync(p,'utf8')).sequence}catch{}if(Number.isSafeInteger(o)&&o>=r.sequence)return;f.writeFileSync(t,s,{mode:0o644,flag:'wx'});f.renameSync(t,p)})";
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type SandboxProcessRequest, type SandboxProcessResult } from "./process.js";
|
|
2
|
+
export type ManagedBranchProcess = (request: SandboxProcessRequest) => Promise<SandboxProcessResult>;
|
|
3
|
+
export interface CheckedOutBranchUpdate {
|
|
4
|
+
readonly repoPath: string;
|
|
5
|
+
readonly worktreePath: string;
|
|
6
|
+
readonly branchRef: string;
|
|
7
|
+
/** The commit the sandbox started from; the branch and worktree must still be exactly there. */
|
|
8
|
+
readonly expected: string;
|
|
9
|
+
readonly imported: string;
|
|
10
|
+
/** Runs git; tests inject one. */
|
|
11
|
+
readonly run?: ManagedBranchProcess;
|
|
12
|
+
}
|
|
13
|
+
export declare function advanceCheckedOutBranch(update: CheckedOutBranchUpdate): Promise<void>;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { ForgeFailureError } from "../session/session.types.js";
|
|
2
|
+
import { requireSandboxProcess } from "./process.js";
|
|
3
|
+
export async function advanceCheckedOutBranch(update) {
|
|
4
|
+
const run = update.run ?? requireSandboxProcess;
|
|
5
|
+
const inWorktree = (args, timeoutMs) => run({ command: "git", args: ["-C", update.worktreePath, ...args], timeoutMs, maxOutputBytes: 4 * 1024 * 1024 });
|
|
6
|
+
const head = (await inWorktree(["rev-parse", "HEAD"], 30_000)).stdout.trim();
|
|
7
|
+
const status = (await inWorktree(["status", "--porcelain=v1", "--untracked-files=no"], 30_000)).stdout;
|
|
8
|
+
if (head !== update.expected || status.trim()) {
|
|
9
|
+
throw conflict("managed worktree changed after sandbox input was captured.");
|
|
10
|
+
}
|
|
11
|
+
await inWorktree(["read-tree", "-m", "-u", update.expected, update.imported], 2 * 60_000);
|
|
12
|
+
try {
|
|
13
|
+
await run({
|
|
14
|
+
command: "git",
|
|
15
|
+
args: ["-C", update.repoPath, "update-ref", update.branchRef, update.imported, update.expected],
|
|
16
|
+
timeoutMs: 30_000,
|
|
17
|
+
maxOutputBytes: 4 * 1024 * 1024,
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
const settled = await followBranch(run, update, inWorktree);
|
|
22
|
+
throw conflict(`managed branch changed while the sandbox result was applied (${messageOf(error)}); its worktree now matches the branch's commit ${settled}.`, { cause: error });
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/** How many times a rollback re-reads a branch that keeps moving before it gives up. */
|
|
26
|
+
const rollbackPasses = 3;
|
|
27
|
+
/** How many times one read of the branch's commit is tried before the rollback gives up on it. */
|
|
28
|
+
const tipReads = 3;
|
|
29
|
+
/**
|
|
30
|
+
* After a lost swap, moves the worktree and index to wherever the branch points (HEAD follows it):
|
|
31
|
+
* the other writer's commit when it won the race, or the input when the swap failed for another
|
|
32
|
+
* reason. The branch can move again while that runs, so the tip is read again after each move and
|
|
33
|
+
* followed; a branch still moving after `rollbackPasses` moves fails closed, naming both commits.
|
|
34
|
+
* A branch whose commit can't be read (after `tipReads` tries) also fails closed, with the worktree
|
|
35
|
+
* left where it is: guessing a commit could leave it on one HEAD doesn't name.
|
|
36
|
+
* Returns the commit the worktree matches.
|
|
37
|
+
*/
|
|
38
|
+
async function followBranch(run, update, inWorktree) {
|
|
39
|
+
let restored = update.imported;
|
|
40
|
+
let target = await readTip(run, update);
|
|
41
|
+
for (let pass = 0; pass < rollbackPasses; pass += 1) {
|
|
42
|
+
if (target === null)
|
|
43
|
+
throw unreadableTip(restored);
|
|
44
|
+
if (target === restored)
|
|
45
|
+
return restored;
|
|
46
|
+
try {
|
|
47
|
+
await inWorktree(["read-tree", "-m", "-u", restored, target], 2 * 60_000);
|
|
48
|
+
}
|
|
49
|
+
catch (rollbackError) {
|
|
50
|
+
throw conflict(`managed branch changed while the sandbox result was applied, and its worktree could not be moved to the branch's commit ${target} `
|
|
51
|
+
+ `(${messageOf(rollbackError)}); it holds the files of ${restored}.`, { cause: rollbackError });
|
|
52
|
+
}
|
|
53
|
+
restored = target;
|
|
54
|
+
target = await readTip(run, update);
|
|
55
|
+
}
|
|
56
|
+
if (target === null)
|
|
57
|
+
throw unreadableTip(restored);
|
|
58
|
+
if (target === restored)
|
|
59
|
+
return restored;
|
|
60
|
+
throw conflict(`managed branch kept moving while its worktree was rolled back after the sandbox result was applied; the worktree matches ${restored} `
|
|
61
|
+
+ `but the branch now points at ${target}.`);
|
|
62
|
+
}
|
|
63
|
+
async function readTip(run, update) {
|
|
64
|
+
for (let read = 0; read < tipReads; read += 1) {
|
|
65
|
+
const tip = await branchTip(run, update).catch(() => null);
|
|
66
|
+
if (tip)
|
|
67
|
+
return tip;
|
|
68
|
+
}
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
function unreadableTip(restored) {
|
|
72
|
+
return conflict(`managed branch changed while the sandbox result was applied, and its commit could not be read; its worktree holds the files of ${restored}, `
|
|
73
|
+
+ "which the branch may no longer point at.");
|
|
74
|
+
}
|
|
75
|
+
async function branchTip(run, update) {
|
|
76
|
+
const result = await run({
|
|
77
|
+
command: "git",
|
|
78
|
+
args: ["-C", update.repoPath, "rev-parse", "-q", "--verify", `${update.branchRef}^{commit}`],
|
|
79
|
+
timeoutMs: 30_000,
|
|
80
|
+
maxOutputBytes: 1024 * 1024,
|
|
81
|
+
});
|
|
82
|
+
const sha = result.stdout.trim();
|
|
83
|
+
return /^[0-9a-f]{40,64}$/iu.test(sha) ? sha : null;
|
|
84
|
+
}
|
|
85
|
+
function conflict(detail, options) {
|
|
86
|
+
return new ForgeFailureError("sandbox_output_conflict", `sandbox_output_conflict: ${detail}`, "sandbox", options);
|
|
87
|
+
}
|
|
88
|
+
function messageOf(error) {
|
|
89
|
+
return error instanceof Error ? error.message : String(error);
|
|
90
|
+
}
|