@loucompanion/forge-bridge 0.1.4-dev.63db04bcffca → 0.1.4-dev.800627ea0931

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 (170) hide show
  1. package/README.md +54 -2
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +16 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +125 -0
  4. package/dist/bridge/bridge.base.d.ts +9 -0
  5. package/dist/bridge/bridge.service.d.ts +85 -3
  6. package/dist/bridge/bridge.service.js +361 -122
  7. package/dist/bridge/bridge.types.d.ts +22 -0
  8. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  9. package/dist/bridge/dispatch-result-outbox.js +31 -6
  10. package/dist/bridge/local-yield-flag.d.ts +6 -0
  11. package/dist/bridge/local-yield-flag.js +34 -0
  12. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  13. package/dist/bridge/runner-host-capabilities.js +4 -0
  14. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  15. package/dist/bridge/test-postgres-capability.js +120 -0
  16. package/dist/cleanup/cleanup.service.d.ts +9 -0
  17. package/dist/cleanup/cleanup.service.js +72 -109
  18. package/dist/cleanup/cleanup.types.d.ts +4 -0
  19. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  20. package/dist/cleanup/forge-owned-paths.js +53 -0
  21. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  22. package/dist/cleanup/host-runtime-ledger.js +109 -0
  23. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  24. package/dist/cleanup/managed-branch-sweep.js +111 -0
  25. package/dist/cli/cli.help.js +18 -0
  26. package/dist/cli/cli.service.d.ts +16 -0
  27. package/dist/cli/cli.service.js +142 -16
  28. package/dist/cli/local-config.d.ts +4 -0
  29. package/dist/cli/local-config.js +26 -4
  30. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  31. package/dist/runtime/attempt-process-supervisor.d.ts +19 -0
  32. package/dist/runtime/attempt-process-supervisor.js +50 -0
  33. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  34. package/dist/runtime/host-database-capability-boundary.js +1 -0
  35. package/dist/runtime/host-facts.d.ts +35 -0
  36. package/dist/runtime/host-facts.js +95 -0
  37. package/dist/runtime/host-load-admission.d.ts +64 -0
  38. package/dist/runtime/host-load-admission.js +99 -0
  39. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  40. package/dist/runtime/host-load-child-environment.js +76 -0
  41. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  42. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  43. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  44. package/dist/runtime/host-load-governor-config.js +83 -0
  45. package/dist/runtime/host-load-governor.d.ts +184 -0
  46. package/dist/runtime/host-load-governor.js +632 -0
  47. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  48. package/dist/runtime/host-load-ledger-lock.js +185 -0
  49. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  50. package/dist/runtime/host-load-runtime-settings.js +78 -0
  51. package/dist/runtime/host-load-sampler.d.ts +126 -0
  52. package/dist/runtime/host-load-sampler.js +232 -0
  53. package/dist/runtime/host-load-step-class.d.ts +70 -0
  54. package/dist/runtime/host-load-step-class.js +161 -0
  55. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  56. package/dist/runtime/host-load-step-reaper.js +95 -0
  57. package/dist/runtime/host-load-step-run.d.ts +73 -0
  58. package/dist/runtime/host-load-step-run.js +102 -0
  59. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  60. package/dist/runtime/host-load-test-slot.js +81 -0
  61. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  62. package/dist/runtime/host-load-token-ledger.js +453 -0
  63. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  64. package/dist/runtime/host-pressure-stall.js +168 -0
  65. package/dist/runtime/host-runtime-contract.d.ts +4 -0
  66. package/dist/runtime/host-runtime-contract.js +6 -1
  67. package/dist/runtime/host-runtime-lease.d.ts +74 -4
  68. package/dist/runtime/host-runtime-lease.js +336 -20
  69. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  70. package/dist/runtime/host-runtime-promotion.js +48 -0
  71. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  72. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  73. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  74. package/dist/runtime/host-runtime-requirements.js +117 -0
  75. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  76. package/dist/runtime/managed-command-teardown.js +607 -0
  77. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  78. package/dist/runtime/playwright-browser-cache.js +227 -0
  79. package/dist/runtime/playwright-host-runtime-adapter.d.ts +18 -0
  80. package/dist/runtime/playwright-host-runtime-adapter.js +61 -55
  81. package/dist/runtime/runner-settings.d.ts +100 -0
  82. package/dist/runtime/runner-settings.js +214 -0
  83. package/dist/sandbox/host-capacity-broker.d.ts +113 -0
  84. package/dist/sandbox/host-capacity-broker.js +334 -0
  85. package/dist/sandbox/runtime.d.ts +10 -1
  86. package/dist/sandbox/runtime.js +45 -2
  87. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  88. package/dist/sandbox/sandbox-cgroups.js +42 -0
  89. package/dist/session/managed-attempt-tools.d.ts +27 -0
  90. package/dist/session/managed-attempt-tools.js +356 -41
  91. package/dist/session/managed-build-coordinator.d.ts +1 -1
  92. package/dist/session/managed-build-coordinator.js +4 -1
  93. package/dist/session/managed-command-host-load.d.ts +47 -0
  94. package/dist/session/managed-command-host-load.js +83 -0
  95. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  96. package/dist/session/mcp-argument-coercion.js +121 -0
  97. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  98. package/dist/session/phase-completion.artifacts.js +98 -25
  99. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  100. package/dist/session/phase-completion.command-validation.js +77 -0
  101. package/dist/session/phase-completion.d.ts +4 -0
  102. package/dist/session/phase-completion.helpers.js +13 -12
  103. package/dist/session/phase-completion.js +4 -0
  104. package/dist/session/phase-completion.prompts.js +6 -1
  105. package/dist/session/phase-completion.runtime.d.ts +5 -3
  106. package/dist/session/phase-completion.runtime.js +70 -35
  107. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  108. package/dist/session/phase-completion.schema-parts.js +188 -0
  109. package/dist/session/phase-completion.schemas.d.ts +3 -3
  110. package/dist/session/phase-completion.schemas.js +206 -221
  111. package/dist/session/phase-completion.validation.d.ts +2 -3
  112. package/dist/session/phase-completion.validation.js +46 -92
  113. package/dist/session/pre-publication-host-load.d.ts +27 -0
  114. package/dist/session/pre-publication-host-load.js +111 -0
  115. package/dist/session/pre-publication-pass.d.ts +60 -0
  116. package/dist/session/pre-publication-pass.js +145 -0
  117. package/dist/session/pre-publication-process.d.ts +23 -0
  118. package/dist/session/pre-publication-process.js +109 -0
  119. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  120. package/dist/session/pre-publication-skipped-tests.js +109 -0
  121. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  122. package/dist/session/pre-publication-step-execution.js +49 -0
  123. package/dist/session/pre-publication-validation.d.ts +30 -20
  124. package/dist/session/pre-publication-validation.js +173 -192
  125. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  126. package/dist/session/provider-cli/claude-background-work.js +180 -0
  127. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  128. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  129. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  130. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  131. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  132. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  133. package/dist/session/provider-cli/provider-cli.process.d.ts +39 -2
  134. package/dist/session/provider-cli/provider-cli.process.js +276 -42
  135. package/dist/session/provider-cli/provider-cli.prompts.d.ts +7 -0
  136. package/dist/session/provider-cli/provider-cli.prompts.js +65 -10
  137. package/dist/session/provider-cli/provider-cli.runtime.js +7 -0
  138. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  139. package/dist/session/provider-cli/provider-cli.service.js +203 -172
  140. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  141. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  142. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  143. package/dist/session/provider-cli/provider-output-state.d.ts +8 -0
  144. package/dist/session/provider-cli/provider-output-state.js +15 -0
  145. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  146. package/dist/session/publishable-worktree-changes.js +193 -0
  147. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  148. package/dist/session/sandbox-host-capacity-gate.js +231 -0
  149. package/dist/session/session.base.d.ts +9 -1
  150. package/dist/session/session.service.d.ts +9 -2
  151. package/dist/session/session.service.js +120 -5
  152. package/dist/session/session.types.d.ts +3 -0
  153. package/dist/session/session.types.js +15 -3
  154. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  155. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  156. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  157. package/dist/shared/process/host-process-supervisor.js +1 -1
  158. package/dist/shared/process/process-tree.d.ts +52 -0
  159. package/dist/shared/process/process-tree.js +144 -0
  160. package/dist/shared/process/process.d.ts +67 -0
  161. package/dist/shared/process/process.js +213 -11
  162. package/dist/shared/provider-capabilities.js +5 -6
  163. package/dist/version.d.ts +1 -1
  164. package/dist/version.js +1 -1
  165. package/dist/worktree/dependency-warmer.d.ts +25 -0
  166. package/dist/worktree/dependency-warmer.js +46 -10
  167. package/dist/worktree/worktree.service.d.ts +10 -1
  168. package/dist/worktree/worktree.service.js +42 -2
  169. package/dist/worktree/worktree.types.d.ts +7 -0
  170. package/package.json +2 -2
