@loucompanion/forge-bridge 0.1.4-dev.bfa11ebe98c6 → 0.1.4-dev.c03d3c89ec4a

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