@loucompanion/forge-bridge 0.1.4-dev.d2d83bc81b6a → 0.1.4-dev.e83e5bc6ecce

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.
Files changed (130) hide show
  1. package/README.md +2 -2
  2. package/dist/bridge/bridge.service.d.ts +5 -1
  3. package/dist/bridge/bridge.service.js +40 -6
  4. package/dist/bridge/bridge.types.d.ts +11 -0
  5. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  6. package/dist/bridge/runner-host-capabilities.js +4 -0
  7. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  8. package/dist/bridge/test-postgres-capability.js +120 -0
  9. package/dist/cleanup/cleanup.service.d.ts +9 -0
  10. package/dist/cleanup/cleanup.service.js +72 -109
  11. package/dist/cleanup/cleanup.types.d.ts +4 -0
  12. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  13. package/dist/cleanup/forge-owned-paths.js +53 -0
  14. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  15. package/dist/cleanup/host-runtime-ledger.js +109 -0
  16. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  17. package/dist/cleanup/managed-branch-sweep.js +111 -0
  18. package/dist/cli/cli.service.js +10 -2
  19. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  20. package/dist/runtime/host-database-capability-boundary.js +1 -0
  21. package/dist/runtime/host-facts.d.ts +35 -0
  22. package/dist/runtime/host-facts.js +95 -0
  23. package/dist/runtime/host-load-admission.d.ts +52 -0
  24. package/dist/runtime/host-load-admission.js +84 -0
  25. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  26. package/dist/runtime/host-load-child-environment.js +65 -0
  27. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  28. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  29. package/dist/runtime/host-load-governor-config.d.ts +34 -0
  30. package/dist/runtime/host-load-governor-config.js +46 -0
  31. package/dist/runtime/host-load-governor.d.ts +172 -0
  32. package/dist/runtime/host-load-governor.js +519 -0
  33. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  34. package/dist/runtime/host-load-ledger-lock.js +185 -0
  35. package/dist/runtime/host-load-sampler.d.ts +126 -0
  36. package/dist/runtime/host-load-sampler.js +232 -0
  37. package/dist/runtime/host-load-step-class.d.ts +68 -0
  38. package/dist/runtime/host-load-step-class.js +106 -0
  39. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  40. package/dist/runtime/host-load-step-reaper.js +95 -0
  41. package/dist/runtime/host-load-step-run.d.ts +73 -0
  42. package/dist/runtime/host-load-step-run.js +102 -0
  43. package/dist/runtime/host-load-token-ledger.d.ts +174 -0
  44. package/dist/runtime/host-load-token-ledger.js +421 -0
  45. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  46. package/dist/runtime/host-pressure-stall.js +168 -0
  47. package/dist/runtime/host-runtime-contract.d.ts +4 -0
  48. package/dist/runtime/host-runtime-contract.js +6 -1
  49. package/dist/runtime/host-runtime-lease.d.ts +17 -3
  50. package/dist/runtime/host-runtime-lease.js +83 -4
  51. package/dist/runtime/host-runtime-promotion.js +12 -0
  52. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  53. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  54. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  55. package/dist/runtime/host-runtime-requirements.js +117 -0
  56. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  57. package/dist/sandbox/host-capacity-broker.js +315 -0
  58. package/dist/sandbox/runtime.d.ts +10 -1
  59. package/dist/sandbox/runtime.js +45 -2
  60. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  61. package/dist/sandbox/sandbox-cgroups.js +42 -0
  62. package/dist/session/managed-attempt-tools.d.ts +2 -0
  63. package/dist/session/managed-attempt-tools.js +156 -37
  64. package/dist/session/managed-command-host-load.d.ts +45 -0
  65. package/dist/session/managed-command-host-load.js +82 -0
  66. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  67. package/dist/session/mcp-argument-coercion.js +121 -0
  68. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  69. package/dist/session/phase-completion.artifacts.js +98 -25
  70. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  71. package/dist/session/phase-completion.command-validation.js +77 -0
  72. package/dist/session/phase-completion.d.ts +4 -0
  73. package/dist/session/phase-completion.helpers.js +13 -12
  74. package/dist/session/phase-completion.js +4 -0
  75. package/dist/session/phase-completion.prompts.js +6 -1
  76. package/dist/session/phase-completion.runtime.d.ts +5 -3
  77. package/dist/session/phase-completion.runtime.js +49 -19
  78. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  79. package/dist/session/phase-completion.schema-parts.js +188 -0
  80. package/dist/session/phase-completion.schemas.d.ts +3 -3
  81. package/dist/session/phase-completion.schemas.js +184 -209
  82. package/dist/session/phase-completion.validation.d.ts +2 -3
  83. package/dist/session/phase-completion.validation.js +46 -92
  84. package/dist/session/pre-publication-host-load.d.ts +27 -0
  85. package/dist/session/pre-publication-host-load.js +111 -0
  86. package/dist/session/pre-publication-process.d.ts +3 -0
  87. package/dist/session/pre-publication-process.js +25 -12
  88. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  89. package/dist/session/pre-publication-skipped-tests.js +109 -0
  90. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  91. package/dist/session/pre-publication-step-execution.js +49 -0
  92. package/dist/session/pre-publication-validation.d.ts +9 -9
  93. package/dist/session/pre-publication-validation.js +44 -59
  94. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  95. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  96. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  97. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  98. package/dist/session/provider-cli/provider-cli.process.d.ts +32 -1
  99. package/dist/session/provider-cli/provider-cli.process.js +122 -30
  100. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  101. package/dist/session/provider-cli/provider-cli.prompts.js +16 -1
  102. package/dist/session/provider-cli/provider-cli.service.js +134 -30
  103. package/dist/session/provider-cli/provider-cli.types.d.ts +4 -0
  104. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  105. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  106. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  107. package/dist/session/provider-cli/provider-output-state.js +9 -0
  108. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  109. package/dist/session/publishable-worktree-changes.js +193 -0
  110. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  111. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  112. package/dist/session/session.base.d.ts +3 -0
  113. package/dist/session/session.service.d.ts +2 -0
  114. package/dist/session/session.service.js +21 -4
  115. package/dist/session/session.types.d.ts +3 -0
  116. package/dist/session/session.types.js +14 -2
  117. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  118. package/dist/shared/process/host-process-supervisor.js +1 -1
  119. package/dist/shared/process/process-tree.d.ts +52 -0
  120. package/dist/shared/process/process-tree.js +144 -0
  121. package/dist/shared/process/process.d.ts +67 -0
  122. package/dist/shared/process/process.js +213 -11
  123. package/dist/version.d.ts +1 -1
  124. package/dist/version.js +1 -1
  125. package/dist/worktree/dependency-warmer.d.ts +25 -0
  126. package/dist/worktree/dependency-warmer.js +46 -10
  127. package/dist/worktree/worktree.service.d.ts +10 -1
  128. package/dist/worktree/worktree.service.js +42 -2
  129. package/dist/worktree/worktree.types.d.ts +7 -0
  130. package/package.json +1 -1
