@loucompanion/forge-bridge 0.1.3-dev.0b2f81d660c0 → 0.1.3-dev.0d26c10244e1

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 (148) hide show
  1. package/README.md +79 -0
  2. package/dist/bridge/bridge.base.d.ts +8 -1
  3. package/dist/bridge/bridge.service.d.ts +77 -3
  4. package/dist/bridge/bridge.service.js +1113 -34
  5. package/dist/bridge/bridge.types.d.ts +168 -1
  6. package/dist/cleanup/cleanup.service.d.ts +14 -2
  7. package/dist/cleanup/cleanup.service.js +469 -3
  8. package/dist/cleanup/cleanup.types.d.ts +10 -0
  9. package/dist/cleanup/index.d.ts +1 -1
  10. package/dist/cleanup/index.js +1 -1
  11. package/dist/cleanup/internals.d.ts +2 -2
  12. package/dist/cleanup/internals.js +1 -1
  13. package/dist/cli/cli.help.js +47 -1
  14. package/dist/cli/cli.service.d.ts +42 -2
  15. package/dist/cli/cli.service.js +357 -26
  16. package/dist/cli/local-config.d.ts +4 -0
  17. package/dist/cli/local-config.js +41 -1
  18. package/dist/runtime/aspnet-runtime-prebuild.d.ts +35 -0
  19. package/dist/runtime/aspnet-runtime-prebuild.js +168 -0
  20. package/dist/runtime/attempt-node-runtime-launcher.d.ts +17 -0
  21. package/dist/runtime/attempt-node-runtime-launcher.js +105 -0
  22. package/dist/runtime/attempt-process-supervisor-registry.d.ts +20 -0
  23. package/dist/runtime/attempt-process-supervisor-registry.js +64 -0
  24. package/dist/runtime/attempt-process-supervisor.d.ts +86 -0
  25. package/dist/runtime/attempt-process-supervisor.js +350 -0
  26. package/dist/runtime/generated-output-reset.d.ts +10 -0
  27. package/dist/runtime/generated-output-reset.js +103 -0
  28. package/dist/runtime/host-listener-inspector.d.ts +46 -0
  29. package/dist/runtime/host-listener-inspector.js +349 -0
  30. package/dist/runtime/host-port-broker.d.ts +76 -0
  31. package/dist/runtime/host-port-broker.js +333 -0
  32. package/dist/runtime/host-runtime-contract.d.ts +47 -0
  33. package/dist/runtime/host-runtime-contract.js +700 -0
  34. package/dist/runtime/host-runtime-lease.d.ts +179 -0
  35. package/dist/runtime/host-runtime-lease.js +1990 -0
  36. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  37. package/dist/runtime/host-runtime-promotion.js +159 -0
  38. package/dist/runtime/node-host-runtime-adapter.d.ts +54 -0
  39. package/dist/runtime/node-host-runtime-adapter.js +284 -0
  40. package/dist/runtime/playwright-host-runtime-adapter.d.ts +20 -0
  41. package/dist/runtime/playwright-host-runtime-adapter.js +220 -0
  42. package/dist/runtime/runtime-isolation-lease.d.ts +67 -0
  43. package/dist/runtime/runtime-isolation-lease.js +158 -0
  44. package/dist/runtime/workspace-resource-estimator.d.ts +16 -0
  45. package/dist/runtime/workspace-resource-estimator.js +165 -0
  46. package/dist/sandbox/command-runner.d.ts +4 -0
  47. package/dist/sandbox/command-runner.js +47 -0
  48. package/dist/sandbox/contract.d.ts +5 -0
  49. package/dist/sandbox/contract.js +276 -0
  50. package/dist/sandbox/event-budget.d.ts +11 -0
  51. package/dist/sandbox/event-budget.js +27 -0
  52. package/dist/sandbox/image-policy.d.ts +35 -0
  53. package/dist/sandbox/image-policy.js +247 -0
  54. package/dist/sandbox/index.d.ts +5 -0
  55. package/dist/sandbox/index.js +5 -0
  56. package/dist/sandbox/lease-watchdog.d.ts +18 -0
  57. package/dist/sandbox/lease-watchdog.js +67 -0
  58. package/dist/sandbox/preflight.d.ts +55 -0
  59. package/dist/sandbox/preflight.js +343 -0
  60. package/dist/sandbox/process.d.ts +20 -0
  61. package/dist/sandbox/process.js +209 -0
  62. package/dist/sandbox/provider-auth/codex.d.ts +26 -0
  63. package/dist/sandbox/provider-auth/codex.js +212 -0
  64. package/dist/sandbox/repository-lock.d.ts +5 -0
  65. package/dist/sandbox/repository-lock.js +119 -0
  66. package/dist/sandbox/runtime.d.ts +297 -0
  67. package/dist/sandbox/runtime.js +2338 -0
  68. package/dist/sandbox/sandbox.types.d.ts +86 -0
  69. package/dist/sandbox/sandbox.types.js +1 -0
  70. package/dist/sandbox/smoke.d.ts +76 -0
  71. package/dist/sandbox/smoke.js +380 -0
  72. package/dist/sandbox/worker-supervisor.d.ts +13 -0
  73. package/dist/sandbox/worker-supervisor.js +36 -0
  74. package/dist/sandbox/worker.d.ts +1 -0
  75. package/dist/sandbox/worker.js +225 -0
  76. package/dist/sandbox/workspace.service.d.ts +13 -0
  77. package/dist/sandbox/workspace.service.js +72 -0
  78. package/dist/session/managed-attempt-tools.d.ts +18 -0
  79. package/dist/session/managed-attempt-tools.js +797 -0
  80. package/dist/session/managed-build-coordinator.d.ts +5 -0
  81. package/dist/session/managed-build-coordinator.js +105 -0
  82. package/dist/session/phase-completion.artifacts.js +21 -3
  83. package/dist/session/phase-completion.d.ts +11 -2
  84. package/dist/session/phase-completion.helpers.d.ts +5 -0
  85. package/dist/session/phase-completion.helpers.js +51 -10
  86. package/dist/session/phase-completion.js +12 -3
  87. package/dist/session/phase-completion.prompts.d.ts +3 -3
  88. package/dist/session/phase-completion.prompts.js +21 -6
  89. package/dist/session/phase-completion.runtime.d.ts +13 -1
  90. package/dist/session/phase-completion.runtime.js +187 -8
  91. package/dist/session/phase-completion.schemas.js +108 -3
  92. package/dist/session/phase-completion.validation.d.ts +4 -1
  93. package/dist/session/phase-completion.validation.js +150 -21
  94. package/dist/session/provider-cli/ci-repair-readiness.d.ts +14 -0
  95. package/dist/session/provider-cli/ci-repair-readiness.js +105 -0
  96. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +3 -2
  97. package/dist/session/provider-cli/provider-cli.artifacts.js +65 -7
  98. package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
  99. package/dist/session/provider-cli/provider-cli.deterministic.d.ts +2 -0
  100. package/dist/session/provider-cli/provider-cli.deterministic.js +66 -9
  101. package/dist/session/provider-cli/provider-cli.process.d.ts +16 -0
  102. package/dist/session/provider-cli/provider-cli.process.js +212 -25
  103. package/dist/session/provider-cli/provider-cli.prompts.d.ts +6 -1
  104. package/dist/session/provider-cli/provider-cli.prompts.js +129 -18
  105. package/dist/session/provider-cli/provider-cli.qa-sidecars.js +1 -0
  106. package/dist/session/provider-cli/provider-cli.runtime.d.ts +1 -1
  107. package/dist/session/provider-cli/provider-cli.runtime.js +3 -2
  108. package/dist/session/provider-cli/provider-cli.service.d.ts +23 -2
  109. package/dist/session/provider-cli/provider-cli.service.js +507 -88
  110. package/dist/session/provider-cli/provider-cli.types.d.ts +5 -0
  111. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  112. package/dist/session/provider-cli/provider-output-state.js +69 -7
  113. package/dist/session/session-redaction.d.ts +3 -0
  114. package/dist/session/session-redaction.js +38 -0
  115. package/dist/session/session.base.d.ts +6 -1
  116. package/dist/session/session.service.d.ts +8 -2
  117. package/dist/session/session.service.js +490 -42
  118. package/dist/session/session.types.d.ts +111 -1
  119. package/dist/session/session.types.js +192 -3
  120. package/dist/shared/format/format-bytes.d.ts +1 -0
  121. package/dist/shared/format/format-bytes.js +9 -0
  122. package/dist/shared/path/path.js +3 -1
  123. package/dist/shared/process/host-process-recovery.d.ts +12 -0
  124. package/dist/shared/process/host-process-recovery.js +78 -0
  125. package/dist/shared/process/host-process-supervisor.d.ts +57 -0
  126. package/dist/shared/process/host-process-supervisor.js +282 -0
  127. package/dist/shared/process/process.d.ts +1 -0
  128. package/dist/shared/process/process.js +1 -0
  129. package/dist/shared/redaction/redaction.js +6 -1
  130. package/dist/version.d.ts +1 -1
  131. package/dist/version.js +1 -1
  132. package/dist/worktree/artifact-injector.d.ts +3 -2
  133. package/dist/worktree/artifact-injector.js +43 -4
  134. package/dist/worktree/dependency-warmer.d.ts +10 -1
  135. package/dist/worktree/dependency-warmer.js +94 -5
  136. package/dist/worktree/index.d.ts +1 -0
  137. package/dist/worktree/index.js +1 -0
  138. package/dist/worktree/prior-phase-artifact-hydrator.d.ts +2 -0
  139. package/dist/worktree/prior-phase-artifact-hydrator.js +136 -0
  140. package/dist/worktree/worktree-paths.d.ts +4 -0
  141. package/dist/worktree/worktree-paths.js +30 -0
  142. package/dist/worktree/worktree.base.d.ts +3 -0
  143. package/dist/worktree/worktree.service.d.ts +8 -2
  144. package/dist/worktree/worktree.service.js +206 -43
  145. package/dist/worktree/worktree.types.d.ts +4 -1
  146. package/package.json +6 -3
  147. package/runtime/windows-job-supervisor.ps1 +356 -0
  148. package/runtime/windows-listener-owner.ps1 +33 -0
