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

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 (136) hide show
  1. package/README.md +56 -1
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +132 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/bridge.base.d.ts +9 -0
  7. package/dist/bridge/bridge.service.d.ts +71 -2
  8. package/dist/bridge/bridge.service.js +282 -114
  9. package/dist/bridge/bridge.types.d.ts +11 -0
  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 +3 -0
  13. package/dist/bridge/runner-host-capabilities.js +13 -0
  14. package/dist/cli/cli.help.js +18 -0
  15. package/dist/cli/cli.service.d.ts +16 -0
  16. package/dist/cli/cli.service.js +132 -14
  17. package/dist/cli/local-config.d.ts +4 -0
  18. package/dist/cli/local-config.js +26 -4
  19. package/dist/runtime/aspnet-runtime-prebuild.d.ts +5 -0
  20. package/dist/runtime/aspnet-runtime-prebuild.js +138 -6
  21. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  22. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  23. package/dist/runtime/docker-engine-probe.js +7 -0
  24. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  25. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  26. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  27. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  28. package/dist/runtime/host-facts.d.ts +2 -1
  29. package/dist/runtime/host-load-admission.d.ts +18 -3
  30. package/dist/runtime/host-load-admission.js +19 -4
  31. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  32. package/dist/runtime/host-load-child-environment.js +22 -11
  33. package/dist/runtime/host-load-governor-config.d.ts +19 -1
  34. package/dist/runtime/host-load-governor-config.js +37 -0
  35. package/dist/runtime/host-load-governor.d.ts +12 -0
  36. package/dist/runtime/host-load-governor.js +139 -26
  37. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  38. package/dist/runtime/host-load-runtime-settings.js +78 -0
  39. package/dist/runtime/host-load-sampler.d.ts +34 -4
  40. package/dist/runtime/host-load-sampler.js +73 -7
  41. package/dist/runtime/host-load-step-class.d.ts +3 -1
  42. package/dist/runtime/host-load-step-class.js +60 -5
  43. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  44. package/dist/runtime/host-load-test-slot.js +81 -0
  45. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  46. package/dist/runtime/host-load-token-ledger.js +93 -61
  47. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  48. package/dist/runtime/host-load-windows-cpu.js +85 -0
  49. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  50. package/dist/runtime/host-runtime-contract.js +29 -1
  51. package/dist/runtime/host-runtime-lease.d.ts +59 -3
  52. package/dist/runtime/host-runtime-lease.js +209 -58
  53. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  54. package/dist/runtime/host-runtime-promotion.js +36 -0
  55. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  56. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  57. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  58. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  59. package/dist/runtime/runner-settings.d.ts +100 -0
  60. package/dist/runtime/runner-settings.js +214 -0
  61. package/dist/sandbox/host-capacity-broker.d.ts +7 -1
  62. package/dist/sandbox/host-capacity-broker.js +23 -4
  63. package/dist/session/architect-waits.d.ts +2 -0
  64. package/dist/session/architect-waits.js +138 -0
  65. package/dist/session/managed-attempt-tools.d.ts +0 -7
  66. package/dist/session/managed-attempt-tools.js +51 -62
  67. package/dist/session/managed-command-host-load.d.ts +2 -0
  68. package/dist/session/managed-command-host-load.js +2 -1
  69. package/dist/session/phase-completion.artifacts.js +2 -1
  70. package/dist/session/phase-completion.d.ts +8 -0
  71. package/dist/session/phase-completion.js +1 -0
  72. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  73. package/dist/session/phase-completion.mcp-args.js +156 -0
  74. package/dist/session/phase-completion.runtime.d.ts +0 -8
  75. package/dist/session/phase-completion.runtime.js +43 -197
  76. package/dist/session/phase-completion.schemas.js +25 -23
  77. package/dist/session/phase-completion.validation.js +3 -1
  78. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  79. package/dist/session/pre-publication-native-postgres.js +111 -0
  80. package/dist/session/pre-publication-pass.d.ts +61 -0
  81. package/dist/session/pre-publication-pass.js +148 -0
  82. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  83. package/dist/session/pre-publication-step-execution.js +6 -5
  84. package/dist/session/pre-publication-validation.d.ts +30 -14
  85. package/dist/session/pre-publication-validation.js +207 -134
  86. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  87. package/dist/session/provider-cli/claude-background-work.js +181 -0
  88. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  89. package/dist/session/provider-cli/host-build-lock.js +30 -0
  90. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  91. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  92. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  93. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  94. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  95. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  96. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  97. package/dist/session/provider-cli/provider-cli.process.js +39 -430
  98. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  99. package/dist/session/provider-cli/provider-cli.prompts.js +71 -31
  100. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  101. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  102. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  103. package/dist/session/provider-cli/provider-cli.service.js +78 -171
  104. package/dist/session/provider-cli/provider-cli.types.d.ts +26 -0
  105. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  106. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  107. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  108. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  109. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  110. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  111. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  112. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  113. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  114. package/dist/session/provider-cli/provider-output-state.js +6 -0
  115. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  116. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  117. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  118. package/dist/session/qa-sidecar-validation.js +28 -0
  119. package/dist/session/sandbox-host-capacity-gate.js +12 -3
  120. package/dist/session/session-redaction.js +31 -181
  121. package/dist/session/session.base.d.ts +6 -1
  122. package/dist/session/session.service.d.ts +7 -2
  123. package/dist/session/session.service.js +100 -2
  124. package/dist/session/session.types.js +4 -4
  125. package/dist/session/sidecar-json-shape.d.ts +31 -0
  126. package/dist/session/sidecar-json-shape.js +217 -0
  127. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  128. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  129. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  130. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  131. package/dist/shared/process/windows-launch.d.ts +18 -0
  132. package/dist/shared/process/windows-launch.js +68 -0
  133. package/dist/shared/provider-capabilities.js +14 -7
  134. package/dist/version.d.ts +1 -1
  135. package/dist/version.js +1 -1
  136. package/package.json +2 -2