@@ -4,9 +4,12 @@ import path from "node:path";
4
4
  import { isAlias, parseDocument, visit } from "yaml";
5
5
  import { readCanonicalSourceFile } from "./canonical-source-file.js";
6
6
  import { isGeneratedOutputDirectoryName } from "./generated-output-reset.js";
7
+ import { parseHostRuntimeRequirements } from "./host-runtime-requirements.js";
7
8
  export const hostRuntimeContractPath = ".forge/forge.runtime.yml";
8
9
  export const hostRuntimeTestPostgresAdminEnvironment = "FORGE_TEST_POSTGRES_ADMIN_CONNECTION_STRING";
9
10
  export const hostRuntimeLegacyTestPostgresEnvironment = "FORGE_TEST_POSTGRES_CONNECTION_STRING";
11
+ // Optional superuser login for operator-run .NET fixtures. Never reaches attempt, validation or provider processes.
12
+ export const hostRuntimeTestPostgresProvisionerEnvironment = "FORGE_TEST_POSTGRES_PROVISIONER_CONNECTION_STRING";
10
13
  const maximumContractBytes = 64 * 1024;
11
14
  const maximumDepth = 12;
12
15
  // Every discovery scan stops after this many directory entries. A monorepo needs a few
@@ -45,7 +48,7 @@ const ignoredDiscoveryDirectories = new Set([
45
48
  "vendor",
46
49
  "venv",
47
50
  ]);
48
- const topLevelKeys = new Set(["schemaVersion", "runtime"]);
51
+ const topLevelKeys = new Set(["schemaVersion", "runtime", "requires", "costHints"]);
49
52
  const runtimeKeys = new Set(["hostConcurrency", "ports", "playwright", "browserProfile", "singletonResources"]);
50
53
  const portKeys = new Set(["adapter", "launch", "env", "baseUrlEnv", "format"]);
51
54
  const launchKeys = new Set(["command", "args", "workingDirectory", "environment"]);
@@ -547,6 +550,7 @@ export function validateHostRuntimeContract(source) {
547
550
  throw new Error("runtime_contract_invalid: runtime.browserProfile must be isolated.");
548
551
  }
549
552
  const ports = parsePorts(runtime.ports);
553
+ const requires = parseHostRuntimeRequirements(root.requires, root.costHints);
550
554
  return {
551
555
  schemaVersion: 1,
552
556
  runtime: {
@@ -556,6 +560,7 @@ export function validateHostRuntimeContract(source) {
556
560
  browserProfile,
557
561
  singletonResources: parseSingletonResources(runtime.singletonResources),
558
562
  },
563
+ ...(requires ? { requires } : {}),
559
564
  };
560
565
  }