@@ -7,11 +7,17 @@ import { promisify } from "node:util";
7
7
  import { resolveCursorAgentDirectLaunch } from "../shared/cursor-agent/cursor-agent.launch.js";
8
8
  import { buildWindowsCmdLaunch } from "../shared/process/windows-launch.js";
9
9
  import { supportsDraftImageAttachmentsFor } from "../shared/provider-capabilities.js";
10
- import { redactSecrets, redactText } from "../shared/redaction/redaction.js";
10
+ import { redactText } from "../shared/redaction/redaction.js";
11
11
  import { defaultBridgeServiceConfig, ForgeBridgeService } from "../bridge/bridge.service.js";
12
12
  import { forgeBridgeVersion } from "../version.js";
13
- import { addRepoMapping, applyLocalConfigDefaults, providerStatusesFor, readLocalConfigSync, removeRepoMapping, resolveLocalConfigPath, writeLocalConfig } from "./local-config.js";
13
+ import { ManagedWorktreeCleanupService } from "../cleanup/cleanup.service.js";
14
+ import { addRepoMapping, applyLocalConfigDefaults, providerStatusesFor, readLocalConfigSync, removeRepoMapping, resolveLocalConfigPath, setSandboxPolicy, setServerUrl, writeLocalConfig } from "./local-config.js";
14
15
  import { BridgeSessionService } from "../session/session.service.js";
16
+ import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "../session/session-redaction.js";
17
+ import { validateDockerfilePolicy, validateSandboxContract } from "../sandbox/contract.js";
18
+ import { DockerPreflight } from "../sandbox/preflight.js";
19
+ import { DockerSandboxRuntime } from "../sandbox/runtime.js";
20
+ import { DockerSandboxSmoke } from "../sandbox/smoke.js";
15
21
  import { parseCompletionMcpArgs, runCompletionMcpServer } from "../session/phase-completion.js";
