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

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 (98) hide show
  1. package/README.md +55 -0
  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 +71 -2
  6. package/dist/bridge/bridge.service.js +282 -114
  7. package/dist/bridge/bridge.types.d.ts +11 -0
  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 +3 -0
  11. package/dist/bridge/runner-host-capabilities.js +13 -0
  12. package/dist/cli/cli.help.js +18 -0
  13. package/dist/cli/cli.service.d.ts +16 -0
  14. package/dist/cli/cli.service.js +132 -14
  15. package/dist/cli/local-config.d.ts +4 -0
  16. package/dist/cli/local-config.js +26 -4
  17. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  18. package/dist/runtime/host-facts.d.ts +2 -1
  19. package/dist/runtime/host-load-admission.d.ts +18 -3
  20. package/dist/runtime/host-load-admission.js +19 -4
  21. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  22. package/dist/runtime/host-load-child-environment.js +22 -11
  23. package/dist/runtime/host-load-governor-config.d.ts +19 -1
  24. package/dist/runtime/host-load-governor-config.js +37 -0
  25. package/dist/runtime/host-load-governor.d.ts +12 -0
  26. package/dist/runtime/host-load-governor.js +139 -26
  27. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  28. package/dist/runtime/host-load-runtime-settings.js +78 -0
  29. package/dist/runtime/host-load-sampler.d.ts +26 -3
  30. package/dist/runtime/host-load-sampler.js +61 -2
  31. package/dist/runtime/host-load-step-class.d.ts +3 -1
  32. package/dist/runtime/host-load-step-class.js +60 -5
  33. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  34. package/dist/runtime/host-load-test-slot.js +81 -0
  35. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  36. package/dist/runtime/host-load-token-ledger.js +93 -61
  37. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  38. package/dist/runtime/host-load-windows-cpu.js +85 -0
  39. package/dist/runtime/host-runtime-lease.d.ts +59 -3
  40. package/dist/runtime/host-runtime-lease.js +199 -8
  41. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  42. package/dist/runtime/host-runtime-promotion.js +36 -0
  43. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  44. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  45. package/dist/runtime/runner-settings.d.ts +100 -0
  46. package/dist/runtime/runner-settings.js +214 -0
  47. package/dist/sandbox/host-capacity-broker.d.ts +7 -1
  48. package/dist/sandbox/host-capacity-broker.js +23 -4
  49. package/dist/session/architect-waits.d.ts +2 -0
  50. package/dist/session/architect-waits.js +138 -0
  51. package/dist/session/managed-attempt-tools.js +8 -9
  52. package/dist/session/managed-command-host-load.d.ts +2 -0
  53. package/dist/session/managed-command-host-load.js +2 -1
  54. package/dist/session/phase-completion.schemas.js +25 -23
  55. package/dist/session/phase-completion.validation.js +3 -1
  56. package/dist/session/pre-publication-pass.d.ts +61 -0
  57. package/dist/session/pre-publication-pass.js +148 -0
  58. package/dist/session/pre-publication-validation.d.ts +23 -11
  59. package/dist/session/pre-publication-validation.js +178 -107
  60. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  61. package/dist/session/provider-cli/claude-background-work.js +180 -0
  62. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  63. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  64. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  65. package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
  66. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  67. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  68. package/dist/session/provider-cli/provider-cli.process.d.ts +13 -22
  69. package/dist/session/provider-cli/provider-cli.process.js +36 -337
  70. package/dist/session/provider-cli/provider-cli.prompts.d.ts +2 -0
  71. package/dist/session/provider-cli/provider-cli.prompts.js +49 -9
  72. package/dist/session/provider-cli/provider-cli.runtime.js +7 -0
  73. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  74. package/dist/session/provider-cli/provider-cli.service.js +74 -151
  75. package/dist/session/provider-cli/provider-cli.types.d.ts +26 -0
  76. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  77. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  78. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  79. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  80. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  81. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  82. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  83. package/dist/session/provider-cli/provider-output-state.js +6 -0
  84. package/dist/session/sandbox-host-capacity-gate.js +12 -3
  85. package/dist/session/session.base.d.ts +6 -1
  86. package/dist/session/session.service.d.ts +7 -2
  87. package/dist/session/session.service.js +100 -2
  88. package/dist/session/session.types.js +3 -3
  89. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  90. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  91. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  92. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  93. package/dist/shared/process/windows-launch.d.ts +18 -0
  94. package/dist/shared/process/windows-launch.js +68 -0
  95. package/dist/shared/provider-capabilities.js +5 -6
  96. package/dist/version.d.ts +1 -1
  97. package/dist/version.js +1 -1
  98. package/package.json +2 -2