561
566
  function parsePlaywright(value, ports) {
@@ -1,4 +1,5 @@
1
- import type { RunOnceDispatchPacket } from "../session/session.types.js";
1
+ import type { HostRequirementsCheck } from "./host-runtime-requirements-check.js";
2
+ import { type RunOnceDispatchPacket } from "../session/session.types.js";
2
3
  import { type ProviderProcessRunner } from "../session/provider-cli/provider-cli.process.js";
3
4
  import { type RuntimeIsolationLease } from "./runtime-isolation-lease.js";
4
5
  import { type LoadedHostRuntimeContract } from "./host-runtime-contract.js";
@@ -12,6 +13,8 @@ import { type MemoryAdmissionDiagnostics } from "./memory-capacity.js";
12
13
  import { PlaywrightHostRuntimeAdapter } from "./playwright-host-runtime-adapter.js";
13
14
  import { HostParallelPromotionStore } from "./host-runtime-promotion.js";
14
15
  import { type HostProcessRecovery } from "../shared/process/host-process-recovery.js";
16
+ import { HostLoadGovernor } from "./host-load-governor.js";
17
+ import { type HostLoadGovernorSource } from "./host-load-sampler.js";
15
18
  export interface HostRuntimeLeaseStart {
16
19
  readonly lease: RuntimeIsolationLease;
17
20
  readonly environment: Readonly<Record<string, string>>;
@@ -25,7 +28,7 @@ export interface HostRuntimeAdmissionCheckpoint {
25
28
  }
26
29
  export type HostRuntimeAdmissionCheckpointHandler = (checkpoint: HostRuntimeAdmissionCheckpoint) => void | Promise<void>;
27
30
  export interface HostRuntimeProjectCheckpoint {
28
- readonly code: "host_runtime_build_started" | "host_runtime_build_cached" | "host_runtime_build_completed" | "host_runtime_database_provisioned";
31
+ readonly code: "host_runtime_build_started" | "host_runtime_build_waiting_for_host_capacity" | "host_runtime_build_cached" | "host_runtime_build_completed" | "host_runtime_database_provisioned";
29
32
  readonly message: string;
30
33
  readonly data?: Readonly<Record<string, unknown>>;
31
34
  }
@@ -92,6 +95,7 @@ export interface HostNodeRuntimeLaunch<T> extends NodeRuntimeAdapterLaunch<T> {
92
95
  readonly runtimeLease: RuntimeIsolationLease;
93
96
  }
94
97
  export interface HostRuntimeLeaseRuntime {
98
+ setRequirementsCheck?(check: HostRequirementsCheck | null): void;
95
99
  acquirePreparation?(dispatch: RunOnceDispatchPacket, signal?: AbortSignal): Promise<readonly string[]>;
96
100
  acquire(dispatch: RunOnceDispatchPacket, signal?: AbortSignal): Promise<readonly string[]>;
97
101
  start(dispatch: RunOnceDispatchPacket, worktreePath: string, signal?: AbortSignal, onAdmissionCheckpoint?: HostRuntimeAdmissionCheckpointHandler): Promise<HostRuntimeLeaseStart>;
@@ -104,7 +108,10 @@ export interface HostRuntimeLeaseRuntime {
104
108
  hasForegroundDemand?(): boolean;
105
109
  reap?(options: HostRuntimeReapOptions): Promise<HostRuntimeReapReport>;
106
110
  snapshot?(): HostRuntimeCapacitySnapshot;
111
+ /** Variables that let the completion MCP server share this host's load governor. */
112
+ hostLoadChildEnvironment?(): Readonly<Record<string, string>>;
107
113
  }
114
+ export type HostRuntimeAdmissionPriority = "foreground" | "background";
108
115
  export interface HostCapacityResourceSample {
109
116
  readonly totalMemoryBytes: number;
110
117
  readonly availableMemoryBytes: number;
@@ -143,7 +150,13 @@ export declare class HostRuntimeLeaseManager implements HostRuntimeLeaseRuntime
143
150
  private readonly capacityConfiguration;
144
151
  private readonly memoryAvailability;
145
152
  private readonly executionRoot;
146
- constructor(stateRoot: string, portBroker?: HostPortBroker, nodeAdapter?: NodeHostRuntimeAdapter, processSupervisors?: AttemptProcessSupervisorRegistry, processRunner?: ProviderProcessRunner, listenerInspector?: HostListenerInspector, promotionStore?: HostParallelPromotionStore, playwrightAdapter?: PlaywrightHostRuntimeAdapter, processRecovery?: HostProcessRecovery, capacityResourceSample?: HostCapacityResourceSample | undefined, executionRoot?: string, databaseBroker?: AttemptDatabaseBroker | null);
153
+ /** Host-wide admission for heavy steps (decision 0013); inert unless FORGE_HOST_LOAD_GOVERNOR=on. */
154
+ readonly hostLoadGovernor: HostLoadGovernor;
155
+ private requirementsCheck;
156
+ /** Installs the decision 0013 accept-time requirements recheck for host attempts. */
157
+ setRequirementsCheck(check: HostRequirementsCheck | null): void;
158
+ constructor(stateRoot: string, portBroker?: HostPortBroker, nodeAdapter?: NodeHostRuntimeAdapter, processSupervisors?: AttemptProcessSupervisorRegistry, processRunner?: ProviderProcessRunner, listenerInspector?: HostListenerInspector, promotionStore?: HostParallelPromotionStore, playwrightAdapter?: PlaywrightHostRuntimeAdapter, processRecovery?: HostProcessRecovery, capacityResourceSample?: HostCapacityResourceSample | undefined, executionRoot?: string, databaseBroker?: AttemptDatabaseBroker | null, hostLoad?: HostLoadGovernorSource | null);
159
+ hostLoadChildEnvironment(): Readonly<Record<string, string>>;
147
160
  reap(options: HostRuntimeReapOptions): Promise<HostRuntimeReapReport>;
148
161
  snapshot(): HostRuntimeCapacitySnapshot;
149
162
  hasForegroundDemand(): boolean;
@@ -215,3 +228,4 @@ export declare class HostRuntimeCapacityRequestImpossibleError extends Error {
215
228
  }
216
229
  export declare function hostRuntimeEventResources(lease: RuntimeIsolationLease, runtimeContract?: LoadedHostRuntimeContract, executionClass?: HostRuntimeExecutionClass): Record<string, unknown>;
217
230
  export declare function hostRuntimeSingletonKeys(dispatch: RunOnceDispatchPacket): readonly string[];
231
+ export declare function runtimeAdmissionPriority(dispatch: RunOnceDispatchPacket): HostRuntimeAdmissionPriority;
@@ -7,6 +7,7 @@ import { assertHostAttemptRootIdentity, retainHostDiagnostics } from "./host-dia
7
7
  import { assertHostExecutionRoot, compactHostAttemptId } from "./host-execution-root.js";
8
8
  import { PreparedRuntimeReadiness } from "./prepared-runtime-readiness.js";
9
9
  import { preparedRuntimeIdentity } from "./prepared-runtime-identity.js";
10
+ import { ForgeFailureError } from "../session/session.types.js";
10
11
  import { resolveExistingDirectoryPath } from "../shared/path/path.js";
11
12
  import { formatBytes } from "../shared/format/format-bytes.js";
12
13
  import { redactText } from "../shared/redaction/redaction.js";
@@ -30,6 +31,11 @@ import { readCanonicalSourceFile } from "./canonical-source-file.js";
30
31
  import { readPinnedSourceDirectory } from "./pinned-source-directory.js";
31
32
  import { architectMinimumWorkspaceEstimateBytes } from "./workspace-resource-estimator.js";
32
33
  import { createAspNetRuntimePrebuildPlan, ensureAspNetRuntimePrebuilt, resolveWorktreeCommitSha, } from "./aspnet-runtime-prebuild.js";
34
+ import { HostLoadGovernor } from "./host-load-governor.js";
35
+ import { hostLoadChildEnvironment } from "./host-load-child-environment.js";
36
+ import { aspNetPrebuildStepClass } from "./host-load-step-class.js";
37
+ import { attachSupervisedStepProcess, runHostGovernedStep } from "./host-load-step-run.js";
38
+ import { HostLoadSampler } from "./host-load-sampler.js";
33
39
  const hostCapacityWaiterScanLimit = 64;
34
40
  const maximumProcessRecoveryMetadataBytes = 1024 * 1024;
35
41
  export class HostRuntimeLeaseManager {
@@ -64,7 +70,14 @@ export class HostRuntimeLeaseManager {
64
70
  capacityConfiguration;
65
71
  memoryAvailability;
66
72
  executionRoot;
67
- constructor(stateRoot, portBroker = new HostPortBroker(), nodeAdapter, processSupervisors = new AttemptProcessSupervisorRegistry(), processRunner = new StreamingProviderProcessRunner(), listenerInspector = new HostListenerInspector(), promotionStore = new HostParallelPromotionStore(stateRoot), playwrightAdapter = new PlaywrightHostRuntimeAdapter(), processRecovery = new ExactHostProcessRecovery(), capacityResourceSample, executionRoot, databaseBroker = null) {
73
+ /** Host-wide admission for heavy steps (decision 0013); inert unless FORGE_HOST_LOAD_GOVERNOR=on. */
74
+ hostLoadGovernor;
75
+ requirementsCheck = null;
76
+ /** Installs the decision 0013 accept-time requirements recheck for host attempts. */
77
+ setRequirementsCheck(check) {
78
+ this.requirementsCheck = check;
79
+ }
80
+ constructor(stateRoot, portBroker = new HostPortBroker(), nodeAdapter, processSupervisors = new AttemptProcessSupervisorRegistry(), processRunner = new StreamingProviderProcessRunner(), listenerInspector = new HostListenerInspector(), promotionStore = new HostParallelPromotionStore(stateRoot), playwrightAdapter = new PlaywrightHostRuntimeAdapter(), processRecovery = new ExactHostProcessRecovery(), capacityResourceSample, executionRoot, databaseBroker = null, hostLoad = null) {
68
81
  this.stateRoot = stateRoot;
69
82
  this.processSupervisors = processSupervisors;
70
83
  this.processRunner = processRunner;
@@ -74,6 +87,7 @@ export class HostRuntimeLeaseManager {
74
87
  this.processRecovery = processRecovery;
75
88
  this.capacityResourceSample = capacityResourceSample;
76
89
  this.databaseBroker = databaseBroker;
90
+ this.hostLoadGovernor = new HostLoadGovernor({ stateRoot, load: hostLoad ?? new HostLoadSampler() });
77
91
  this.executionRoot = path.resolve(executionRoot ?? stateRoot);
78
92
  if (executionRoot !== undefined)
79
93
  assertHostExecutionRoot(this.executionRoot);
@@ -83,7 +97,12 @@ export class HostRuntimeLeaseManager {
83
97
  this.capacityConfiguration = loadHostCapacityConfiguration(capacityResourceSample);
84
98
  this.memoryAvailability = new RecoveryStabilizedMemory(this.capacityConfiguration.memoryRecoverySamples, this.capacityConfiguration.memoryRecoverySampleIntervalMs);
85
99
  }
100
+ hostLoadChildEnvironment() {
101
+ return this.hostLoadGovernor.enabled ? hostLoadChildEnvironment(this.stateRoot) : {};
102
+ }
86
103
  async reap(options) {
104
+ // Heavy-step tokens whose owner died or whose lease lapsed are returned first.
105
+ await this.hostLoadGovernor.reclaim().catch(() => undefined);
87
106
  await this.refreshKnownPromotions();
88
107
  const recoveredAttempts = [];
89
108
  const report = {
@@ -208,6 +227,11 @@ export class HostRuntimeLeaseManager {
208
227
  // drop that met a lingering session) are removed once no live lease holds them.
209
228
  // A degraded lease may still own running processes after a restart, so its database is kept.
210
229
  await this.databaseBroker?.reapOrphans(id => this.active.has(id) || this.degraded.has(id)).catch(() => undefined);
230
+ // Heavy-step tokens of a dead owner with no recorded process tree (an attempt that
231
+ // ended with a crashed bridge or MCP server) are returned once no live lease holds
232
+ // their attempt; a degraded lease may still own the running step, so its tokens stay.
233
+ await this.hostLoadGovernor.releaseOrphaned(token => !token.dispatchAttemptId
234
+ || (!this.active.has(token.dispatchAttemptId) && !this.degraded.has(token.dispatchAttemptId))).catch(() => undefined);
211
235
  return report;
212
236
  }
213
237
  snapshot() {
@@ -925,6 +949,15 @@ export class HostRuntimeLeaseManager {
925
949
  let attemptRootIdentity = null;
926
950
  try {
927
951
  const runtimeContract = await loadHostRuntimeContract(normalizedWorktreePath);
952
+ // Decision 0013 accept-time recheck. Readiness probes are exempt: they are how the
953
+ // API learns the requirements in the first place.
954
+ const unmetRequirements = dispatch.workItem.kind === "runtime_readiness"
955
+ ? []
956
+ : this.requirementsCheck?.(runtimeContract.contract.requires) ?? [];
957
+ if (unmetRequirements.length > 0) {
958
+ // Typed, so the API receives the retryable code and re-places the work (not bridge.execution_failed).
959
+ throw new ForgeFailureError("placement_requirements_unmet", `placement_requirements_unmet: this host does not meet the project's requirements: ${unmetRequirements.join("; ")}.`);
960
+ }
928
961
  if (runtimeContract.contract.runtime.hostConcurrency === "disabled") {
929
962
  throw new Error("host_runtime_disabled: project runtime configuration requires Docker execution.");
930
963
  }
@@ -1226,7 +1259,29 @@ export class HostRuntimeLeaseManager {
1226
1259
  message: `Preparing the ASP.NET runtime for commit ${active.inputCommitSha.slice(0, 12)} before binding its assigned port.`,
1227
1260
  data: { input_commit_sha: active.inputCommitSha, project_path: prebuild.projectPath },
1228
1261
  });
1229
- const build = await ensureAspNetRuntimePrebuilt(prebuild, async (plan, buildSignal) => await executeAspNetRuntimeBuild(active.processSupervisor, logDirectory, plan, buildSignal, capabilitySecrets), signal);
1262
+ let hostLoadWaitMs = null;
1263
+ const build = await ensureAspNetRuntimePrebuilt(prebuild,
1264
+ // Only a real build (not a verified cache hit) takes a host load token.
1265
+ async (plan, buildSignal) => await runHostGovernedStep(this.hostLoadGovernor, {
1266
+ classification: aspNetPrebuildStepClass,
1267
+ label: prebuild.projectPath,
1268
+ dispatchAttemptId,
1269
+ priority: this.admissions.get(dispatchAttemptId)?.priority ?? "foreground",
1270
+ signal: buildSignal,
1271
+ onWaiting: async (decision) => await onProjectCheckpoint?.({
1272
+ code: "host_runtime_build_waiting_for_host_capacity",
1273
+ message: `The ASP.NET runtime build is waiting for host capacity: ${decision.detail}`,
1274
+ data: { status: "waiting_for_host_capacity", step_class: aspNetPrebuildStepClass.stepClass, reason: decision.reason },
1275
+ }),
1276
+ }, async (waitMs, control) => {
1277
+ hostLoadWaitMs = waitMs;
1278
+ // A reclaimed token stops the build: its capacity is no longer reserved. So does a
1279
+ // build whose process tree cannot be recorded on its token (a reclaim could not stop it).
1280
+ const unrecorded = new AbortController();
1281
+ const stepSignal = anySignal(buildSignal, control.fenced, unrecorded.signal);
1282
+ return await executeAspNetRuntimeBuild(active.processSupervisor, logDirectory, plan, stepSignal, capabilitySecrets, async (metadataPath) => await attachSupervisedStepProcess(control, metadataPath)
1283
+ .catch((error) => { unrecorded.abort(error); }));
1284
+ }), signal);
1230
1285
  await onProjectCheckpoint?.({
1231
1286
  code: build.cacheHit ? "host_runtime_build_cached" : "host_runtime_build_completed",
1232
1287
  message: build.cacheHit
@@ -1236,6 +1291,7 @@ export class HostRuntimeLeaseManager {
1236
1291
  input_commit_sha: active.inputCommitSha,
1237
1292
  build_fingerprint: build.fingerprint,
1238
1293
  receipt_path: build.receiptPath,
1294
+ ...(hostLoadWaitMs === null ? {} : { host_load_wait_ms: hostLoadWaitMs }),
1239
1295
  },
1240
1296
  });
1241
1297
  }
@@ -1420,6 +1476,9 @@ export class HostRuntimeLeaseManager {
1420
1476
  if (!preservePreparation)
1421
1477
  this.pendingRenewals.delete(dispatchAttemptId);
1422
1478
  if (!active) {
1479
+ // Queued steps are cancelled and running ones stopped; each returns its own
1480
+ // token once its processes are gone (never before, or capacity is reused early).
1481
+ this.hostLoadGovernor.stopAttempt(dispatchAttemptId);
1423
1482
  this.cancelAdmissionWaiters(dispatchAttemptId, fencingToken, "Managed host admission was released before acquisition.");
1424
1483
  this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
1425
1484
  this.releaseParallelProjects(dispatchAttemptId, fencingToken);
@@ -1429,6 +1488,11 @@ export class HostRuntimeLeaseManager {
1429
1488
  if (active.lease.fencingToken !== fencingToken)
1430
1489
  return null;
1431
1490
  active.releasing = true;
1491
+ // Attempt teardown cancels the attempt's queued heavy steps and stops its running
1492
+ // ones. Each running step (an ASP.NET prebuild, an install, a validation step)
1493
+ // returns its own token only after its processes have exited, so the capacity is
1494
+ // not reused while, say, a build is still being terminated.
1495
+ this.hostLoadGovernor.stopAttempt(dispatchAttemptId);
1432
1496
  for (const pending of active.pendingAdapterLaunches.values()) {
1433
1497
  pending.controller.abort("Host runtime release cancelled the pending adapter launch.");
1434
1498
  }
@@ -1440,6 +1504,15 @@ export class HostRuntimeLeaseManager {
1440
1504
  try {
1441
1505
  if (!active.runtimeResourcesReleased) {
1442
1506
  await active.processSupervisor.stopAll(fencingToken, "Host runtime lease released.");
1507
+ // The attempt's MCP servers and process trees are stopped now; tokens they held
1508
+ // belong to dead owners and go back to the host budget at once, including any
1509
+ // without a recorded process tree (their steps were inside the stopped trees).
1510
+ await this.hostLoadGovernor.reclaim().catch(() => undefined);
1511
+ await this.hostLoadGovernor.releaseOrphaned(token => token.dispatchAttemptId === dispatchAttemptId)
1512
+ .catch(() => undefined);
1513
+ // This bridge's own steps whose trees only stopAll could prove gone (a supervised
1514
+ // validation step whose termination failed earlier) return their tokens now.
1515
+ await this.hostLoadGovernor.releaseRetainedAfterTeardown(dispatchAttemptId).catch(() => undefined);
1443
1516
  await releaseAdapterResources(active.adapterCleanups);
1444
1517
  if (active.databaseCapability && this.databaseBroker) {
1445
1518
  // A database the broker cannot drop now is reaped later; it must not hold host capacity.
@@ -2140,7 +2213,12 @@ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClas
2140
2213
  environment.FORGE_BASE_URL = resolvedBaseUrls[0];
2141
2214
  return environment;
2142
2215
  }
2143
- async function executeAspNetRuntimeBuild(supervisor, logDirectory, plan, signal, exactSecrets = []) {
2216
+ function anySignal(...signals) {
2217
+ return AbortSignal.any(signals.filter((signal) => signal !== undefined));
2218
+ }
2219
+ async function executeAspNetRuntimeBuild(supervisor, logDirectory, plan, signal, exactSecrets = [],
2220
+ /** Once the build's supervised tree is up: records it on the build's host load token. */
2221
+ onStarted) {
2144
2222
  const childName = `runtime-build-${plan.fingerprint.slice(-12)}`;
2145
2223
  const stdoutLogPath = path.join(logDirectory, `${childName}.stdout.log`);
2146
2224
  const stderrLogPath = path.join(logDirectory, `${childName}.stderr.log`);
@@ -2165,6 +2243,7 @@ async function executeAspNetRuntimeBuild(supervisor, logDirectory, plan, signal,
2165
2243
  await append(stderrLogPath, line);
2166
2244
  },
2167
2245
  }, signal, { maxStartAttempts: 2, retryDelayMs: 250 });
2246
+ await onStarted?.(child.metadataPath);
2168
2247
  const result = await child.result;
2169
2248
  return {
2170
2249
  exitCode: result.exitCode,
@@ -2207,7 +2286,7 @@ function runtimeExecutionClass(dispatch) {
2207
2286
  ? "analysis_only"
2208
2287
  : "managed_runtime";
2209
2288
  }
2210
- function runtimeAdmissionPriority(dispatch) {
2289
+ export function runtimeAdmissionPriority(dispatch) {
2211
2290
  return dispatch.execution.lane.trim().toLowerCase() === "runtime_readiness"
2212
2291
  || dispatch.cycleRun.phase.trim().toLowerCase() === "readiness_probe"
2213
2292
  ? "background"
@@ -145,12 +145,24 @@ export function hostRuntimeContractFingerprint(runtimeContract) {
145
145
  const canonical = JSON.stringify({
146
146
  schemaVersion: runtimeContract.contract.schemaVersion,
147
147
  runtime: runtimeContract.contract.runtime,
148
+ // Requirements join the fingerprint only when declared, so fingerprints of contracts
149
+ // written before decision 0013 (and their stored promotions) stay unchanged.
150
+ ...requirementsFingerprintPart(runtimeContract.contract.requires),
148
151
  derivedCandidateFingerprint: runtimeContract.source === "derived"
149
152
  ? runtimeContract.discovery?.candidateFingerprint ?? null
150
153
  : null,
151
154
  });
152
155
  return `sha256:${createHash("sha256").update(canonical).digest("hex")}`;
153
156
  }
157
+ // Cost hints are estimates, not placement constraints: they never change the fingerprint.
158
+ function requirementsFingerprintPart(requires) {
159
+ if (!requires)
160
+ return {};
161
+ const { costHints: _costHints, ...constraints } = requires;
162
+ const declared = constraints.minThreads !== null || constraints.minMemoryGiB !== null || constraints.toolchains.length > 0
163
+ || constraints.docker || constraints.playwright !== null || constraints.testPostgres !== null;
164
+ return declared ? { requires: constraints } : {};
165
+ }
154
166
  export function hostRuntimeParallelEligible(runtimeContract) {
155
167
  const runtime = runtimeContract.contract.runtime;
156
168
  const launchedPorts = runtime.ports.filter(port => port.launch !== null);
@@ -0,0 +1,17 @@
1
+ import type { HostRuntimeRequirements } from "./host-runtime-requirements.js";
2
+ /** What this bridge host offers, for the accept-time requirements recheck (decision 0013). */
3
+ export interface HostRequirementFacts {
4
+ readonly logicalThreads: number;
5
+ readonly totalMemoryBytes: number;
6
+ readonly availableToolchains: readonly string[];
7
+ readonly dockerAvailable: boolean;
8
+ readonly browserLaunch: boolean;
9
+ readonly testPostgresSuperuser: boolean | null;
10
+ }
11
+ export type HostRequirementsCheck = (requires: HostRuntimeRequirements | null | undefined) => readonly string[];
12
+ /**
13
+ * Reasons this host fails a host-mode attempt's declared requirements. The API filters on
14
+ * stored requirements; this recheck closes the gap when they were not reported yet or the
15
+ * attempt's contract differs from the probed one. Mirrors the API's wording.
16
+ */
17
+ export declare function unmetHostRuntimeRequirements(requires: HostRuntimeRequirements | null | undefined, facts: HostRequirementFacts): readonly string[];
@@ -0,0 +1,29 @@
1
+ const gib = 1024 * 1024 * 1024;
2
+ /**
3
+ * Reasons this host fails a host-mode attempt's declared requirements. The API filters on
4
+ * stored requirements; this recheck closes the gap when they were not reported yet or the
5
+ * attempt's contract differs from the probed one. Mirrors the API's wording.
6
+ */
7
+ export function unmetHostRuntimeRequirements(requires, facts) {
8
+ if (!requires)
9
+ return [];
10
+ const unmet = [];
11
+ if (requires.minThreads !== null && facts.logicalThreads < requires.minThreads) {
12
+ unmet.push(`needs ≥ ${requires.minThreads} threads; this host has ${facts.logicalThreads}`);
13
+ }
14
+ if (requires.minMemoryGiB !== null && facts.totalMemoryBytes / gib < requires.minMemoryGiB) {
15
+ unmet.push(`needs ≥ ${requires.minMemoryGiB} GiB; this host has ${(Math.floor(facts.totalMemoryBytes / gib * 100) / 100)}`);
16
+ }
17
+ const available = new Set(facts.availableToolchains.map(name => name.toLowerCase()));
18
+ const missing = requires.toolchains.filter(name => !available.has(name));
19
+ if (missing.length > 0)
20
+ unmet.push(`needs ${missing.join(", ")}; this host does not have ${missing.length === 1 ? "it" : "them"}`);
21
+ if (requires.docker && !facts.dockerAvailable)
22
+ unmet.push("needs Docker; this host does not have it");
23
+ if (requires.testPostgres?.superuser && !facts.dockerAvailable && facts.testPostgresSuperuser !== true) {
24
+ unmet.push("needs Docker or a superuser test database; this host has neither");
25
+ }
26
+ if (requires.playwright && !facts.browserLaunch)
27
+ unmet.push("needs Playwright browsers; this host cannot launch them");
28
+ return unmet;
29
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Project host requirements declared in `.forge/forge.runtime.yml` (decision 0013 §3).
3
+ *
4
+ * The bridge parses them with the runtime contract and reports them, with the contract
5
+ * fingerprint, in its readiness payload. The API stores them per fingerprint and uses them
6
+ * as hard placement filters. A contract without a `requires` section has no requirements.
7
+ */
8
+ export interface HostRuntimePlaywrightRequirement {
9
+ /** Pinned Playwright revision. Recorded; enforced once bridges probe browser revisions. */
10
+ readonly revision: string | null;
11
+ }
12
+ export interface HostRuntimeTestPostgresRequirement {
13
+ readonly extensions: readonly string[];
14
+ /** Suites need a superuser role (or Docker-backed Testcontainers). */
15
+ readonly superuser: boolean;
16
+ }
17
+ export interface HostRuntimeCostHint {
18
+ readonly cores: number | null;
19
+ readonly memoryGiB: number | null;
20
+ }
21
+ export interface HostRuntimeRequirements {
22
+ readonly minThreads: number | null;
23
+ readonly minMemoryGiB: number | null;
24
+ readonly toolchains: readonly string[];
25
+ /** Suites need a Docker engine (for example Testcontainers). */
26
+ readonly docker: boolean;
27
+ readonly playwright: HostRuntimePlaywrightRequirement | null;
28
+ readonly testPostgres: HostRuntimeTestPostgresRequirement | null;
29
+ /** Accepted and reported, not yet used for placement. */
30
+ readonly costHints: Readonly<Record<string, HostRuntimeCostHint>>;
31
+ }
32
+ /**
33
+ * Validates the optional top-level `requires` and `costHints` sections. Returns null when
34
+ * neither section is present, so contracts written before decision 0013 keep their meaning.
35
+ */
36
+ export declare function parseHostRuntimeRequirements(requires: unknown, costHints: unknown): HostRuntimeRequirements | null;
@@ -0,0 +1,117 @@
1
+ const requiresKeys = new Set(["minThreads", "minMemoryGiB", "toolchains", "docker", "playwright", "testPostgres"]);
2
+ const playwrightKeys = new Set(["revision"]);
3
+ const testPostgresKeys = new Set(["extensions", "superuser"]);
4
+ const costHintKeys = new Set(["cores", "memoryGiB"]);
5
+ const toolchainPattern = /^[a-z][a-z0-9_.-]{0,63}$/u;
6
+ const extensionPattern = /^[a-z][a-z0-9_]{0,62}$/u;
7
+ const stepClassPattern = /^[a-z][a-z0-9_.:-]{0,127}$/u;
8
+ const revisionPattern = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/u;
9
+ /**
10
+ * Validates the optional top-level `requires` and `costHints` sections. Returns null when
11
+ * neither section is present, so contracts written before decision 0013 keep their meaning.
12
+ */
13
+ export function parseHostRuntimeRequirements(requires, costHints) {
14
+ if (isAbsent(requires) && isAbsent(costHints))
15
+ return null;
16
+ const section = isAbsent(requires) ? {} : object(requires, "requires");
17
+ rejectUnknownKeys(section, requiresKeys, "requires");
18
+ return {
19
+ minThreads: optionalNumber(section.minThreads, "requires.minThreads", 1, 1024, true),
20
+ minMemoryGiB: optionalNumber(section.minMemoryGiB, "requires.minMemoryGiB", 0.125, 4096, false),
21
+ toolchains: nameList(section.toolchains, "requires.toolchains", toolchainPattern, 32),
22
+ docker: optionalBoolean(section.docker, "requires.docker"),
23
+ playwright: parsePlaywright(section.playwright),
24
+ testPostgres: parseTestPostgres(section.testPostgres),
25
+ costHints: parseCostHints(costHints),
26
+ };
27
+ }
28
+ function parsePlaywright(value) {
29
+ if (isAbsent(value) || value === false)
30
+ return null;
31
+ if (value === true)
32
+ return { revision: null };
33
+ const playwright = object(value, "requires.playwright");
34
+ rejectUnknownKeys(playwright, playwrightKeys, "requires.playwright");
35
+ if (isAbsent(playwright.revision))
36
+ return { revision: null };
37
+ if (typeof playwright.revision !== "string" || !revisionPattern.test(playwright.revision.trim())) {
38
+ throw invalid("requires.playwright.revision must be a version or revision string.");
39
+ }
40
+ return { revision: playwright.revision.trim() };
41
+ }
42
+ function parseTestPostgres(value) {
43
+ if (isAbsent(value))
44
+ return null;
45
+ const testPostgres = object(value, "requires.testPostgres");
46
+ rejectUnknownKeys(testPostgres, testPostgresKeys, "requires.testPostgres");
47
+ return {
48
+ extensions: nameList(testPostgres.extensions, "requires.testPostgres.extensions", extensionPattern, 16),
49
+ superuser: optionalBoolean(testPostgres.superuser, "requires.testPostgres.superuser"),
50
+ };
51
+ }
52
+ function parseCostHints(value) {
53
+ if (isAbsent(value))
54
+ return {};
55
+ const hints = object(value, "costHints");
56
+ const entries = Object.entries(hints);
57
+ if (entries.length > 32)
58
+ throw invalid("costHints may declare at most 32 step classes.");
59
+ const parsed = {};
60
+ for (const [stepClass, hint] of entries.sort(([left], [right]) => left.localeCompare(right))) {
61
+ if (!stepClassPattern.test(stepClass))
62
+ throw invalid(`costHints step class '${stepClass}' is invalid.`);
63
+ const entry = object(hint, `costHints.${stepClass}`);
64
+ rejectUnknownKeys(entry, costHintKeys, `costHints.${stepClass}`);
65
+ parsed[stepClass] = {
66
+ cores: optionalNumber(entry.cores, `costHints.${stepClass}.cores`, 0.01, 1024, false),
67
+ memoryGiB: optionalNumber(entry.memoryGiB, `costHints.${stepClass}.memoryGiB`, 0.01, 4096, false),
68
+ };
69
+ }
70
+ return parsed;
71
+ }
72
+ function optionalNumber(value, label, minimum, maximum, integer) {
73
+ if (isAbsent(value))
74
+ return null;
75
+ if (typeof value !== "number" || !Number.isFinite(value) || value < minimum || value > maximum
76
+ || (integer && !Number.isSafeInteger(value))) {
77
+ throw invalid(`${label} must be ${integer ? "an integer" : "a number"} between ${minimum} and ${maximum}.`);
78
+ }
79
+ return value;
80
+ }
81
+ function nameList(value, label, pattern, maximum) {
82
+ if (isAbsent(value))
83
+ return [];
84
+ if (!Array.isArray(value) || value.length > maximum) {
85
+ throw invalid(`${label} must be a list with at most ${maximum} entries.`);
86
+ }
87
+ const names = value.map((entry, index) => {
88
+ const name = typeof entry === "string" ? entry.trim().toLowerCase() : "";
89
+ if (!pattern.test(name))
90
+ throw invalid(`${label}[${index}] is invalid.`);
91
+ return name;
92
+ });
93
+ return [...new Set(names)].sort((left, right) => left.localeCompare(right));
94
+ }
95
+ function optionalBoolean(value, label) {
96
+ if (isAbsent(value))
97
+ return false;
98
+ if (typeof value !== "boolean")
99
+ throw invalid(`${label} must be true or false.`);
100
+ return value;
101
+ }
102
+ function isAbsent(value) {
103
+ return value === undefined || value === null;
104
+ }
105
+ function object(value, label) {
106
+ if (!value || typeof value !== "object" || Array.isArray(value))
107
+ throw invalid(`${label} must be an object.`);
108
+ return value;
109
+ }
110
+ function rejectUnknownKeys(value, allowed, label) {
111
+ const unknown = Object.keys(value).find(key => !allowed.has(key));
112
+ if (unknown)
113
+ throw invalid(`unknown ${label} key '${unknown}'.`);
114
+ }
115
+ function invalid(message) {
116
+ return new Error(`runtime_contract_invalid: ${message}`);
117
+ }
@@ -0,0 +1,107 @@
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";
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
+ private release;
86
+ /** Queues the newest state for a request; at most one delivery per request is in flight. */
87
+ private respond;
88
+ private pump;
89
+ }
90
+ /**
91
+ * Adds the broker variables to a worker `docker create` command, just before
92
+ * its image: the protocol, and the host's maximum queue wait so the
93
+ * container's own fail-safe never fires before the host answers.
94
+ */
95
+ export declare function withSandboxHostCapacityBroker(createArgs: readonly string[], image: string, maxWaitMs: number): string[];
96
+ /** `docker exec` arguments that write one reply into the container as root. */
97
+ export declare function sandboxHostCapacityDeliveryExecArgs(container: string): string[];
98
+ /**
99
+ * The `node -e` script that writes one response file inside the container, run
100
+ * as root. It keeps the newest reply: one with a lower or equal sequence than
101
+ * the file already holds is dropped, so a late delivery can never replace a
102
+ * newer state. Replies are world-readable but owned by the writer (root, via
103
+ * `docker exec --user 0`). The directory must already be owned by that same uid
104
+ * and writable by no one else, i.e. the root-owned reply mount; it is never
105
+ * created here, where it could turn out to be the sandbox's own directory.
106
+ */
107
+ export declare const sandboxHostCapacityResponseScript: string;