16
22
  import { failureResult, parseRunOnceDispatchPacket } from "../session/session.types.js";
17
23
  import { commandHelpText, helpText } from "./cli.help.js";
@@ -21,10 +27,12 @@ export class ForgeBridgeCliService {
21
27
  sessions;
22
28
  bridgeFactory;
23
29
  pairRunner;
24
- constructor(sessions = new BridgeSessionService(), bridgeFactory = (config) => new ForgeBridgeService(config), pairRunner = claimBridgeRunner) {
30
+ cleanupFactory;
31
+ constructor(sessions = new BridgeSessionService(), bridgeFactory = (config) => new ForgeBridgeService(config), pairRunner = claimBridgeRunner, cleanupFactory = stateRoot => new ManagedWorktreeCleanupService(stateRoot)) {
25
32
  this.sessions = sessions;
26
33
  this.bridgeFactory = bridgeFactory;
27
34
  this.pairRunner = pairRunner;
35
+ this.cleanupFactory = cleanupFactory;
28
36
  }
29
37
  async run(argv, io = { stdout: process.stdout, stderr: process.stderr }) {
30
38
  if (argv.length === 0 || argv[0] === "--help" || argv[0] === "-h") {
@@ -64,6 +72,10 @@ export class ForgeBridgeCliService {
64
72
  process.once("SIGINT", stop);
65
73
  process.once("SIGTERM", stop);
66
74
  try {
75
+ if (config.cleanupWorktrees && config.repoMappings.some(mapping => mapping.localPath?.trim())) {
76
+ io.stdout.write("Cleaning stale managed worktrees before accepting dispatches.\n");
77
+ await cleanupRepos(config, "stale", true, this.cleanupFactory(config.sandboxStateRoot), io);
78
+ }
67
79
  io.stdout.write(connectStartupText(config));
68
80
  await this.bridgeFactory(config).run(controller.signal);
69
81
  return 0;
@@ -89,6 +101,7 @@ export class ForgeBridgeCliService {
89
101
  if (args.command === "pair") {
90
102
  try {
91
103
  const current = readLocalConfigSync();
104
+ io.stdout.write(`Pairing with server: ${args.serverUrl}\n`);
92
105
  const code = await resolvePairingCode(args.code);
93
106
  const repoRoot = await resolvePairRepoRoot(args.repoRoot, current.defaultRepoRoot);
94
107
  await fs.mkdir(repoRoot, { recursive: true });
@@ -118,12 +131,66 @@ export class ForgeBridgeCliService {
118
131
  return 2;
119
132
  }
120
133
  }
134
+ if (args.command === "server-show") {
135
+ const saved = readLocalConfigSync().serverUrl ?? "not configured";
136
+ io.stdout.write(`Saved server: ${saved}\n`);
137
+ if (process.env.FORGE_URL?.trim()) {
138
+ io.stdout.write(`Effective server: ${process.env.FORGE_URL.trim()} (FORGE_URL override)\n`);
139
+ }
140
+ else {
141
+ io.stdout.write(`Effective server: ${args.config.serverUrl || "not configured"}\n`);
142
+ }
143
+ return 0;
144
+ }
145
+ if (args.command === "server-set") {
146
+ try {
147
+ const config = await setServerUrl(args.serverUrl);
148
+ io.stdout.write(`Saved Forge server: ${config.serverUrl}\n`);
149
+ io.stdout.write("Existing runner credentials were retained. Re-run `forge-bridge pair --server <url>` if this is a different Forge deployment.\n");
150
+ if (process.env.FORGE_URL?.trim()) {
151
+ io.stdout.write(`Warning: FORGE_URL is set to ${process.env.FORGE_URL.trim()} and overrides the saved server.\n`);
152
+ }
153
+ return 0;
154
+ }
155
+ catch (error) {
156
+ io.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
157
+ return 2;
158
+ }
159
+ }
121
160
  if (args.command === "status") {
122
161
  await writeStatus(args.config, args.checkUpdates, io);
123
162
  return 0;
124
163
  }
125
164
  if (args.command === "cleanup") {
126
- return await cleanupRepos(args.config, args.mode, args.force, io);
165
+ return await cleanupRepos(args.config, args.mode, args.force, this.cleanupFactory(args.config.sandboxStateRoot), io);
166
+ }
167
+ if (args.command === "sandbox-init") {
168
+ return await initializeSandbox(args.repoPath, io);
169
+ }
170
+ if (args.command === "sandbox-doctor") {
171
+ return await diagnoseSandbox(args.repoPath, args.requirePinnedBase, io);
172
+ }
173
+ if (args.command === "sandbox-smoke") {
174
+ return await smokeSandbox(args.repoPath, args.reportPath, args.requirePinnedBase, args.probeLoopbackPort, io);
175
+ }
176
+ if (args.command === "sandbox-reap") {
177
+ return await reapSandboxes(io);
178
+ }
179
+ if (args.command === "sandbox-on") {
180
+ const saved = await setSandboxPolicy(true, args.allowOpenPublic);
181
+ io.stdout.write("Saved local Docker sandbox policy. Restart the bridge to apply it.\n");
182
+ writeSandboxPolicyStatus(saved, io);
183
+ return 0;
184
+ }
185
+ if (args.command === "sandbox-off") {
186
+ const saved = await setSandboxPolicy(false, false);
187
+ io.stdout.write("Disabled local Docker sandbox placement. Restart the bridge to apply it.\n");
188
+ writeSandboxPolicyStatus(saved, io);
189
+ return 0;
190
+ }
191
+ if (args.command === "sandbox-status") {
192
+ writeSandboxPolicyStatus(readLocalConfigSync(), io);
193
+ return 0;
127
194
  }
128
195
  if (args.command === "mcp") {
129
196
  const parsed = parseCompletionMcpArgs(args.argv);
@@ -143,12 +210,12 @@ export class ForgeBridgeCliService {
143
210
  emit: async (event) => {
144
211
  const line = {
145
212
  type: "runner_event",
146
- event: redactSecrets(event, redactionSecrets)
213
+ event: redactRunnerDispatchEvent(event, redactionSecrets)
147
214
  };
148
215
  io.stdout.write(`${JSON.stringify(line)}\n`);
149
216
  }
150
217
  });
151
- await writeJsonAtomic(args.resultPath, redactSecrets(result, redactionSecrets));
218
+ await writeJsonAtomic(args.resultPath, redactRunOnceResultPacket(result, redactionSecrets));
152
219
  return result.exitCode;
153
220
  }
154
221
  catch (error) {
@@ -234,6 +301,15 @@ export function parseArgs(argv) {
234
301
  }
235
302
  return { ok: true, command: "remove-repo", label: argv[1] };
236
303
  }
304
+ if (argv[0] === "server") {
305
+ if (argv.length === 1 || (argv[1] === "show" && argv.length === 2)) {
306
+ return { ok: true, command: "server-show", config: configuredBridgeServiceConfig() };
307
+ }
308
+ if (argv[1] === "set" && argv[2] && argv.length === 3) {
309
+ return { ok: true, command: "server-set", serverUrl: argv[2] };
310
+ }
311
+ return { ok: false, error: "Usage: forge-bridge server <show|set <url>>" };
312
+ }
237
313
  if (argv[0] === "status") {
238
314
  let checkUpdates = false;
239
315
  for (let index = 1; index < argv.length; index += 1) {
@@ -253,6 +329,9 @@ export function parseArgs(argv) {
253
329
  if (argv[0] === "mcp") {
254
330
  return { ok: true, command: "mcp", argv };
255
331
  }
332
+ if (argv[0] === "sandbox") {
333
+ return parseSandboxArgs(argv);
334
+ }
256
335
  if (argv[0] !== "run-once") {
257
336
  return {
258
337
  ok: false,
@@ -283,6 +362,230 @@ export function parseArgs(argv) {
283
362
  resultPath: path.resolve(resultPath)
284
363
  };
285
364
  }
365
+ function parseSandboxArgs(argv) {
366
+ const action = argv[1];
367
+ if (action === "on") {
368
+ let allowOpenPublic = false;
369
+ for (let index = 2; index < argv.length; index += 1) {
370
+ if (argv[index] === "--allow-open-public") {
371
+ allowOpenPublic = true;
372
+ }
373
+ else {
374
+ return { ok: false, error: `Unknown sandbox argument: ${argv[index]}` };
375
+ }
376
+ }
377
+ return { ok: true, command: "sandbox-on", allowOpenPublic };
378
+ }
379
+ if (action === "off" && argv.length === 2)
380
+ return { ok: true, command: "sandbox-off" };
381
+ if (action === "status" && argv.length === 2)
382
+ return { ok: true, command: "sandbox-status" };
383
+ let repoPath = process.cwd();
384
+ let reportPath;
385
+ let requirePinnedBase = false;
386
+ let probeLoopbackPort = false;
387
+ for (let index = 2; index < argv.length; index += 1) {
388
+ const arg = argv[index];
389
+ if (arg === "--repo") {
390
+ repoPath = argv[++index] ?? "";
391
+ if (!repoPath)
392
+ return { ok: false, error: "--repo requires a path." };
393
+ }
394
+ else if (arg === "--report" && action === "smoke") {
395
+ reportPath = argv[++index];
396
+ if (!reportPath)
397
+ return { ok: false, error: "--report requires a path." };
398
+ }
399
+ else if (arg === "--require-pinned-base" && (action === "doctor" || action === "smoke")) {
400
+ requirePinnedBase = true;
401
+ }
402
+ else if (arg === "--probe-loopback-port" && action === "smoke") {
403
+ probeLoopbackPort = true;
404
+ }
405
+ else {
406
+ return { ok: false, error: `Unknown sandbox argument: ${arg}` };
407
+ }
408
+ }
409
+ if (action === "init")
410
+ return { ok: true, command: "sandbox-init", repoPath: path.resolve(repoPath) };
411
+ if (action === "doctor")
412
+ return { ok: true, command: "sandbox-doctor", repoPath: path.resolve(repoPath), requirePinnedBase };
413
+ if (action === "smoke")
414
+ return {
415
+ ok: true,
416
+ command: "sandbox-smoke",
417
+ repoPath: path.resolve(repoPath),
418
+ reportPath: reportPath ? path.resolve(reportPath) : undefined,
419
+ requirePinnedBase,
420
+ probeLoopbackPort,
421
+ };
422
+ if (action === "reap" && argv.length === 2)
423
+ return { ok: true, command: "sandbox-reap" };
424
+ return { ok: false, error: "Usage: forge-bridge sandbox <on|off|status|init|doctor|smoke|reap> [--allow-open-public] [--repo <path>] [--report <path>] [--require-pinned-base] [--probe-loopback-port]" };
425
+ }
426
+ const sandboxContractTemplate = `schemaVersion: 1
427
+ workingDirectory: /workspace
428
+ commands:
429
+ install: npm ci
430
+ test: npm test
431
+ caches:
432
+ - name: npm
433
+ mode: readonly
434
+ services: []
435
+ environment: []
436
+ artifacts: []
437
+ logs: []
438
+ browser: false
439
+ `;
440
+ const sandboxDockerfileTemplate = `# Pin this base by digest before enabling sandbox_required.
441
+ FROM node:22.17.0-bookworm-slim
442
+ WORKDIR /workspace
443
+ `;
444
+ async function initializeSandbox(repoPath, io) {
445
+ const forgePath = path.join(repoPath, ".forge");
446
+ const files = [
447
+ ["forge.sandbox.yml", sandboxContractTemplate],
448
+ ["Dockerfile", sandboxDockerfileTemplate],
449
+ ["forge.env.example", "# List non-secret variable names in forge.sandbox.yml. Never commit secret values.\n"]
450
+ ];
451
+ await fs.mkdir(forgePath, { recursive: true });
452
+ let created = 0;
453
+ for (const [name, contents] of files) {
454
+ const target = path.join(forgePath, name);
455
+ try {
456
+ const handle = await fs.open(target, "wx", 0o600);
457
+ await handle.writeFile(contents);
458
+ await handle.close();
459
+ io.stdout.write(`Created ${path.relative(repoPath, target)}\n`);
460
+ created += 1;
461
+ }
462
+ catch (error) {
463
+ if (error.code !== "EEXIST")
464
+ throw error;
465
+ io.stdout.write(`Kept existing ${path.relative(repoPath, target)}\n`);
466
+ }
467
+ }
468
+ io.stdout.write(created > 0 ? "Sandbox scaffold is ready. Run `forge-bridge sandbox doctor`.\n" : "Sandbox scaffold already exists.\n");
469
+ return 0;
470
+ }
471
+ async function diagnoseSandbox(repoPath, requirePinnedBase, io) {
472
+ try {
473
+ const forgePath = path.join(repoPath, ".forge");
474
+ const contractSource = await fs.readFile(path.join(forgePath, "forge.sandbox.yml"), "utf8");
475
+ const dockerfile = await fs.readFile(path.join(forgePath, "Dockerfile"), "utf8");
476
+ const contract = validateSandboxContract(contractSource);
477
+ const warnings = validateDockerfilePolicy(dockerfile, requirePinnedBase);
478
+ io.stdout.write(`Contract: valid (${contract.digest})\n`);
479
+ for (const warning of warnings)
480
+ io.stdout.write(`Warning: ${warning}\n`);
481
+ const config = defaultBridgeServiceConfig();
482
+ const preflight = new DockerPreflight({
483
+ dockerExecutable: config.dockerExecutable,
484
+ dockerContext: config.dockerContext,
485
+ stateRoot: config.sandboxStateRoot,
486
+ maxConcurrentSandboxes: config.maxConcurrentSandboxes,
487
+ diskHighWatermarkPercent: config.diskHighWatermarkPercent,
488
+ diskLowWatermarkPercent: config.diskLowWatermarkPercent,
489
+ minimumWorkspaceBytes: config.minimumWorkspaceBytes,
490
+ hostMemoryReserveBytes: config.sandboxHostMemoryReserveBytes,
491
+ defaultWorkerMemoryLimitBytes: config.defaultSandboxWorkerMemoryLimitBytes,
492
+ defaultServiceMemoryLimitBytes: config.defaultSandboxServiceMemoryLimitBytes,
493
+ runtimeOverheadBytes: config.sandboxRuntimeOverheadBytes,
494
+ requireRootless: config.requireRootlessDocker
495
+ });
496
+ try {
497
+ const result = await preflight.refresh();
498
+ if (!result.healthy) {
499
+ io.stderr.write(`Docker: unavailable (${result.unavailableCode ?? "preflight_failed"}): ${result.unavailableReason ?? "unknown reason"}\n`);
500
+ return 1;
501
+ }
502
+ io.stdout.write(`Docker: healthy (${result.runtimeVersion}; capacity ${result.maxConcurrentSandboxes})\n`);
503
+ return 0;
504
+ }
505
+ finally {
506
+ await preflight.release();
507
+ }
508
+ }
509
+ catch (error) {
510
+ io.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
511
+ return 1;
512
+ }
513
+ }
514
+ async function smokeSandbox(repoPath, reportPath, requirePinnedBase, probeLoopbackPort, io) {
515
+ try {
516
+ const result = await new DockerSandboxSmoke(defaultBridgeServiceConfig()).run({
517
+ repoPath,
518
+ reportPath,
519
+ requirePinnedBase,
520
+ probeLoopbackPort,
521
+ onProgress: (stage) => io.stdout.write(`Smoke: ${stage}...\n`),
522
+ });
523
+ const { report } = result;
524
+ if (report.repository.contractDigest)
525
+ io.stdout.write(`Contract: valid (${report.repository.contractDigest})\n`);
526
+ for (const warning of report.repository.policyWarnings)
527
+ io.stdout.write(`Warning: ${warning}\n`);
528
+ if (report.docker.runtimeVersion) {
529
+ io.stdout.write(`Docker: healthy (${report.docker.runtimeVersion}; capacity ${report.docker.capacity})\n`);
530
+ }
531
+ io.stdout.write(`Attempt: ${report.dispatchAttemptId}\n`);
532
+ io.stdout.write(`Resource lease: ${report.resourceLeaseId}\n`);
533
+ if (report.publishedPortProbe) {
534
+ io.stdout.write(`Loopback port: ${report.publishedPortProbe.hostIp}:${report.publishedPortProbe.hostPort} -> ${report.publishedPortProbe.containerPort}/tcp\n`);
535
+ }
536
+ io.stdout.write(`Cleanup: ${report.cleanup.verified ? "verified (zero exact-label resources)" : "failed"}\n`);
537
+ io.stdout.write(`Report: ${result.reportPath}\n`);
538
+ if (report.status === "passed") {
539
+ io.stdout.write("Sandbox smoke: PASS\n");
540
+ return 0;
541
+ }
542
+ io.stderr.write(`Sandbox smoke: FAIL (${report.failure?.code ?? "sandbox_smoke_failed"} at ${report.failure?.stage ?? "unknown"}): ${report.failure?.message ?? "unknown failure"}\n`);
543
+ return 1;
544
+ }
545
+ catch (error) {
546
+ io.stderr.write(`Sandbox smoke could not write its report: ${error instanceof Error ? error.message : String(error)}\n`);
547
+ return 1;
548
+ }
549
+ }
550
+ async function reapSandboxes(io) {
551
+ const config = defaultBridgeServiceConfig();
552
+ if (!/^[0-9a-f-]{32,36}$/iu.test(config.runnerId)) {
553
+ io.stderr.write("FORGE_RUNNER_ID must identify the runner whose exact-labeled resources may be reaped.\n");
554
+ return 2;
555
+ }
556
+ const preflight = new DockerPreflight({
557
+ dockerExecutable: config.dockerExecutable,
558
+ dockerContext: config.dockerContext,
559
+ stateRoot: config.sandboxStateRoot,
560
+ maxConcurrentSandboxes: config.maxConcurrentSandboxes,
561
+ diskHighWatermarkPercent: config.diskHighWatermarkPercent,
562
+ diskLowWatermarkPercent: config.diskLowWatermarkPercent,
563
+ minimumWorkspaceBytes: config.minimumWorkspaceBytes,
564
+ hostMemoryReserveBytes: config.sandboxHostMemoryReserveBytes,
565
+ defaultWorkerMemoryLimitBytes: config.defaultSandboxWorkerMemoryLimitBytes,
566
+ defaultServiceMemoryLimitBytes: config.defaultSandboxServiceMemoryLimitBytes,
567
+ runtimeOverheadBytes: config.sandboxRuntimeOverheadBytes,
568
+ requireRootless: config.requireRootlessDocker
569
+ });
570
+ try {
571
+ const result = await preflight.refresh();
572
+ if (!result.healthy && result.unavailableCode !== "docker_disk_low") {
573
+ io.stderr.write(`Docker: unavailable (${result.unavailableCode ?? "preflight_failed"}): ${result.unavailableReason ?? "unknown reason"}\n`);
574
+ return 1;
575
+ }
576
+ const runtime = new DockerSandboxRuntime(config);
577
+ await runtime.reap({ diskLow: result.diskLow });
578
+ io.stdout.write(`Sandbox reaper completed for runner ${config.runnerId}.\n`);
579
+ return 0;
580
+ }
581
+ catch (error) {
582
+ io.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
583
+ return 1;
584
+ }
585
+ finally {
586
+ await preflight.release();
587
+ }
588
+ }
286
589
  function parseConnectArgs(argv) {
287
590
  let serverUrl = null;
288
591
  let runnerId = null;
@@ -415,7 +718,7 @@ function parsePairArgs(argv) {
415
718
  name: name?.trim() || defaultName,
416
719
  fingerprint: fingerprint?.trim() || `local-bridge:${os.hostname()}:${user}`,
417
720
  repoRoot: repoRoot?.trim() ? path.resolve(repoRoot) : undefined,
418
- cleanupWorktrees: cleanupWorktrees ?? localConfig.cleanupWorktrees ?? false,
721
+ cleanupWorktrees: cleanupWorktrees ?? defaultConfig.cleanupWorktrees,
419
722
  cliProviders: cliProviders.length > 0 ? cliProviders : localConfig.cliProviders && localConfig.cliProviders.length > 0 ? [...localConfig.cliProviders] : ["codex"],
420
723
  projectLabels: projectLabels.length > 0 ? projectLabels : localConfig.projectLabels ? [...localConfig.projectLabels] : []
421
724
  };
@@ -471,7 +774,7 @@ async function claimBridgeRunner(args) {
471
774
  })
472
775
  });
473
776
  if (!response.ok) {
474
- throw new Error(`Pairing failed (${response.status}): ${await response.text()}`);
777
+ throw new Error(formatPairingFailure(response.status, args.serverUrl, await response.text()));
475
778
  }
476
779
  const value = await response.json();
477
780
  if (!value.runnerId || !value.deviceToken) {
@@ -546,6 +849,12 @@ async function resolvePairRepoRoot(repoRoot, configuredRoot) {
546
849
  function normalizePairingCode(code) {
547
850
  return code?.replace(/[\s-]/g, "").trim() ?? "";
548
851
  }
852
+ function formatPairingFailure(status, serverUrl, body) {
853
+ const hint = body.includes("runner.invalid_pairing_code")
854
+ ? " Make sure the code was generated by the same Forge server shown above."
855
+ : "";
856
+ return `Pairing failed (${status}) against ${serverUrl}: ${body}${hint}`;
857
+ }
549
858
  function normalizeServerUrl(serverUrl) {
550
859
  return serverUrl.endsWith("/") ? serverUrl : `${serverUrl}/`;
551
860
  }
@@ -564,11 +873,27 @@ function connectStartupText(config) {
564
873
  ` repo folder: ${config.defaultRepoRoot || "not configured"}`,
565
874
  ` providers: ${formatList(config.cliProviders)}`,
566
875
  ` cleanup worktrees: ${config.cleanupWorktrees ? "enabled" : "disabled"}`,
876
+ ` open public sandbox networking: ${config.allowOpenPublicSandbox ? "enabled" : "disabled"}`,
567
877
  "",
568
878
  "Press Ctrl+C to stop.",
569
879
  "",
570
880
  ].join("\n");
571
881
  }
882
+ function writeSandboxPolicyStatus(local, io) {
883
+ const effective = configuredBridgeServiceConfig({}, local);
884
+ io.stdout.write(`Config: ${resolveLocalConfigPath()}\n`);
885
+ io.stdout.write(`Docker sandbox placement: ${effective.dockerEnabled ? "on" : "off"}\n`);
886
+ io.stdout.write(`Open public sandbox networking: ${effective.allowOpenPublicSandbox ? "allowed" : "denied"}\n`);
887
+ if (process.env.FORGE_DOCKER_SANDBOX !== undefined) {
888
+ io.stdout.write("Docker setting source: FORGE_DOCKER_SANDBOX override\n");
889
+ }
890
+ if (process.env.FORGE_ALLOW_OPEN_PUBLIC_SANDBOX !== undefined) {
891
+ io.stdout.write("Open public setting source: FORGE_ALLOW_OPEN_PUBLIC_SANDBOX override\n");
892
+ }
893
+ if (effective.allowOpenPublicSandbox) {
894
+ io.stdout.write("Warning: open_public permits unrestricted outbound network access from developer sandboxes.\n");
895
+ }
896
+ }
572
897
  function formatList(values) {
573
898
  return values.length > 0 ? values.join(", ") : "none";
574
899
  }
@@ -605,7 +930,7 @@ async function writeStatus(config, checkUpdates, io) {
605
930
  io.stdout.write("Update check: no update channel configured.\n");
606
931
  }
607
932
  }
608
- async function cleanupRepos(config, mode, force, io) {
933
+ async function cleanupRepos(config, mode, force, cleanup, io) {
609
934
  const repos = config.repoMappings.filter((mapping) => mapping.localPath?.trim());
610
935
  if (repos.length === 0) {
611
936
  io.stdout.write("No repos configured.\n");
@@ -614,20 +939,28 @@ async function cleanupRepos(config, mode, force, io) {
614
939
  let failures = 0;
615
940
  for (const repo of repos) {
616
941
  const repoPath = path.resolve(repo.localPath);
617
- const worktreeRoot = path.join(path.dirname(repoPath), ".forge-worktrees", path.basename(repoPath));
618
- if (!force) {
619
- const action = mode === "all" ? "remove" : "prune";
620
- io.stdout.write(`[dry-run] Would ${action} ${worktreeRoot}\n`);
621
- continue;
622
- }
623
942
  try {
624
- if (mode === "all") {
625
- await fs.rm(worktreeRoot, { recursive: true, force: true });
626
- await runGit(repoPath, ["worktree", "prune"]);
627
- io.stdout.write(`Removed ${worktreeRoot}\n`);
943
+ const result = await cleanup.run({
944
+ repoRoot: repoPath,
945
+ allowedRepoRoot: config.defaultRepoRoot || undefined,
946
+ mode,
947
+ force,
948
+ });
949
+ if (!force) {
950
+ const action = mode === "all"
951
+ ? "remove"
952
+ : mode === "stale"
953
+ ? `remove ${result.candidateWorktrees} stale managed ${result.candidateWorktrees === 1 ? "worktree" : "worktrees"} from`
954
+ : "prune";
955
+ io.stdout.write(`[dry-run] Would ${action} ${result.worktreeRoot}\n`);
956
+ }
957
+ else if (mode === "all") {
958
+ io.stdout.write(`Removed ${result.worktreeRoot}\n`);
959
+ }
960
+ else if (mode === "stale") {
961
+ io.stdout.write(`Removed ${result.removedWorktrees} stale managed ${result.removedWorktrees === 1 ? "worktree" : "worktrees"} from ${result.worktreeRoot}\n`);
628
962
  }
629
963
  else {
630
- await runGit(repoPath, ["worktree", "prune"]);
631
964
  io.stdout.write(`Pruned stale worktree metadata for ${repoPath}\n`);
632
965
  }
633
966
  }
@@ -776,8 +1109,8 @@ function uniqueModels(models) {
776
1109
  function isRecord(value) {
777
1110
  return typeof value === "object" && value !== null;
778
1111
  }
779
- async function withDetectedCliProviders(config) {
780
- const detected = await detectCliProviders(configuredProviderCandidates(config.cliProviders));
1112
+ async function withDetectedCliProviders(config, candidates = config.cliProviders) {
1113
+ const detected = await detectCliProviders(uniqueProviders(candidates));
781
1114
  const found = detected.filter((result) => result.found);
782
1115
  if (found.length === 0) {
783
1116
  return config;
@@ -801,6 +1134,7 @@ async function withDetectedCliProviders(config) {
801
1134
  };
802
1135
  }
803
1136
  async function withDetectedPairCliProviders(args) {
1137
+ const configured = configuredProviderCandidates(args.cliProviders);
804
1138
  const detectedConfig = await withDetectedCliProviders({
805
1139
  ...defaultBridgeServiceConfig({
806
1140
  serverUrl: args.serverUrl,
@@ -810,7 +1144,7 @@ async function withDetectedPairCliProviders(args) {
810
1144
  cleanupWorktrees: args.cleanupWorktrees,
811
1145
  defaultRepoRoot: args.repoRoot ?? defaultBridgeServiceConfig().defaultRepoRoot
812
1146
  })
813
- });
1147
+ }, configured);
814
1148
  return {
815
1149
  ...args,
816
1150
  cliProviders: detectedConfig.cliProviders
@@ -825,6 +1159,3 @@ function uniqueProviders(providers) {
825
1159
  .filter((provider) => provider.length > 0)
826
1160
  .filter((provider, index, all) => all.findIndex((candidate) => candidate.toLowerCase() === provider.toLowerCase()) === index);
827
1161
  }
828
- async function runGit(cwd, args) {
829
- await execFileAsync("git", args, { cwd, timeout: 10_000 });
830
- }
@@ -7,6 +7,8 @@ export interface BridgeLocalConfig {
7
7
  readonly deviceName?: string;
8
8
  readonly defaultRepoRoot?: string;
9
9
  readonly cleanupWorktrees?: boolean;
10
+ readonly dockerEnabled?: boolean;
11
+ readonly allowOpenPublicSandbox?: boolean;
10
12
  readonly cliProviders?: readonly string[];
11
13
  readonly providerStatuses?: Readonly<Record<string, BridgeProviderStatus>>;
12
14
  readonly projectLabels?: readonly string[];
@@ -34,4 +36,6 @@ export declare function removeRepoMapping(label: string): Promise<{
34
36
  readonly config: BridgeLocalConfig;
35
37
  readonly removed: boolean;
36
38
  }>;
39
+ export declare function setServerUrl(serverUrl: string): Promise<BridgeLocalConfig>;
40
+ export declare function setSandboxPolicy(dockerEnabled: boolean, allowOpenPublicSandbox: boolean): Promise<BridgeLocalConfig>;
37
41
  export declare function providerStatusesFor(providers: readonly string[]): Readonly<Record<string, BridgeProviderStatus>>;
@@ -45,6 +45,12 @@ export function applyLocalConfigDefaults(config, local) {
45
45
  deviceName: process.env.FORGE_DEVICE_NAME ?? local.deviceName ?? config.deviceName,
46
46
  defaultRepoRoot: process.env.FORGE_REPO_ROOT ?? local.defaultRepoRoot ?? config.defaultRepoRoot,
47
47
  cleanupWorktrees: local.cleanupWorktrees ?? config.cleanupWorktrees,
48
+ dockerEnabled: process.env.FORGE_DOCKER_SANDBOX === undefined
49
+ ? local.dockerEnabled ?? config.dockerEnabled
50
+ : config.dockerEnabled,
51
+ allowOpenPublicSandbox: process.env.FORGE_ALLOW_OPEN_PUBLIC_SANDBOX === undefined
52
+ ? local.allowOpenPublicSandbox ?? config.allowOpenPublicSandbox
53
+ : config.allowOpenPublicSandbox,
48
54
  cliProviders,
49
55
  providerStatuses: normalizeProviderStatuses(local.providerStatuses) ?? providerStatusesFor(cliProviders),
50
56
  projectLabels: local.projectLabels ?? config.projectLabels,
@@ -88,6 +94,19 @@ export async function removeRepoMapping(label) {
88
94
  await writeLocalConfig(next);
89
95
  return { config: next, removed: after.length !== before.length };
90
96
  }
97
+ export async function setServerUrl(serverUrl) {
98
+ const normalized = normalizeServerUrl(serverUrl);
99
+ const current = await readLocalConfig();
100
+ const next = normalizeLocalConfig({ ...current, serverUrl: normalized });
101
+ await writeLocalConfig(next);
102
+ return next;
103
+ }
104
+ export async function setSandboxPolicy(dockerEnabled, allowOpenPublicSandbox) {
105
+ const current = await readLocalConfig();
106
+ const next = normalizeLocalConfig({ ...current, dockerEnabled, allowOpenPublicSandbox });
107
+ await writeLocalConfig(next);
108
+ return next;
109
+ }
91
110
  export function providerStatusesFor(providers) {
92
111
  return Object.fromEntries(providers.map((provider) => [provider, { signedIn: true, version: "", models: configuredModelsFor(provider) }]));
93
112
  }
@@ -106,6 +125,8 @@ function normalizeLocalConfig(config) {
106
125
  deviceName: cleanString(config.deviceName),
107
126
  defaultRepoRoot: cleanString(config.defaultRepoRoot),
108
127
  cleanupWorktrees: config.cleanupWorktrees,
128
+ dockerEnabled: config.dockerEnabled,
129
+ allowOpenPublicSandbox: config.allowOpenPublicSandbox,
109
130
  cliProviders: cleanList(config.cliProviders),
110
131
  providerStatuses: normalizeProviderStatuses(config.providerStatuses),
111
132
  projectLabels: cleanList(config.projectLabels),
@@ -200,10 +221,11 @@ function normalizeQaAppLaunchTarget(value) {
200
221
  command: cleanString(value.command),
201
222
  working_directory: cleanString(value.working_directory),
202
223
  ready_url: cleanString(value.ready_url),
224
+ managed_runtime_port: cleanString(value.managed_runtime_port),
203
225
  routes,
204
226
  notes: cleanString(value.notes)
205
227
  };
206
- return normalized.url || normalized.command || normalized.ready_url || routes?.length
228
+ return normalized.url || normalized.command || normalized.ready_url || normalized.managed_runtime_port
207
229
  ? normalized
208
230
  : undefined;
209
231
  }
@@ -211,6 +233,24 @@ function cleanString(value) {
211
233
  const clean = value?.trim();
212
234
  return clean ? clean : undefined;
213
235
  }
236
+ function normalizeServerUrl(value) {
237
+ const clean = value.trim();
238
+ let parsed;
239
+ try {
240
+ parsed = new URL(clean);
241
+ }
242
+ catch {
243
+ throw new Error(`Invalid Forge server URL: ${value}`);
244
+ }
245
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
246
+ throw new Error("Forge server URL must use http or https.");
247
+ }
248
+ if (parsed.username || parsed.password || parsed.search || parsed.hash) {
249
+ throw new Error("Forge server URL cannot include credentials, a query string, or a fragment.");
250
+ }
251
+ parsed.pathname = parsed.pathname.replace(/\/+$/u, "") || "/";
252
+ return parsed.toString().replace(/\/$/u, "");
253
+ }
214
254
  function cleanList(values) {
215
255
  const clean = [...new Set((values ?? []).map((value) => value.trim()).filter(Boolean))];
216
256
  return clean.length > 0 ? clean : undefined;
@@ -0,0 +1,35 @@
1
+ export interface AspNetRuntimePrebuildPlan {
2
+ readonly fingerprint: string;
3
+ readonly receiptPath: string;
4
+ readonly command: string;
5
+ readonly args: readonly string[];
6
+ readonly cwd: string;
7
+ readonly environment: Readonly<Record<string, string>>;
8
+ readonly projectPath: string;
9
+ readonly inputCommitSha: string;
10
+ }
11
+ export interface AspNetRuntimePrebuildResult {
12
+ readonly cacheHit: boolean;
13
+ readonly receiptPath: string;
14
+ readonly fingerprint: string;
15
+ }
16
+ export interface AspNetRuntimeBuildExecutionResult {
17
+ readonly exitCode: number;
18
+ readonly stdoutTail: string;
19
+ readonly stderrTail: string;
20
+ readonly stdoutLogPath: string;
21
+ readonly stderrLogPath: string;
22
+ }
23
+ export type AspNetRuntimeBuildExecutor = (plan: AspNetRuntimePrebuildPlan, signal?: AbortSignal) => Promise<AspNetRuntimeBuildExecutionResult>;
24
+ export declare function createAspNetRuntimePrebuildPlan(options: {
25
+ readonly command: string;
26
+ readonly args: readonly string[];
27
+ readonly cwd: string;
28
+ readonly worktreePath: string;
29
+ readonly environment?: Readonly<Record<string, string>>;
30
+ readonly inputCommitSha: string;
31
+ readonly runtimeContractFingerprint: string;
32
+ }): AspNetRuntimePrebuildPlan | null;
33
+ export declare function ensureAspNetRuntimePrebuilt(plan: AspNetRuntimePrebuildPlan, execute: AspNetRuntimeBuildExecutor, signal?: AbortSignal): Promise<AspNetRuntimePrebuildResult>;
34
+ export declare function withAspNetPrebuiltRunArguments(command: string, args: readonly string[]): readonly string[];
35
+ export declare function resolveWorktreeCommitSha(worktreePath: string, supplied?: string | null): Promise<string>;