@loucompanion/forge-bridge 0.1.4-dev.81e48ecc185d → 0.1.4-dev.866b33be3065

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 (61) hide show
  1. package/README.md +3 -0
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +1 -1
  3. package/dist/bridge/bridge-chat-provider-command.js +16 -4
  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/runner-host-capabilities.d.ts +3 -0
  7. package/dist/bridge/runner-host-capabilities.js +13 -0
  8. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  9. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  10. package/dist/runtime/docker-engine-probe.js +7 -0
  11. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  12. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  13. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  14. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  15. package/dist/runtime/host-facts.d.ts +2 -1
  16. package/dist/runtime/host-load-admission.d.ts +4 -1
  17. package/dist/runtime/host-load-sampler.d.ts +34 -4
  18. package/dist/runtime/host-load-sampler.js +73 -7
  19. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  20. package/dist/runtime/host-load-windows-cpu.js +85 -0
  21. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  22. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  23. package/dist/session/architect-waits.d.ts +2 -0
  24. package/dist/session/architect-waits.js +138 -0
  25. package/dist/session/managed-attempt-tools.d.ts +0 -7
  26. package/dist/session/managed-attempt-tools.js +44 -54
  27. package/dist/session/phase-completion.artifacts.js +2 -1
  28. package/dist/session/phase-completion.runtime.js +1 -1
  29. package/dist/session/phase-completion.schemas.js +3 -11
  30. package/dist/session/phase-completion.validation.js +3 -1
  31. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  32. package/dist/session/pre-publication-native-postgres.js +111 -0
  33. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  34. package/dist/session/pre-publication-step-execution.js +6 -5
  35. package/dist/session/pre-publication-validation.d.ts +7 -3
  36. package/dist/session/pre-publication-validation.js +32 -30
  37. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  38. package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
  39. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  40. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  41. package/dist/session/provider-cli/provider-cli.process.d.ts +8 -30
  42. package/dist/session/provider-cli/provider-cli.process.js +25 -376
  43. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  44. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  45. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  46. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  47. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  48. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  49. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  50. package/dist/session/qa-sidecar-validation.js +28 -0
  51. package/dist/session/session-redaction.js +31 -181
  52. package/dist/session/session.types.js +1 -1
  53. package/dist/session/sidecar-json-shape.d.ts +31 -0
  54. package/dist/session/sidecar-json-shape.js +217 -0
  55. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  56. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  57. package/dist/shared/process/windows-launch.d.ts +18 -0
  58. package/dist/shared/process/windows-launch.js +68 -0
  59. package/dist/version.d.ts +1 -1
  60. package/dist/version.js +1 -1
  61. package/package.json +1 -1
@@ -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
+ }
@@ -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,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,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) {
@@ -481,7 +481,7 @@ function unvalidatedFailureFactsForCode(code, source) {
481
481
  if (["prepublication_validation_failed", "prepublication_contract_invalid", "prepublication_execution_scope_invalid"].includes(code)) {
482
482
  return facts(code, "domain", "validation", source, "non_retryable", "fix_input");
483
483
  }
484
- if (code === "comment_repair_changed_files_mismatch") {
484
+ if (["comment_repair_changed_files_mismatch", "runner_result_sidecar_malformed"].includes(code)) {
485
485
  return facts(code, "domain", "validation", source, "non_retryable", "inspect_failure");
486
486
  }
487
487
  if (["generated_output_reset_failed", "generated_output_reset_unverified", "worktree_prepare_failed", "host_runtime_ledger_write_failed", "host_diagnostics_temporary_unavailable", "attempt_process_supervisor_start_failed", "attempt_process_supervisor_start_timeout"].includes(code)) {
@@ -0,0 +1,31 @@
1
+ export declare const maximumIntegrityJsonBytes: number;
2
+ /** A JSON text that breaks a shape rule. `reason` names the rule and never quotes file content. */
3
+ export declare class JsonShapeError extends Error {
4
+ readonly reason: string;
5
+ constructor(reason: string);
6
+ }
7
+ export declare const oversizedJsonReason = "it is larger than the 8 MiB JSON inspection limit";
8
+ /**
9
+ * Checks a bounded JSON text and calls `onString` with every decoded string token (property names
10
+ * and values). Throws JsonShapeError for a shape problem; errors thrown by `onString` propagate.
11
+ */
12
+ export declare function inspectJsonText(value: string, onString?: (decoded: string) => void): void;
13
+ export declare function decodeJsonStringToken(value: string, openingQuoteIndex: number): {
14
+ readonly decoded: string;
15
+ readonly nextIndex: number;
16
+ };
17
+ /**
18
+ * Why a sidecar that looks like JSON is not acceptable JSON, or null when it is fine: valid JSON,
19
+ * plain text that does not start like JSON, or binary content that is not named *.json.
20
+ */
21
+ export declare function sidecarJsonShapeProblem(content: Uint8Array, path: string, onString?: (decoded: string) => void): string | null;
22
+ /** The instruction an agent gets when it records a sidecar that fails the shape check. */
23
+ export declare function sidecarJsonRepairInstruction(path: string, reason: string): string;
24
+ /**
25
+ * Best-effort decoding of every JSON escape in a text that failed the shape check, so a secret
26
+ * hidden behind escapes still gets the secret error rather than the malformed-sidecar error.
27
+ */
28
+ export declare function decodeJsonEscapesLeniently(value: string): string;
29
+ export declare function looksLikeJson(value: string, path: string): boolean;
30
+ export declare function isJsonWhitespace(code: number): boolean;
31
+ export declare function isJsonPunctuation(code: number): boolean;