@@ -0,0 +1,131 @@
1
+ import { execFile } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { promisify } from "node:util";
5
+ import { resolveCursorAgentDirectLaunch } from "../../shared/cursor-agent/cursor-agent.launch.js";
6
+ import { buildWindowsLaunchCommand, chooseWindowsCommandCandidate, resolveWindowsCommandFromPath, } from "../../shared/process/windows-launch.js";
7
+ // How a provider or validation command is launched on Windows: npm-installed
8
+ // shims run their JavaScript entry point directly under Node, everything else
9
+ // goes through the Windows launch command.
10
+ const execFileAsync = promisify(execFile);
11
+ export async function resolveWindowsProviderLaunch(command, args) {
12
+ const cursorDirect = await resolveCursorAgentDirectLaunch(command, args);
13
+ if (cursorDirect) {
14
+ return cursorDirect;
15
+ }
16
+ const resolved = await resolveWindowsCommand(command);
17
+ if (!resolved) {
18
+ return { command, args };
19
+ }
20
+ return resolveCodexNpmDirectLaunch(resolved, args)
21
+ ?? resolveClaudeNpmDirectLaunch(resolved, args)
22
+ ?? resolvePackageManagerDirectLaunch(resolved, args)
23
+ ?? buildWindowsLaunchCommand(resolved, args);
24
+ }
25
+ export function resolveCodexNpmDirectLaunch(commandPath, args) {
26
+ const extension = path.extname(commandPath).toLowerCase();
27
+ if ((extension !== ".cmd" && extension !== ".ps1")
28
+ || path.basename(commandPath, extension).toLowerCase() !== "codex") {
29
+ return null;
30
+ }
31
+ const entryPoint = path.join(path.dirname(commandPath), "node_modules", "@openai", "codex", "bin", "codex.js");
32
+ return fs.existsSync(entryPoint)
33
+ ? { command: process.execPath, args: [entryPoint, ...args] }
34
+ : null;
35
+ }
36
+ /**
37
+ * npm installs of Claude Code (`npm i -g @anthropic-ai/claude-code`) put a `claude.cmd` shim on
38
+ * PATH; launch its cli.js directly for the same Job Object reasons as Codex. The native installer
39
+ * ships `claude.exe`, which is preferred by PATH resolution and needs no rewrite.
40
+ */
41
+ export function resolveClaudeNpmDirectLaunch(commandPath, args) {
42
+ const extension = path.extname(commandPath).toLowerCase();
43
+ if ((extension !== ".cmd" && extension !== ".ps1")
44
+ || path.basename(commandPath, extension).toLowerCase() !== "claude") {
45
+ return null;
46
+ }
47
+ const entryPoint = path.join(path.dirname(commandPath), "node_modules", "@anthropic-ai", "claude-code", "cli.js");
48
+ return fs.existsSync(entryPoint)
49
+ ? { command: process.execPath, args: [entryPoint, ...args] }
50
+ : null;
51
+ }
52
+ const packageManagers = ["corepack", "npm", "npx", "pnpm", "pnpx", "yarn", "yarnpkg"];
53
+ /**
54
+ * Avoids cmd.exe's nested-quote handling for package-manager shims. That
55
+ * quoting loses executable paths containing spaces after the command is
56
+ * wrapped by the Windows Job Object supervisor.
57
+ *
58
+ * Launches the entry point the shim itself runs. A Windows Node install ships
59
+ * both npm's own CLI and Corepack's npm shim next to `npm.cmd`, and `npm.cmd`
60
+ * runs npm's CLI. Launching Corepack's shim instead would apply Corepack's
61
+ * strict `packageManager` check: in a repository whose root pins pnpm, an npm
62
+ * package below it (with its own package-lock) is refused although its scripts
63
+ * pass when npm runs them. A shim that names none of the candidates prefers
64
+ * the tool's own CLI over Corepack's.
65
+ */
66
+ export function resolvePackageManagerDirectLaunch(commandPath, args) {
67
+ const extension = path.extname(commandPath).toLowerCase();
68
+ if (extension !== ".cmd" && extension !== ".ps1")
69
+ return null;
70
+ const packageManager = path.basename(commandPath, extension).toLowerCase();
71
+ if (!packageManagers.includes(packageManager))
72
+ return null;
73
+ const root = path.dirname(commandPath);
74
+ const candidates = [
75
+ ...ownCliEntryPoints(packageManager),
76
+ ["corepack", "dist", packageManager === "corepack" ? "corepack.js" : `${packageManager}.js`],
77
+ ].map(segments => path.join(root, "node_modules", ...segments));
78
+ const existing = candidates.filter(candidate => fs.existsSync(candidate));
79
+ const shim = normalizeShimPath(readShim(commandPath));
80
+ const entryPoint = existing.find(candidate => shim.includes(normalizeShimPath(path.relative(root, candidate))))
81
+ ?? existing[0];
82
+ if (!entryPoint)
83
+ return null;
84
+ const adjacentNode = path.join(root, "node.exe");
85
+ return {
86
+ command: fs.existsSync(adjacentNode) ? adjacentNode : process.execPath,
87
+ args: [entryPoint, ...args],
88
+ };
89
+ }
90
+ function ownCliEntryPoints(packageManager) {
91
+ switch (packageManager) {
92
+ case "npm":
93
+ case "npx":
94
+ return [["npm", "bin", `${packageManager}-cli.js`]];
95
+ case "pnpm":
96
+ case "pnpx":
97
+ return [["pnpm", "bin", `${packageManager}.cjs`]];
98
+ case "yarn":
99
+ case "yarnpkg":
100
+ return [["yarn", "bin", "yarn.js"]];
101
+ default:
102
+ return [];
103
+ }
104
+ }
105
+ function readShim(commandPath) {
106
+ try {
107
+ return fs.readFileSync(commandPath, "utf8");
108
+ }
109
+ catch {
110
+ return "";
111
+ }
112
+ }
113
+ function normalizeShimPath(value) {
114
+ return value.replaceAll("/", "\\").toLowerCase();
115
+ }
116
+ async function resolveWindowsCommand(command) {
117
+ if (path.isAbsolute(command)) {
118
+ return command;
119
+ }
120
+ const resolvedFromPath = resolveWindowsCommandFromPath(command);
121
+ if (resolvedFromPath) {
122
+ return resolvedFromPath;
123
+ }
124
+ try {
125
+ const result = await execFileAsync("where.exe", [command], { timeout: 2000 });
126
+ return chooseWindowsCommandCandidate(result.stdout.split(/\r?\n/));
127
+ }
128
+ catch {
129
+ return null;
130
+ }
131
+ }
@@ -4,3 +4,7 @@
4
4
  * Unreadable or stale receipts do not count.