@@ -10,17 +10,26 @@ import { persistHostProcessSupervisorMetadata, resolveHostProcessSupervisedLaunc
10
10
  import { buildWindowsLaunchCommand } from "../../shared/process/windows-launch.js";
11
11
  import { assertHostDatabaseCapabilityBoundary } from "../../runtime/host-database-capability-boundary.js";
12
12
  import { ForgeFailureError } from "../session.types.js";
13
+ import { BackgroundWorkStopFailingRunner, ClaudeBackgroundTurnEndWatch, providerTurnEndedWithBackgroundWorkFailure } from "./claude-background-work.js";
14
+ import { hasNonterminalManagedCommand, isProviderTerminalFailure, isProviderTerminalSuccess, isProviderTurnActivity } from "./provider-in-flight-work.js";
13
15
  const execFileAsync = promisify(execFile);
14
16
  // Provider processes can emit many gigabytes over a long-running session. The
15
17
  // line handlers stream that output to Forge as it arrives; the completed result
16
18
  // only needs a bounded diagnostic tail for failure classification.
17
19
  export const PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS = 128 * 1024;
18
20
  const PROVIDER_TERMINAL_EXIT_GRACE_MS = 15_000;
21
+ // A provider that keeps starting turns after its first successful one (background-task
22
+ // notifications) is still stopped once this much time without supervised work in flight
23
+ // has passed since that first success.
24
+ const PROVIDER_TERMINAL_SUCCESS_CEILING_MS = 10 * 60_000;
25
+ // How often the end-of-turn timers re-check whether supervised work is still in flight.
26
+ const PROVIDER_TERMINAL_WORK_POLL_MS = 1_000;
19
27
  const maximumRecoverableCodexModelsCacheBytes = 16 * 1024 * 1024;
20
28
  /** Recovery must wrap the attempt coordinator, never its raw OS runner. Each
21
- * relaunch needs a new fenced child generation and exclusive launch files. */
29
+ * relaunch needs a new fenced child generation and exclusive launch files. The outer
30
+ * layer fails any run Forge stopped because its turn ended with background work live. */
22
31
  export function recoveringProviderProcessRunner(inner) {
23
- return new CodexResumeRecoveringProcessRunner(new CodexModelsCacheRecoveringProcessRunner(inner));
32
+ return new BackgroundWorkStopFailingRunner(new CodexResumeRecoveringProcessRunner(new CodexModelsCacheRecoveringProcessRunner(inner)));
24
33
  }
25
34
  /**
26
35
  * Codex Desktop and an independently installed Codex CLI can briefly disagree
@@ -44,6 +53,7 @@ export class CodexModelsCacheRecoveringProcessRunner {
44
53
  const recovered = await quarantineIncompatibleCodexModelsCache(request.env).catch(() => false);
45
54
  if (!recovered || signal?.aborted)
46
55
  return first;
56
+ handlers?.onGenerationStart?.();
47
57
  return await this.inner.run(request, handlers, signal);
48
58
  }
49
59
  }
@@ -66,7 +76,10 @@ export class CodexResumeRecoveringProcessRunner {
66
76
  return first;
67
77
  }
68
78
  const fallback = codexFreshTurnRequest(request);
69
- return fallback ? await this.inner.run(fallback, handlers, signal) : first;
79
+ if (!fallback)
80
+ return first;
81
+ handlers?.onGenerationStart?.();
82
+ return await this.inner.run(fallback, handlers, signal);
70
83
  }
71
84
  }
72
85
  function isRecoverableCodexResumeFailure(command, result) {
@@ -104,7 +117,8 @@ function codexFreshTurnRequest(request) {
104
117
  const cd = args.splice(cdIndex, 2);
105
118
  args.splice(args.length - 1, 0, ...cd);
106
119
  }
107
- return { ...request, args };
120
+ // The fallback starts a fresh thread, so it has no replayed turn to discount.
121
+ return { ...request, args, resumesProviderThread: false };
108
122
  }
109
123
  function isCodexCommand(command) {
110
124
  return path.parse(command).name.toLowerCase() === "codex";
@@ -313,22 +327,45 @@ function setEnvironmentValueIfMissing(env, name, value) {
313
327
  }
314
328
  export class StreamingProviderProcessRunner {
315
329
  terminalExitGraceMs;
316
- constructor(terminalExitGraceMs = PROVIDER_TERMINAL_EXIT_GRACE_MS) {
330
+ terminalSuccessCeilingMs;
331
+ terminalWorkPollMs;
332
+ constructor(terminalExitGraceMs = PROVIDER_TERMINAL_EXIT_GRACE_MS, terminalSuccessCeilingMs = PROVIDER_TERMINAL_SUCCESS_CEILING_MS, terminalWorkPollMs = PROVIDER_TERMINAL_WORK_POLL_MS) {
317
333
  this.terminalExitGraceMs = terminalExitGraceMs;
334
+ this.terminalSuccessCeilingMs = terminalSuccessCeilingMs;
335
+ this.terminalWorkPollMs = terminalWorkPollMs;
318
336
  }
319
337
  async run(request, handlers = {}, signal) {
320
338
  assertHostDatabaseCapabilityBoundary();
339
+ // Every child this runner launches is a new generation, including supervisor retries.
340
+ handlers.onGenerationStart?.();
321
341
  const providerLaunch = await resolveProviderProcessLaunch(request.command, request.args);
322
342
  const supervisedLaunch = resolveHostProcessSupervisedLaunch(request, providerLaunch.command, providerLaunch.args);
323
343
  // An unsupervised Unix provider still gets a dedicated process group so a
324
344
  // cancellation can stop descendants instead of only the CLI root.
325
345
  const launch = supervisedLaunch ?? { ...providerLaunch, detached: process.platform !== "win32" };
346
+ const childEnvironment = buildProviderChildEnvironment(request.env);
347
+ // A piped prompt must reach the provider promptly (Claude Code abandons a
348
+ // silent stdin after ~3s), but the provider must not run before Forge has
349
+ // recorded its start. Off Windows, hold the launch behind a start gate in
350
+ // the same process: the prompt is written immediately and buffers in the
351
+ // pipe, and the gate execs the provider only once onStarted succeeds.
352
+ const startGated = process.platform !== "win32"
353
+ && supervisedLaunch?.strategy !== "windows_job_object"
354
+ && request.stdin !== undefined
355
+ && fs.existsSync(UNIX_PROVIDER_START_GATE_SHELL)
356
+ && isUnixExecutableAvailable(launch.command, childEnvironment.PATH, request.cwd);
357
+ const spawnLaunch = startGated
358
+ ? buildUnixProviderStartGateLaunch(launch.command, launch.args)
359
+ : launch;
326
360
  return await new Promise((resolve, reject) => {
327
361
  const rootCreatedAt = new Date().toISOString();
328
- const child = spawn(launch.command, launch.args, {
362
+ const stdinMode = request.stdin === undefined ? "ignore" : "pipe";
363
+ const child = spawn(spawnLaunch.command, spawnLaunch.args, {
329
364
  cwd: request.cwd,
330
- env: buildProviderChildEnvironment(request.env),
331
- stdio: [request.stdin === undefined ? "ignore" : "pipe", "pipe", "pipe"],
365
+ env: childEnvironment,
366
+ stdio: startGated
367
+ ? [stdinMode, "pipe", "pipe", "pipe"]
368
+ : [stdinMode, "pipe", "pipe"],
332
369
  windowsHide: true,
333
370
  detached: launch.detached,
334
371
  });
@@ -344,7 +381,7 @@ export class StreamingProviderProcessRunner {
344
381
  const childStderr = child.stderr;
345
382
  if (!childStdout || !childStderr) {
346
383
  const pipeError = new Error("Provider process stdout/stderr streams were not piped.");
347
- void terminate().then(() => reject(pipeError), terminationError => reject(new AggregateError([pipeError, terminationError], "Provider launch failed and its process tree could not be proven stopped.")));
384
+ void terminate().then(() => reject(pipeError), terminationError => reject(new AggregateError([pipeError, terminationError], "host_process_supervisor_termination_failed: Provider launch failed and its process tree could not be proven stopped.")));
348
385
  return;
349
386
  }
350
387
  const stdout = new BoundedOutputTail(PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS);
@@ -352,14 +389,26 @@ export class StreamingProviderProcessRunner {
352
389
  let settled = false;
353
390
  let closed = false;
354
391
  let cancellationRequested = false;
392
+ let cancelledBeforeClose = false;
355
393
  let terminalTerminationStarted = false;
356
- let terminalExitTimer = null;
394
+ let terminalStopReason = null;
395
+ // Idle time (no supervised work in flight) accrued against the end-of-turn grace and
396
+ // the success ceiling; null while that timer is not armed.
397
+ let graceIdleMs = null;
398
+ let ceilingIdleMs = null;
399
+ let terminalSuccessCount = 0;
400
+ let replayedTurnCeilingSkipped = false;
401
+ let terminalWorkTimer = null;
402
+ let terminalWorkTickAt = 0;
403
+ let terminalWorkTickRunning = false;
404
+ let latestTurnFailed = false;
357
405
  let readiness = null;
406
+ const backgroundTurnEnd = new ClaudeBackgroundTurnEndWatch(request.command, this.terminalExitGraceMs, () => finishAfterTerminalSuccess("turn_ended_with_background_work"));
358
407
  const cleanup = () => {
359
- if (terminalExitTimer) {
360
- clearTimeout(terminalExitTimer);
361
- terminalExitTimer = null;
362
- }
408
+ stopTerminalWorkTimer();
409
+ backgroundTurnEnd.stop();
410
+ graceIdleMs = null;
411
+ ceilingIdleMs = null;
363
412
  signal?.removeEventListener("abort", abort);
364
413
  };
365
414
  const fail = (error) => {
@@ -370,22 +419,43 @@ export class StreamingProviderProcessRunner {
370
419
  cleanup();
371
420
  // Do not release the caller's reservation/worktree/port ownership until
372
421
  // descendant termination has completed (or failed with explicit proof).
373
- void terminate().then(() => reject(error), terminationError => reject(new AggregateError([error, terminationError], "Provider process failed and its process tree could not be proven stopped.")));
422
+ void terminate().then(() => reject(error), terminationError => reject(new AggregateError([error, terminationError], "host_process_supervisor_termination_failed: Provider process failed and its process tree could not be proven stopped.")));
374
423
  };
375
424
  const abort = () => {
425
+ if (!closed)
426
+ cancelledBeforeClose = true;
376
427
  cancellationRequested = true;
377
428
  // Cancellation is not a launch failure when the supervised tree can be
378
429
  // proven stopped. Let the close handler settle the command after exact
379
430
  // termination; only a failed termination proof rejects the run.
380
431
  void terminate().catch(fail);
381
432
  };
382
- if (signal?.aborted) {
433
+ if (signal?.aborted)
383
434
  abort();
384
- }
385
- else {
435
+ else
386
436
  signal?.addEventListener("abort", abort, { once: true });
387
- }
388
437
  child.on("error", fail);
438
+ const startGrant = startGated ? child.stdio[3] : null;
439
+ if (startGated && !startGrant) {
440
+ fail(new Error("Provider start-grant stream was not piped."));
441
+ return;
442
+ }
443
+ startGrant?.on("error", error => {
444
+ // A broken grant pipe means the gate already exited (terminated before
445
+ // its grant, or it died on its own). Its close event carries the real
446
+ // exit status, so an EPIPE here must not replace that result.
447
+ if (isBrokenPipeError(error))
448
+ return;
449
+ fail(error);
450
+ });
451
+ const grantUnixProviderStart = () => {
452
+ if (!startGrant)
453
+ return;
454
+ // Never release a provider whose launch was cancelled or already failed.
455
+ if (closed || settled || cancellationRequested || signal?.aborted)
456
+ return;
457
+ startGrant.end(UNIX_PROVIDER_START_GRANT_LINE, "utf8");
458
+ };
389
459
  child.once("spawn", () => {
390
460
  readiness = (async () => {
391
461
  const providerReady = supervisedLaunch?.strategy === "windows_job_object"
@@ -398,6 +468,9 @@ export class StreamingProviderProcessRunner {
398
468
  if (supervisedLaunch?.strategy === "windows_job_object") {
399
469
  grantWindowsProviderStart(supervisedLaunch);
400
470
  }
471
+ else if (startGated) {
472
+ grantUnixProviderStart();
473
+ }
401
474
  })();
402
475
  void readiness.catch(error => {
403
476
  if (!closed && !signal?.aborted)
@@ -413,15 +486,20 @@ export class StreamingProviderProcessRunner {
413
486
  return;
414
487
  }
415
488
  child.stdin.on("error", (error) => {
489
+ // A prompt still buffered when Forge stops the process (cancellation,
490
+ // or a refused start grant) cannot be delivered; that broken pipe is
491
+ // not a failure. Any other stdin error still is.
492
+ if ((cancellationRequested || termination) && isBrokenPipeError(error))
493
+ return;
416
494
  void terminate();
417
495
  fail(error);
418
496
  });
419
497
  child.stdin.end(request.stdin, "utf8");
420
498
  };
421
499
  if (request.stdin !== undefined) {
422
- if (supervisedLaunch?.strategy === "windows_job_object") {
423
- // The outer supervisor must receive stdin before it can launch the
424
- // inner provider. Its start-grant file prevents prompt delivery.
500
+ if (supervisedLaunch?.strategy === "windows_job_object" || startGated) {
501
+ // The outer supervisor / Unix start gate must receive stdin before it
502
+ // can launch the provider. Its start grant fences prompt processing.
425
503
  writeProviderInput();
426
504
  }
427
505
  else {
@@ -430,19 +508,111 @@ export class StreamingProviderProcessRunner {
430
508
  });
431
509
  }
432
510
  }
511
+ const finishAfterTerminalSuccess = (reason) => {
512
+ if (closed || settled || cancellationRequested || terminalTerminationStarted)
513
+ return;
514
+ terminalTerminationStarted = true;
515
+ terminalStopReason = reason;
516
+ stopTerminalWorkTimer();
517
+ void terminate().catch(fail);
518
+ };
519
+ const workInFlight = async () => {
520
+ try {
521
+ if (handlers.isToolCallInFlight?.())
522
+ return true;
523
+ }
524
+ catch {
525
+ // A failing probe must not keep the provider open or stop it early on its own.
526
+ }
527
+ return await hasNonterminalManagedCommand(request.env?.FORGE_LOG_DIR).catch(() => false);
528
+ };
529
+ // The grace and the ceiling only count time in which no supervised work is in flight:
530
+ // a provider waiting on an MCP tool call or on a managed command it started is not
531
+ // finished, even when its turn has ended. The grace restarts once that work is done.
532
+ const terminalWorkTick = async () => {
533
+ if (terminalWorkTickRunning)
534
+ return;
535
+ terminalWorkTickRunning = true;
536
+ try {
537
+ const inFlight = await workInFlight();
538
+ const now = performance.now();
539
+ const elapsed = Math.max(0, now - terminalWorkTickAt);
540
+ terminalWorkTickAt = now;
541
+ if (closed || settled || terminalTerminationStarted)
542
+ return;
543
+ if (inFlight) {
544
+ if (graceIdleMs !== null)
545
+ graceIdleMs = 0;
546
+ return;
547
+ }
548
+ if (graceIdleMs !== null)
549
+ graceIdleMs += elapsed;
550
+ if (ceilingIdleMs !== null)
551
+ ceilingIdleMs += elapsed;
552
+ if (graceIdleMs !== null && graceIdleMs >= this.terminalExitGraceMs) {
553
+ finishAfterTerminalSuccess("turn_exit_grace");
554
+ }
555
+ else if (ceilingIdleMs !== null && ceilingIdleMs >= this.terminalSuccessCeilingMs) {
556
+ finishAfterTerminalSuccess("success_ceiling");
557
+ }
558
+ }
559
+ finally {
560
+ terminalWorkTickRunning = false;
561
+ if (graceIdleMs === null && ceilingIdleMs === null)
562
+ stopTerminalWorkTimer();
563
+ }
564
+ };
565
+ function stopTerminalWorkTimer() {
566
+ if (terminalWorkTimer) {
567
+ clearInterval(terminalWorkTimer);
568
+ terminalWorkTimer = null;
569
+ }
570
+ }
571
+ const startTerminalWorkTimer = () => {
572
+ if (terminalWorkTimer)
573
+ return;
574
+ terminalWorkTickAt = performance.now();
575
+ const intervalMs = Math.max(1, Math.min(this.terminalWorkPollMs, this.terminalExitGraceMs, this.terminalSuccessCeilingMs));
576
+ terminalWorkTimer = setInterval(() => { void terminalWorkTick().catch(fail); }, intervalMs);
577
+ terminalWorkTimer.unref?.();
578
+ };
579
+ const armTerminalExit = () => {
580
+ terminalSuccessCount += 1;
581
+ graceIdleMs = 0;
582
+ // Later turns may postpone the grace period, but never past this ceiling.
583
+ ceilingIdleMs ??= 0;
584
+ startTerminalWorkTimer();
585
+ };
433
586
  const readers = [
434
587
  readProcessLines(childStdout, (line) => {
435
588
  if (request.captureOutput !== false)
436
589
  stdout.appendLine(line);
437
590
  const handled = handlers.onStdoutLine?.(line);
438
- if (!terminalExitTimer && isProviderTerminalSuccess(line)) {
439
- terminalExitTimer = setTimeout(() => {
440
- if (closed || settled || cancellationRequested)
441
- return;
442
- terminalTerminationStarted = true;
443
- void terminate().catch(fail);
444
- }, this.terminalExitGraceMs);
445
- terminalExitTimer.unref?.();
591
+ backgroundTurnEnd.consume(line);
592
+ if (!terminalTerminationStarted) {
593
+ if (isProviderTerminalSuccess(line)) {
594
+ latestTurnFailed = false;
595
+ armTerminalExit();
596
+ }
597
+ else if (isProviderTerminalFailure(line)) {
598
+ // A later turn that fails reports its failure even after an earlier success.
599
+ latestTurnFailed = true;
600
+ }
601
+ else if (graceIdleMs !== null && isProviderTurnActivity(line)) {
602
+ // A terminal event ends a turn, not necessarily the provider. Claude Code
603
+ // stays resident while background tasks it started are pending and begins a
604
+ // new turn when one reports. A provider that is working again is not finished;
605
+ // the grace period restarts at its next terminal event.
606
+ graceIdleMs = null;
607
+ // A resumed session can replay a queued notification turn before the
608
+ // prompt's own turn. The replayed turn must not consume the ceiling, or the
609
+ // resumed agent is stopped mid-work, but the prompt's turn still needs a
610
+ // watchdog: restart the ceiling from here instead of dropping it.
611
+ if (request.resumesProviderThread && terminalSuccessCount === 1 && !replayedTurnCeilingSkipped) {
612
+ replayedTurnCeilingSkipped = true;
613
+ ceilingIdleMs = 0;
614
+ }
615
+ }
446
616
  }
447
617
  return handled;
448
618
  }),
@@ -489,28 +659,34 @@ export class StreamingProviderProcessRunner {
489
659
  // that event, terminate the supervised tree after a short grace
490
660
  // period and preserve the successful handoff so the existing
491
661
  // artifact, commit, and publication gates can run.
492
- exitCode: terminalTerminationStarted && !cancellationRequested ? 0 : code ?? 1,
662
+ // A provider stopped after a successful turn keeps that success. Whenever the
663
+ // most recent turn failed, the run fails, however the process ended.
664
+ exitCode: latestTurnFailed
665
+ ? code && code !== 0 ? code : 1
666
+ : terminalTerminationStarted && !cancellationRequested ? 0 : code ?? 1,
493
667
  stdout: stdout.toString(),
494
668
  stderr: stderr.toString(),
495
669
  ...(memory ?? {}),
670
+ ...(cancelledBeforeClose ? { cancelled: true } : {}),
671
+ ...(terminalStopReason && !cancellationRequested ? { terminalStopReason } : {}),
496
672
  });
497
673
  }).catch(fail);
498
674
  });
499
675
  });
500
676
  }
501
677
  }
502
- function isProviderTerminalSuccess(line) {
503
- const trimmed = line.trim();
504
- if (!trimmed.startsWith("{"))
505
- return false;
506
- try {
507
- const event = JSON.parse(trimmed);
508
- return event.type === "turn.completed"
509
- || (event.type === "result" && event.subtype === "success" && event.is_error !== true);
510
- }
511
- catch {
512
- return false;
678
+ /**
679
+ * The typed failure for a provider run that ended without calling its required Forge
680
+ * completion tool. A run Forge stopped at the success ceiling or for background work is
681
+ * reported as such, so it is not mistaken for an agent that simply ended its turn.
682
+ */
683
+ export function providerCompletionToolMissingFailure(message, result) {
684
+ if (result?.terminalStopReason === "turn_ended_with_background_work")
685
+ return providerTurnEndedWithBackgroundWorkFailure(message);
686
+ if (result?.terminalStopReason === "success_ceiling") {
687
+ return new ForgeFailureError("provider_terminated_at_turn_ceiling", `${message} Forge stopped the provider at its post-turn success ceiling while it was still working.`);
513
688
  }
689
+ return new ForgeFailureError("provider_completion_tool_missing", message);
514
690
  }
515
691
  class HostProcessTreeMemoryObserver {
516
692
  launch;
@@ -682,6 +858,64 @@ async function resolveProviderProcessLaunch(command, args) {
682
858
  ?? resolvePackageManagerDirectLaunch(resolved, args)
683
859
  ?? buildWindowsLaunchCommand(resolved, args);
684
860
  }
861
+ const UNIX_PROVIDER_START_GATE_SHELL = "/bin/sh";
862
+ const UNIX_PROVIDER_START_GATE_NAME = "forge-provider-start-gate";
863
+ export const UNIX_PROVIDER_START_GRANT_LINE = "forge-provider-start-granted\n";
864
+ /**
865
+ * Blocks on fd 3 until the bridge writes the exact grant line, then replaces
866
+ * itself with the provider (`exec`), so the supervised root PID, process group
867
+ * and birth identity stay the provider's. The provider command and arguments
868
+ * are passed positionally and expanded only as "$@"; nothing is interpolated
869
+ * into the script. EOF, a read error, or any other content on fd 3 exits
870
+ * without running the provider. fd 3 is closed before exec so the provider and
871
+ * its descendants never inherit the grant channel. stdin is not touched, so
872
+ * the prompt stays buffered in its pipe for the provider.
873
+ */
874
+ const UNIX_PROVIDER_START_GATE_SCRIPT = [
875
+ "IFS= read -r forge_start_grant <&3 || { echo \"$0: provider start was not granted\" >&2; exit 125; }",
876
+ `[ "$forge_start_grant" = "${UNIX_PROVIDER_START_GRANT_LINE.trim()}" ] || { echo "$0: provider start grant was invalid" >&2; exit 125; }`,
877
+ "exec \"$@\" 3<&-",
878
+ ].join("\n");
879
+ export function buildUnixProviderStartGateLaunch(command, args) {
880
+ return {
881
+ command: UNIX_PROVIDER_START_GATE_SHELL,
882
+ args: ["-c", UNIX_PROVIDER_START_GATE_SCRIPT, UNIX_PROVIDER_START_GATE_NAME, command, ...args],
883
+ };
884
+ }
885
+ /**
886
+ * Mirrors the executable lookup the gate's `exec` will perform. A command that
887
+ * cannot be found is spawned directly instead so it keeps failing as a spawn
888
+ * ENOENT before any start is recorded; nothing can run in that case. The check
889
+ * is advisory: if the executable disappears between this lookup and the gated
890
+ * `exec`, the gate exits 127 with the shell's "not found" message after the
891
+ * start was recorded, which surfaces as an ordinary provider failure.
892
+ */
893
+ function isUnixExecutableAvailable(command, pathValue, cwd) {
894
+ if (!command || command.startsWith("-"))
895
+ return false;
896
+ const candidates = command.includes("/")
897
+ ? [path.resolve(cwd, command)]
898
+ : pathValue === undefined
899
+ ? null
900
+ : pathValue.split(path.delimiter).map(directory => path.resolve(cwd, directory || ".", command));
901
+ if (candidates === null)
902
+ return true;
903
+ return candidates.some(candidate => {
904
+ try {
905
+ if (!fs.statSync(candidate).isFile())
906
+ return false;
907
+ fs.accessSync(candidate, fs.constants.X_OK);
908
+ return true;
909
+ }
910
+ catch {
911
+ return false;
912
+ }
913
+ });
914
+ }
915
+ function isBrokenPipeError(error) {
916
+ const code = error?.code;
917
+ return code === "EPIPE" || code === "ERR_STREAM_DESTROYED" || code === "ECONNRESET";
918
+ }
685
919
  function grantWindowsProviderStart(launch) {
686
920
  if (!launch.startGrantPath) {
687
921
  throw new Error("host_process_supervisor_invalid: Windows provider start-grant path was not assigned.");
@@ -34,7 +34,14 @@ export declare function codexSandboxModeForPlatform(platform?: NodeJS.Platform,
34
34
  export declare function buildArchitectPrompt(dispatch: RunOnceDispatchPacket): string;
35
35
  export declare function architectDependencyInstruction(dispatch: RunOnceDispatchPacket): string;
36
36
  export declare function designerRefInstruction(dispatch: RunOnceDispatchPacket): string;
37
+ export declare function designerRefBuildInstruction(dispatch: RunOnceDispatchPacket): string;
38
+ export declare function designerRefQaInstruction(dispatch: RunOnceDispatchPacket): string;
37
39
  export declare function architectRevisionInstruction(dispatch: RunOnceDispatchPacket): string;
40
+ /**
41
+ * Headless providers must not end a turn to wait: Forge stops the provider shortly after
42
+ * a turn ends, and nothing started in the background reports back.
43
+ */
44
+ export declare function providerTurnEndRule(completionStep: string): string;
38
45
  export declare function buildImplementationPrompt(dispatch: RunOnceDispatchPacket, phase?: import("../phase-completion.js").CompletionPhase): string;
39
46
  export declare function buildDevelopCyclePrompt(dispatch: RunOnceDispatchPacket, phase?: import("../phase-completion.js").CompletionPhase): string;
40
47
  export declare function buildDebugCyclePrompt(dispatch: RunOnceDispatchPacket, phase?: import("../phase-completion.js").CompletionPhase): string;