@loucompanion/forge-bridge 0.1.3-dev.9bc5014a2270 → 0.1.3-dev.a58d7cd1092f

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 (168) hide show
  1. package/README.md +127 -0
  2. package/dist/bridge/bridge.base.d.ts +8 -1
  3. package/dist/bridge/bridge.service.d.ts +93 -3
  4. package/dist/bridge/bridge.service.js +1358 -47
  5. package/dist/bridge/bridge.types.d.ts +202 -1
  6. package/dist/bridge/runner-host-capabilities.d.ts +15 -0
  7. package/dist/bridge/runner-host-capabilities.js +93 -0
  8. package/dist/cleanup/cleanup.service.d.ts +14 -2
  9. package/dist/cleanup/cleanup.service.js +496 -3
  10. package/dist/cleanup/cleanup.types.d.ts +10 -0
  11. package/dist/cleanup/index.d.ts +1 -1
  12. package/dist/cleanup/index.js +1 -1
  13. package/dist/cleanup/internals.d.ts +2 -2
  14. package/dist/cleanup/internals.js +1 -1
  15. package/dist/cli/cli.help.js +47 -1
  16. package/dist/cli/cli.service.d.ts +45 -2
  17. package/dist/cli/cli.service.js +378 -26
  18. package/dist/cli/local-config.d.ts +7 -0
  19. package/dist/cli/local-config.js +51 -3
  20. package/dist/runtime/aspnet-runtime-prebuild.d.ts +36 -0
  21. package/dist/runtime/aspnet-runtime-prebuild.js +340 -0
  22. package/dist/runtime/attempt-node-runtime-launcher.d.ts +17 -0
  23. package/dist/runtime/attempt-node-runtime-launcher.js +105 -0
  24. package/dist/runtime/attempt-process-supervisor-registry.d.ts +20 -0
  25. package/dist/runtime/attempt-process-supervisor-registry.js +64 -0
  26. package/dist/runtime/attempt-process-supervisor.d.ts +97 -0
  27. package/dist/runtime/attempt-process-supervisor.js +386 -0
  28. package/dist/runtime/docker-engine-probe.d.ts +83 -0
  29. package/dist/runtime/docker-engine-probe.js +300 -0
  30. package/dist/runtime/generated-output-reset.d.ts +10 -0
  31. package/dist/runtime/generated-output-reset.js +103 -0
  32. package/dist/runtime/host-listener-inspector.d.ts +46 -0
  33. package/dist/runtime/host-listener-inspector.js +349 -0
  34. package/dist/runtime/host-port-broker.d.ts +76 -0
  35. package/dist/runtime/host-port-broker.js +333 -0
  36. package/dist/runtime/host-runtime-contract.d.ts +47 -0
  37. package/dist/runtime/host-runtime-contract.js +700 -0
  38. package/dist/runtime/host-runtime-lease.d.ts +197 -0
  39. package/dist/runtime/host-runtime-lease.js +2203 -0
  40. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  41. package/dist/runtime/host-runtime-promotion.js +159 -0
  42. package/dist/runtime/memory-capacity.d.ts +68 -0
  43. package/dist/runtime/memory-capacity.js +121 -0
  44. package/dist/runtime/node-host-runtime-adapter.d.ts +54 -0
  45. package/dist/runtime/node-host-runtime-adapter.js +284 -0
  46. package/dist/runtime/playwright-host-runtime-adapter.d.ts +21 -0
  47. package/dist/runtime/playwright-host-runtime-adapter.js +231 -0
  48. package/dist/runtime/runtime-isolation-lease.d.ts +67 -0
  49. package/dist/runtime/runtime-isolation-lease.js +158 -0
  50. package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
  51. package/dist/runtime/workspace-resource-estimator.js +174 -0
  52. package/dist/sandbox/command-runner.d.ts +4 -0
  53. package/dist/sandbox/command-runner.js +47 -0
  54. package/dist/sandbox/contract.d.ts +5 -0
  55. package/dist/sandbox/contract.js +276 -0
  56. package/dist/sandbox/event-budget.d.ts +11 -0
  57. package/dist/sandbox/event-budget.js +27 -0
  58. package/dist/sandbox/image-policy.d.ts +35 -0
  59. package/dist/sandbox/image-policy.js +247 -0
  60. package/dist/sandbox/index.d.ts +5 -0
  61. package/dist/sandbox/index.js +5 -0
  62. package/dist/sandbox/lease-watchdog.d.ts +18 -0
  63. package/dist/sandbox/lease-watchdog.js +67 -0
  64. package/dist/sandbox/preflight.d.ts +84 -0
  65. package/dist/sandbox/preflight.js +521 -0
  66. package/dist/sandbox/process.d.ts +20 -0
  67. package/dist/sandbox/process.js +209 -0
  68. package/dist/sandbox/provider-auth/codex.d.ts +26 -0
  69. package/dist/sandbox/provider-auth/codex.js +212 -0
  70. package/dist/sandbox/repository-lock.d.ts +5 -0
  71. package/dist/sandbox/repository-lock.js +121 -0
  72. package/dist/sandbox/runtime.d.ts +297 -0
  73. package/dist/sandbox/runtime.js +2338 -0
  74. package/dist/sandbox/sandbox.types.d.ts +93 -0
  75. package/dist/sandbox/sandbox.types.js +1 -0
  76. package/dist/sandbox/smoke.d.ts +76 -0
  77. package/dist/sandbox/smoke.js +380 -0
  78. package/dist/sandbox/worker-supervisor.d.ts +13 -0
  79. package/dist/sandbox/worker-supervisor.js +36 -0
  80. package/dist/sandbox/worker.d.ts +1 -0
  81. package/dist/sandbox/worker.js +225 -0
  82. package/dist/sandbox/workspace.service.d.ts +13 -0
  83. package/dist/sandbox/workspace.service.js +72 -0
  84. package/dist/session/managed-attempt-tools.d.ts +21 -0
  85. package/dist/session/managed-attempt-tools.js +912 -0
  86. package/dist/session/managed-build-coordinator.d.ts +5 -0
  87. package/dist/session/managed-build-coordinator.js +105 -0
  88. package/dist/session/managed-build-receipt.d.ts +21 -0
  89. package/dist/session/managed-build-receipt.js +335 -0
  90. package/dist/session/phase-completion.artifacts.d.ts +17 -0
  91. package/dist/session/phase-completion.artifacts.js +256 -26
  92. package/dist/session/phase-completion.d.ts +12 -2
  93. package/dist/session/phase-completion.helpers.d.ts +5 -0
  94. package/dist/session/phase-completion.helpers.js +51 -10
  95. package/dist/session/phase-completion.js +14 -3
  96. package/dist/session/phase-completion.prompts.d.ts +3 -3
  97. package/dist/session/phase-completion.prompts.js +24 -8
  98. package/dist/session/phase-completion.runtime.d.ts +13 -1
  99. package/dist/session/phase-completion.runtime.js +189 -8
  100. package/dist/session/phase-completion.schemas.js +117 -4
  101. package/dist/session/phase-completion.validation.d.ts +4 -1
  102. package/dist/session/phase-completion.validation.js +153 -22
  103. package/dist/session/pre-publication-validation.d.ts +46 -0
  104. package/dist/session/pre-publication-validation.js +208 -0
  105. package/dist/session/provider-cli/ci-repair-readiness.d.ts +16 -0
  106. package/dist/session/provider-cli/ci-repair-readiness.js +110 -0
  107. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +3 -2
  108. package/dist/session/provider-cli/provider-cli.artifacts.js +65 -7
  109. package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
  110. package/dist/session/provider-cli/provider-cli.deterministic.d.ts +2 -0
  111. package/dist/session/provider-cli/provider-cli.deterministic.js +66 -9
  112. package/dist/session/provider-cli/provider-cli.process.d.ts +26 -0
  113. package/dist/session/provider-cli/provider-cli.process.js +474 -23
  114. package/dist/session/provider-cli/provider-cli.prompts.d.ts +16 -2
  115. package/dist/session/provider-cli/provider-cli.prompts.js +224 -24
  116. package/dist/session/provider-cli/provider-cli.qa-sidecars.js +1 -0
  117. package/dist/session/provider-cli/provider-cli.runtime.d.ts +1 -1
  118. package/dist/session/provider-cli/provider-cli.runtime.js +6 -3
  119. package/dist/session/provider-cli/provider-cli.service.d.ts +26 -3
  120. package/dist/session/provider-cli/provider-cli.service.js +646 -90
  121. package/dist/session/provider-cli/provider-cli.types.d.ts +5 -0
  122. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  123. package/dist/session/provider-cli/provider-output-state.js +91 -16
  124. package/dist/session/provider-cli/provider-usage.d.ts +7 -0
  125. package/dist/session/provider-cli/provider-usage.js +28 -5
  126. package/dist/session/session-redaction.d.ts +3 -0
  127. package/dist/session/session-redaction.js +38 -0
  128. package/dist/session/session.base.d.ts +6 -1
  129. package/dist/session/session.service.d.ts +8 -2
  130. package/dist/session/session.service.js +530 -42
  131. package/dist/session/session.types.d.ts +124 -1
  132. package/dist/session/session.types.js +231 -4
  133. package/dist/shared/format/format-bytes.d.ts +1 -0
  134. package/dist/shared/format/format-bytes.js +9 -0
  135. package/dist/shared/path/path.d.ts +1 -0
  136. package/dist/shared/path/path.js +21 -1
  137. package/dist/shared/process/dotnet-toolchain.d.ts +14 -0
  138. package/dist/shared/process/dotnet-toolchain.js +179 -0
  139. package/dist/shared/process/host-process-recovery.d.ts +12 -0
  140. package/dist/shared/process/host-process-recovery.js +78 -0
  141. package/dist/shared/process/host-process-supervisor.d.ts +59 -0
  142. package/dist/shared/process/host-process-supervisor.js +330 -0
  143. package/dist/shared/process/process.d.ts +1 -0
  144. package/dist/shared/process/process.js +1 -0
  145. package/dist/shared/process/windows-launch.d.ts +1 -1
  146. package/dist/shared/process/windows-launch.js +6 -3
  147. package/dist/shared/provider-capabilities.d.ts +1 -0
  148. package/dist/shared/provider-capabilities.js +3 -0
  149. package/dist/shared/redaction/redaction.js +16 -4
  150. package/dist/version.d.ts +1 -1
  151. package/dist/version.js +1 -1
  152. package/dist/worktree/artifact-injector.d.ts +3 -2
  153. package/dist/worktree/artifact-injector.js +43 -4
  154. package/dist/worktree/dependency-warmer.d.ts +36 -2
  155. package/dist/worktree/dependency-warmer.js +347 -11
  156. package/dist/worktree/index.d.ts +2 -1
  157. package/dist/worktree/index.js +1 -0
  158. package/dist/worktree/prior-phase-artifact-hydrator.d.ts +2 -0
  159. package/dist/worktree/prior-phase-artifact-hydrator.js +136 -0
  160. package/dist/worktree/worktree-paths.d.ts +4 -0
  161. package/dist/worktree/worktree-paths.js +30 -0
  162. package/dist/worktree/worktree.base.d.ts +3 -0
  163. package/dist/worktree/worktree.service.d.ts +13 -2
  164. package/dist/worktree/worktree.service.js +238 -47
  165. package/dist/worktree/worktree.types.d.ts +5 -1
  166. package/package.json +8 -4
  167. package/runtime/windows-job-supervisor.ps1 +444 -0
  168. package/runtime/windows-listener-owner.ps1 +33 -0
