@loucompanion/forge-bridge 0.1.4-dev.1ff37038366e → 0.1.4-dev.318bc3bd5b6a
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.
- package/README.md +1 -1
- package/dist/cli/cli.help.js +2 -2
- package/dist/runtime/attempt-process-supervisor.d.ts +24 -0
- package/dist/runtime/attempt-process-supervisor.js +77 -3
- package/dist/runtime/host-diagnostics.js +4 -3
- package/dist/runtime/host-runtime-lease.js +50 -9
- package/dist/runtime/managed-command-teardown.d.ts +62 -0
- package/dist/runtime/managed-command-teardown.js +607 -0
- package/dist/runtime/node-host-runtime-adapter.js +5 -4
- package/dist/sandbox/repository-lock.js +3 -2
- package/dist/sandbox/runtime.js +5 -4
- package/dist/session/managed-attempt-tools.d.ts +25 -0
- package/dist/session/managed-attempt-tools.js +216 -18
- package/dist/session/managed-build-coordinator.d.ts +1 -1
- package/dist/session/managed-build-coordinator.js +8 -4
- package/dist/session/phase-completion.runtime.js +22 -17
- package/dist/session/provider-cli/provider-cli.process.d.ts +6 -1
- package/dist/session/provider-cli/provider-cli.process.js +198 -16
- package/dist/session/provider-cli/provider-cli.runtime.d.ts +6 -0
- package/dist/session/provider-cli/provider-cli.runtime.js +11 -0
- package/dist/session/provider-cli/provider-cli.service.js +10 -5
- package/dist/session/provider-cli/provider-usage.d.ts +2 -1
- package/dist/shared/process/host-process-recovery.js +3 -2
- package/dist/shared/process/host-process-supervisor.js +5 -4
- package/dist/shared/time/monotonic.d.ts +1 -0
- package/dist/shared/time/monotonic.js +8 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/dependency-warmer.js +74 -0
- package/package.json +1 -1
|
@@ -16,6 +16,9 @@ const execFileAsync = promisify(execFile);
|
|
|
16
16
|
// only needs a bounded diagnostic tail for failure classification.
|
|
17
17
|
export const PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS = 128 * 1024;
|
|
18
18
|
const PROVIDER_TERMINAL_EXIT_GRACE_MS = 15_000;
|
|
19
|
+
// A provider that keeps starting turns after its first successful one (background-task
|
|
20
|
+
// notifications) is still stopped this long after that first success.
|
|
21
|
+
const PROVIDER_TERMINAL_SUCCESS_CEILING_MS = 10 * 60_000;
|
|
19
22
|
const maximumRecoverableCodexModelsCacheBytes = 16 * 1024 * 1024;
|
|
20
23
|
/** Recovery must wrap the attempt coordinator, never its raw OS runner. Each
|
|
21
24
|
* relaunch needs a new fenced child generation and exclusive launch files. */
|
|
@@ -313,8 +316,10 @@ function setEnvironmentValueIfMissing(env, name, value) {
|
|
|
313
316
|
}
|
|
314
317
|
export class StreamingProviderProcessRunner {
|
|
315
318
|
terminalExitGraceMs;
|
|
316
|
-
|
|
319
|
+
terminalSuccessCeilingMs;
|
|
320
|
+
constructor(terminalExitGraceMs = PROVIDER_TERMINAL_EXIT_GRACE_MS, terminalSuccessCeilingMs = PROVIDER_TERMINAL_SUCCESS_CEILING_MS) {
|
|
317
321
|
this.terminalExitGraceMs = terminalExitGraceMs;
|
|
322
|
+
this.terminalSuccessCeilingMs = terminalSuccessCeilingMs;
|
|
318
323
|
}
|
|
319
324
|
async run(request, handlers = {}, signal) {
|
|
320
325
|
assertHostDatabaseCapabilityBoundary();
|
|
@@ -323,12 +328,29 @@ export class StreamingProviderProcessRunner {
|
|
|
323
328
|
// An unsupervised Unix provider still gets a dedicated process group so a
|
|
324
329
|
// cancellation can stop descendants instead of only the CLI root.
|
|
325
330
|
const launch = supervisedLaunch ?? { ...providerLaunch, detached: process.platform !== "win32" };
|
|
331
|
+
const childEnvironment = buildProviderChildEnvironment(request.env);
|
|
332
|
+
// A piped prompt must reach the provider promptly (Claude Code abandons a
|
|
333
|
+
// silent stdin after ~3s), but the provider must not run before Forge has
|
|
334
|
+
// recorded its start. Off Windows, hold the launch behind a start gate in
|
|
335
|
+
// the same process: the prompt is written immediately and buffers in the
|
|
336
|
+
// pipe, and the gate execs the provider only once onStarted succeeds.
|
|
337
|
+
const startGated = process.platform !== "win32"
|
|
338
|
+
&& supervisedLaunch?.strategy !== "windows_job_object"
|
|
339
|
+
&& request.stdin !== undefined
|
|
340
|
+
&& fs.existsSync(UNIX_PROVIDER_START_GATE_SHELL)
|
|
341
|
+
&& isUnixExecutableAvailable(launch.command, childEnvironment.PATH, request.cwd);
|
|
342
|
+
const spawnLaunch = startGated
|
|
343
|
+
? buildUnixProviderStartGateLaunch(launch.command, launch.args)
|
|
344
|
+
: launch;
|
|
326
345
|
return await new Promise((resolve, reject) => {
|
|
327
346
|
const rootCreatedAt = new Date().toISOString();
|
|
328
|
-
const
|
|
347
|
+
const stdinMode = request.stdin === undefined ? "ignore" : "pipe";
|
|
348
|
+
const child = spawn(spawnLaunch.command, spawnLaunch.args, {
|
|
329
349
|
cwd: request.cwd,
|
|
330
|
-
env:
|
|
331
|
-
stdio:
|
|
350
|
+
env: childEnvironment,
|
|
351
|
+
stdio: startGated
|
|
352
|
+
? [stdinMode, "pipe", "pipe", "pipe"]
|
|
353
|
+
: [stdinMode, "pipe", "pipe"],
|
|
332
354
|
windowsHide: true,
|
|
333
355
|
detached: launch.detached,
|
|
334
356
|
});
|
|
@@ -352,14 +374,21 @@ export class StreamingProviderProcessRunner {
|
|
|
352
374
|
let settled = false;
|
|
353
375
|
let closed = false;
|
|
354
376
|
let cancellationRequested = false;
|
|
377
|
+
let cancelledBeforeClose = false;
|
|
355
378
|
let terminalTerminationStarted = false;
|
|
356
379
|
let terminalExitTimer = null;
|
|
380
|
+
let terminalCeilingTimer = null;
|
|
381
|
+
let latestTurnFailed = false;
|
|
357
382
|
let readiness = null;
|
|
358
383
|
const cleanup = () => {
|
|
359
384
|
if (terminalExitTimer) {
|
|
360
385
|
clearTimeout(terminalExitTimer);
|
|
361
386
|
terminalExitTimer = null;
|
|
362
387
|
}
|
|
388
|
+
if (terminalCeilingTimer) {
|
|
389
|
+
clearTimeout(terminalCeilingTimer);
|
|
390
|
+
terminalCeilingTimer = null;
|
|
391
|
+
}
|
|
363
392
|
signal?.removeEventListener("abort", abort);
|
|
364
393
|
};
|
|
365
394
|
const fail = (error) => {
|
|
@@ -373,6 +402,8 @@ export class StreamingProviderProcessRunner {
|
|
|
373
402
|
void terminate().then(() => reject(error), terminationError => reject(new AggregateError([error, terminationError], "Provider process failed and its process tree could not be proven stopped.")));
|
|
374
403
|
};
|
|
375
404
|
const abort = () => {
|
|
405
|
+
if (!closed)
|
|
406
|
+
cancelledBeforeClose = true;
|
|
376
407
|
cancellationRequested = true;
|
|
377
408
|
// Cancellation is not a launch failure when the supervised tree can be
|
|
378
409
|
// proven stopped. Let the close handler settle the command after exact
|
|
@@ -386,6 +417,27 @@ export class StreamingProviderProcessRunner {
|
|
|
386
417
|
signal?.addEventListener("abort", abort, { once: true });
|
|
387
418
|
}
|
|
388
419
|
child.on("error", fail);
|
|
420
|
+
const startGrant = startGated ? child.stdio[3] : null;
|
|
421
|
+
if (startGated && !startGrant) {
|
|
422
|
+
fail(new Error("Provider start-grant stream was not piped."));
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
startGrant?.on("error", error => {
|
|
426
|
+
// A broken grant pipe means the gate already exited (terminated before
|
|
427
|
+
// its grant, or it died on its own). Its close event carries the real
|
|
428
|
+
// exit status, so an EPIPE here must not replace that result.
|
|
429
|
+
if (isBrokenPipeError(error))
|
|
430
|
+
return;
|
|
431
|
+
fail(error);
|
|
432
|
+
});
|
|
433
|
+
const grantUnixProviderStart = () => {
|
|
434
|
+
if (!startGrant)
|
|
435
|
+
return;
|
|
436
|
+
// Never release a provider whose launch was cancelled or already failed.
|
|
437
|
+
if (closed || settled || cancellationRequested || signal?.aborted)
|
|
438
|
+
return;
|
|
439
|
+
startGrant.end(UNIX_PROVIDER_START_GRANT_LINE, "utf8");
|
|
440
|
+
};
|
|
389
441
|
child.once("spawn", () => {
|
|
390
442
|
readiness = (async () => {
|
|
391
443
|
const providerReady = supervisedLaunch?.strategy === "windows_job_object"
|
|
@@ -398,6 +450,9 @@ export class StreamingProviderProcessRunner {
|
|
|
398
450
|
if (supervisedLaunch?.strategy === "windows_job_object") {
|
|
399
451
|
grantWindowsProviderStart(supervisedLaunch);
|
|
400
452
|
}
|
|
453
|
+
else if (startGated) {
|
|
454
|
+
grantUnixProviderStart();
|
|
455
|
+
}
|
|
401
456
|
})();
|
|
402
457
|
void readiness.catch(error => {
|
|
403
458
|
if (!closed && !signal?.aborted)
|
|
@@ -413,15 +468,20 @@ export class StreamingProviderProcessRunner {
|
|
|
413
468
|
return;
|
|
414
469
|
}
|
|
415
470
|
child.stdin.on("error", (error) => {
|
|
471
|
+
// A prompt still buffered when Forge stops the process (cancellation,
|
|
472
|
+
// or a refused start grant) cannot be delivered; that broken pipe is
|
|
473
|
+
// not a failure. Any other stdin error still is.
|
|
474
|
+
if ((cancellationRequested || termination) && isBrokenPipeError(error))
|
|
475
|
+
return;
|
|
416
476
|
void terminate();
|
|
417
477
|
fail(error);
|
|
418
478
|
});
|
|
419
479
|
child.stdin.end(request.stdin, "utf8");
|
|
420
480
|
};
|
|
421
481
|
if (request.stdin !== undefined) {
|
|
422
|
-
if (supervisedLaunch?.strategy === "windows_job_object") {
|
|
423
|
-
// The outer supervisor must receive stdin before it
|
|
424
|
-
//
|
|
482
|
+
if (supervisedLaunch?.strategy === "windows_job_object" || startGated) {
|
|
483
|
+
// The outer supervisor / Unix start gate must receive stdin before it
|
|
484
|
+
// can launch the provider. Its start grant fences prompt processing.
|
|
425
485
|
writeProviderInput();
|
|
426
486
|
}
|
|
427
487
|
else {
|
|
@@ -430,19 +490,46 @@ export class StreamingProviderProcessRunner {
|
|
|
430
490
|
});
|
|
431
491
|
}
|
|
432
492
|
}
|
|
493
|
+
const finishAfterTerminalSuccess = () => {
|
|
494
|
+
if (closed || settled || cancellationRequested || terminalTerminationStarted)
|
|
495
|
+
return;
|
|
496
|
+
terminalTerminationStarted = true;
|
|
497
|
+
void terminate().catch(fail);
|
|
498
|
+
};
|
|
499
|
+
const armTerminalExit = () => {
|
|
500
|
+
if (terminalExitTimer)
|
|
501
|
+
clearTimeout(terminalExitTimer);
|
|
502
|
+
terminalExitTimer = setTimeout(finishAfterTerminalSuccess, this.terminalExitGraceMs);
|
|
503
|
+
terminalExitTimer.unref?.();
|
|
504
|
+
// Later turns may postpone the grace period, but never past this ceiling.
|
|
505
|
+
if (!terminalCeilingTimer) {
|
|
506
|
+
terminalCeilingTimer = setTimeout(finishAfterTerminalSuccess, this.terminalSuccessCeilingMs);
|
|
507
|
+
terminalCeilingTimer.unref?.();
|
|
508
|
+
}
|
|
509
|
+
};
|
|
433
510
|
const readers = [
|
|
434
511
|
readProcessLines(childStdout, (line) => {
|
|
435
512
|
if (request.captureOutput !== false)
|
|
436
513
|
stdout.appendLine(line);
|
|
437
514
|
const handled = handlers.onStdoutLine?.(line);
|
|
438
|
-
if (!
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
515
|
+
if (!terminalTerminationStarted) {
|
|
516
|
+
if (isProviderTerminalSuccess(line)) {
|
|
517
|
+
latestTurnFailed = false;
|
|
518
|
+
armTerminalExit();
|
|
519
|
+
}
|
|
520
|
+
else if (isProviderTerminalFailure(line)) {
|
|
521
|
+
// A later turn that fails reports its failure even after an earlier success.
|
|
522
|
+
latestTurnFailed = true;
|
|
523
|
+
}
|
|
524
|
+
else if (terminalExitTimer && isProviderTurnActivity(line)) {
|
|
525
|
+
// A terminal event ends a turn, not necessarily the provider. Claude Code
|
|
526
|
+
// stays resident while background tasks it started are pending and begins a
|
|
527
|
+
// new turn when one reports (and a resumed session can replay a queued
|
|
528
|
+
// notification turn first). A provider that is working again is not finished;
|
|
529
|
+
// the grace period restarts at its next terminal event.
|
|
530
|
+
clearTimeout(terminalExitTimer);
|
|
531
|
+
terminalExitTimer = null;
|
|
532
|
+
}
|
|
446
533
|
}
|
|
447
534
|
return handled;
|
|
448
535
|
}),
|
|
@@ -489,16 +576,53 @@ export class StreamingProviderProcessRunner {
|
|
|
489
576
|
// that event, terminate the supervised tree after a short grace
|
|
490
577
|
// period and preserve the successful handoff so the existing
|
|
491
578
|
// artifact, commit, and publication gates can run.
|
|
492
|
-
|
|
579
|
+
// A provider stopped after a successful turn keeps that success. Whenever the
|
|
580
|
+
// most recent turn failed, the run fails, however the process ended.
|
|
581
|
+
exitCode: latestTurnFailed
|
|
582
|
+
? code && code !== 0 ? code : 1
|
|
583
|
+
: terminalTerminationStarted && !cancellationRequested ? 0 : code ?? 1,
|
|
493
584
|
stdout: stdout.toString(),
|
|
494
585
|
stderr: stderr.toString(),
|
|
495
586
|
...(memory ?? {}),
|
|
587
|
+
...(cancelledBeforeClose ? { cancelled: true } : {}),
|
|
496
588
|
});
|
|
497
589
|
}).catch(fail);
|
|
498
590
|
});
|
|
499
591
|
});
|
|
500
592
|
}
|
|
501
593
|
}
|
|
594
|
+
/** A stream event that shows the provider is working on a turn: model output or a tool result. */
|
|
595
|
+
function isProviderTurnActivity(line) {
|
|
596
|
+
const trimmed = line.trim();
|
|
597
|
+
if (!trimmed.startsWith("{"))
|
|
598
|
+
return false;
|
|
599
|
+
try {
|
|
600
|
+
const event = JSON.parse(trimmed);
|
|
601
|
+
return event.type === "assistant"
|
|
602
|
+
|| event.type === "user"
|
|
603
|
+
|| (event.type === "system" && event.subtype === "init")
|
|
604
|
+
|| event.type === "turn.started"
|
|
605
|
+
|| event.type === "item.started";
|
|
606
|
+
}
|
|
607
|
+
catch {
|
|
608
|
+
return false;
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
function isProviderTerminalFailure(line) {
|
|
612
|
+
const trimmed = line.trim();
|
|
613
|
+
if (!trimmed.startsWith("{"))
|
|
614
|
+
return false;
|
|
615
|
+
try {
|
|
616
|
+
const event = JSON.parse(trimmed);
|
|
617
|
+
// The same events the output parsers report as provider errors.
|
|
618
|
+
return event.type === "turn.failed"
|
|
619
|
+
|| event.type === "error"
|
|
620
|
+
|| (event.type === "result" && (event.subtype !== "success" || event.is_error === true));
|
|
621
|
+
}
|
|
622
|
+
catch {
|
|
623
|
+
return false;
|
|
624
|
+
}
|
|
625
|
+
}
|
|
502
626
|
function isProviderTerminalSuccess(line) {
|
|
503
627
|
const trimmed = line.trim();
|
|
504
628
|
if (!trimmed.startsWith("{"))
|
|
@@ -682,6 +806,64 @@ async function resolveProviderProcessLaunch(command, args) {
|
|
|
682
806
|
?? resolvePackageManagerDirectLaunch(resolved, args)
|
|
683
807
|
?? buildWindowsLaunchCommand(resolved, args);
|
|
684
808
|
}
|
|
809
|
+
const UNIX_PROVIDER_START_GATE_SHELL = "/bin/sh";
|
|
810
|
+
const UNIX_PROVIDER_START_GATE_NAME = "forge-provider-start-gate";
|
|
811
|
+
export const UNIX_PROVIDER_START_GRANT_LINE = "forge-provider-start-granted\n";
|
|
812
|
+
/**
|
|
813
|
+
* Blocks on fd 3 until the bridge writes the exact grant line, then replaces
|
|
814
|
+
* itself with the provider (`exec`), so the supervised root PID, process group
|
|
815
|
+
* and birth identity stay the provider's. The provider command and arguments
|
|
816
|
+
* are passed positionally and expanded only as "$@"; nothing is interpolated
|
|
817
|
+
* into the script. EOF, a read error, or any other content on fd 3 exits
|
|
818
|
+
* without running the provider. fd 3 is closed before exec so the provider and
|
|
819
|
+
* its descendants never inherit the grant channel. stdin is not touched, so
|
|
820
|
+
* the prompt stays buffered in its pipe for the provider.
|
|
821
|
+
*/
|
|
822
|
+
const UNIX_PROVIDER_START_GATE_SCRIPT = [
|
|
823
|
+
"IFS= read -r forge_start_grant <&3 || { echo \"$0: provider start was not granted\" >&2; exit 125; }",
|
|
824
|
+
`[ "$forge_start_grant" = "${UNIX_PROVIDER_START_GRANT_LINE.trim()}" ] || { echo "$0: provider start grant was invalid" >&2; exit 125; }`,
|
|
825
|
+
"exec \"$@\" 3<&-",
|
|
826
|
+
].join("\n");
|
|
827
|
+
export function buildUnixProviderStartGateLaunch(command, args) {
|
|
828
|
+
return {
|
|
829
|
+
command: UNIX_PROVIDER_START_GATE_SHELL,
|
|
830
|
+
args: ["-c", UNIX_PROVIDER_START_GATE_SCRIPT, UNIX_PROVIDER_START_GATE_NAME, command, ...args],
|
|
831
|
+
};
|
|
832
|
+
}
|
|
833
|
+
/**
|
|
834
|
+
* Mirrors the executable lookup the gate's `exec` will perform. A command that
|
|
835
|
+
* cannot be found is spawned directly instead so it keeps failing as a spawn
|
|
836
|
+
* ENOENT before any start is recorded; nothing can run in that case. The check
|
|
837
|
+
* is advisory: if the executable disappears between this lookup and the gated
|
|
838
|
+
* `exec`, the gate exits 127 with the shell's "not found" message after the
|
|
839
|
+
* start was recorded, which surfaces as an ordinary provider failure.
|
|
840
|
+
*/
|
|
841
|
+
function isUnixExecutableAvailable(command, pathValue, cwd) {
|
|
842
|
+
if (!command || command.startsWith("-"))
|
|
843
|
+
return false;
|
|
844
|
+
const candidates = command.includes("/")
|
|
845
|
+
? [path.resolve(cwd, command)]
|
|
846
|
+
: pathValue === undefined
|
|
847
|
+
? null
|
|
848
|
+
: pathValue.split(path.delimiter).map(directory => path.resolve(cwd, directory || ".", command));
|
|
849
|
+
if (candidates === null)
|
|
850
|
+
return true;
|
|
851
|
+
return candidates.some(candidate => {
|
|
852
|
+
try {
|
|
853
|
+
if (!fs.statSync(candidate).isFile())
|
|
854
|
+
return false;
|
|
855
|
+
fs.accessSync(candidate, fs.constants.X_OK);
|
|
856
|
+
return true;
|
|
857
|
+
}
|
|
858
|
+
catch {
|
|
859
|
+
return false;
|
|
860
|
+
}
|
|
861
|
+
});
|
|
862
|
+
}
|
|
863
|
+
function isBrokenPipeError(error) {
|
|
864
|
+
const code = error?.code;
|
|
865
|
+
return code === "EPIPE" || code === "ERR_STREAM_DESTROYED" || code === "ECONNRESET";
|
|
866
|
+
}
|
|
685
867
|
function grantWindowsProviderStart(launch) {
|
|
686
868
|
if (!launch.startGrantPath) {
|
|
687
869
|
throw new Error("host_process_supervisor_invalid: Windows provider start-grant path was not assigned.");
|
|
@@ -3,6 +3,12 @@ import type { ProviderCliRunContext } from "./provider-cli.types.js";
|
|
|
3
3
|
import type { ProviderOutputState } from "./provider-output-state.js";
|
|
4
4
|
import { type ProviderUsage } from "./provider-usage.js";
|
|
5
5
|
export declare function providerProcessEnv(dispatch: RunOnceDispatchPacket, runtimeEnvironment?: Readonly<Record<string, string>>): Readonly<Record<string, string>>;
|
|
6
|
+
/**
|
|
7
|
+
* Pre-publication validation runs the attempt's own checks, whose E2E fixtures log in to the
|
|
8
|
+
* brokered attempt database. Unlike the provider's shell, it receives that capability; the
|
|
9
|
+
* validator redacts it from every command's output.
|
|
10
|
+
*/
|
|
11
|
+
export declare function prePublicationValidationEnv(dispatch: RunOnceDispatchPacket, runtimeEnvironment?: Readonly<Record<string, string>>): Readonly<Record<string, string>>;
|
|
6
12
|
export declare function providerRuntimeEnvironment(runtimeEnvironment?: Readonly<Record<string, string>>): Readonly<Record<string, string>>;
|
|
7
13
|
export declare function providerCredentialEnv(dispatch: RunOnceDispatchPacket): Readonly<Record<string, string>>;
|
|
8
14
|
/**
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { attemptDatabaseCapabilityEnvironment } from "../../runtime/attempt-database-broker.js";
|
|
1
2
|
import { completionRedactionEnv } from "../phase-completion.js";
|
|
2
3
|
import { addUsage, buildProviderUsageEvent, emptyUsage, hasUsage } from "./provider-usage.js";
|
|
3
4
|
export function providerProcessEnv(dispatch, runtimeEnvironment) {
|
|
@@ -12,6 +13,16 @@ export function providerProcessEnv(dispatch, runtimeEnvironment) {
|
|
|
12
13
|
// Bridge environment, including credentials outside the provider contract.
|
|
13
14
|
return env;
|
|
14
15
|
}
|
|
16
|
+
/**
|
|
17
|
+
* Pre-publication validation runs the attempt's own checks, whose E2E fixtures log in to the
|
|
18
|
+
* brokered attempt database. Unlike the provider's shell, it receives that capability; the
|
|
19
|
+
* validator redacts it from every command's output.
|
|
20
|
+
*/
|
|
21
|
+
export function prePublicationValidationEnv(dispatch, runtimeEnvironment) {
|
|
22
|
+
const env = providerProcessEnv(dispatch, runtimeEnvironment);
|
|
23
|
+
const capability = runtimeEnvironment?.[attemptDatabaseCapabilityEnvironment]?.trim();
|
|
24
|
+
return capability ? { ...env, [attemptDatabaseCapabilityEnvironment]: capability } : env;
|
|
25
|
+
}
|
|
15
26
|
export function providerRuntimeEnvironment(runtimeEnvironment) {
|
|
16
27
|
if (!runtimeEnvironment)
|
|
17
28
|
return {};
|
|
@@ -10,7 +10,7 @@ import { cleanupCompletionTools, commitWorktreeChanges, completionPhaseFromArtif
|
|
|
10
10
|
import { DeterministicProviderCliService } from "./provider-cli.deterministic.js";
|
|
11
11
|
import { buildArchitectPrompt, buildConflictResolvePrompt, buildDebugCyclePrompt, buildDevelopCyclePrompt, buildDraftPrompt, buildDraftSpec, buildImplementationPrompt, buildProviderCliPrompt, buildProviderCliCommand, durableDraftInput, buildPullRequestCheckRepairPrompt, buildPullRequestCommentsPrompt, buildQaPrompt, formatProviderCliCommandForCheckpoint, isDecomposeDraftDispatch, isPullRequestCheckRepairDispatch, isPullRequestCommentsDispatch } from "./provider-cli.prompts.js";
|
|
12
12
|
import { isTransientCodexProviderNotFoundFailure, recoveringProviderProcessRunner, StreamingProviderProcessRunner } from "./provider-cli.process.js";
|
|
13
|
-
import { emitProviderUsageEvent, providerProcessEnv } from "./provider-cli.runtime.js";
|
|
13
|
+
import { emitProviderUsageEvent, prePublicationValidationEnv, providerProcessEnv } from "./provider-cli.runtime.js";
|
|
14
14
|
import { clip, createProviderOutputState, parseJsonLine } from "./provider-output-state.js";
|
|
15
15
|
import { writeCiRepairReadinessManifest } from "./ci-repair-readiness.js";
|
|
16
16
|
import { assertRepairHeadEpoch } from "./provider-cli.repair-epoch.js";
|
|
@@ -1397,10 +1397,14 @@ export class ProcessBackedProviderCliService {
|
|
|
1397
1397
|
session: { ...dispatch.session, resumeProviderThreadId: providerThreadId },
|
|
1398
1398
|
};
|
|
1399
1399
|
const recoveryPrompt = [
|
|
1400
|
-
"Forge did not receive the required forge.complete_comment_repair call from your previous turn.",
|
|
1400
|
+
"Forge did not receive the required forge.complete_comment_repair call from your previous turn, so the provider process exited.",
|
|
1401
|
+
"Background watchers, monitors and notifications from that turn did not survive and will never report back,",
|
|
1402
|
+
"and Forge stopped any managed command that process was still running; its receipt reports that.",
|
|
1401
1403
|
"Resume the existing work exactly where it is. Do not reimplement or discard the prepared changes.",
|
|
1402
|
-
"Review the current diff and the durable review snapshot
|
|
1403
|
-
"
|
|
1404
|
+
"Review the current diff and the durable review snapshot and preserve the validation evidence already gathered.",
|
|
1405
|
+
"Check each managed command with forge.get_managed_command, restart any that were interrupted,",
|
|
1406
|
+
"and block on long commands with forge.wait_managed_command, calling it again while command_continues is true.",
|
|
1407
|
+
"Do not end your turn until you have called forge.complete_comment_repair with an evidence-backed disposition for every actionable finding.",
|
|
1404
1408
|
"Do not commit or push; Forge owns publication after the completion gate succeeds.",
|
|
1405
1409
|
].join(" ");
|
|
1406
1410
|
const providerPrompt = buildProviderCliPrompt(recoveryDispatch, recoveryPrompt, repairEnvironment);
|
|
@@ -1489,9 +1493,10 @@ export class ProcessBackedProviderCliService {
|
|
|
1489
1493
|
const { dispatch, worktree } = context;
|
|
1490
1494
|
const processRunner = recoveringProviderProcessRunner(context.processRunner ?? this.processRunner);
|
|
1491
1495
|
const environment = providerProcessEnv(dispatch, repairEnvironment);
|
|
1496
|
+
const validationEnvironment = prePublicationValidationEnv(dispatch, repairEnvironment);
|
|
1492
1497
|
for (let repairTurn = 0;; repairTurn += 1) {
|
|
1493
1498
|
try {
|
|
1494
|
-
await this.prePublicationValidator.validate(worktree.worktreePath, validationProfile, publicationCapabilities(context, repairEnvironment), context.emit, context.signal, prePublicationExecution(context,
|
|
1499
|
+
await this.prePublicationValidator.validate(worktree.worktreePath, validationProfile, publicationCapabilities(context, repairEnvironment), context.emit, context.signal, prePublicationExecution(context, validationEnvironment, this.processRunner, preparedHeadSha));
|
|
1495
1500
|
if (repairTurn > 0) {
|
|
1496
1501
|
await context.emit({
|
|
1497
1502
|
role: "runner",
|
|
@@ -4,7 +4,8 @@ export type InputTokenSemantics = "includes_cached_input" | "excludes_cache_toke
|
|
|
4
4
|
export declare const PROVIDER_USAGE_SCHEMA_VERSION = 1;
|
|
5
5
|
/**
|
|
6
6
|
* Normalized, provider-agnostic token usage accumulated for a dispatch. Cost is never computed
|
|
7
|
-
* here; the API recomputes cost from these tokens x model rates (
|
|
7
|
+
* here; the API recomputes cost from these tokens x model rates (legacy
|
|
8
|
+
* ADR-0006, .forge-designer/decisions/legacy/0006-cost-capture.md).
|
|
8
9
|
*/
|
|
9
10
|
export interface ProviderUsage {
|
|
10
11
|
/** Normalized total input. Cached input is a subset, never an additive peer. */
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { captureHostProcessIdentity } from "./host-process-supervisor.js";
|
|
2
|
+
import { monotonicNowMs } from "../time/monotonic.js";
|
|
2
3
|
/** Exact, birth-marker-fenced recovery for a process tree left by an old bridge. */
|
|
3
4
|
export class ExactHostProcessRecovery {
|
|
4
5
|
platform;
|
|
@@ -71,8 +72,8 @@ function signalExactProcessGroup(pid, signal) {
|
|
|
71
72
|
}
|
|
72
73
|
}
|
|
73
74
|
async function waitForExit(pid, timeoutMs) {
|
|
74
|
-
const deadline =
|
|
75
|
-
while (
|
|
75
|
+
const deadline = monotonicNowMs() + timeoutMs;
|
|
76
|
+
while (monotonicNowMs() < deadline && processExists(pid)) {
|
|
76
77
|
await new Promise(resolve => setTimeout(resolve, 25));
|
|
77
78
|
}
|
|
78
79
|
}
|
|
@@ -3,6 +3,7 @@ import { execFileSync } from "node:child_process";
|
|
|
3
3
|
import fs from "node:fs";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { monotonicNowMs } from "../time/monotonic.js";
|
|
6
7
|
const windowsJobSupervisorPath = fileURLToPath(new URL("../../../runtime/windows-job-supervisor.ps1", import.meta.url));
|
|
7
8
|
export function resolveHostProcessSupervisedLaunch(request, resolvedCommand, resolvedArgs, platform = process.platform) {
|
|
8
9
|
const env = request.env;
|
|
@@ -277,8 +278,8 @@ function unixProcessGroupExists(processGroupId) {
|
|
|
277
278
|
}
|
|
278
279
|
}
|
|
279
280
|
async function waitForUnixProcessGroupExit(processGroupId, timeoutMs) {
|
|
280
|
-
const deadline =
|
|
281
|
-
while (
|
|
281
|
+
const deadline = monotonicNowMs() + timeoutMs;
|
|
282
|
+
while (monotonicNowMs() < deadline && unixProcessGroupExists(processGroupId)) {
|
|
282
283
|
await new Promise(resolve => setTimeout(resolve, 25));
|
|
283
284
|
}
|
|
284
285
|
}
|
|
@@ -307,8 +308,8 @@ function processExists(pid) {
|
|
|
307
308
|
}
|
|
308
309
|
}
|
|
309
310
|
async function waitForExactProcessExit(pid, identity, timeoutMs, platform) {
|
|
310
|
-
const deadline =
|
|
311
|
-
while (
|
|
311
|
+
const deadline = monotonicNowMs() + timeoutMs;
|
|
312
|
+
while (monotonicNowMs() < deadline && exactProcessExists(pid, identity, platform)) {
|
|
312
313
|
await new Promise(resolve => setTimeout(resolve, 25));
|
|
313
314
|
}
|
|
314
315
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function monotonicNowMs(): number;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Elapsed time and local deadlines use the monotonic clock. The wall clock can step:
|
|
2
|
+
// a WSL VM's clock is corrected in multi-second jumps, which would end a local wait
|
|
3
|
+
// early or count time that never passed. Timestamps that are persisted or compared
|
|
4
|
+
// across processes (lease expiry, receipts, file mtimes) stay on the wall clock.
|
|
5
|
+
// Read through the global so test fake timers that replace `performance` apply.
|
|
6
|
+
export function monotonicNowMs() {
|
|
7
|
+
return performance.now();
|
|
8
|
+
}
|
package/dist/version.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const forgeBridgeVersion = "0.1.4-dev.
|
|
1
|
+
export declare const forgeBridgeVersion = "0.1.4-dev.318bc3bd5b6a";
|
package/dist/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const forgeBridgeVersion = "0.1.4-dev.
|
|
1
|
+
export const forgeBridgeVersion = "0.1.4-dev.318bc3bd5b6a";
|
|
@@ -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.
|
|
3
|
+
"version": "0.1.4-dev.318bc3bd5b6a",
|
|
4
4
|
"description": "Forge runner bridge CLI for connecting local developer machines to Forge dispatch.",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"type": "module",
|