5
5
  */
6
6
  export declare function hasNonterminalManagedCommand(logDirectory: string | undefined, nowMs?: number): Promise<boolean>;
7
+ /** A stream event that shows the provider is working on a turn: model output or a tool result. */
8
+ export declare function isProviderTurnActivity(line: string): boolean;
9
+ export declare function isProviderTerminalFailure(line: string): boolean;
10
+ export declare function isProviderTerminalSuccess(line: string): boolean;
@@ -45,3 +45,48 @@ async function receiptHoldsProvider(receiptPath, nowMs) {
45
45
  return false;
46
46
  }
47
47
  }
48
+ /** A stream event that shows the provider is working on a turn: model output or a tool result. */
49
+ export function isProviderTurnActivity(line) {
50
+ const trimmed = line.trim();
51
+ if (!trimmed.startsWith("{"))
52
+ return false;
53
+ try {
54
+ const event = JSON.parse(trimmed);
55
+ return event.type === "assistant"
56
+ || event.type === "user"
57
+ || (event.type === "system" && event.subtype === "init")
58
+ || event.type === "turn.started"
59
+ || event.type === "item.started";
60
+ }
61
+ catch {
62
+ return false;
63
+ }
64
+ }
65
+ export function isProviderTerminalFailure(line) {
66
+ const trimmed = line.trim();
67
+ if (!trimmed.startsWith("{"))
68
+ return false;
69
+ try {
70
+ const event = JSON.parse(trimmed);
71
+ // The same events the output parsers report as provider errors.
72
+ return event.type === "turn.failed"
73
+ || event.type === "error"
74
+ || (event.type === "result" && (event.subtype !== "success" || event.is_error === true));
75
+ }
76
+ catch {
77
+ return false;
78
+ }
79
+ }
80
+ export function isProviderTerminalSuccess(line) {
81
+ const trimmed = line.trim();
82
+ if (!trimmed.startsWith("{"))
83
+ return false;
84
+ try {
85
+ const event = JSON.parse(trimmed);
86
+ return event.type === "turn.completed"
87
+ || (event.type === "result" && event.subtype === "success" && event.is_error !== true);
88
+ }
89
+ catch {
90
+ return false;
91
+ }
92
+ }
@@ -0,0 +1,30 @@
1
+ import type { ChildProcess } from "node:child_process";
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 declare const PROVIDER_OUTPUT_PIPE_RELEASE_GRACE_MS = 5000;
13
+ export interface OutputPipeReleaseFields {
14
+ /** Present when Forge closed the provider's output pipes because they outlived its root process. */
15
+ readonly outputPipesReleasedAfterExit?: true;
16
+ }
17
+ /** Closes a child's output pipes a bounded grace after the child exits, unless they close first. */
18
+ export declare class OutputPipeRelease {
19
+ private readonly child;
20
+ private readonly graceMs;
21
+ private readonly onRelease;
22
+ private timer;
23
+ private released;
24
+ constructor(child: ChildProcess, graceMs: number, onRelease: (message: string) => void);
25
+ resultFields(): OutputPipeReleaseFields;
26
+ stop(): void;
27
+ private arm;
28
+ private release;
29
+ }
30
+ export declare function readProcessLines(stream: NodeJS.ReadableStream, onLine: (line: string) => Promise<void> | void): Promise<void>;
@@ -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 "";
@@ -0,0 +1,69 @@
1
+ import path from "node:path";
2
+ import { ForgeFailureError } from "../session.types.js";
3
+ /** Providers whose user configuration the helpers below shut out. Any other provider is refused. */
4
+ export declare const userConfigIsolatedProviders: readonly string[];
5
+ /**
6
+ * Variables that choose where a provider CLI finds the user's configuration: Claude Code's config
7
+ * directory, and the home directory under which Claude reads `.claude` and `.claude.json` (HOME;
8
+ * USERPROFILE on Windows, which HOMEDRIVE and HOMEPATH resolve to when it is unset). Only the
9
+ * bridge's own environment sets them (provider-cli.child-environment.ts); a project's runtime
10
+ * environment can't, or it could point the provider at another user's configuration.
11
+ */
12
+ export declare const providerConfigLocationVariables: readonly string[];
13
+ /** A strict MCP configuration with no servers, for Claude turns that get no Forge tools. */
14
+ export declare const emptyClaudeMcpConfig: string;
15
+ /**
16
+ * Claude Code launch arguments:
17
+ * - `--setting-sources project,local` drops the user settings source: `~/.claude/settings.json`
18
+ * (hooks, env, permissions, enabled and claude.ai-synced plugins), `~/.claude/CLAUDE.md`,
19
+ * user rules, skills, agents, commands and output styles.
20
+ * - `--mcp-config` plus `--strict-mcp-config` load only Forge's own MCP server (or none), never
21
+ * `~/.claude.json`, plugin or claude.ai connector servers.
22
+ */
23
+ export declare function claudeUserConfigIsolationArgs(forgeMcpConfigPath?: string | null): readonly string[];
24
+ /**
25
+ * Claude Code settings, passed with `--settings`:
26
+ * - `claudeMdExcludes` drops the instruction files Claude Code reads from every directory above
27
+ * the working directory (the user's home and folders such as `~/Repos`). They belong to the
28
+ * host, not to the repository, and the project settings source would otherwise load them.
29
+ * - `autoMemoryEnabled: false`: without the user settings source auto memory falls back to its
30
+ * default, and its memory files accumulate outside the repository between sessions.
31
+ */
32
+ export declare function claudeUserConfigIsolationSettings(workingDirectory: string, pathApi?: path.PlatformPath): Readonly<Record<string, unknown>>;
33
+ /**
34
+ * Every Claude Code agent launch: the isolation arguments, then one `--settings` value that carries
35
+ * the isolation settings and, for headless agent turns, the background-work restrictions with
36
+ * their tool deny list (`claude-background-work.ts`).
37
+ */
38
+ export declare function claudeIsolatedLaunchArgs(options: {
39
+ readonly workingDirectory: string;
40
+ readonly forgeMcpConfigPath?: string | null;
41
+ readonly headless: boolean;
42
+ }): readonly string[];
43
+ /**
44
+ * Instruction-file patterns for each directory strictly above the working directory. Windows
45
+ * paths are listed both as written and with forward slashes, the form glob matchers expect.
46
+ */
47
+ export declare function ancestorInstructionExcludes(workingDirectory: string, pathApi?: path.PlatformPath): readonly string[];
48
+ /**
49
+ * Codex reads `config.toml` (MCP servers, profiles, plugins), `AGENTS.md`, `AGENTS.override.md`,
50
+ * rules and skills from `CODEX_HOME`, so Forge runs it with a home of its own on each runner
51
+ * instead of the user's `~/.codex`. Codex's `--ignore-user-config` still loads the global
52
+ * `AGENTS.md`, so a separate home is the only full isolation. API-key turns authenticate through
53
+ * the environment; a local Codex CLI login is made once into this home
54
+ * (`CODEX_HOME=<path> codex login`).
55
+ *
56
+ * In a Forge sandbox container (`FORGE_RUNTIME_MODE=docker`) `~/.codex` is already Forge's own:
57
+ * an attempt-scoped volume that holds only the copied `auth.json` (sandbox/provider-auth/codex.ts).
58
+ */
59
+ export declare function forgeCodexHome(homeDirectory?: string, environment?: NodeJS.ProcessEnv): string;
60
+ export declare function codexUserConfigIsolationEnv(homeDirectory?: string, environment?: NodeJS.ProcessEnv): Readonly<Record<string, string>>;
61
+ /** The provider environment that shuts out the user's own configuration. */
62
+ export declare function providerUserConfigIsolationEnv(provider: string, homeDirectory?: string, environment?: NodeJS.ProcessEnv): Readonly<Record<string, string>>;
63
+ /**
64
+ * cursor-agent has no flag or environment variable that keeps it from reading `~/.cursor`
65
+ * (`mcp.json`, `cli-config.json`, rules), and `--approve-mcps` would approve every server there;
66
+ * other CLIs are unknown. Forge refuses to launch them.
67
+ */
68
+ export declare function providerUserConfigIsolationUnsupported(provider: string): ForgeFailureError;
69
+ export declare function isProviderUserConfigIsolated(provider: string): boolean;
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Forge agents get only the context Forge gives them: Forge's prompts and `.forge/` artifacts,
3
+ * Forge's MCP tools, and the repository they work in. Nothing from the host user's own provider
4
+ * setup reaches an agent session on any runner: no user instruction files, settings, hooks,
5
+ * skills, plugins, rules, custom agents or commands, and no user, account or plugin MCP servers.
6
+ *
7
+ * Every agent launch path (session runs, repair and recovery turns, chat turns) builds its
8
+ * provider command from these helpers, and a provider whose user configuration Forge cannot
9
+ * shut out is refused rather than launched. `provider-user-config-isolation.test.ts` fails when a
10
+ * launch path stops applying them.
11
+ */
12
+ import fs from "node:fs";
13
+ import os from "node:os";
14
+ import path from "node:path";
15
+ import { ForgeFailureError } from "../session.types.js";
16
+ import { claudeHeadlessToolArgs } from "./claude-background-work.js";
17
+ /** Providers whose user configuration the helpers below shut out. Any other provider is refused. */
18
+ export const userConfigIsolatedProviders = Object.freeze(["claude", "codex"]);
19
+ /**
20
+ * Variables that choose where a provider CLI finds the user's configuration: Claude Code's config
21
+ * directory, and the home directory under which Claude reads `.claude` and `.claude.json` (HOME;
22
+ * USERPROFILE on Windows, which HOMEDRIVE and HOMEPATH resolve to when it is unset). Only the
23
+ * bridge's own environment sets them (provider-cli.child-environment.ts); a project's runtime
24
+ * environment can't, or it could point the provider at another user's configuration.
25
+ */
26
+ export const providerConfigLocationVariables = Object.freeze(["CLAUDE_CONFIG_DIR", "HOME", "USERPROFILE", "HOMEDRIVE", "HOMEPATH"]);
27
+ /** A strict MCP configuration with no servers, for Claude turns that get no Forge tools. */
28
+ export const emptyClaudeMcpConfig = JSON.stringify({ mcpServers: {} });
29
+ /**
30
+ * Claude Code launch arguments:
31
+ * - `--setting-sources project,local` drops the user settings source: `~/.claude/settings.json`
32
+ * (hooks, env, permissions, enabled and claude.ai-synced plugins), `~/.claude/CLAUDE.md`,
33
+ * user rules, skills, agents, commands and output styles.
34
+ * - `--mcp-config` plus `--strict-mcp-config` load only Forge's own MCP server (or none), never
35
+ * `~/.claude.json`, plugin or claude.ai connector servers.
36
+ */
37
+ export function claudeUserConfigIsolationArgs(forgeMcpConfigPath) {
38
+ return [
39
+ "--setting-sources", "project,local",
40
+ "--mcp-config", forgeMcpConfigPath?.trim() || emptyClaudeMcpConfig,
41
+ "--strict-mcp-config",
42
+ ];
43
+ }
44
+ /**
45
+ * Claude Code settings, passed with `--settings`:
46
+ * - `claudeMdExcludes` drops the instruction files Claude Code reads from every directory above
47
+ * the working directory (the user's home and folders such as `~/Repos`). They belong to the
48
+ * host, not to the repository, and the project settings source would otherwise load them.
49
+ * - `autoMemoryEnabled: false`: without the user settings source auto memory falls back to its
50
+ * default, and its memory files accumulate outside the repository between sessions.
51
+ */
52
+ export function claudeUserConfigIsolationSettings(workingDirectory, pathApi = path) {
53
+ return {
54
+ autoMemoryEnabled: false,
55
+ claudeMdExcludes: ancestorInstructionExcludes(workingDirectory, pathApi),
56
+ };
57
+ }
58
+ /**
59
+ * Every Claude Code agent launch: the isolation arguments, then one `--settings` value that carries
60
+ * the isolation settings and, for headless agent turns, the background-work restrictions with
61
+ * their tool deny list (`claude-background-work.ts`).
62
+ */
63
+ export function claudeIsolatedLaunchArgs(options) {
64
+ const settings = claudeUserConfigIsolationSettings(options.workingDirectory);
65
+ return [
66
+ ...claudeUserConfigIsolationArgs(options.forgeMcpConfigPath),
67
+ ...(options.headless ? claudeHeadlessToolArgs(settings) : ["--settings", JSON.stringify(settings)]),
68
+ ];
69
+ }
70
+ const ancestorInstructionEntries = ["CLAUDE.md", "CLAUDE.local.md", ".claude/CLAUDE.md", ".claude/rules/**"];
71
+ /**
72
+ * Instruction-file patterns for each directory strictly above the working directory. Windows
73
+ * paths are listed both as written and with forward slashes, the form glob matchers expect.
74
+ */
75
+ export function ancestorInstructionExcludes(workingDirectory, pathApi = path) {
76
+ const patterns = new Set();
77
+ let current = pathApi.resolve(workingDirectory);
78
+ for (let parent = pathApi.dirname(current); parent !== current; current = parent, parent = pathApi.dirname(current)) {
79
+ for (const entry of ancestorInstructionEntries) {
80
+ const pattern = pathApi.join(parent, entry);
81
+ patterns.add(pattern);
82
+ patterns.add(pattern.replaceAll("\\", "/"));
83
+ }
84
+ }
85
+ return [...patterns];
86
+ }
87
+ /**
88
+ * Codex reads `config.toml` (MCP servers, profiles, plugins), `AGENTS.md`, `AGENTS.override.md`,
89
+ * rules and skills from `CODEX_HOME`, so Forge runs it with a home of its own on each runner
90
+ * instead of the user's `~/.codex`. Codex's `--ignore-user-config` still loads the global
91
+ * `AGENTS.md`, so a separate home is the only full isolation. API-key turns authenticate through
92
+ * the environment; a local Codex CLI login is made once into this home
93
+ * (`CODEX_HOME=<path> codex login`).
94
+ *
95
+ * In a Forge sandbox container (`FORGE_RUNTIME_MODE=docker`) `~/.codex` is already Forge's own:
96
+ * an attempt-scoped volume that holds only the copied `auth.json` (sandbox/provider-auth/codex.ts).
97
+ */
98
+ export function forgeCodexHome(homeDirectory = os.homedir(), environment = process.env) {
99
+ return isForgeSandboxContainer(environment)
100
+ ? path.join(homeDirectory, ".codex")
101
+ : path.join(homeDirectory, ...forgeCodexHomeSegments);
102
+ }
103
+ const forgeCodexHomeSegments = [".forge", "provider-homes", "codex"];
104
+ export function codexUserConfigIsolationEnv(homeDirectory = os.homedir(), environment = process.env) {
105
+ const codexHome = forgeCodexHome(homeDirectory, environment);
106
+ if (!isForgeSandboxContainer(environment)) {
107
+ ensureForgeCodexHome(homeDirectory);
108
+ }
109
+ return { CODEX_HOME: codexHome };
110
+ }
111
+ /**
112
+ * Creates Forge's Codex home one directory at a time. Each directory Forge owns on the way
113
+ * (`.forge`, `provider-homes`, `codex`) must be a real directory: a symlink or Windows junction
114
+ * there, stale or user-made, would hand Codex another directory such as the user's `~/.codex`, so
115
+ * the launch is refused instead. The user's home directory itself may be reached through a link.
116
+ * The home is private whether Forge creates it now or it already exists, like Forge's other
117
+ * private directories; Windows keeps the profile's inherited ACL.
118
+ */
119
+ function ensureForgeCodexHome(homeDirectory) {
120
+ let current = homeDirectory;
121
+ for (const segment of forgeCodexHomeSegments) {
122
+ current = path.join(current, segment);
123
+ const stat = lstatIfPresent(current);
124
+ if (stat && (stat.isSymbolicLink() || !stat.isDirectory())) {
125
+ throw new ForgeFailureError("provider_home_redirected", `Forge can't run Codex with its own home: ${current} is a link or not a directory, so Codex could read another configuration, such as the user's own ~/.codex. Remove it; Forge recreates its own directory there on the next launch.`);
126
+ }
127
+ if (!stat)
128
+ fs.mkdirSync(current, { mode: 0o700 });
129
+ }
130
+ if (process.platform !== "win32")
131
+ fs.chmodSync(current, 0o700);
132
+ }
133
+ function lstatIfPresent(target) {
134
+ try {
135
+ return fs.lstatSync(target);
136
+ }
137
+ catch (error) {
138
+ if (error.code === "ENOENT")
139
+ return null;
140
+ throw error;
141
+ }
142
+ }
143
+ function isForgeSandboxContainer(environment) {
144
+ return environment.FORGE_RUNTIME_MODE?.trim().toLowerCase() === "docker";
145
+ }
146
+ /** The provider environment that shuts out the user's own configuration. */
147
+ export function providerUserConfigIsolationEnv(provider, homeDirectory = os.homedir(), environment = process.env) {
148
+ return normalizeProvider(provider) === "codex" ? codexUserConfigIsolationEnv(homeDirectory, environment) : {};
149
+ }
150
+ /**
151
+ * cursor-agent has no flag or environment variable that keeps it from reading `~/.cursor`
152
+ * (`mcp.json`, `cli-config.json`, rules), and `--approve-mcps` would approve every server there;
153
+ * other CLIs are unknown. Forge refuses to launch them.
154
+ */
155
+ export function providerUserConfigIsolationUnsupported(provider) {
156
+ const name = provider.trim() || "this provider";
157
+ return new ForgeFailureError("provider_user_config_isolation_unsupported", `Forge can't launch ${name}: it can't keep the host user's own ${name} configuration (instruction files, settings, rules, MCP servers, plugins) out of the agent session. Forge agents get only the context Forge gives them, so only ${userConfigIsolatedProviders.join(" and ")} sessions run on Forge runners.`);
158
+ }
159
+ export function isProviderUserConfigIsolated(provider) {
160
+ return userConfigIsolatedProviders.includes(normalizeProvider(provider));
161
+ }
162
+ function normalizeProvider(provider) {
163
+ return provider.trim().toLowerCase();
164
+ }
@@ -1,3 +1,9 @@
1
1
  export declare function isPathUnderRoot(root: string, target: string): boolean;
