@loucompanion/forge-bridge 0.1.4-dev.86fc5d1208e6 → 0.1.4-dev.9e8a5b93cbcb

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.
@@ -75,6 +75,8 @@ export declare class StreamingProviderProcessRunner implements ProviderProcessRu
75
75
  }
76
76
  /** Returns aggregate resident bytes for the exact supervised Unix process group. */
77
77
  export declare function processGroupResidentMemoryBytes(processGroupId: number, platform?: NodeJS.Platform, procRoot?: string): number | null;
78
+ export declare const UNIX_PROVIDER_START_GRANT_LINE = "forge-provider-start-granted\n";
79
+ export declare function buildUnixProviderStartGateLaunch(command: string, args: readonly string[]): LaunchCommand;
78
80
  export declare function resolveCodexNpmDirectLaunch(commandPath: string, args: readonly string[]): LaunchCommand | null;
79
81
  /**
80
82
  * npm installs of Claude Code (`npm i -g @anthropic-ai/claude-code`) put a `claude.cmd` shim on
@@ -323,12 +323,29 @@ export class StreamingProviderProcessRunner {
323
323
  // An unsupervised Unix provider still gets a dedicated process group so a
324
324
  // cancellation can stop descendants instead of only the CLI root.
325
325
  const launch = supervisedLaunch ?? { ...providerLaunch, detached: process.platform !== "win32" };
326
+ const childEnvironment = buildProviderChildEnvironment(request.env);
327
+ // A piped prompt must reach the provider promptly (Claude Code abandons a
328
+ // silent stdin after ~3s), but the provider must not run before Forge has
329
+ // recorded its start. Off Windows, hold the launch behind a start gate in
330
+ // the same process: the prompt is written immediately and buffers in the
331
+ // pipe, and the gate execs the provider only once onStarted succeeds.
332
+ const startGated = process.platform !== "win32"
333
+ && supervisedLaunch?.strategy !== "windows_job_object"
334
+ && request.stdin !== undefined
335
+ && fs.existsSync(UNIX_PROVIDER_START_GATE_SHELL)
336
+ && isUnixExecutableAvailable(launch.command, childEnvironment.PATH, request.cwd);
337
+ const spawnLaunch = startGated
338
+ ? buildUnixProviderStartGateLaunch(launch.command, launch.args)
339
+ : launch;
326
340
  return await new Promise((resolve, reject) => {
327
341
  const rootCreatedAt = new Date().toISOString();
328
- const child = spawn(launch.command, launch.args, {
342
+ const stdinMode = request.stdin === undefined ? "ignore" : "pipe";
343
+ const child = spawn(spawnLaunch.command, spawnLaunch.args, {
329
344
  cwd: request.cwd,
330
- env: buildProviderChildEnvironment(request.env),
331
- stdio: [request.stdin === undefined ? "ignore" : "pipe", "pipe", "pipe"],
345
+ env: childEnvironment,
346
+ stdio: startGated
347
+ ? [stdinMode, "pipe", "pipe", "pipe"]
348
+ : [stdinMode, "pipe", "pipe"],
332
349
  windowsHide: true,
333
350
  detached: launch.detached,
334
351
  });
@@ -386,6 +403,27 @@ export class StreamingProviderProcessRunner {
386
403
  signal?.addEventListener("abort", abort, { once: true });
387
404
  }
388
405
  child.on("error", fail);
406
+ const startGrant = startGated ? child.stdio[3] : null;
407
+ if (startGated && !startGrant) {
408
+ fail(new Error("Provider start-grant stream was not piped."));
409
+ return;
410
+ }
411
+ startGrant?.on("error", error => {
412
+ // A broken grant pipe means the gate already exited (terminated before
413
+ // its grant, or it died on its own). Its close event carries the real
414
+ // exit status, so an EPIPE here must not replace that result.
415
+ if (isBrokenPipeError(error))
416
+ return;
417
+ fail(error);
418
+ });
419
+ const grantUnixProviderStart = () => {
420
+ if (!startGrant)
421
+ return;
422
+ // Never release a provider whose launch was cancelled or already failed.
423
+ if (closed || settled || cancellationRequested || signal?.aborted)
424
+ return;
425
+ startGrant.end(UNIX_PROVIDER_START_GRANT_LINE, "utf8");
426
+ };
389
427
  child.once("spawn", () => {
390
428
  readiness = (async () => {
391
429
  const providerReady = supervisedLaunch?.strategy === "windows_job_object"
@@ -398,6 +436,9 @@ export class StreamingProviderProcessRunner {
398
436
  if (supervisedLaunch?.strategy === "windows_job_object") {
399
437
  grantWindowsProviderStart(supervisedLaunch);
400
438
  }
439
+ else if (startGated) {
440
+ grantUnixProviderStart();
441
+ }
401
442
  })();
402
443
  void readiness.catch(error => {
403
444
  if (!closed && !signal?.aborted)
@@ -413,15 +454,20 @@ export class StreamingProviderProcessRunner {
413
454
  return;
414
455
  }
415
456
  child.stdin.on("error", (error) => {
457
+ // A prompt still buffered when Forge stops the process (cancellation,
458
+ // or a refused start grant) cannot be delivered; that broken pipe is
459
+ // not a failure. Any other stdin error still is.
460
+ if ((cancellationRequested || termination) && isBrokenPipeError(error))
461
+ return;
416
462
  void terminate();
417
463
  fail(error);
418
464
  });
419
465
  child.stdin.end(request.stdin, "utf8");
420
466
  };
421
467
  if (request.stdin !== undefined) {
422
- if (supervisedLaunch?.strategy === "windows_job_object") {
423
- // The outer supervisor must receive stdin before it can launch the
424
- // inner provider. Its start-grant file prevents prompt delivery.
468
+ if (supervisedLaunch?.strategy === "windows_job_object" || startGated) {
469
+ // The outer supervisor / Unix start gate must receive stdin before it
470
+ // can launch the provider. Its start grant fences prompt processing.
425
471
  writeProviderInput();
426
472
  }
427
473
  else {
@@ -682,6 +728,64 @@ async function resolveProviderProcessLaunch(command, args) {
682
728
  ?? resolvePackageManagerDirectLaunch(resolved, args)
683
729
  ?? buildWindowsLaunchCommand(resolved, args);
684
730
  }
731
+ const UNIX_PROVIDER_START_GATE_SHELL = "/bin/sh";
732
+ const UNIX_PROVIDER_START_GATE_NAME = "forge-provider-start-gate";
733
+ export const UNIX_PROVIDER_START_GRANT_LINE = "forge-provider-start-granted\n";
734
+ /**
735
+ * Blocks on fd 3 until the bridge writes the exact grant line, then replaces
736
+ * itself with the provider (`exec`), so the supervised root PID, process group
737
+ * and birth identity stay the provider's. The provider command and arguments
738
+ * are passed positionally and expanded only as "$@"; nothing is interpolated
739
+ * into the script. EOF, a read error, or any other content on fd 3 exits
740
+ * without running the provider. fd 3 is closed before exec so the provider and
741
+ * its descendants never inherit the grant channel. stdin is not touched, so
742
+ * the prompt stays buffered in its pipe for the provider.
743
+ */
744
+ const UNIX_PROVIDER_START_GATE_SCRIPT = [
745
+ "IFS= read -r forge_start_grant <&3 || { echo \"$0: provider start was not granted\" >&2; exit 125; }",
746
+ `[ "$forge_start_grant" = "${UNIX_PROVIDER_START_GRANT_LINE.trim()}" ] || { echo "$0: provider start grant was invalid" >&2; exit 125; }`,
747
+ "exec \"$@\" 3<&-",
748
+ ].join("\n");
749
+ export function buildUnixProviderStartGateLaunch(command, args) {
750
+ return {
751
+ command: UNIX_PROVIDER_START_GATE_SHELL,
752
+ args: ["-c", UNIX_PROVIDER_START_GATE_SCRIPT, UNIX_PROVIDER_START_GATE_NAME, command, ...args],
753
+ };
754
+ }
755
+ /**
756
+ * Mirrors the executable lookup the gate's `exec` will perform. A command that
757
+ * cannot be found is spawned directly instead so it keeps failing as a spawn
758
+ * ENOENT before any start is recorded; nothing can run in that case. The check
759
+ * is advisory: if the executable disappears between this lookup and the gated
760
+ * `exec`, the gate exits 127 with the shell's "not found" message after the
761
+ * start was recorded, which surfaces as an ordinary provider failure.
762
+ */
763
+ function isUnixExecutableAvailable(command, pathValue, cwd) {
764
+ if (!command || command.startsWith("-"))
765
+ return false;
766
+ const candidates = command.includes("/")
767
+ ? [path.resolve(cwd, command)]
768
+ : pathValue === undefined
769
+ ? null
770
+ : pathValue.split(path.delimiter).map(directory => path.resolve(cwd, directory || ".", command));
771
+ if (candidates === null)
772
+ return true;
773
+ return candidates.some(candidate => {
774
+ try {
775
+ if (!fs.statSync(candidate).isFile())
776
+ return false;
777
+ fs.accessSync(candidate, fs.constants.X_OK);
778
+ return true;
779
+ }
780
+ catch {
781
+ return false;
782
+ }
783
+ });
784
+ }
785
+ function isBrokenPipeError(error) {
786
+ const code = error?.code;
787
+ return code === "EPIPE" || code === "ERR_STREAM_DESTROYED" || code === "ECONNRESET";
788
+ }
685
789
  function grantWindowsProviderStart(launch) {
686
790
  if (!launch.startGrantPath) {
687
791
  throw new Error("host_process_supervisor_invalid: Windows provider start-grant path was not assigned.");
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const forgeBridgeVersion = "0.1.4-dev.86fc5d1208e6";
1
+ export declare const forgeBridgeVersion = "0.1.4-dev.9e8a5b93cbcb";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const forgeBridgeVersion = "0.1.4-dev.86fc5d1208e6";
1
+ export const forgeBridgeVersion = "0.1.4-dev.9e8a5b93cbcb";
@@ -36,6 +36,7 @@ const dependencyPreparationCoordinator = new RepositoryCoordinatorLock(defaultWo
36
36
  export async function detectWarmPaths(repoRoot, warmPathOverrides = []) {
37
37
  const entries = new Map();
38
38
  await collectDetectedPaths(repoRoot, repoRoot, entries, 0);
39
+ await collectSolutionProjectRestores(repoRoot, entries);
39
40
  for (const override of warmPathOverrides) {
40
41
  const normalized = normalizeRelativePath(override);
41
42
  if (!normalized) {
@@ -539,6 +540,79 @@ async function hasPythonMarker(dir) {
539
540
  return (await pathExists(path.join(dir, "pyproject.toml")))
540
541
  || (await pathExists(path.join(dir, "requirements.txt")));
541
542
  }
543
+ const solutionProjectPattern = /^Project\("\{[0-9A-Fa-f-]+\}"\)\s*=\s*"[^"]*"\s*,\s*"([^"]+\.(?:cs|fs|vb)proj)"/gimu;
544
+ const slnxProjectPattern = /<Project\b[^>]*\bPath\s*=\s*"([^"]+\.(?:cs|fs|vb)proj)"/giu;
545
+ const projectFilePattern = /\.(?:cs|fs|vb)proj$/iu;
546
+ const solutionFilePattern = /\.(?:sln|slnx|slnf)$/iu;
547
+ /**
548
+ * A worktree built from a never-built base checkout (a fresh runner clone has no bin/ or obj/)
549
+ * still needs its .NET projects restored, or the --no-restore runtime build fails with NETSDK1004.
550
+ * Restore exactly the projects the root solution(s) (.sln, .slnx, .slnf) list, or a lone root
551
+ * project when there is no solution. Other projects (fixtures, samples) keep the base-checkout
552
+ * output heuristic above.
553
+ */
554
+ async function collectSolutionProjectRestores(repoRoot, entries) {
555
+ const rootNames = await fs.readdir(repoRoot).catch(() => []);
556
+ const solutions = rootNames.filter((name) => solutionFilePattern.test(name));
557
+ if (solutions.length === 0) {
558
+ const rootProjects = rootNames.filter((name) => name.toLowerCase().endsWith(".csproj"));
559
+ if (rootProjects.length === 1) {
560
+ addEntry(entries, repoRoot, "", "obj", "dotnet", "obj");
561
+ }
562
+ return;
563
+ }
564
+ for (const solution of solutions) {
565
+ for (const listed of await readSolutionProjectPaths(repoRoot, solution)) {
566
+ const projectPath = path.posix.normalize(normalizeRelativePath(listed));
567
+ if (!projectPath || projectPath === ".." || projectPath.startsWith("../") || path.posix.isAbsolute(projectPath)) {
568
+ continue;
569
+ }
570
+ const absoluteProject = path.resolve(repoRoot, ...projectPath.split("/"));
571
+ if (!isSubPath(repoRoot, absoluteProject) || !(await pathExists(absoluteProject))) {
572
+ continue;
573
+ }
574
+ const projectDir = path.posix.dirname(projectPath);
575
+ // The fallback runs a bare `dotnet restore` in the project's directory. Beside the solution,
576
+ // or next to another project file, that restore is ambiguous (MSB1011); leave those layouts
577
+ // to the base-checkout output heuristic.
578
+ if (projectDir === "." || (await countProjectFiles(path.dirname(absoluteProject))) !== 1) {
579
+ continue;
580
+ }
581
+ addEntry(entries, repoRoot, projectDir, "obj", "dotnet", joinRelative(projectDir, "obj"));
582
+ }
583
+ }
584
+ }
585
+ /** Project paths a root solution lists, relative to the repo root (forward slashes). */
586
+ async function readSolutionProjectPaths(repoRoot, solution) {
587
+ const text = await fs.readFile(path.join(repoRoot, solution), "utf8").catch(() => "");
588
+ const lower = solution.toLowerCase();
589
+ if (lower.endsWith(".sln")) {
590
+ return [...text.matchAll(solutionProjectPattern)].map((match) => match[1].replace(/\\/g, "/"));
591
+ }
592
+ if (lower.endsWith(".slnx")) {
593
+ return [...text.matchAll(slnxProjectPattern)].map((match) => match[1].replace(/\\/g, "/"));
594
+ }
595
+ // .slnf: {"solution": {"path": "<solution>", "projects": [...]}}, projects relative to that solution.
596
+ let filter;
597
+ try {
598
+ filter = JSON.parse(text.replace(/^\uFEFF/u, ""));
599
+ }
600
+ catch {
601
+ return [];
602
+ }
603
+ const body = filter?.solution;
604
+ if (!body || typeof body.path !== "string" || !Array.isArray(body.projects)) {
605
+ return [];
606
+ }
607
+ const solutionDir = path.posix.dirname(body.path.replace(/\\/g, "/"));
608
+ return body.projects
609
+ .filter((project) => typeof project === "string" && projectFilePattern.test(project))
610
+ .map((project) => path.posix.join(solutionDir, project.replace(/\\/g, "/")));
611
+ }
612
+ async function countProjectFiles(dir) {
613
+ const names = await fs.readdir(dir).catch(() => []);
614
+ return names.filter((name) => projectFilePattern.test(name)).length;
615
+ }
542
616
  async function hasDotNetMarker(dir) {
543
617
  const entries = await fs.readdir(dir).catch(() => []);
544
618
  return entries.some((name) => name.endsWith(".csproj") || name.endsWith(".sln"));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@loucompanion/forge-bridge",
3
- "version": "0.1.4-dev.86fc5d1208e6",
3
+ "version": "0.1.4-dev.9e8a5b93cbcb",
4
4
  "description": "Forge runner bridge CLI for connecting local developer machines to Forge dispatch.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",