@@ -0,0 +1,64 @@
1
+ import { AttemptProcessSupervisor, } from "./attempt-process-supervisor.js";
2
+ /** Runner-local authority for active host attempt process coordinators. */
3
+ export class AttemptProcessSupervisorRegistry {
4
+ active = new Map();
5
+ register(identity, runner, options = {}) {
6
+ const existing = this.active.get(identity.dispatchAttemptId);
7
+ if (existing) {
8
+ if (existing.fencingToken !== identity.fencingToken) {
9
+ throw new Error("attempt_process_registry_conflict: dispatch attempt is registered under a different fence.");
10
+ }
11
+ return existing.supervisor;
12
+ }
13
+ const supervisor = new AttemptProcessSupervisor(identity, runner, options);
14
+ this.active.set(identity.dispatchAttemptId, { fencingToken: identity.fencingToken, supervisor });
15
+ return supervisor;
16
+ }
17
+ require(dispatchAttemptId, fencingToken) {
18
+ const registered = this.active.get(dispatchAttemptId);
19
+ if (!registered) {
20
+ throw new Error("attempt_process_registry_missing: no process coordinator owns this dispatch attempt.");
21
+ }
22
+ if (registered.fencingToken !== fencingToken) {
23
+ throw new Error("attempt_process_registry_fenced: process coordinator fence does not match the dispatch.");
24
+ }
25
+ return registered.supervisor;
26
+ }
27
+ unregister(dispatchAttemptId, fencingToken) {
28
+ const registered = this.active.get(dispatchAttemptId);
29
+ if (!registered || registered.fencingToken !== fencingToken)
30
+ return false;
31
+ return this.active.delete(dispatchAttemptId);
32
+ }
33
+ has(dispatchAttemptId) {
34
+ return this.active.has(dispatchAttemptId);
35
+ }
36
+ }
37
+ /**
38
+ * Routes managed-host provider commands through the attempt's named provider
39
+ * child while retaining the raw runner for Docker and unmanaged execution.
40
+ */
41
+ export class AttemptCoordinatedProviderProcessRunner {
42
+ registry;
43
+ rawRunner;
44
+ constructor(registry, rawRunner) {
45
+ this.registry = registry;
46
+ this.rawRunner = rawRunner;
47
+ }
48
+ async run(request, handlers, signal) {
49
+ if (request.env?.FORGE_RUNTIME_MODE !== "host") {
50
+ return await this.rawRunner.run(request, handlers, signal);
51
+ }
52
+ const dispatchAttemptId = requiredEnvironment(request, "FORGE_DISPATCH_ATTEMPT_ID");
53
+ const fencingToken = requiredEnvironment(request, "FORGE_FENCING_TOKEN");
54
+ const supervisor = this.registry.require(dispatchAttemptId, fencingToken);
55
+ const child = await supervisor.startChildReady("provider", request, handlers, signal, { maxStartAttempts: request.stdin === undefined ? 1 : 3, retryDelayMs: 100 });
56
+ return await child.result;
57
+ }
58
+ }
59
+ function requiredEnvironment(request, name) {
60
+ const value = request.env?.[name]?.trim();
61
+ if (!value)
62
+ throw new Error(`attempt_process_registry_invalid: ${name} is required for managed-host execution.`);
63
+ return value;
64
+ }
@@ -0,0 +1,97 @@
1
+ import type { ProviderProcessHandlers, ProviderProcessRunRequest, ProviderProcessRunner, ProviderProcessRunResult } from "../session/provider-cli/provider-cli.process.js";
2
+ export type AttemptProcessChildStatus = "starting" | "running" | "stopping" | "exited" | "failed";
3
+ export type AttemptProcessSupervisorStatus = "active" | "stopping" | "stopped" | "degraded";
4
+ export interface AttemptProcessSupervisorIdentity {
5
+ readonly processSupervisorId: string;
6
+ readonly dispatchAttemptId: string;
7
+ readonly executionLeaseId: string;
8
+ readonly fencingToken: string;
9
+ readonly logDirectory: string;
10
+ }
11
+ export interface AttemptProcessChildLedgerEntry {
12
+ readonly name: string;
13
+ readonly generation: number;
14
+ readonly childId: string;
15
+ readonly processSupervisorId: string;
16
+ readonly metadataPath: string;
17
+ readonly status: AttemptProcessChildStatus;
18
+ readonly startedAt: string;
19
+ readonly settledAt?: string;
20
+ readonly exitCode?: number;
21
+ readonly failure?: string;
22
+ readonly peakMemoryBytes?: number;
23
+ readonly memorySampleCount?: number;
24
+ readonly memorySource?: string;
25
+ readonly memoryObservedAt?: string;
26
+ }
27
+ export interface AttemptProcessSupervisorLedger {
28
+ readonly schemaVersion: 1;
29
+ readonly attemptSupervisorId: string;
30
+ readonly dispatchAttemptId: string;
31
+ readonly executionLeaseId: string;
32
+ readonly status: AttemptProcessSupervisorStatus;
33
+ readonly updatedAt: string;
34
+ readonly children: readonly AttemptProcessChildLedgerEntry[];
35
+ }
36
+ export interface AttemptProcessChildHandle {
37
+ readonly name: string;
38
+ readonly generation: number;
39
+ readonly childId: string;
40
+ readonly processSupervisorId: string;
41
+ readonly metadataPath: string;
42
+ readonly ready: Promise<void>;
43
+ readonly result: Promise<ProviderProcessRunResult>;
44
+ stop(fencingToken: string): Promise<ProviderProcessRunResult>;
45
+ }
46
+ export interface AttemptProcessSupervisorOptions {
47
+ readonly metadataReadyTimeoutMs?: number;
48
+ readonly signal?: AbortSignal;
49
+ }
50
+ export interface AttemptProcessChildReadyOptions {
51
+ readonly maxStartAttempts?: number;
52
+ readonly retryDelayMs?: number;
53
+ }
54
+ /**
55
+ * Owns the independently supervised process trees that belong to one host
56
+ * dispatch attempt. Each named child gets a distinct Windows Job Object or
57
+ * Unix process group through the existing process runner, while this
58
+ * coordinator supplies shared fencing, cancellation, and a durable ledger.
59
+ */
60
+ export declare class AttemptProcessSupervisor {
61
+ private readonly runner;
62
+ readonly ledgerPath: string;
63
+ private readonly identity;
64
+ private readonly metadataReadyTimeoutMs;
65
+ private readonly records;
66
+ private readonly currentByName;
67
+ private readonly attemptController;
68
+ private status;
69
+ private persistTail;
70
+ private persistenceFailure;
71
+ private stopOperation;
72
+ constructor(identity: AttemptProcessSupervisorIdentity, runner: ProviderProcessRunner, options?: AttemptProcessSupervisorOptions);
73
+ startChild(name: string, request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal): Promise<AttemptProcessChildHandle>;
74
+ /**
75
+ * Starts a child and proves that the OS process tree is supervised before
76
+ * returning it to the caller. A launch that settles before producing its
77
+ * provider-ready supervision record is safe to retry: the raw runner only
78
+ * persists that record after the actual provider child has started, before
79
+ * Forge announces the provider as active.
80
+ */
81
+ startChildReady(name: string, request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal, options?: AttemptProcessChildReadyOptions): Promise<AttemptProcessChildHandle>;
82
+ stopChild(name: string, generation: number, fencingToken: string, reason?: unknown): Promise<ProviderProcessRunResult>;
83
+ stopAll(fencingToken: string, reason?: unknown): Promise<void>;
84
+ private performStopAll;
85
+ snapshot(): AttemptProcessSupervisorLedger;
86
+ providerMemoryTelemetry(): AttemptProcessTreeMemoryTelemetry | null;
87
+ private observeChildReady;
88
+ private settleChild;
89
+ private assertFence;
90
+ private persist;
91
+ }
92
+ export interface AttemptProcessTreeMemoryTelemetry {
93
+ readonly peakMemoryBytes: number;
94
+ readonly sampleCount: number;
95
+ readonly source: string;
96
+ readonly observedAt: string;
97
+ }
@@ -0,0 +1,386 @@
1
+ import { createHash } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ const terminalChildStatuses = new Set(["exited", "failed"]);
5
+ const defaultMetadataReadyTimeoutMs = process.platform === "win32" ? 60_000 : 10_000;
6
+ /**
7
+ * Owns the independently supervised process trees that belong to one host
8
+ * dispatch attempt. Each named child gets a distinct Windows Job Object or
9
+ * Unix process group through the existing process runner, while this
10
+ * coordinator supplies shared fencing, cancellation, and a durable ledger.
11
+ */
12
+ export class AttemptProcessSupervisor {
13
+ runner;
14
+ ledgerPath;
15
+ identity;
16
+ metadataReadyTimeoutMs;
17
+ records = [];
18
+ currentByName = new Map();
19
+ attemptController = new AbortController();
20
+ status = "active";
21
+ persistTail = Promise.resolve();
22
+ persistenceFailure;
23
+ stopOperation = null;
24
+ constructor(identity, runner, options = {}) {
25
+ this.runner = runner;
26
+ this.identity = validateIdentity(identity);
27
+ this.metadataReadyTimeoutMs = boundedInteger(options.metadataReadyTimeoutMs ?? defaultMetadataReadyTimeoutMs, 100, 120_000, "metadataReadyTimeoutMs");
28
+ this.ledgerPath = path.join(this.identity.logDirectory, "attempt-process-supervisor.json");
29
+ if (options.signal?.aborted) {
30
+ this.status = "stopping";
31
+ this.attemptController.abort(options.signal.reason);
32
+ }
33
+ else {
34
+ options.signal?.addEventListener("abort", () => {
35
+ // stopAll already persists a degraded terminal snapshot when a child
36
+ // rejects during cancellation. Do not relabel that process failure as
37
+ // a persistence failure: doing so poisons every later cleanup retry,
38
+ // even after all supervised processes have exited.
39
+ void this.stopAll(this.identity.fencingToken, options.signal?.reason).catch(() => undefined);
40
+ }, { once: true });
41
+ }
42
+ }
43
+ async startChild(name, request, handlers = {}, signal) {
44
+ assertChildName(name);
45
+ if (this.status !== "active" || this.attemptController.signal.aborted) {
46
+ throw new Error("attempt_process_supervisor_closed: the attempt no longer accepts child processes.");
47
+ }
48
+ if (signal?.aborted)
49
+ throw cancellationError(signal);
50
+ const existing = this.currentByName.get(name);
51
+ if (existing && !terminalChildStatuses.has(existing.status)) {
52
+ throw new Error(`attempt_process_supervisor_conflict: child '${name}' is already active.`);
53
+ }
54
+ const generation = (existing?.generation ?? 0) + 1;
55
+ const childId = `${name}:${generation}`;
56
+ const processSupervisorId = childProcessSupervisorId(this.identity.processSupervisorId, childId);
57
+ const metadataPath = path.join(this.identity.logDirectory, `process-supervisor.${name}.${generation}.json`);
58
+ const controller = new AbortController();
59
+ const combinedSignal = signal
60
+ ? AbortSignal.any([this.attemptController.signal, controller.signal, signal])
61
+ : AbortSignal.any([this.attemptController.signal, controller.signal]);
62
+ const childRequest = {
63
+ ...request,
64
+ env: {
65
+ ...request.env,
66
+ FORGE_RUNTIME_MODE: "host",
67
+ FORGE_RESOURCE_LEASE_ID: this.identity.executionLeaseId,
68
+ FORGE_EXECUTION_LEASE_ID: this.identity.executionLeaseId,
69
+ FORGE_DISPATCH_ATTEMPT_ID: this.identity.dispatchAttemptId,
70
+ FORGE_FENCING_TOKEN: this.identity.fencingToken,
71
+ FORGE_LOG_DIR: this.identity.logDirectory,
72
+ FORGE_PROCESS_SUPERVISOR_ID: processSupervisorId,
73
+ FORGE_PROCESS_SUPERVISOR_METADATA_PATH: metadataPath,
74
+ FORGE_PROCESS_CHILD_ID: childId,
75
+ FORGE_PROCESS_CHILD_NAME: name,
76
+ FORGE_PROCESS_CHILD_GENERATION: String(generation),
77
+ },
78
+ };
79
+ const startedAt = new Date().toISOString();
80
+ const record = {
81
+ name,
82
+ generation,
83
+ childId,
84
+ processSupervisorId,
85
+ metadataPath,
86
+ controller,
87
+ startedAt,
88
+ status: "starting",
89
+ result: Promise.resolve({ exitCode: 1, stdout: "", stderr: "not started" }),
90
+ };
91
+ this.records.push(record);
92
+ this.currentByName.set(name, record);
93
+ const result = this.runner.run(childRequest, handlers, combinedSignal);
94
+ record.result = result;
95
+ void result.then(value => this.settleChild(record, "exited", value.exitCode, undefined, value), error => this.settleChild(record, "failed", undefined, error));
96
+ try {
97
+ await this.persist();
98
+ }
99
+ catch (error) {
100
+ controller.abort("Attempt process ledger could not be persisted.");
101
+ await result.catch(() => undefined);
102
+ throw error;
103
+ }
104
+ const ready = this.observeChildReady(record);
105
+ void ready.catch(() => undefined);
106
+ return {
107
+ name,
108
+ generation,
109
+ childId,
110
+ processSupervisorId,
111
+ metadataPath,
112
+ ready,
113
+ result,
114
+ stop: async (fencingToken) => await this.stopChild(name, generation, fencingToken),
115
+ };
116
+ }
117
+ /**
118
+ * Starts a child and proves that the OS process tree is supervised before
119
+ * returning it to the caller. A launch that settles before producing its
120
+ * provider-ready supervision record is safe to retry: the raw runner only
121
+ * persists that record after the actual provider child has started, before
122
+ * Forge announces the provider as active.
123
+ */
124
+ async startChildReady(name, request, handlers = {}, signal, options = {}) {
125
+ const maxStartAttempts = boundedInteger(options.maxStartAttempts ?? 1, 1, 5, "maxStartAttempts");
126
+ const retryDelayMs = boundedInteger(options.retryDelayMs ?? 100, 0, 5_000, "retryDelayMs");
127
+ let lastError;
128
+ for (let attempt = 1; attempt <= maxStartAttempts; attempt += 1) {
129
+ const child = await this.startChild(name, request, handlers, signal);
130
+ try {
131
+ await child.ready;
132
+ return child;
133
+ }
134
+ catch (error) {
135
+ lastError = error;
136
+ await child.result.catch(() => undefined);
137
+ if (!isRetryableStartFailure(error) || attempt === maxStartAttempts)
138
+ throw error;
139
+ if (signal?.aborted)
140
+ throw cancellationError(signal);
141
+ if (retryDelayMs > 0)
142
+ await wait(retryDelayMs * attempt);
143
+ }
144
+ }
145
+ throw lastError;
146
+ }
147
+ async stopChild(name, generation, fencingToken, reason = "Forge stopped the supervised child.") {
148
+ this.assertFence(fencingToken);
149
+ const record = this.currentByName.get(name);
150
+ if (!record || record.generation !== generation) {
151
+ throw new Error(`attempt_process_supervisor_stale: child '${name}' generation ${generation} is no longer current.`);
152
+ }
153
+ if (!terminalChildStatuses.has(record.status)) {
154
+ record.status = "stopping";
155
+ record.controller.abort(reason);
156
+ await this.persist();
157
+ }
158
+ return await record.result;
159
+ }
160
+ async stopAll(fencingToken, reason = "Forge stopped the supervised attempt.") {
161
+ this.assertFence(fencingToken);
162
+ // The durable terminal ledger is part of the stop operation's contract.
163
+ // Join an in-flight stop before inspecting terminal state so lease cleanup
164
+ // cannot remove the log directory underneath its final persistence.
165
+ if (this.stopOperation)
166
+ return await this.stopOperation;
167
+ if (this.status === "stopped")
168
+ return;
169
+ const operation = this.performStopAll(reason);
170
+ this.stopOperation = operation;
171
+ void operation.catch(() => undefined).finally(() => {
172
+ if (this.stopOperation === operation && this.status !== "stopped")
173
+ this.stopOperation = null;
174
+ });
175
+ return await this.stopOperation;
176
+ }
177
+ async performStopAll(reason) {
178
+ this.status = "stopping";
179
+ this.attemptController.abort(reason);
180
+ const active = [...this.currentByName.values()].filter(record => !terminalChildStatuses.has(record.status));
181
+ for (const record of active)
182
+ record.status = "stopping";
183
+ await this.persist();
184
+ const results = await Promise.allSettled(active.map(record => record.result));
185
+ const rejected = results.filter((result) => result.status === "rejected");
186
+ const terminalStatus = rejected.length > 0 || this.persistenceFailure !== undefined ? "degraded" : "stopped";
187
+ await this.persist({
188
+ ...this.snapshot(),
189
+ status: terminalStatus,
190
+ updatedAt: new Date().toISOString(),
191
+ });
192
+ this.status = terminalStatus;
193
+ if (rejected.length > 0) {
194
+ throw new AggregateError(rejected.map(result => result.reason), "attempt_process_supervisor_cleanup_degraded");
195
+ }
196
+ if (this.persistenceFailure !== undefined)
197
+ throw this.persistenceFailure;
198
+ }
199
+ snapshot() {
200
+ return {
201
+ schemaVersion: 1,
202
+ attemptSupervisorId: this.identity.processSupervisorId,
203
+ dispatchAttemptId: this.identity.dispatchAttemptId,
204
+ executionLeaseId: this.identity.executionLeaseId,
205
+ status: this.status,
206
+ updatedAt: new Date().toISOString(),
207
+ children: this.records.map(record => ({
208
+ name: record.name,
209
+ generation: record.generation,
210
+ childId: record.childId,
211
+ processSupervisorId: record.processSupervisorId,
212
+ metadataPath: record.metadataPath,
213
+ status: record.status,
214
+ startedAt: record.startedAt,
215
+ ...(record.settledAt ? { settledAt: record.settledAt } : {}),
216
+ ...(record.exitCode === undefined ? {} : { exitCode: record.exitCode }),
217
+ ...(record.failure ? { failure: record.failure } : {}),
218
+ ...(record.peakMemoryBytes === undefined ? {} : { peakMemoryBytes: record.peakMemoryBytes }),
219
+ ...(record.memorySampleCount === undefined ? {} : { memorySampleCount: record.memorySampleCount }),
220
+ ...(record.memorySource ? { memorySource: record.memorySource } : {}),
221
+ ...(record.memoryObservedAt ? { memoryObservedAt: record.memoryObservedAt } : {}),
222
+ })),
223
+ };
224
+ }
225
+ providerMemoryTelemetry() {
226
+ const observations = this.records
227
+ .filter(record => record.name === "provider"
228
+ && record.peakMemoryBytes !== undefined
229
+ && record.peakMemoryBytes > 0
230
+ && record.memorySampleCount !== undefined
231
+ && record.memorySampleCount > 0
232
+ && record.memorySource
233
+ && record.memoryObservedAt);
234
+ if (observations.length === 0)
235
+ return null;
236
+ const peak = observations.reduce((current, candidate) => (candidate.peakMemoryBytes ?? 0) > (current.peakMemoryBytes ?? 0) ? candidate : current);
237
+ return {
238
+ peakMemoryBytes: peak.peakMemoryBytes,
239
+ sampleCount: observations.reduce((total, candidate) => total + (candidate.memorySampleCount ?? 0), 0),
240
+ source: peak.memorySource,
241
+ observedAt: peak.memoryObservedAt,
242
+ };
243
+ }
244
+ async observeChildReady(record) {
245
+ const deadline = Date.now() + this.metadataReadyTimeoutMs;
246
+ while (Date.now() <= deadline) {
247
+ if (await fileExists(record.metadataPath)) {
248
+ if (record.status === "starting") {
249
+ record.status = "running";
250
+ await this.persist();
251
+ }
252
+ return;
253
+ }
254
+ if (terminalChildStatuses.has(record.status)) {
255
+ const detail = await childStartFailureDetail(record);
256
+ throw new Error(`attempt_process_supervisor_start_failed: child '${record.childId}' exited before supervision metadata was produced${detail ? `: ${detail}` : "."}`);
257
+ }
258
+ await wait(25);
259
+ }
260
+ record.controller.abort("Supervised child metadata was not produced before the readiness deadline.");
261
+ const detail = await childStartFailureDetail(record);
262
+ throw new Error(`attempt_process_supervisor_start_timeout: child '${record.childId}' did not become supervised${detail ? `: ${detail}` : "."}`);
263
+ }
264
+ async settleChild(record, status, exitCode, failure, result) {
265
+ record.status = status;
266
+ record.settledAt = new Date().toISOString();
267
+ record.exitCode = exitCode;
268
+ record.failure = failure === undefined ? undefined : boundedFailure(failure);
269
+ if (result?.peakMemoryBytes !== undefined
270
+ && result.peakMemoryBytes > 0
271
+ && result.memorySampleCount !== undefined
272
+ && result.memorySampleCount > 0
273
+ && result.memorySource
274
+ && result.memoryObservedAt) {
275
+ record.peakMemoryBytes = result.peakMemoryBytes;
276
+ record.memorySampleCount = result.memorySampleCount;
277
+ record.memorySource = result.memorySource;
278
+ record.memoryObservedAt = result.memoryObservedAt;
279
+ }
280
+ await this.persist().catch(error => {
281
+ this.persistenceFailure ??= error;
282
+ this.status = "degraded";
283
+ });
284
+ }
285
+ assertFence(fencingToken) {
286
+ if (fencingToken !== this.identity.fencingToken) {
287
+ throw new Error("attempt_process_supervisor_fenced: fencing token does not own this attempt.");
288
+ }
289
+ }
290
+ persist(snapshot = this.snapshot()) {
291
+ const operation = this.persistTail.then(async () => {
292
+ await ensurePrivateDirectory(this.identity.logDirectory);
293
+ const temporary = `${this.ledgerPath}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`;
294
+ try {
295
+ const handle = await fs.open(temporary, "wx", 0o600);
296
+ try {
297
+ await handle.writeFile(`${JSON.stringify(snapshot)}\n`);
298
+ await handle.sync();
299
+ }
300
+ finally {
301
+ await handle.close();
302
+ }
303
+ await fs.rename(temporary, this.ledgerPath);
304
+ }
305
+ catch (error) {
306
+ await fs.rm(temporary, { force: true }).catch(() => undefined);
307
+ throw error;
308
+ }
309
+ });
310
+ this.persistTail = operation.catch(() => undefined);
311
+ return operation;
312
+ }
313
+ }
314
+ function validateIdentity(identity) {
315
+ if (!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/u.test(identity.processSupervisorId)) {
316
+ throw new Error("attempt_process_supervisor_invalid: process supervisor id is invalid.");
317
+ }
318
+ assertUuid(identity.dispatchAttemptId, "dispatch attempt");
319
+ assertUuid(identity.executionLeaseId, "execution lease");
320
+ assertUuid(identity.fencingToken, "fencing token");
321
+ if (!path.isAbsolute(identity.logDirectory)) {
322
+ throw new Error("attempt_process_supervisor_invalid: log directory must be absolute.");
323
+ }
324
+ return { ...identity, logDirectory: path.resolve(identity.logDirectory) };
325
+ }
326
+ function assertChildName(name) {
327
+ if (!/^[a-z][a-z0-9_-]{0,31}$/u.test(name)) {
328
+ throw new Error("attempt_process_supervisor_invalid: child name must be a safe lowercase identifier.");
329
+ }
330
+ }
331
+ function childProcessSupervisorId(attemptSupervisorId, childId) {
332
+ const digest = createHash("sha256")
333
+ .update(JSON.stringify([attemptSupervisorId, childId]))
334
+ .digest("hex")
335
+ .slice(0, 32);
336
+ return `host-${digest}`;
337
+ }
338
+ function assertUuid(value, label) {
339
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(value)) {
340
+ throw new Error(`attempt_process_supervisor_invalid: ${label} id must be a UUID.`);
341
+ }
342
+ }
343
+ function boundedInteger(value, minimum, maximum, name) {
344
+ if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {
345
+ throw new Error(`attempt_process_supervisor_invalid: ${name} must be between ${minimum} and ${maximum}.`);
346
+ }
347
+ return value;
348
+ }
349
+ function boundedFailure(error) {
350
+ const message = error instanceof Error ? error.message : String(error);
351
+ return message.replaceAll(/[\r\n\t]+/gu, " ").slice(0, 512);
352
+ }
353
+ async function childStartFailureDetail(record) {
354
+ try {
355
+ const result = await record.result;
356
+ const stderr = boundedDiagnostic(result.stderr);
357
+ return stderr
358
+ ? `exit ${result.exitCode}; stderr: ${stderr}`
359
+ : `exit ${result.exitCode}`;
360
+ }
361
+ catch (error) {
362
+ return boundedFailure(error);
363
+ }
364
+ }
365
+ function boundedDiagnostic(value) {
366
+ return value.replaceAll(/[\r\n\t]+/gu, " ").trim().slice(0, 512);
367
+ }
368
+ function isRetryableStartFailure(error) {
369
+ return error instanceof Error
370
+ && (error.message.startsWith("attempt_process_supervisor_start_failed:")
371
+ || error.message.startsWith("attempt_process_supervisor_start_timeout:"));
372
+ }
373
+ function cancellationError(signal) {
374
+ return new Error(String(signal.reason ?? "Supervised child launch was cancelled."));
375
+ }
376
+ async function ensurePrivateDirectory(directory) {
377
+ await fs.mkdir(directory, { recursive: true, mode: 0o700 });
378
+ if (process.platform !== "win32")
379
+ await fs.chmod(directory, 0o700);
380
+ }
381
+ async function fileExists(target) {
382
+ return await fs.stat(target).then(() => true, () => false);
383
+ }
384
+ function wait(milliseconds) {
385
+ return new Promise(resolve => setTimeout(resolve, milliseconds));
386
+ }
@@ -0,0 +1,83 @@
1
+ import type { CommandRunner } from "../sandbox/sandbox.types.js";
2
+ export interface DockerEngineCapabilitySnapshot {
3
+ readonly available: boolean;
4
+ readonly sampledAt: string;
5
+ readonly runtimeVersion: string | null;
6
+ readonly operatingSystem: string | null;
7
+ readonly context: string;
8
+ readonly unavailableCode: string | null;
9
+ readonly unavailableReason: string | null;
10
+ }
11
+ export interface DockerEngineProbeOptions {
12
+ readonly dockerExecutable?: string;
13
+ readonly dockerContext?: string;
14
+ readonly recovery?: DockerEngineRecoveryPolicy;
15
+ readonly recoveryExecutor?: DockerEngineRecoveryExecutor;
16
+ readonly platform?: NodeJS.Platform;
17
+ readonly dockerHost?: string;
18
+ readonly now?: () => number;
19
+ readonly wait?: (delayMs: number) => Promise<void>;
20
+ readonly onStatus?: (message: string) => void;
21
+ }
22
+ export interface DockerEngineRecoveryPolicy {
23
+ readonly enabled: boolean;
24
+ readonly failureThreshold?: number;
25
+ readonly confirmationDelayMs?: number;
26
+ readonly cooldownMs?: number;
27
+ readonly startupTimeoutMs?: number;
28
+ readonly pollIntervalMs?: number;
29
+ readonly canRecover?: () => boolean;
30
+ }
31
+ export interface DockerEngineRecoveryResult {
32
+ readonly started: boolean;
33
+ readonly reason?: string;
34
+ }
35
+ export interface DockerEngineRecoveryExecutor {
36
+ restart(): Promise<DockerEngineRecoveryResult>;
37
+ }
38
+ /**
39
+ * Probes ordinary Docker-daemon access for host-run Testcontainers and project
40
+ * services. This is deliberately independent from the stricter Forge sandbox
41
+ * preflight: a usable Docker Desktop engine may satisfy docker_engine even
42
+ * when it is not approved to host an agent sandbox.
43
+ */
44
+ export declare class DockerEngineProbe {
45
+ private readonly commands;
46
+ private readonly cacheMs;
47
+ private cached;
48
+ private sampledAtMs;
49
+ private inFlight;
50
+ private consecutiveFailures;
51
+ private lastRecoveryAttemptAtMs;
52
+ private readonly docker;
53
+ private readonly context;
54
+ private readonly platform;
55
+ private readonly dockerHost;
56
+ private readonly now;
57
+ private readonly wait;
58
+ private readonly recovery;
59
+ private readonly recoveryExecutor;
60
+ private readonly onStatus;
61
+ constructor(options?: DockerEngineProbeOptions, commands?: CommandRunner, cacheMs?: number);
62
+ current(): DockerEngineCapabilitySnapshot | null;
63
+ refresh(force?: boolean): Promise<DockerEngineCapabilitySnapshot>;
64
+ private inspectSafely;
65
+ private recoverIfEligible;
66
+ private isLocalDockerDesktopContext;
67
+ private inspect;
68
+ }
69
+ /**
70
+ * Restarts only the local Docker Desktop installation. It never targets a
71
+ * remote daemon and is used only behind the explicit bridge recovery policy.
72
+ */
73
+ export declare class WindowsDockerDesktopRecoveryExecutor implements DockerEngineRecoveryExecutor {
74
+ private readonly platform;
75
+ private readonly commands;
76
+ private readonly programFiles;
77
+ private readonly wait;
78
+ constructor(platform?: NodeJS.Platform, commands?: CommandRunner, programFiles?: string, wait?: (delayMs: number) => Promise<void>);
79
+ restart(): Promise<DockerEngineRecoveryResult>;
80
+ private readProcessState;
81
+ private cleanupOrphanedCompanions;
82
+ private startDesktop;
83
+ }