2
2
  export declare function ensureNoSymbolicLinkPathSegments(root: string, targetDirectory: string, errorMessage: string): Promise<void>;
3
3
  export declare function sha256File(filePath: string): Promise<string>;
4
+ /**
5
+ * Applies the end-of-run sidecar shape check when a QA gate records the sidecar, so the agent
6
+ * learns about a malformed file (for example a JSON array followed by a summary line) while it
7
+ * can still rewrite it, instead of the whole attempt failing after the run.
8
+ */
9
+ export declare function assertQaSidecarJsonShape(fullPath: string, sidecarPath: string, label: string): Promise<void>;
@@ -2,6 +2,7 @@ import crypto from "node:crypto";
2
2
  import { createReadStream } from "node:fs";
3
3
  import fs from "node:fs/promises";
4
4
  import path from "node:path";
5
+ import { looksLikeJson, maximumIntegrityJsonBytes, oversizedJsonReason, sidecarJsonShapeProblem, sidecarJsonRepairInstruction, } from "./sidecar-json-shape.js";
5
6
  export function isPathUnderRoot(root, target) {
6
7
  const relative = path.relative(path.resolve(root), path.resolve(target));
7
8
  return Boolean(relative)
@@ -42,3 +43,30 @@ export async function sha256File(filePath) {
42
43
  }
43
44
  return hash.digest("hex");
44
45
  }
