@loucompanion/forge-bridge 0.1.4-dev.ccffca94938b → 0.1.4-dev.deb7f72e7930

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 (141) hide show
  1. package/README.md +87 -1
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +4 -1
  3. package/dist/bridge/bridge-chat-provider-command.js +14 -19
  4. package/dist/bridge/bridge-state-file.d.ts +161 -0
  5. package/dist/bridge/bridge-state-file.js +376 -0
  6. package/dist/bridge/bridge-state-io.d.ts +11 -0
  7. package/dist/bridge/bridge-state-io.js +50 -0
  8. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  9. package/dist/bridge/bridge-state-lock.js +102 -0
  10. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  11. package/dist/bridge/bridge-state-unpublished.js +111 -0
  12. package/dist/bridge/bridge.service.d.ts +16 -12
  13. package/dist/bridge/bridge.service.js +131 -243
  14. package/dist/bridge/bridge.types.d.ts +5 -0
  15. package/dist/bridge/in-flight-registry.d.ts +62 -0
  16. package/dist/bridge/in-flight-registry.js +207 -0
  17. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  18. package/dist/bridge/readiness-result-outbox.js +20 -0
  19. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  20. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  21. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  22. package/dist/cleanup/cleanup-wip.js +66 -0
  23. package/dist/cleanup/cleanup.service.d.ts +11 -1
  24. package/dist/cleanup/cleanup.service.js +80 -62
  25. package/dist/cleanup/cleanup.types.d.ts +2 -0
  26. package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
  27. package/dist/cleanup/host-runtime-ledger.js +30 -9
  28. package/dist/cli/cli.help.js +56 -12
  29. package/dist/cli/cli.service.d.ts +3 -10
  30. package/dist/cli/cli.service.js +10 -171
  31. package/dist/cli/idle-status.d.ts +84 -0
  32. package/dist/cli/idle-status.js +181 -0
  33. package/dist/cli/local-config.d.ts +2 -0
  34. package/dist/cli/local-config.js +7 -1
  35. package/dist/cli/provider-cli-detection.d.ts +10 -0
  36. package/dist/cli/provider-cli-detection.js +160 -0
  37. package/dist/runtime/aspnet-runtime-prebuild.d.ts +5 -0
  38. package/dist/runtime/aspnet-runtime-prebuild.js +46 -1
  39. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  40. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  41. package/dist/runtime/docker-engine-probe.js +7 -0
  42. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  43. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  44. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  45. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  46. package/dist/runtime/host-load-governor.d.ts +2 -0
  47. package/dist/runtime/host-load-ledger-lock.js +6 -4
  48. package/dist/runtime/host-load-runtime-settings.js +4 -2
  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.js +10 -50
  52. package/dist/runtime/managed-command-teardown.js +5 -16
  53. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  54. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  55. package/dist/runtime/runner-settings.d.ts +4 -0
  56. package/dist/runtime/runner-settings.js +22 -0
  57. package/dist/sandbox/host-capacity-broker.d.ts +3 -1
  58. package/dist/sandbox/host-capacity-broker.js +4 -2
  59. package/dist/sandbox/managed-branch.d.ts +13 -0
  60. package/dist/sandbox/managed-branch.js +36 -0
  61. package/dist/sandbox/provider-auth/codex.js +11 -11
  62. package/dist/sandbox/runtime.js +2 -6
  63. package/dist/session/managed-attempt-tools.d.ts +0 -7
  64. package/dist/session/managed-attempt-tools.js +45 -77
  65. package/dist/session/managed-build-receipt.d.ts +5 -0
  66. package/dist/session/managed-build-receipt.js +8 -3
  67. package/dist/session/phase-completion.artifacts.js +2 -1
  68. package/dist/session/phase-completion.d.ts +8 -0
  69. package/dist/session/phase-completion.js +1 -0
  70. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  71. package/dist/session/phase-completion.mcp-args.js +156 -0
  72. package/dist/session/phase-completion.runtime.d.ts +0 -8
  73. package/dist/session/phase-completion.runtime.js +43 -197
  74. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  75. package/dist/session/pre-publication-native-postgres.js +111 -0
  76. package/dist/session/pre-publication-process.js +10 -10
  77. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  78. package/dist/session/pre-publication-step-execution.js +6 -5
  79. package/dist/session/pre-publication-validation.d.ts +7 -3
  80. package/dist/session/pre-publication-validation.js +32 -30
  81. package/dist/session/provider-cli/claude-background-work.d.ts +3 -2
  82. package/dist/session/provider-cli/claude-background-work.js +4 -3
  83. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  84. package/dist/session/provider-cli/host-build-lock.js +30 -0
  85. package/dist/session/provider-cli/pre-publication-repair.d.ts +16 -0
  86. package/dist/session/provider-cli/pre-publication-repair.js +33 -0
  87. package/dist/session/provider-cli/provider-cli.child-environment.js +4 -2
  88. package/dist/session/provider-cli/provider-cli.process.d.ts +2 -14
  89. package/dist/session/provider-cli/provider-cli.process.js +4 -94
  90. package/dist/session/provider-cli/provider-cli.prompts.d.ts +3 -0
  91. package/dist/session/provider-cli/provider-cli.prompts.js +27 -27
  92. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  93. package/dist/session/provider-cli/provider-cli.runtime.js +23 -2
  94. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  95. package/dist/session/provider-cli/provider-cli.service.js +27 -43
  96. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  97. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  98. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  99. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  100. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  101. package/dist/session/qa-sidecar-validation.js +28 -0
  102. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  103. package/dist/session/sandbox-host-capacity-gate.js +34 -15
  104. package/dist/session/session-redaction.js +31 -181
  105. package/dist/session/session.service.d.ts +2 -0
  106. package/dist/session/session.service.js +62 -56
  107. package/dist/session/session.types.js +1 -1
  108. package/dist/session/sidecar-json-shape.d.ts +31 -0
  109. package/dist/session/sidecar-json-shape.js +217 -0
  110. package/dist/shared/fs/file-identity.d.ts +10 -0
  111. package/dist/shared/fs/file-identity.js +15 -0
  112. package/dist/shared/fs/replace-file.d.ts +7 -0
  113. package/dist/shared/fs/replace-file.js +33 -0
  114. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  115. package/dist/shared/process/host-process-recovery.js +23 -3
  116. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  117. package/dist/shared/process/host-process-supervisor.js +66 -14
  118. package/dist/shared/provider-capabilities.js +9 -1
  119. package/dist/version.d.ts +1 -1
  120. package/dist/version.js +1 -1
  121. package/dist/worktree/wip-git.d.ts +33 -0
  122. package/dist/worktree/wip-git.js +122 -0
  123. package/dist/worktree/wip-refs.d.ts +62 -0
  124. package/dist/worktree/wip-refs.js +119 -0
  125. package/dist/worktree/wip-restore.d.ts +38 -0
  126. package/dist/worktree/wip-restore.js +190 -0
  127. package/dist/worktree/wip-snapshot.d.ts +50 -0
  128. package/dist/worktree/wip-snapshot.js +268 -0
  129. package/dist/worktree/worktree-inputs.d.ts +8 -0
  130. package/dist/worktree/worktree-inputs.js +134 -0
  131. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  132. package/dist/worktree/worktree-origin-sync.js +127 -0
  133. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  134. package/dist/worktree/worktree-wip-events.js +98 -0
  135. package/dist/worktree/worktree-wip.d.ts +49 -0
  136. package/dist/worktree/worktree-wip.js +182 -0
  137. package/dist/worktree/worktree.base.d.ts +7 -1
  138. package/dist/worktree/worktree.service.d.ts +27 -5
  139. package/dist/worktree/worktree.service.js +106 -181
  140. package/dist/worktree/worktree.types.d.ts +31 -0
  141. package/package.json +1 -1