@@ -0,0 +1,67 @@
1
+ import readline from "node:readline";
2
+ /**
3
+ * How long Forge keeps waiting, once the provider's root process has exited, for its output
4
+ * pipes to reach end-of-file. Node reports a child's "close" only after every copy of its
5
+ * stdout and stderr write ends is closed, and a descendant that escaped the provider's
6
+ * supervision can hold an inherited copy for as long as it runs: on Windows, a process that a
7
+ * Microsoft Store app-execution alias (`...\WindowsApps\pwsh.exe`) created outside the provider's
8
+ * Job Object; elsewhere, one that left the provider's process group. Output the root wrote
9
+ * before it exited drains within this grace. After it, Forge closes its read ends, so the run
10
+ * settles on the root's exit instead of on that descendant's.
11
+ */
12
+ export const PROVIDER_OUTPUT_PIPE_RELEASE_GRACE_MS = 5_000;
13
+ /** Closes a child's output pipes a bounded grace after the child exits, unless they close first. */
14
+ export class OutputPipeRelease {
15
+ child;
16
+ graceMs;
17
+ onRelease;
18
+ timer = null;
19
+ released = false;
20
+ constructor(child, graceMs, onRelease) {
21
+ this.child = child;
22
+ this.graceMs = graceMs;
23
+ this.onRelease = onRelease;
24
+ child.once("exit", () => this.arm());
25
+ child.once("close", () => this.stop());
26
+ }
27
+ resultFields() {
28
+ return this.released ? { outputPipesReleasedAfterExit: true } : {};
29
+ }
30
+ stop() {
31
+ if (!this.timer)
32
+ return;
33
+ clearTimeout(this.timer);
34
+ this.timer = null;
35
+ }
36
+ arm() {
37
+ if (this.timer || this.released)
38
+ return;
39
+ this.timer = setTimeout(() => this.release(), Math.max(0, this.graceMs));
40
+ }
41
+ release() {
42
+ this.timer = null;
43
+ // fd 0 is the child's input; Node's "close" waits only for the others.
44
+ const open = this.child.stdio.slice(1).filter(stream => stream && !stream.destroyed);
45
+ if (open.length === 0)
46
+ return;
47
+ this.released = true;
48
+ this.onRelease(`forge-bridge: the provider's output pipes were still open ${this.graceMs} ms after its process exited, `
49
+ + "so a descendant outside its supervision still holds them. Forge closed them to settle the run.");
50
+ for (const stream of open)
51
+ stream?.destroy();
52
+ }
53
+ }
54
+ export async function readProcessLines(stream, onLine) {
55
+ const reader = readline.createInterface({ input: stream });
56
+ // readline finishes on "end" only. A stream OutputPipeRelease destroys closes without one;
57
+ // closing the reader then still delivers every line already read.
58
+ stream.once("close", () => reader.close());
59
+ try {
60
+ for await (const line of reader) {
61
+ await onLine(line);
62
+ }
63
+ }
64
+ finally {
65
+ reader.close();
66
+ }
67
+ }
@@ -1,6 +1,8 @@
1
1
  import type { RunnerDispatchEvent } from "../session.types.js";
2
2
  import { type ProviderUsage } from "./provider-usage.js";
3
3
  export declare function messageFromError(error: unknown): string;
4
+ /** Keeps the end of `value`, where a process's failure detail is, within `maximumLength`. */
5
+ export declare function clipTail(value: string, maximumLength: number): string;
4
6
  export declare function clip(value: string, maxLength: number): string;