46
+ /**
47
+ * Applies the end-of-run sidecar shape check when a QA gate records the sidecar, so the agent
48
+ * learns about a malformed file (for example a JSON array followed by a summary line) while it
49
+ * can still rewrite it, instead of the whole attempt failing after the run.
50
+ */
51
+ export async function assertQaSidecarJsonShape(fullPath, sidecarPath, label) {
52
+ const problem = await qaSidecarJsonShapeProblem(fullPath, sidecarPath);
53
+ if (problem !== null) {
54
+ throw new Error(`${label}: ${sidecarJsonRepairInstruction(sidecarPath, problem)}`);
55
+ }
56
+ }
57
+ async function qaSidecarJsonShapeProblem(fullPath, sidecarPath) {
58
+ const handle = await fs.open(fullPath, "r");
59
+ try {
60
+ const { size } = await handle.stat();
61
+ if (size <= maximumIntegrityJsonBytes) {
62
+ return sidecarJsonShapeProblem(await handle.readFile(), sidecarPath);
63
+ }
64
+ // Too large to inspect as JSON: only a file that starts like JSON is a problem.
65
+ const prefix = Buffer.alloc(4096);
66
+ const { bytesRead } = await handle.read(prefix, 0, prefix.length, 0);
67
+ return looksLikeJson(prefix.subarray(0, bytesRead).toString("utf8"), sidecarPath) ? oversizedJsonReason : null;
68
+ }
69
+ finally {
70
+ await handle.close();
71
+ }
72
+ }
@@ -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)