@@ -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
+ }
@@ -1,3 +1,4 @@
1
+ import { type BigIntStats } from "node:fs";
1
2
  import { type HostLoadAcquireOptions, type HostLoadAdmission, type HostLoadStepGate, type HostLoadStepRequest } from "../runtime/host-load-governor.js";
2
3
  export interface SandboxHostCapacityGateOptions {
3
4
  readonly write?: (line: string) => void;
@@ -7,13 +8,33 @@ export interface SandboxHostCapacityGateOptions {
7
8
  readonly maxWaitMs?: number;
8
9
  /** Owner of authentic replies (root in the container; tests use their own uid). */
9
10
  readonly trustedOwnerUid?: number;
11
+ /**
12
+ * How a reply is proven the bridge's; by default POSIX ownership by trustedOwnerUid,
13
+ * which is what the Linux sandbox has. A test standing in for the container on a
14
+ * host without POSIX ownership supplies the provenance it can prove instead.
15
+ */
16
+ readonly replyOwnership?: SandboxReplyOwnership;
10
17
  }
18
+ /**
19
+ * Whether the bridge owns a reply, judged from the stat of the open handle of a
20
+ * regular file with a single link: null when it does, otherwise why it does not.
21
+ * The stat is exact (bigint): no owner id or file identity is rounded to a double.
22
+ */
23
+ export type SandboxReplyOwnership = (stat: BigIntStats) => string | null;
24
+ /**
25
+ * Inside the Linux sandbox a reply is the bridge's when the trusted uid (root)
26
+ * owns it and no one else can write it: the sandbox user can create neither.
27
+ * Windows has no such proof in a file's stat (Node reports uid 0 for every file
28
+ * and derives the mode from the read-only attribute alone), so there no reply
29
+ * is ever trusted: the gate fails closed rather than read a read-only file as root's.
30
+ */
31
+ export declare function posixReplyOwnership(trustedOwnerUid: number, platform?: NodeJS.Platform): SandboxReplyOwnership;
11
32
  export declare class SandboxBrokeredHostLoadGate implements HostLoadStepGate {
12
33
  readonly enabled = true;
13
34
  private readonly write;
14
35
  private readonly responseRoot;
15
36
  private readonly pollMs;
16
- private readonly trustedOwnerUid;
37
+ private readonly replyOwnership;
17
38
  readonly maxWaitMs: number;
18
39
  constructor(options?: SandboxHostCapacityGateOptions);
19
40
  acquire(request: HostLoadStepRequest, options?: HostLoadAcquireOptions): Promise<HostLoadAdmission>;
@@ -8,18 +8,37 @@ import { HostCapacityTokenFencedError } from "../runtime/host-load-token-ledger.
8
8
  import { sandboxHostCapacityBrokerEnvironment, sandboxHostCapacityBrokerProtocol, sandboxHostCapacityLineType, sandboxHostCapacityMaxWaitEnvironment, sandboxHostCapacityResponseOwnerUid, sandboxHostCapacityResponseRoot, } from "../sandbox/host-capacity-broker.js";
9
9
  import { monotonicNowMs } from "../shared/time/monotonic.js";
10
10
  import { ForgeFailureError } from "./session.types.js";
11
+ /**
12
+ * Inside the Linux sandbox a reply is the bridge's when the trusted uid (root)
13
+ * owns it and no one else can write it: the sandbox user can create neither.
14
+ * Windows has no such proof in a file's stat (Node reports uid 0 for every file
15
+ * and derives the mode from the read-only attribute alone), so there no reply
16
+ * is ever trusted: the gate fails closed rather than read a read-only file as root's.
17
+ */
18
+ export function posixReplyOwnership(trustedOwnerUid, platform = process.platform) {
19
+ return stat => {
20
+ if (platform === "win32")
21
+ return "file ownership cannot be proven on Windows";
22
+ if (stat.uid !== BigInt(trustedOwnerUid))
23
+ return `it is owned by uid ${stat.uid}, not the bridge`;
24
+ if ((stat.mode & 18n) !== 0n)
25
+ return "others can write it";
26
+ return null;
27
+ };
28
+ }
11
29
  export class SandboxBrokeredHostLoadGate {
12
30
  enabled = true;
13
31
  write;
14
32
  responseRoot;
15
33
  pollMs;
16
- trustedOwnerUid;
34
+ replyOwnership;
17
35
  maxWaitMs;
18
36
  constructor(options = {}) {
19
37
  this.write = options.write ?? (line => { process.stdout.write(line); });
20
38
  this.responseRoot = options.responseRoot ?? sandboxHostCapacityResponseRoot;
21
39
  this.pollMs = options.pollMs ?? 250;
22
- this.trustedOwnerUid = options.trustedOwnerUid ?? sandboxHostCapacityResponseOwnerUid;
40
+ this.replyOwnership = options.replyOwnership
41
+ ?? posixReplyOwnership(options.trustedOwnerUid ?? sandboxHostCapacityResponseOwnerUid);
23
42
  this.maxWaitMs = options.maxWaitMs ?? defaultHostLoadGovernorConfig.maxWaitMs + 2 * 60_000;
24
43
  }
25
44
  async acquire(request, options = {}) {
@@ -32,7 +51,7 @@ export class SandboxBrokeredHostLoadGate {
32
51
  while (true) {
33
52
  if (options.signal?.aborted)
34
53
  throw options.signal.reason ?? new Error("The host capacity wait was cancelled.");
35
- const response = await readResponse(responsePath, requestId, this.trustedOwnerUid);
54
+ const response = await readResponse(responsePath, requestId, this.replyOwnership);
36
55
  if (response?.status === "waiting" && !waitingReported) {
37
56
  waitingReported = true;
38
57
  void Promise.resolve(options.onWaiting?.(decision(false, response))).catch(() => undefined);
@@ -57,7 +76,7 @@ export class SandboxBrokeredHostLoadGate {
57
76
  const fenced = new AbortController();
58
77
  // The bridge rewrites the response as "fenced" if it lost the token; the step then stops.
59
78
  const watch = setInterval(() => {
60
- void readResponse(responsePath, requestId, this.trustedOwnerUid).then(current => {
79
+ void readResponse(responsePath, requestId, this.replyOwnership).then(current => {
61
80
  if (current?.status === "fenced" && !fenced.signal.aborted) {
62
81
  fenced.abort(new HostCapacityTokenFencedError(requestId, "renew"));
63
82
  }
@@ -180,12 +199,13 @@ function responseError(request, response) {
180
199
  }
181
200
  /**
182
201
  * 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).
202
+ * replaced by a newer reply). Only a regular file with a single link that the
203
+ * reply ownership rule proves the bridge's (in the sandbox: owned by the trusted
204
+ * uid and writable by no one else) is the bridge's: the sandbox user can create
205
+ * none of those (see host-capacity-broker.ts).
186
206
  * Anything else fails closed with sandbox_host_capacity_reply_untrusted.
187
207
  */
188
- async function readResponse(responsePath, requestId, trustedOwnerUid) {
208
+ async function readResponse(responsePath, requestId, replyOwnership) {
189
209
  let handle;
190
210
  try {
191
211
  handle = await fs.open(responsePath, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0));
@@ -197,19 +217,18 @@ async function readResponse(responsePath, requestId, trustedOwnerUid) {
197
217
  }
198
218
  let content;
199
219
  try {
200
- const stat = await handle.stat();
220
+ const stat = await handle.stat({ bigint: true });
201
221
  // No link left: the bridge renamed a newer reply over this one after it was opened
202
222
  // (waiting -> admitted, admitted -> fenced). It is not a forgery, and nothing is read
203
223
  // from it; the next poll opens the newer reply. Only the bridge can replace a reply,
204
224
  // since the directory is root-owned and not writable by the sandbox user.
205
- if (stat.isFile() && stat.nlink === 0)
225
+ if (stat.isFile() && stat.nlink === 0n)
206
226
  return null;
207
- if (!stat.isFile() || stat.nlink !== 1)
227
+ if (!stat.isFile() || stat.nlink !== 1n)
208
228
  throw untrustedReply(responsePath, "it is not a regular file with a single link");
209
- if (stat.uid !== trustedOwnerUid)
210
- throw untrustedReply(responsePath, `it is owned by uid ${stat.uid}, not the bridge`);
211
- if ((stat.mode & 0o022) !== 0)
212
- throw untrustedReply(responsePath, "others can write it");
229
+ const notTheBridges = replyOwnership(stat);
230
+ if (notTheBridges !== null)
231
+ throw untrustedReply(responsePath, notTheBridges);
213
232
  content = await handle.readFile("utf8");
214
233
  }
215
234
  finally {
@@ -1,14 +1,14 @@
1
1
  import { redactText, shouldRedactJsonProperty } from "../shared/redaction/redaction.js";
2
- import { TextDecoder } from "node:util";
2
+ import { decodeJsonEscapesLeniently, decodeJsonStringToken, inspectJsonText, isJsonPunctuation, isJsonWhitespace, JsonShapeError, sidecarJsonShapeProblem, } from "./sidecar-json-shape.js";
3
+ import { ForgeFailureError } from "./session.types.js";
3
4
  const integrityProtectedEventDataTypes = new Set(["sandbox_started"]);
4
5
  const structuralSecretMessage = "runner result structural metadata contains protected secret material and cannot be redacted without changing protocol identity.";
5
6
  const sidecarSecretMessage = "runner result sidecar contains protected secret material and cannot be redacted without invalidating integrity metadata.";
6
7
  const artifactJsonMessage = "runner result artifact JSON is invalid or exceeds safe inspection limits; transport was rejected.";
7
8
  const artifactJsonKeySecretMessage = "runner result artifact JSON property name contains protected secret material and cannot be redacted without changing protocol identity.";
8
9
  const artifactJsonPrimitiveSecretMessage = "runner result artifact JSON primitive contains protected secret material and cannot be redacted without changing protocol identity.";
9
- const maximumIntegrityJsonBytes = 8 * 1024 * 1024;
10
- const maximumIntegrityJsonDepth = 128;
11
- const maximumIntegrityJsonTokens = 262_144;
10
+ // Stable failure code for a sidecar that starts like JSON but does not parse (see sidecar-json-shape.ts).
11
+ const malformedSidecarFailureCode = "runner_result_sidecar_malformed";
12
12
  export function redactRunnerDispatchEvent(event, exactSecrets = []) {
13
13
  assertStructuralFieldsDoNotContainSecrets([
14
14
  event.role,
@@ -149,7 +149,7 @@ function redactArtifactJson(value, exactSecrets) {
149
149
  }
150
150
  continue;
151
151
  }
152
- const token = decodeJsonStringToken(value, index, artifactJsonMessage);
152
+ const token = decodeArtifactJsonStringToken(value, index);
153
153
  const afterToken = skipJsonWhitespace(value, token.nextIndex);
154
154
  if (value.charCodeAt(afterToken) === 0x3a) {
155
155
  assertJsonStringDoesNotContainSecrets(token.decoded, exactSecrets, artifactJsonKeySecretMessage);
@@ -159,7 +159,7 @@ function redactArtifactJson(value, exactSecrets) {
159
159
  const valueStart = skipJsonWhitespace(value, afterToken + 1);
160
160
  const valueEnd = jsonValueEnd(value, valueStart);
161
161
  if (value[valueStart] !== '"'
162
- || decodeJsonStringToken(value, valueStart, artifactJsonMessage).decoded !== "[REDACTED]") {
162
+ || decodeArtifactJsonStringToken(value, valueStart).decoded !== "[REDACTED]") {
163
163
  replace(valueStart, valueEnd, '"[REDACTED]"');
164
164
  }
165
165
  index = valueEnd;
@@ -193,13 +193,13 @@ function skipJsonWhitespace(value, start) {
193
193
  // value (including objects/arrays) without decoding or rewriting adjacent data.
194
194
  function jsonValueEnd(value, start) {
195
195
  if (value.charCodeAt(start) === 0x22) {
196
- return decodeJsonStringToken(value, start, artifactJsonMessage).nextIndex;
196
+ return decodeArtifactJsonStringToken(value, start).nextIndex;
197
197
  }
198
198
  if (value[start] === "{" || value[start] === "[") {
199
199
  let depth = 0;
200
200
  for (let index = start; index < value.length; index += 1) {
201
201
  if (value[index] === '"') {
202
- index = decodeJsonStringToken(value, index, artifactJsonMessage).nextIndex - 1;
202
+ index = decodeArtifactJsonStringToken(value, index).nextIndex - 1;
203
203
  }
204
204
  else if (value[index] === "{" || value[index] === "[") {
205
205
  depth += 1;
@@ -248,7 +248,7 @@ function assertSidecarsDoNotContainSecrets(sidecars, exactSecrets) {
248
248
  throw new Error(sidecarSecretMessage);
249
249
  }
250
250
  }
251
- assertSidecarJsonDoesNotContainSecrets(decoded, sidecar.path, exactSecrets, sidecarSecretMessage);
251
+ assertSidecarJsonShape(decoded, sidecar.path, exactSecrets);
252
252
  }
253
253
  }
254
254
  function assertSerializedJsonDoesNotContainSecrets(value, exactSecrets, errorMessage) {
@@ -257,187 +257,37 @@ function assertSerializedJsonDoesNotContainSecrets(value, exactSecrets, errorMes
257
257
  assertJsonStringDoesNotContainSecrets(value, exactSecrets, errorMessage);
258
258
  inspectJsonStringTokens(value, exactSecrets, errorMessage);
259
259
  }
260
- function assertSidecarJsonDoesNotContainSecrets(value, path, exactSecrets, errorMessage) {
261
- let decoded;
262
- try {
263
- decoded = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(value);
264
- }
265
- catch {
266
- if (path.toLowerCase().endsWith(".json"))
267
- throw new Error(errorMessage);
260
+ function assertSidecarJsonShape(content, path, exactSecrets) {
261
+ const problem = sidecarJsonShapeProblem(content, path, decoded => assertJsonStringDoesNotContainSecrets(decoded, exactSecrets, sidecarSecretMessage));
262
+ if (problem === null)
268
263
  return;
269
- }
270
- if (!looksLikeJson(decoded, path))
271
- return;
272
- const hasUtf8Bom = value.length >= 3
273
- && value[0] === 0xef
274
- && value[1] === 0xbb
275
- && value[2] === 0xbf;
276
- if (hasUtf8Bom)
277
- throw new Error(errorMessage);
278
- inspectJsonStringTokens(decoded, exactSecrets, errorMessage);
264
+ // A malformed file cannot be read token by token, so decode its escapes leniently first: a
265
+ // secret hidden behind JSON escapes keeps the secret error instead of the malformed one.
266
+ assertJsonStringDoesNotContainSecrets(decodeJsonEscapesLeniently(content.toString("utf8")), exactSecrets, sidecarSecretMessage);
267
+ // Still fail closed: the bytes cannot be redacted, so the result is rejected either way. The
268
+ // distinct code and message say the file is malformed, not that a secret was found.
269
+ throw new ForgeFailureError(malformedSidecarFailureCode, `runner result sidecar ${path} looks like JSON but is not valid JSON (${problem}); `
270
+ + "Forge rejects sidecars it cannot fully inspect, so the result was not accepted.");
279
271
  }
280
272
  function inspectJsonStringTokens(value, exactSecrets, errorMessage) {
281
- if (Buffer.byteLength(value, "utf8") > maximumIntegrityJsonBytes) {
282
- throw new Error(errorMessage);
283
- }
284
- const containers = [];
285
- let index = 0;
286
- let tokenCount = 0;
287
- const countToken = () => {
288
- tokenCount += 1;
289
- if (tokenCount > maximumIntegrityJsonTokens)
290
- throw new Error(errorMessage);
291
- };
292
- while (index < value.length) {
293
- const code = value.charCodeAt(index);
294
- if (code === 0x22) {
295
- countToken();
296
- const token = decodeJsonStringToken(value, index, errorMessage);
297
- assertJsonStringDoesNotContainSecrets(token.decoded, exactSecrets, errorMessage);
298
- index = token.nextIndex;
299
- continue;
300
- }
301
- if (code === 0x7b || code === 0x5b) {
302
- countToken();
303
- containers.push(code);
304
- if (containers.length > maximumIntegrityJsonDepth)
305
- throw new Error(errorMessage);
306
- index += 1;
307
- continue;
308
- }
309
- if (code === 0x7d || code === 0x5d) {
310
- countToken();
311
- const expected = code === 0x7d ? 0x7b : 0x5b;
312
- if (containers.pop() !== expected)
313
- throw new Error(errorMessage);
314
- index += 1;
315
- continue;
316
- }
317
- if (code === 0x2c || code === 0x3a) {
318
- index += 1;
319
- continue;
320
- }
321
- if (isJsonWhitespace(code)) {
322
- index += 1;
323
- continue;
324
- }
325
- countToken();
326
- do {
327
- index += 1;
328
- } while (index < value.length
329
- && !isJsonWhitespace(value.charCodeAt(index))
330
- && !isJsonPunctuation(value.charCodeAt(index)));
331
- }
332
- if (containers.length !== 0)
333
- throw new Error(errorMessage);
334
273
  try {
335
- JSON.parse(value);
274
+ inspectJsonText(value, decoded => assertJsonStringDoesNotContainSecrets(decoded, exactSecrets, errorMessage));
336
275
  }
337
- catch {
338
- throw new Error(errorMessage);
276
+ catch (error) {
277
+ if (error instanceof JsonShapeError)
278
+ throw new Error(errorMessage, { cause: error });
279
+ throw error;
339
280
  }
340
281
  }
341
- function decodeJsonStringToken(value, openingQuoteIndex, errorMessage) {
342
- const chunks = [];
343
- let segmentStart = openingQuoteIndex + 1;
344
- let index = segmentStart;
345
- while (index < value.length) {
346
- const code = value.charCodeAt(index);
347
- if (code === 0x22) {
348
- chunks.push(value.slice(segmentStart, index));
349
- const decoded = chunks.join("");
350
- if (!isWellFormedUnicode(decoded))
351
- throw new Error(errorMessage);
352
- return { decoded, nextIndex: index + 1 };
353
- }
354
- if (code < 0x20)
355
- throw new Error(errorMessage);
356
- if (code !== 0x5c) {
357
- index += 1;
358
- continue;
359
- }
360
- chunks.push(value.slice(segmentStart, index));
361
- index += 1;
362
- if (index >= value.length)
363
- throw new Error(errorMessage);
364
- const escaped = value[index];
365
- switch (escaped) {
366
- case "\"":
367
- chunks.push("\"");
368
- index += 1;
369
- break;
370
- case "\\":
371
- chunks.push("\\");
372
- index += 1;
373
- break;
374
- case "/":
375
- chunks.push("/");
376
- index += 1;
377
- break;
378
- case "b":
379
- chunks.push("\b");
380
- index += 1;
381
- break;
382
- case "f":
383
- chunks.push("\f");
384
- index += 1;
385
- break;
386
- case "n":
387
- chunks.push("\n");
388
- index += 1;
389
- break;
390
- case "r":
391
- chunks.push("\r");
392
- index += 1;
393
- break;
394
- case "t":
395
- chunks.push("\t");
396
- index += 1;
397
- break;
398
- case "u": {
399
- const hex = value.slice(index + 1, index + 5);
400
- if (!/^[0-9a-fA-F]{4}$/u.test(hex))
401
- throw new Error(errorMessage);
402
- chunks.push(String.fromCharCode(Number.parseInt(hex, 16)));
403
- index += 5;
404
- break;
405
- }
406
- default: throw new Error(errorMessage);
407
- }
408
- segmentStart = index;
282
+ function decodeArtifactJsonStringToken(value, openingQuoteIndex) {
283
+ try {
284
+ return decodeJsonStringToken(value, openingQuoteIndex);
409
285
  }
410
- throw new Error(errorMessage);
411
- }
412
- function isWellFormedUnicode(value) {
413
- for (let index = 0; index < value.length; index += 1) {
414
- const code = value.charCodeAt(index);
415
- if (code >= 0xd800 && code <= 0xdbff) {
416
- if (index + 1 >= value.length)
417
- return false;
418
- const next = value.charCodeAt(index + 1);
419
- if (next < 0xdc00 || next > 0xdfff)
420
- return false;
421
- index += 1;
422
- }
423
- else if (code >= 0xdc00 && code <= 0xdfff) {
424
- return false;
425
- }
286
+ catch (error) {
287
+ if (error instanceof JsonShapeError)
288
+ throw new Error(artifactJsonMessage, { cause: error });
289
+ throw error;
426
290
  }
427
- return true;
428
- }
429
- function looksLikeJson(value, path) {
430
- if (path.toLowerCase().endsWith(".json"))
431
- return true;
432
- const candidate = value.trimStart().replace(/^\uFEFF/u, "").trimStart();
433
- return candidate.startsWith("{") || candidate.startsWith("[") || candidate.startsWith("\"");
434
- }
435
- function isJsonWhitespace(code) {
436
- return code === 0x20 || code === 0x09 || code === 0x0a || code === 0x0d;
437
- }
438
- function isJsonPunctuation(code) {
439
- return code === 0x7b || code === 0x7d || code === 0x5b || code === 0x5d
440
- || code === 0x2c || code === 0x3a || code === 0x22;
441
291
  }
442
292
  function assertJsonStringDoesNotContainSecrets(value, exactSecrets, errorMessage) {
443
293
  for (const secret of exactSecrets) {
@@ -20,4 +20,6 @@ export declare class BridgeSessionService implements SessionService {
20
20
  runtimeCapacity(): HostRuntimeCapacitySnapshot | null;
21
21
  probeHostRuntime(request: HostRuntimeReadinessProbeRequest, signal?: AbortSignal): Promise<HostRuntimeReadinessProbeResult>;
22
22
  runOnce(dispatch: RunOnceDispatchPacket, sink: SessionEventSink, signal?: AbortSignal): Promise<RunOnceResultPacket>;
23
+ /** Reports the provider's peak memory and releases the attempt's host runtime lease. */
24
+ private releaseHostRuntime;
23
25
  }