5
7
  export interface ProviderOutputState {
6
8
  readonly sessionLabel: string | null;
@@ -2,6 +2,12 @@ import { addUsage, emptyUsage, readUsageNumber } from "./provider-usage.js";
2
2
  export function messageFromError(error) {
3
3
  return error instanceof Error ? error.message : String(error);
4
4
  }
5
+ /** Keeps the end of `value`, where a process's failure detail is, within `maximumLength`. */
6
+ export function clipTail(value, maximumLength) {
7
+ if (value.length <= maximumLength)
8
+ return value;
9
+ return `...${value.slice(-(maximumLength - 3))}`;
10
+ }
5
11
  export function clip(value, maxLength) {
6
12
  if (maxLength <= 0) {
7
13
  return "";
@@ -107,6 +107,8 @@ export class SandboxBrokeredHostLoadGate {
107
107
  holding = true;
108
108
  if (!fenced.signal.aborted)
109
109
  fenced.abort(reason);
110
+ // The bridge marks the host token retained, so this attempt's next step does not wait for it.
111
+ this.send("retain", requestId, request);
110
112
  if (!stillGone)
111
113
  return;
112
114
  let checking = false;
@@ -177,9 +179,10 @@ function responseError(request, response) {
177
179
  return new ForgeFailureError(response.code ?? "host_capacity_broker_failed", message, "bridge");
178
180
  }
179
181
  /**
180
- * The bridge's reply, or null while there is none. Only a regular file with a
181
- * single link, owned by the trusted uid and writable by no one else, is the
182
- * bridge's: the sandbox user can create none of those (see host-capacity-broker.ts).
182
+ * The bridge's reply, or null while there is none (or the one opened was just
183
+ * replaced by a newer reply). Only a regular file with a single link, owned by the
184
+ * trusted uid and writable by no one else, is the bridge's: the sandbox user can
185
+ * create none of those (see host-capacity-broker.ts).
183
186
  * Anything else fails closed with sandbox_host_capacity_reply_untrusted.
184
187
  */
185
188
  async function readResponse(responsePath, requestId, trustedOwnerUid) {
@@ -195,6 +198,12 @@ async function readResponse(responsePath, requestId, trustedOwnerUid) {
195
198
  let content;
196
199
  try {
197
200
  const stat = await handle.stat();
201
+ // No link left: the bridge renamed a newer reply over this one after it was opened
202
+ // (waiting -> admitted, admitted -> fenced). It is not a forgery, and nothing is read
203
+ // from it; the next poll opens the newer reply. Only the bridge can replace a reply,
204
+ // since the directory is root-owned and not writable by the sandbox user.
205
+ if (stat.isFile() && stat.nlink === 0)
206
+ return null;
198
207
  if (!stat.isFile() || stat.nlink !== 1)
199
208
  throw untrustedReply(responsePath, "it is not a regular file with a single link");
200
209
  if (stat.uid !== trustedOwnerUid)
@@ -1,6 +1,7 @@
1
1
  import type { HostRequirementsCheck } from "../runtime/host-runtime-requirements-check.js";
2
2
  import type { HostRuntimeReadinessProbeRequest, HostRuntimeReadinessProbeResult, RunOnceDispatchPacket, RunOnceResultPacket, RunnerDispatchEvent } from "./session.types.js";
3
- import type { HostRuntimeCapacitySnapshot, HostRuntimeReapOptions, HostRuntimeReapReport } from "../runtime/host-runtime-lease.js";
3
+ import type { RunnerHostDefaults } from "../runtime/runner-settings.js";
4
+ import type { HostCapacityLimits, HostRuntimeCapacitySnapshot, HostRuntimeReapOptions, HostRuntimeReapReport } from "../runtime/host-runtime-lease.js";
4
5
  export interface SessionEventSink {
5
6
  emit(event: RunnerDispatchEvent): Promise<void>;
6
7
  }
@@ -12,4 +13,8 @@ export interface SessionService {
12
13
  probeHostRuntime?(request: HostRuntimeReadinessProbeRequest, signal?: AbortSignal): Promise<HostRuntimeReadinessProbeResult>;
13
14
  /** Decision 0013: host attempts recheck the project's requirements before starting. */
14
15
  setHostRequirementsCheck?(check: HostRequirementsCheck | null): void;
16
+ /** Decision 0014: the host's max attempts and memory reserve defaults; null without host attempts. */
17
+ runnerLimitDefaults?(): RunnerHostDefaults | null;
18
+ /** Decision 0014: applies the effective max attempts and memory reserve to host attempt admission. */
19
+ applyRunnerLimits?(limits: HostCapacityLimits): void | Promise<void>;
15
20
  }
@@ -3,13 +3,18 @@ import type { ProviderCliService } from "./provider-cli/provider-cli.base.js";
3
3
  import type { SessionEventSink, SessionService } from "./session.base.js";
4
4
  import type { HostRuntimeReadinessProbeRequest, HostRuntimeReadinessProbeResult, RunOnceDispatchPacket, RunOnceResultPacket } from "./session.types.js";
5
5
  import type { WorktreeService } from "../worktree/worktree.base.js";
6
- import { type HostRuntimeCapacitySnapshot, type HostRuntimeLeaseRuntime, type HostRuntimeReapOptions, type HostRuntimeReapReport } from "../runtime/host-runtime-lease.js";
6
+ import { type HostCapacityLimits, type HostRuntimeCapacitySnapshot, type HostRuntimeLeaseRuntime, type HostRuntimeReapOptions, type HostRuntimeReapReport } from "../runtime/host-runtime-lease.js";
7
+ import type { RunnerHostDefaults } from "../runtime/runner-settings.js";
8
+ import { type WorkspaceRuntimeFingerprintReader } from "./workspace-runtime-fingerprint.js";
7
9
  export declare class BridgeSessionService implements SessionService {
8
10
  private readonly worktrees;
9
11
  private readonly providerCli;
10
12
  private readonly hostRuntime?;
11
- constructor(worktrees?: WorktreeService, providerCli?: ProviderCliService, hostRuntime?: HostRuntimeLeaseRuntime | undefined);
13
+ private readonly workspaceFingerprint;
14
+ constructor(worktrees?: WorktreeService, providerCli?: ProviderCliService, hostRuntime?: HostRuntimeLeaseRuntime | undefined, workspaceFingerprint?: WorkspaceRuntimeFingerprintReader);
12
15
  setHostRequirementsCheck(check: HostRequirementsCheck | null): void;
16
+ runnerLimitDefaults(): RunnerHostDefaults | null;
17
+ applyRunnerLimits(limits: HostCapacityLimits): void;
13
18
  updateLease(dispatchAttemptId: string, fencingToken: string, expiresAt: string): Promise<void>;
14
19
  reapHostRuntime(options: HostRuntimeReapOptions): Promise<HostRuntimeReapReport | null>;
15
20
  runtimeCapacity(): HostRuntimeCapacitySnapshot | null;
@@ -4,23 +4,32 @@ import { RoutingProviderCliService } from "./provider-cli/provider-cli.service.j
4
4
  import { ForgeFailureError, waitKindForEvent, waitWakeCondition } from "./session.types.js";
5
5
  import { GitWorktreeService } from "../worktree/worktree.service.js";
6
6
  import { SandboxWorkspaceService } from "../sandbox/workspace.service.js";
7
- import { HostRuntimeAdmissionExpiredError, hostRuntimeEventResources, runtimeAdmissionPriority, } from "../runtime/host-runtime-lease.js";
7
+ import { HostRuntimeAdmissionExpiredError, hostRuntimeEventResources, hostRuntimeStackEnvironmentKeys, runtimeAdmissionPriority, } from "../runtime/host-runtime-lease.js";
8
8
  import { configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, } from "../runtime/host-runtime-promotion.js";
9
+ import { readWorkspaceRuntimeFingerprint, sameWorkspaceRuntimeFingerprint, workspaceRuntimeFingerprintChanges, } from "./workspace-runtime-fingerprint.js";
9
10
  const minimumReadinessProbeStartupBudgetMs = 150_000;
10
11
  export class BridgeSessionService {
11
12
  worktrees;
12
13
  providerCli;
13
14
  hostRuntime;
15
+ workspaceFingerprint;
14
16
  constructor(worktrees = process.env.FORGE_SANDBOX_ID
15
17
  ? new SandboxWorkspaceService()
16
- : new GitWorktreeService(), providerCli = new RoutingProviderCliService(), hostRuntime) {
18
+ : new GitWorktreeService(), providerCli = new RoutingProviderCliService(), hostRuntime, workspaceFingerprint = readWorkspaceRuntimeFingerprint) {
17
19
  this.worktrees = worktrees;
18
20
  this.providerCli = providerCli;
19
21
  this.hostRuntime = hostRuntime;
22
+ this.workspaceFingerprint = workspaceFingerprint;
20
23
  }
21
24
  setHostRequirementsCheck(check) {
22
25
  this.hostRuntime?.setRequirementsCheck?.(check);
23
26
  }
27
+ runnerLimitDefaults() {
28
+ return this.hostRuntime?.capacityLimitDefaults?.() ?? null;
29
+ }
30
+ applyRunnerLimits(limits) {
31
+ this.hostRuntime?.applyCapacityLimits?.(limits);
32
+ }
24
33
  async updateLease(dispatchAttemptId, fencingToken, expiresAt) {
25
34
  await this.hostRuntime?.updateLease(dispatchAttemptId, fencingToken, expiresAt);
26
35
  }
@@ -338,6 +347,92 @@ export class BridgeSessionService {
338
347
  });
339
348
  }
340
349
  }
350
+ // The stack was built and launched from this workspace state. Pre-publication
351
+ // validation restarts it when the provider has changed the source since.
352
+ let refreshRuntimeEnvironment;
353
+ const hostRuntime = this.hostRuntime;
354
+ if (hostLease && dispatch.sandbox && hostRuntime?.restartConfiguredProject
355
+ && hostLease.executionClass === "managed_runtime"
356
+ && configuredLaunchPortNames(hostLease.runtimeContract).length > 0) {
357
+ const worktreePath = worktree.worktreePath;
358
+ const dispatchAttemptId = dispatch.sandbox.dispatchAttemptId;
359
+ const fencingToken = dispatch.lease.fencingToken;
360
+ const restartConfiguredProject = hostRuntime.restartConfiguredProject.bind(hostRuntime);
361
+ let launchFingerprint = await this.workspaceFingerprint(worktreePath)
362
+ .catch(() => null);
363
+ // Set while the stack may not match the workspace: a failed restart is retried on the next pass.
364
+ let restartPending = false;
365
+ refreshRuntimeEnvironment = async (refreshSignal) => {
366
+ const current = await this.workspaceFingerprint(worktreePath).catch(() => null);
367
+ if (!restartPending && sameWorkspaceRuntimeFingerprint(launchFingerprint, current))
368
+ return null;
369
+ // Every cause that applies is reported; `reason` is the first of them. Changes are named
370
+ // only when both states were read: an unreadable baseline is not a workspace change.
371
+ const comparable = launchFingerprint !== null && current !== null;
372
+ const changes = comparable ? workspaceRuntimeFingerprintChanges(launchFingerprint, current) : [];
373
+ const causes = [
374
+ ...(restartPending ? ["previous_restart_incomplete"] : []),
375
+ ...(comparable ? [] : ["fingerprint_unavailable"]),
376
+ ...(changes.length > 0 ? ["workspace_changed"] : []),
377
+ ];
378
+ const reason = causes[0] ?? "workspace_changed";
379
+ const changeText = changes.length > 0 ? ` The workspace also changed since launch (${changes.join(", ")}).` : "";
380
+ await emitLifecycle({
381
+ role: "runner",
382
+ kind: "checkpoint",
383
+ content: reason === "workspace_changed"
384
+ ? `The workspace changed since the attempt runtime stack was launched (${changes.join(", ")}); restarting it so validation runs against the current source.`
385
+ : reason === "previous_restart_incomplete"
386
+ ? `The previous attempt runtime restart did not complete; restarting it again so validation runs against the current source.${changeText}`
387
+ : `The workspace state could not be compared with the attempt runtime stack; restarting it so validation runs against the current source.`,
388
+ eventType: "host_runtime_restart_started",
389
+ data: JSON.stringify({
390
+ reason,
391
+ causes,
392
+ changes,
393
+ head_sha: current?.headSha ?? null,
394
+ merge_in_progress: Boolean(current?.mergeHead),
395
+ }),
396
+ });
397
+ restartPending = true;
398
+ let restarted;
399
+ try {
400
+ restarted = await restartConfiguredProject(dispatchAttemptId, fencingToken, refreshSignal ?? signal, async (checkpoint) => {
401
+ await emitLifecycle({
402
+ role: "runner",
403
+ kind: "checkpoint",
404
+ content: checkpoint.message,
405
+ eventType: checkpoint.code,
406
+ data: checkpoint.data ? JSON.stringify(checkpoint.data) : undefined,
407
+ });
408
+ });
409
+ }
410
+ catch (error) {
411
+ await emitLifecycle({
412
+ role: "runner",
413
+ kind: "error",
414
+ content: `Restarting the attempt runtime stack failed: ${failureMessage(error)}`,
415
+ eventType: "host_runtime_restart_failed",
416
+ data: JSON.stringify({ reason, causes, changes }),
417
+ }).catch(() => undefined);
418
+ throw error;
419
+ }
420
+ hostLease = restarted;
421
+ // The restarted stack serves the workspace as it is now. Read that state again rather than
422
+ // keep the pre-restart reading, which is null when it could not be collected; a null
423
+ // baseline never matches, so every later pass would restart and rotate ports again.
424
+ launchFingerprint = await this.workspaceFingerprint(worktreePath).catch(() => current);
425
+ restartPending = false;
426
+ await emitLifecycle({
427
+ role: "runner",
428
+ kind: "checkpoint",
429
+ content: `Restarted the supervised project runtime on ${restarted.lease.resources.ports.map(port => `${port.name} ${port.hostIp}:${port.hostPort}`).join(", ") || "no ports"}.`,
430
+ eventType: "host_runtime_restarted",
431
+ data: JSON.stringify(hostRuntimeEventResources(restarted.lease, restarted.runtimeContract, restarted.executionClass)),
432
+ });
433
+ return { environment: restarted.environment, reason, changes };
434
+ };
435
+ }
341
436
  providerDispatch = withMaterializedManagedQaTarget(providerDispatch, hostLease);
342
437
  const providerEnvironment = {
343
438
  runtimeEnvironment: hostLease?.environment,
@@ -384,6 +479,9 @@ export class BridgeSessionService {
384
479
  processRunner: hostLease && dispatch.sandbox
385
480
  ? this.hostRuntime?.providerProcessRunner?.(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken) ?? undefined
386
481
  : undefined,
482
+ ...(refreshRuntimeEnvironment && hostLease
483
+ ? { refreshRuntimeEnvironment, runtimeStackEnvironmentKeys: hostRuntimeStackEnvironmentKeys(hostLease.runtimeContract) }
484
+ : {}),
387
485
  emit,
388
486
  signal
389
487
  };
@@ -469,7 +469,7 @@ function unvalidatedFailureFactsForCode(code, source) {
469
469
  if (code === "bridge.unavailable") {
470
470
  return facts(code, "transport", "offer", source, "retryable", "retry_dispatch");
471
471
  }
472
- if (["capacity_unavailable", "bridge.runner_draining", "docker_engine_unavailable", "docker_memory_low", "docker_memory_sample_unavailable", "docker_cpu_low", "docker_disk_low", "server_local.resource_pressure", "server_local.capacity_unavailable", "dispatch.preparation_resource_pressure", "sandbox_capacity_profile_unavailable", "host_runtime_admission_expired", "placement_requirements_unmet"].includes(code)) {
472
+ if (["capacity_unavailable", "bridge.runner_draining", "docker_engine_unavailable", "docker_memory_low", "docker_memory_sample_unavailable", "docker_cpu_low", "docker_disk_low", "server_local.resource_pressure", "server_local.capacity_unavailable", "dispatch.preparation_resource_pressure", "sandbox_capacity_profile_unavailable", "host_runtime_admission_expired", "placement_requirements_unmet", "runner_yielding", "runner_settings_pending", "runner_settings_apply_failed", "runner_tier_light", "runner_project_not_allowed"].includes(code)) {
473
473
  return facts(code, "resource", "offer", source, "retryable", "retry_dispatch");
474
474
  }
475
475
  if (["bridge.lease_retry_exhausted", "bridge.capacity_wait_exhausted"].includes(code)) {
@@ -496,7 +496,7 @@ function unvalidatedFailureFactsForCode(code, source) {
496
496
  if (code === "provider_configuration_invalid") {
497
497
  return facts(code, "provider", "prepare", source, "non_retryable", "fix_environment");
498
498
  }
499
- if (["host_port_collision", "host_runtime_process_exited", "host_runtime_listener_timeout", "host_runtime_http_readiness_timeout", "host_runtime_prepared_source_changed", "host_runtime_prepared_probe_incomplete", "host_runtime_prepared_probe_cleanup_unconfirmed"].includes(code)) {
499
+ if (["host_port_collision", "host_runtime_process_exited", "host_runtime_listener_timeout", "host_runtime_http_readiness_timeout", "host_runtime_prepared_source_changed", "host_runtime_contract_changed", "host_runtime_prepared_probe_incomplete", "host_runtime_prepared_probe_cleanup_unconfirmed"].includes(code)) {
500
500
  return facts(code, "resource", "prepare", source, "retryable", "retry_dispatch");
501
501
  }
502
502
  if (code === "host_runtime_project_start_failed") {
@@ -525,7 +525,7 @@ function unvalidatedFailureFactsForCode(code, source) {
525
525
  if (code === "provider_completion_tool_missing") {
526
526
  return facts(code, "provider", "agent", source, "non_retryable", "inspect_failure");
527
527
  }
528
- if (code === "provider_terminated_at_turn_ceiling") {
528
+ if (["provider_terminated_at_turn_ceiling", "provider_turn_ended_with_background_work"].includes(code)) {
529
529
  return facts(code, "provider", "agent", source, "retryable", "retry_with_policy");
530
530
  }
531
531
  if (code === "provider_context_window_exhausted") {
@@ -0,0 +1,32 @@
1
+ import { GitClient } from "../shared/git/git.js";
2
+ /**
3
+ * What the attempt's host runtime stack was built and launched from. When the
4
+ * workspace no longer matches, the running API binary and dev server are stale:
5
+ * an uncommitted edit or an in-progress `merge --no-commit` changes the source
6
+ * without moving HEAD.
7
+ */
8
+ export interface WorkspaceRuntimeFingerprint {
9
+ readonly headSha: string;
10
+ /** Contents of MERGE_HEAD while a merge is in progress, else null. */
11
+ readonly mergeHead: string | null;
12
+ /** sha256 of `git diff HEAD --binary` (staged and unstaged changes to tracked files, mode changes included). */
13
+ readonly diffDigest: string;
14
+ /**
15
+ * sha256 over untracked, non-ignored file names, their executable bit, and their contents (or
16
+ * size and mtime for large files).
17
+ */
18
+ readonly untrackedDigest: string;
19
+ /**
20
+ * sha256 over the runtime contract as loaded now and the files its launch commands name. Git's
21
+ * views above skip ignored files, and a project may ignore its contract or a launch script; a
22
+ * change there alters what the stack runs without changing anything git reports.
23
+ */
24
+ readonly runtimeInputsDigest: string;
25
+ /** One digest over every field above. */
26
+ readonly digest: string;
27
+ }
28
+ export type WorkspaceRuntimeFingerprintReader = (worktreePath: string) => Promise<WorkspaceRuntimeFingerprint>;
29
+ export declare function readWorkspaceRuntimeFingerprint(worktreePath: string, git?: Pick<GitClient, "run">): Promise<WorkspaceRuntimeFingerprint>;
30
+ export declare function sameWorkspaceRuntimeFingerprint(left: WorkspaceRuntimeFingerprint | null, right: WorkspaceRuntimeFingerprint | null): boolean;
31
+ /** Names what changed between two fingerprints, for the restart checkpoint. */
32
+ export declare function workspaceRuntimeFingerprintChanges(previous: WorkspaceRuntimeFingerprint | null, current: WorkspaceRuntimeFingerprint): readonly string[];
@@ -0,0 +1,138 @@
1
+ import { createHash } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { GitClient } from "../shared/git/git.js";
5
+ import { loadHostRuntimeContract } from "../runtime/host-runtime-contract.js";
6
+ import { hostRuntimeContractFingerprint } from "../runtime/host-runtime-promotion.js";
7
+ import { isRuntimeOnlyPath } from "./publishable-worktree-changes.js";
8
+ /** Untracked files up to this size are hashed by content; larger ones by size and mtime. */
9
+ const untrackedContentHashLimitBytes = 1024 * 1024;
10
+ /**
11
+ * Forge's own runtime output never changes what the application runs, and Forge
12
+ * rewrites some of it (readiness manifests, completion artifacts) between passes.
13
+ */
14
+ const runtimeOnlyPathspecs = [
15
+ ":(exclude).local",
16
+ ":(exclude).forge/work-items",
17
+ ":(exclude).forge/stories",
18
+ ];
19
+ export async function readWorkspaceRuntimeFingerprint(worktreePath, git = new GitClient()) {
20
+ const headSha = (await git.run(worktreePath, ["rev-parse", "--verify", "HEAD^{commit}"])).trim().toLowerCase();
21
+ const mergeHead = await readMergeHead(git, worktreePath);
22
+ // A mode change (chmod +x on a launch script) changes what runs. The repository may set
23
+ // core.fileMode=false, which would drop it from the diff, so this read always records modes.
24
+ const diff = await git.run(worktreePath, ["-c", "core.fileMode=true", "diff", "HEAD", "--binary", "--no-ext-diff", "--no-textconv", "--", ".", ...runtimeOnlyPathspecs]);
25
+ const diffDigest = sha256(diff);
26
+ const untracked = (await git.run(worktreePath, [
27
+ "ls-files", "--others", "--exclude-standard", "-z", "--", ".", ...runtimeOnlyPathspecs,
28
+ ]))
29
+ .split("\0")
30
+ .filter(entry => entry.length > 0 && !isRuntimeOnlyPath(entry))
31
+ .sort((left, right) => left.localeCompare(right));
32
+ const untrackedHash = createHash("sha256");
33
+ for (const relative of untracked) {
34
+ untrackedHash.update(relative).update("\0");
35
+ const absolute = path.join(worktreePath, relative);
36
+ const stat = await fs.lstat(absolute).catch(() => null);
37
+ if (!stat) {
38
+ untrackedHash.update("missing\0");
39
+ continue;
40
+ }
41
+ // Like git, record the executable bit: chmod changes what runs without touching content or mtime.
42
+ untrackedHash.update(stat.isFile() && (stat.mode & 0o111) !== 0 ? "exec\0" : "plain\0");
43
+ if (stat.isFile() && stat.size <= untrackedContentHashLimitBytes) {
44
+ const content = await fs.readFile(absolute).catch(() => null);
45
+ untrackedHash.update(content ? `content:${sha256(content)}\0` : `unreadable:${stat.size}:${stat.mtimeMs}\0`);
46
+ }
47
+ else {
48
+ untrackedHash.update(`stat:${stat.size}:${stat.mtimeMs}\0`);
49
+ }
50
+ }
51
+ const untrackedDigest = `sha256:${untrackedHash.digest("hex")}`;
52
+ const runtimeInputsDigest = await readRuntimeInputsDigest(worktreePath);
53
+ const digest = sha256(JSON.stringify({ headSha, mergeHead, diffDigest, untrackedDigest, runtimeInputsDigest }));
54
+ return { headSha, mergeHead, diffDigest, untrackedDigest, runtimeInputsDigest, digest };
55
+ }
56
+ export function sameWorkspaceRuntimeFingerprint(left, right) {
57
+ return left !== null && right !== null && left.digest === right.digest;
58
+ }
59
+ /** Names what changed between two fingerprints, for the restart checkpoint. */
60
+ export function workspaceRuntimeFingerprintChanges(previous, current) {
61
+ if (!previous)
62
+ return ["unrecorded"];
63
+ const changes = [];
64
+ if (previous.headSha !== current.headSha)
65
+ changes.push("head");
66
+ if (previous.mergeHead !== current.mergeHead)
67
+ changes.push("merge_head");
68
+ if (previous.diffDigest !== current.diffDigest)
69
+ changes.push("tracked_changes");
70
+ if (previous.untrackedDigest !== current.untrackedDigest)
71
+ changes.push("untracked_files");
72
+ if (previous.runtimeInputsDigest !== current.runtimeInputsDigest)
73
+ changes.push("runtime_inputs");
74
+ return changes;
75
+ }
76
+ /**
77
+ * The loaded runtime contract (project file or derived) and each regular file inside the worktree
78
+ * that a configured launch names as its command or an argument, by executable bit and content.
79
+ * Ignored or not: these are exactly what the stack was launched from. Nothing else ignored is read.
80
+ */
81
+ async function readRuntimeInputsDigest(worktreePath) {
82
+ const hash = createHash("sha256");
83
+ let contract;
84
+ try {
85
+ contract = await loadHostRuntimeContract(worktreePath);
86
+ }
87
+ catch (error) {
88
+ // An unloadable contract is a state of its own; the restart reports why it cannot load.
89
+ const message = error instanceof Error ? error.message : String(error);
90
+ return sha256(`unloadable:${message.split(":", 1)[0]}`);
91
+ }
92
+ hash.update(`contract:${hostRuntimeContractFingerprint(contract)}\0`);
93
+ const root = await fs.realpath(worktreePath);
94
+ const named = new Set();
95
+ for (const port of contract.contract.runtime.ports) {
96
+ if (!port.launch)
97
+ continue;
98
+ const workingDirectory = path.resolve(root, port.launch.workingDirectory);
99
+ for (const candidate of [port.launch.command, ...port.launch.args]) {
100
+ if (!candidate || candidate.startsWith("-"))
101
+ continue;
102
+ const absolute = path.resolve(workingDirectory, candidate);
103
+ const relative = path.relative(root, absolute);
104
+ if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative))
105
+ continue;
106
+ named.add(relative);
107
+ }
108
+ }
109
+ for (const relative of [...named].sort((left, right) => left.localeCompare(right))) {
110
+ const stat = await fs.stat(path.join(root, relative)).catch(() => null);
111
+ if (!stat?.isFile())
112
+ continue;
113
+ hash.update(relative).update("\0").update((stat.mode & 0o111) !== 0 ? "exec\0" : "plain\0");
114
+ if (stat.size <= untrackedContentHashLimitBytes) {
115
+ const content = await fs.readFile(path.join(root, relative)).catch(() => null);
116
+ hash.update(content ? `content:${sha256(content)}\0` : `unreadable:${stat.size}:${stat.mtimeMs}\0`);
117
+ }
118
+ else {
119
+ hash.update(`stat:${stat.size}:${stat.mtimeMs}\0`);
120
+ }
121
+ }
122
+ return `sha256:${hash.digest("hex")}`;
123
+ }
124
+ async function readMergeHead(git, worktreePath) {
125
+ const relative = (await git.run(worktreePath, ["rev-parse", "--git-path", "MERGE_HEAD"])).trim();
126
+ if (!relative)
127
+ return null;
128
+ const mergeHeadPath = path.resolve(worktreePath, relative);
129
+ const content = await fs.readFile(mergeHeadPath, "utf8").catch((error) => {
130
+ if (error.code === "ENOENT")
131
+ return null;
132
+ throw error;
133
+ });
134
+ return content === null ? null : content.trim().toLowerCase();
135
+ }
136
+ function sha256(value) {
137
+ return `sha256:${createHash("sha256").update(value).digest("hex")}`;
138
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Tools an agent commonly starts by bare name. When one of them resolves to a Microsoft Store
3
+ * app-execution alias (`%LOCALAPPDATA%\Microsoft\WindowsApps\pwsh.exe` and the like), Windows
4
+ * creates the process it starts outside the provider's Job Object: it survives the job, keeps the
5
+ * pipe handles it inherited, and holds the attempt's output open until it exits on its own.
6
+ */
7
+ export declare const APP_EXECUTION_ALIAS_SENSITIVE_TOOLS: readonly ["pwsh", "node", "dotnet"];
8
+ export interface AppExecutionAliasFinding {
9
+ readonly tool: string;
10
+ /** The alias the tool's bare name resolves to. */
11
+ readonly aliasPath: string;
12
+ /** The first regular install later on PATH, or null when the alias is the only one. */
13
+ readonly nextInstallPath: string | null;
14
+ }
15
+ /** The sensitive tools whose bare name resolves, on this PATH, to an app-execution alias. */
16
+ export declare function findAppExecutionAliasTools(pathValue: string, pathExtValue?: string, tools?: readonly string[]): AppExecutionAliasFinding[];
17
+ export declare function describeAppExecutionAliasFindings(findings: readonly AppExecutionAliasFinding[]): string | null;
18
+ /** Reads PATH and PATHEXT from an environment whose key case is not normalized (Windows: "Path"). */
19
+ export declare function appExecutionAliasWarning(env: Readonly<Record<string, string | undefined>>, platform?: NodeJS.Platform): string | null;
@@ -0,0 +1,45 @@
1
+ import { isWindowsAppExecutionAliasPath, resolveWindowsCommandFromPath } from "./windows-launch.js";
2
+ /**
3
+ * Tools an agent commonly starts by bare name. When one of them resolves to a Microsoft Store
4
+ * app-execution alias (`%LOCALAPPDATA%\Microsoft\WindowsApps\pwsh.exe` and the like), Windows
5
+ * creates the process it starts outside the provider's Job Object: it survives the job, keeps the
6
+ * pipe handles it inherited, and holds the attempt's output open until it exits on its own.
7
+ */
8
+ export const APP_EXECUTION_ALIAS_SENSITIVE_TOOLS = ["pwsh", "node", "dotnet"];
9
+ /** The sensitive tools whose bare name resolves, on this PATH, to an app-execution alias. */
10
+ export function findAppExecutionAliasTools(pathValue, pathExtValue, tools = APP_EXECUTION_ALIAS_SENSITIVE_TOOLS) {
11
+ const findings = [];
12
+ for (const tool of tools) {
13
+ const aliasPath = resolveWindowsCommandFromPath(tool, pathValue, pathExtValue);
14
+ if (!aliasPath || !isWindowsAppExecutionAliasPath(aliasPath))
15
+ continue;
16
+ const nextInstallPath = resolveWindowsCommandFromPath(tool, pathValue, pathExtValue, { skipAppExecutionAliases: true });
17
+ findings.push({ tool, aliasPath, nextInstallPath });
18
+ }
19
+ return findings;
20
+ }
21
+ export function describeAppExecutionAliasFindings(findings) {
22
+ if (findings.length === 0)
23
+ return null;
24
+ const tools = findings.map(finding => `${finding.tool} -> ${finding.aliasPath}${finding.nextInstallPath
25
+ ? ` (a regular install later on PATH: ${finding.nextInstallPath})`
26
+ : " (no regular install on PATH)"}`);
27
+ return "Host readiness warning: on the provider PATH, "
28
+ + `${tools.join("; ")} resolve${findings.length === 1 ? "s" : ""} to a Microsoft Store app-execution alias under WindowsApps. `
29
+ + "A process started through an alias is created outside the provider's Windows Job Object, survives it, "
30
+ + "and can hold the attempt's output pipes open until it exits. Install the tool normally "
31
+ + "(for PowerShell, the MSI under C:\\Program Files\\PowerShell\\7) and put it ahead of WindowsApps on PATH.";
32
+ }
33
+ /** Reads PATH and PATHEXT from an environment whose key case is not normalized (Windows: "Path"). */
34
+ export function appExecutionAliasWarning(env, platform = process.platform) {
35
+ if (platform !== "win32")
36
+ return null;
37
+ const pathValue = environmentValue(env, "PATH");
38
+ if (!pathValue)
39
+ return null;
40
+ return describeAppExecutionAliasFindings(findAppExecutionAliasTools(pathValue, environmentValue(env, "PATHEXT")));
41
+ }
42
+ function environmentValue(env, name) {
43
+ const key = Object.keys(env).find(candidate => candidate.toUpperCase() === name);
44
+ return key === undefined ? undefined : env[key];
45
+ }
@@ -6,3 +6,21 @@ export declare function buildWindowsCmdLaunch(command: string, args: readonly st
6
6
  export declare function buildWindowsLaunchCommand(commandPath: string, args: readonly string[]): LaunchCommand;
7
7
  export declare function windowsCommandLine(command: string, args: readonly string[]): string;
8
8
  export declare function quoteWindowsCommandLineArg(value: string): string;
9
+ export interface WindowsCommandPathOptions {
10
+ /**
11
+ * Skip candidates under a `WindowsApps` directory. Those are Microsoft Store app-execution
12
+ * aliases: the process they start is created outside the caller's Job Object, so it survives the
13
+ * job and keeps any inherited pipe open. Resolve the next real install on PATH instead.
14
+ */
15
+ readonly skipAppExecutionAliases?: boolean;
16
+ }
17
+ /**
18
+ * Resolves Windows commands without spawning where.exe. Runtime launches can
19
+ * happen while the machine is under enough process pressure for where.exe to
20
+ * miss its timeout; returning the unresolved package-manager name in that case
21
+ * makes Node fall back to a shell shim that cannot survive Job Object wrapping.
22
+ */
23
+ export declare function resolveWindowsCommandFromPath(command: string, pathValue?: string, pathExtValue?: string, options?: WindowsCommandPathOptions): string | null;
24
+ export declare function chooseWindowsCommandCandidate(candidates: readonly string[]): string | null;
25
+ /** True for a path inside a `WindowsApps` directory, where Store app-execution aliases live. */
26
+ export declare function isWindowsAppExecutionAliasPath(candidate: string): boolean;