@loucompanion/forge-bridge 0.1.4-dev.1ff37038366e → 0.1.4-dev.2a748b7b0dfc
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 +55 -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/runtime/playwright-browser-cache.d.ts +39 -0
- package/dist/runtime/playwright-browser-cache.js +227 -0
- package/dist/runtime/playwright-host-runtime-adapter.d.ts +11 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +48 -54
- 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
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
2
|
import fs from "node:fs/promises";
|
|
3
|
+
import os from "node:os";
|
|
3
4
|
import path from "node:path";
|
|
4
5
|
import { resetGeneratedOutputs } from "../runtime/generated-output-reset.js";
|
|
5
6
|
import { DockerEngineProbe } from "../runtime/docker-engine-probe.js";
|
|
@@ -11,6 +12,8 @@ import { ManagedBuildCoordinator } from "./managed-build-coordinator.js";
|
|
|
11
12
|
import { managedBuildConfiguration, publishManagedBuildReceipt, verifyManagedBuildReceipt, } from "./managed-build-receipt.js";
|
|
12
13
|
import { managedLongTierTimeoutMs, managedMaximumCommandTimeoutMs, managedVerificationTierTimeoutMs, } from "./managed-verification-timeouts.js";
|
|
13
14
|
import { resolveWindowsCommandFromPath, StreamingProviderProcessRunner } from "./provider-cli/provider-cli.process.js";
|
|
15
|
+
import { monotonicNowMs } from "../shared/time/monotonic.js";
|
|
16
|
+
import { captureHostProcessIdentity } from "../shared/process/host-process-supervisor.js";
|
|
14
17
|
const managedCommandNames = new Set(["forge.run_managed_command", "run_managed_command"]);
|
|
15
18
|
const startManagedCommandNames = new Set(["forge.start_managed_command", "start_managed_command"]);
|
|
16
19
|
const getManagedCommandNames = new Set(["forge.get_managed_command", "get_managed_command"]);
|
|
@@ -40,6 +43,14 @@ const terminalManagedCommandStatuses = new Set([
|
|
|
40
43
|
]);
|
|
41
44
|
const managedVerificationBuildCoverage = "forge_dotnet_test_graph_v1";
|
|
42
45
|
const managedCommandTasks = new Map();
|
|
46
|
+
// Every command this MCP server is supervising, synchronous or not. The server is the only
|
|
47
|
+
// writer of their receipts, so it stops them before it exits.
|
|
48
|
+
const activeManagedCommands = new Map();
|
|
49
|
+
const ownerExitStoppedCommands = new Set();
|
|
50
|
+
let ownerProcessIdentity;
|
|
51
|
+
let managedCommandOwnerShuttingDown = false;
|
|
52
|
+
let ownerExitSweep = null;
|
|
53
|
+
const managedCommandOwnerExitMessage = "managed_command_owner_exited: Forge stopped this managed command because the Forge MCP server that supervised it is exiting; its provider process ended before the command finished. Its result is unknown; start it again if it is still needed.";
|
|
43
54
|
export const managedAttemptToolNames = [
|
|
44
55
|
"forge.run_managed_command",
|
|
45
56
|
"run_managed_command",
|
|
@@ -54,6 +65,76 @@ export const managedAttemptToolNames = [
|
|
|
54
65
|
"forge.reset_generated_outputs",
|
|
55
66
|
"reset_generated_outputs",
|
|
56
67
|
];
|
|
68
|
+
/**
|
|
69
|
+
* Stops every managed command this MCP server started, proves each process tree stopped,
|
|
70
|
+
* and writes their terminal receipts. Called when the provider closes the MCP connection
|
|
71
|
+
* or the server is signalled: once this server exits nothing could supervise them.
|
|
72
|
+
*/
|
|
73
|
+
export async function stopManagedCommandsForOwnerExit() {
|
|
74
|
+
// One sweep at a time: a signal that arrives while a sweep runs waits for that sweep.
|
|
75
|
+
ownerExitSweep ??= sweepManagedCommandsForOwnerExit().finally(() => { ownerExitSweep = null; });
|
|
76
|
+
await ownerExitSweep;
|
|
77
|
+
}
|
|
78
|
+
async function sweepManagedCommandsForOwnerExit() {
|
|
79
|
+
// From here on this server refuses new commands, so a request still being handled
|
|
80
|
+
// cannot launch one behind the sweep. Repeat until none is left: a launch that passed
|
|
81
|
+
// its last check just before the flag was set registers synchronously and is caught.
|
|
82
|
+
managedCommandOwnerShuttingDown = true;
|
|
83
|
+
while (activeManagedCommands.size > 0) {
|
|
84
|
+
const active = [...activeManagedCommands.entries()];
|
|
85
|
+
for (const [commandId, command] of active) {
|
|
86
|
+
ownerExitStoppedCommands.add(commandId);
|
|
87
|
+
command.controller.abort(new Error(managedCommandOwnerExitMessage));
|
|
88
|
+
}
|
|
89
|
+
await Promise.allSettled(active.map(([, command]) => command.task));
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/** Test support: lets one test process act as a fresh MCP server after a simulated exit. */
|
|
93
|
+
export function resetManagedCommandOwnerShutdownForTesting() {
|
|
94
|
+
managedCommandOwnerShuttingDown = false;
|
|
95
|
+
}
|
|
96
|
+
function assertManagedCommandsAccepted() {
|
|
97
|
+
if (managedCommandOwnerShuttingDown) {
|
|
98
|
+
throw new Error("managed_command_unavailable: the Forge MCP server is shutting down and accepts no new managed commands.");
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
const ownerShutdownSignals = ["SIGTERM", "SIGHUP", "SIGINT"];
|
|
102
|
+
/**
|
|
103
|
+
* Makes a termination signal stop this server's managed commands before it exits, so none
|
|
104
|
+
* outlives its only supervisor. Returns a function that removes the handlers.
|
|
105
|
+
*/
|
|
106
|
+
export function installOwnerShutdownHandlers(target = process, exit = code => process.exit(code)) {
|
|
107
|
+
const handlers = ownerShutdownSignals.map(signal => {
|
|
108
|
+
const handler = () => {
|
|
109
|
+
void stopManagedCommandsForOwnerExit().finally(() => exit(128 + os.constants.signals[signal]));
|
|
110
|
+
};
|
|
111
|
+
target.once(signal, handler);
|
|
112
|
+
return { signal, handler };
|
|
113
|
+
});
|
|
114
|
+
return () => {
|
|
115
|
+
for (const { signal, handler } of handlers)
|
|
116
|
+
target.removeListener(signal, handler);
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Runs an MCP server body, then stops every managed command it started before returning.
|
|
121
|
+
* The signal handlers stay installed until that stop completes: a signal during the body
|
|
122
|
+
* or the stop exits only after the same stop finishes, never by Node's default exit.
|
|
123
|
+
*/
|
|
124
|
+
export async function runWithOwnerShutdown(body, target = process, exit = code => process.exit(code)) {
|
|
125
|
+
const removeShutdownHandlers = installOwnerShutdownHandlers(target, exit);
|
|
126
|
+
try {
|
|
127
|
+
return await body();
|
|
128
|
+
}
|
|
129
|
+
finally {
|
|
130
|
+
try {
|
|
131
|
+
await stopManagedCommandsForOwnerExit();
|
|
132
|
+
}
|
|
133
|
+
finally {
|
|
134
|
+
removeShutdownHandlers();
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
57
138
|
export function isManagedAttemptTool(name) {
|
|
58
139
|
return managedCommandNames.has(name)
|
|
59
140
|
|| startManagedCommandNames.has(name)
|
|
@@ -174,6 +255,7 @@ export async function callManagedAttemptTool(name, input, worktreePath) {
|
|
|
174
255
|
return await launchManagedCommand(asRecord(input), worktreePath, startManagedCommandNames.has(name));
|
|
175
256
|
}
|
|
176
257
|
async function launchManagedCommand(record, worktreePath, forceAsync, verificationProfile, buildProducingOverride, buildReceiptReuse) {
|
|
258
|
+
assertManagedCommandsAccepted();
|
|
177
259
|
const command = requiredInputString(record, "command");
|
|
178
260
|
const args = requiredStringArray(record, "args");
|
|
179
261
|
const timeoutMs = optionalTimeout(record.timeout_ms);
|
|
@@ -198,6 +280,7 @@ async function launchManagedCommand(record, worktreePath, forceAsync, verificati
|
|
|
198
280
|
worktreePath,
|
|
199
281
|
buildProducing: buildProducingOverride ?? isBuildProducingManagedCommand(command, args),
|
|
200
282
|
buildReceiptReuse,
|
|
283
|
+
controller: new AbortController(),
|
|
201
284
|
};
|
|
202
285
|
if (forceAsync || timeoutMs > maximumSynchronousWaitMs) {
|
|
203
286
|
const started = managedCommandResult({
|
|
@@ -207,9 +290,25 @@ async function launchManagedCommand(record, worktreePath, forceAsync, verificati
|
|
|
207
290
|
exitCode: null,
|
|
208
291
|
stdout: "",
|
|
209
292
|
stderr: "",
|
|
293
|
+
launchRequested: false,
|
|
210
294
|
});
|
|
211
295
|
await persistManagedCommandReceipt(receiptPath, started.structuredContent);
|
|
212
|
-
|
|
296
|
+
if (managedCommandOwnerShuttingDown) {
|
|
297
|
+
// Shutdown began while the receipt was written; the command never starts.
|
|
298
|
+
const refused = managedCommandResult({
|
|
299
|
+
...invocation,
|
|
300
|
+
timedOut: false,
|
|
301
|
+
status: "runner_error",
|
|
302
|
+
exitCode: null,
|
|
303
|
+
stdout: "",
|
|
304
|
+
stderr: appendBounded("", managedCommandOwnerExitMessage),
|
|
305
|
+
launchRequested: false,
|
|
306
|
+
terminationReason: "owner_exited",
|
|
307
|
+
});
|
|
308
|
+
await persistManagedCommandReceipt(receiptPath, refused.structuredContent);
|
|
309
|
+
assertManagedCommandsAccepted();
|
|
310
|
+
}
|
|
311
|
+
const task = trackManagedCommand(invocation);
|
|
213
312
|
managedCommandTasks.set(commandId, task);
|
|
214
313
|
void task.finally(() => managedCommandTasks.delete(commandId)).catch(() => undefined);
|
|
215
314
|
return {
|
|
@@ -220,7 +319,16 @@ async function launchManagedCommand(record, worktreePath, forceAsync, verificati
|
|
|
220
319
|
}],
|
|
221
320
|
};
|
|
222
321
|
}
|
|
223
|
-
return await
|
|
322
|
+
return await trackManagedCommand(invocation);
|
|
323
|
+
}
|
|
324
|
+
function trackManagedCommand(invocation) {
|
|
325
|
+
const task = executeManagedCommand(invocation);
|
|
326
|
+
activeManagedCommands.set(invocation.commandId, { controller: invocation.controller, task });
|
|
327
|
+
void task.finally(() => {
|
|
328
|
+
activeManagedCommands.delete(invocation.commandId);
|
|
329
|
+
ownerExitStoppedCommands.delete(invocation.commandId);
|
|
330
|
+
}).catch(() => undefined);
|
|
331
|
+
return task;
|
|
224
332
|
}
|
|
225
333
|
async function startManagedVerification(input, worktreePath) {
|
|
226
334
|
const record = asRecord(input);
|
|
@@ -383,19 +491,45 @@ function optionValue(args, name) {
|
|
|
383
491
|
async function executeManagedCommand(invocation) {
|
|
384
492
|
if (!invocation.buildProducing)
|
|
385
493
|
return await executeManagedCommandProcess(invocation);
|
|
386
|
-
|
|
387
|
-
|
|
494
|
+
let processStarted = false;
|
|
495
|
+
try {
|
|
496
|
+
return await new ManagedBuildCoordinator().withBuildSlot(invocation.worktreePath, async (buildQueueWaitMs) => {
|
|
497
|
+
processStarted = true;
|
|
498
|
+
return await executeManagedCommandProcess({ ...invocation, buildQueueWaitMs });
|
|
499
|
+
}, async () => {
|
|
500
|
+
const waiting = managedCommandResult({
|
|
501
|
+
...invocation,
|
|
502
|
+
timedOut: false,
|
|
503
|
+
status: "waiting_for_build_slot",
|
|
504
|
+
exitCode: null,
|
|
505
|
+
stdout: "",
|
|
506
|
+
stderr: "",
|
|
507
|
+
launchRequested: false,
|
|
508
|
+
});
|
|
509
|
+
await persistManagedCommandReceipt(invocation.receiptPath, waiting.structuredContent);
|
|
510
|
+
}, invocation.controller.signal);
|
|
511
|
+
}
|
|
512
|
+
catch (error) {
|
|
513
|
+
if (processStarted)
|
|
514
|
+
throw error;
|
|
515
|
+
// The command never started (its build-slot wait failed or was stopped). Its receipt
|
|
516
|
+
// must still become terminal, or a waiting agent sees it queued forever.
|
|
517
|
+
const ownerExited = ownerExitStoppedCommands.has(invocation.commandId);
|
|
518
|
+
const receipt = managedCommandResult({
|
|
388
519
|
...invocation,
|
|
389
520
|
timedOut: false,
|
|
390
|
-
status: "
|
|
521
|
+
status: "runner_error",
|
|
391
522
|
exitCode: null,
|
|
392
523
|
stdout: "",
|
|
393
|
-
stderr: "",
|
|
524
|
+
stderr: appendBounded("", ownerExited ? managedCommandOwnerExitMessage : redactText(error instanceof Error ? error.message : String(error), [])),
|
|
525
|
+
terminationReason: ownerExited ? "owner_exited" : undefined,
|
|
526
|
+
launchRequested: false,
|
|
394
527
|
});
|
|
395
|
-
await persistManagedCommandReceipt(invocation.receiptPath,
|
|
396
|
-
|
|
528
|
+
await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
|
|
529
|
+
return managedCommandPublicResult(receipt);
|
|
530
|
+
}
|
|
397
531
|
}
|
|
398
|
-
async function
|
|
532
|
+
async function managedCommandProcessEnvironment(invocation) {
|
|
399
533
|
assertHostDatabaseCapabilityBoundary();
|
|
400
534
|
const databaseEnvironment = invocation.verificationProfile
|
|
401
535
|
? await managedVerificationDatabaseEnvironment()
|
|
@@ -429,9 +563,32 @@ async function executeManagedCommandProcess(invocation) {
|
|
|
429
563
|
}
|
|
430
564
|
: {}),
|
|
431
565
|
});
|
|
566
|
+
return { environment, exactSecrets };
|
|
567
|
+
}
|
|
568
|
+
async function executeManagedCommandProcess(invocation) {
|
|
569
|
+
let prepared;
|
|
570
|
+
try {
|
|
571
|
+
prepared = await managedCommandProcessEnvironment(invocation);
|
|
572
|
+
}
|
|
573
|
+
catch (error) {
|
|
574
|
+
// The call still fails (the database capability boundary or the verification
|
|
575
|
+
// database probe refused it), but its receipt must not stay "starting" forever.
|
|
576
|
+
const receipt = managedCommandResult({
|
|
577
|
+
...invocation,
|
|
578
|
+
timedOut: false,
|
|
579
|
+
status: "runner_error",
|
|
580
|
+
exitCode: null,
|
|
581
|
+
stdout: "",
|
|
582
|
+
stderr: appendBounded("", redactText(error instanceof Error ? error.message : String(error), [])),
|
|
583
|
+
launchRequested: false,
|
|
584
|
+
});
|
|
585
|
+
await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent).catch(() => undefined);
|
|
586
|
+
throw error;
|
|
587
|
+
}
|
|
588
|
+
const { exactSecrets } = prepared;
|
|
432
589
|
let stdout = "";
|
|
433
590
|
let stderr = "";
|
|
434
|
-
const controller =
|
|
591
|
+
const controller = invocation.controller;
|
|
435
592
|
let timedOut = false;
|
|
436
593
|
let timer = null;
|
|
437
594
|
let outputRevision = 0;
|
|
@@ -464,11 +621,23 @@ async function executeManagedCommandProcess(invocation) {
|
|
|
464
621
|
controller.abort(new Error(`managed_command_launch_timeout: process supervisor was not ready within ${managedCommandLaunchTimeoutMs}ms.`));
|
|
465
622
|
}, managedCommandLaunchTimeoutMs);
|
|
466
623
|
try {
|
|
624
|
+
if (controller.signal.aborted)
|
|
625
|
+
throw controller.signal.reason;
|
|
626
|
+
// Recorded before the spawn: the process record is written only once the child has
|
|
627
|
+
// spawned, so teardown must know a launch may exist without one.
|
|
628
|
+
await persistManagedCommandReceipt(invocation.receiptPath, managedCommandResult({
|
|
629
|
+
...invocation,
|
|
630
|
+
timedOut: false,
|
|
631
|
+
status: "starting",
|
|
632
|
+
exitCode: null,
|
|
633
|
+
stdout,
|
|
634
|
+
stderr,
|
|
635
|
+
}).structuredContent);
|
|
467
636
|
const result = await new StreamingProviderProcessRunner().run({
|
|
468
637
|
command: invocation.command,
|
|
469
638
|
args: invocation.args,
|
|
470
639
|
cwd: invocation.cwd,
|
|
471
|
-
env: environment,
|
|
640
|
+
env: prepared.environment,
|
|
472
641
|
captureOutput: false,
|
|
473
642
|
}, {
|
|
474
643
|
onStarted: async () => {
|
|
@@ -516,7 +685,16 @@ async function executeManagedCommandProcess(invocation) {
|
|
|
516
685
|
},
|
|
517
686
|
}, controller.signal);
|
|
518
687
|
await settleProgress();
|
|
519
|
-
|
|
688
|
+
// Only a stop that interrupted the process relabels it. A command that exited on its own
|
|
689
|
+
// just before its owner asked for the stop keeps its real result.
|
|
690
|
+
const ownerExited = !timedOut && result.cancelled === true && ownerExitStoppedCommands.has(invocation.commandId);
|
|
691
|
+
if (ownerExited) {
|
|
692
|
+
stderr = appendBounded(stderr, managedCommandOwnerExitMessage);
|
|
693
|
+
outputRevision += 1;
|
|
694
|
+
lastOutputAt = Date.now();
|
|
695
|
+
lastOutputStream = "stderr";
|
|
696
|
+
}
|
|
697
|
+
const status = timedOut ? "timed_out" : ownerExited ? "runner_error" : result.exitCode === 0 ? "pass" : "fail";
|
|
520
698
|
const receiptCoverage = managedBuildReceiptCoverage(invocation);
|
|
521
699
|
const buildReceipt = status === "pass" && receiptCoverage
|
|
522
700
|
? await publishManagedBuildReceipt({
|
|
@@ -539,6 +717,9 @@ async function executeManagedCommandProcess(invocation) {
|
|
|
539
717
|
lastOutputStream,
|
|
540
718
|
buildReceipt,
|
|
541
719
|
buildReceiptReused: invocation.buildReceiptReuse !== undefined,
|
|
720
|
+
terminationReason: ownerExited ? "owner_exited" : undefined,
|
|
721
|
+
// The runner resolves only after the stopped tree is proven gone.
|
|
722
|
+
processTreeTerminated: ownerExited ? true : undefined,
|
|
542
723
|
});
|
|
543
724
|
await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
|
|
544
725
|
return managedCommandPublicResult(receipt);
|
|
@@ -546,7 +727,10 @@ async function executeManagedCommandProcess(invocation) {
|
|
|
546
727
|
catch (error) {
|
|
547
728
|
// The failure may be a progress write itself; it is reported below.
|
|
548
729
|
await settleProgress().catch(() => undefined);
|
|
549
|
-
const
|
|
730
|
+
const ownerExited = !timedOut && ownerExitStoppedCommands.has(invocation.commandId);
|
|
731
|
+
const message = ownerExited
|
|
732
|
+
? managedCommandOwnerExitMessage
|
|
733
|
+
: redactText(error instanceof Error ? error.message : String(error), exactSecrets);
|
|
550
734
|
stderr = appendBounded(stderr, message);
|
|
551
735
|
outputRevision += 1;
|
|
552
736
|
lastOutputAt = Date.now();
|
|
@@ -561,6 +745,9 @@ async function executeManagedCommandProcess(invocation) {
|
|
|
561
745
|
outputRevision,
|
|
562
746
|
lastOutputAt,
|
|
563
747
|
lastOutputStream,
|
|
748
|
+
terminationReason: ownerExited ? "owner_exited" : undefined,
|
|
749
|
+
// The runner rejected, so its tree was not proven stopped; teardown still stops it.
|
|
750
|
+
processTreeTerminated: false,
|
|
564
751
|
});
|
|
565
752
|
await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
|
|
566
753
|
return managedCommandPublicResult(receipt);
|
|
@@ -612,7 +799,7 @@ async function waitManagedCommand(input) {
|
|
|
612
799
|
const commandId = validatedCommandId(record);
|
|
613
800
|
const requestedWaitTimeoutMs = optionalWaitTimeout(record.wait_timeout_ms);
|
|
614
801
|
const waitTimeoutMs = Math.min(requestedWaitTimeoutMs, maximumSynchronousWaitMs);
|
|
615
|
-
const deadline =
|
|
802
|
+
const deadline = monotonicNowMs() + waitTimeoutMs;
|
|
616
803
|
const receiptPath = managedCommandReceiptPath(requiredAttemptEnvironment("FORGE_LOG_DIR"), commandId);
|
|
617
804
|
const task = managedCommandTasks.get(commandId);
|
|
618
805
|
if (task) {
|
|
@@ -623,12 +810,12 @@ async function waitManagedCommand(input) {
|
|
|
623
810
|
if (result)
|
|
624
811
|
return result;
|
|
625
812
|
}
|
|
626
|
-
while (
|
|
813
|
+
while (monotonicNowMs() < deadline) {
|
|
627
814
|
const result = await readManagedCommand({ command_id: commandId });
|
|
628
815
|
if (terminalManagedCommandStatuses.has(String(result.structuredContent.status))) {
|
|
629
816
|
return result;
|
|
630
817
|
}
|
|
631
|
-
await delay(Math.min(managedCommandReceiptPollIntervalMs, Math.max(1, deadline -
|
|
818
|
+
await delay(Math.min(managedCommandReceiptPollIntervalMs, Math.max(1, deadline - monotonicNowMs())));
|
|
632
819
|
}
|
|
633
820
|
const receipt = await readManagedCommand({ command_id: commandId });
|
|
634
821
|
// Only a running receipt is refreshed on a heartbeat; queued or starting receipts are
|
|
@@ -649,7 +836,7 @@ async function waitManagedCommand(input) {
|
|
|
649
836
|
...receipt,
|
|
650
837
|
content: [{
|
|
651
838
|
type: "text",
|
|
652
|
-
text: `Forge is still supervising managed command ${commandId} after this ${waitTimeoutMs}ms transport-safe wait.${progress} Continue independent work or call forge.wait_managed_command again after ${managedCommandRetryAfterMs}ms. Its durable receipt remains at ${receiptPath}.`,
|
|
839
|
+
text: `Forge is still supervising managed command ${commandId} after this ${waitTimeoutMs}ms transport-safe wait.${progress} Continue independent work or call forge.wait_managed_command again after ${managedCommandRetryAfterMs}ms. Do not end your turn to wait for it: Forge ends the provider run shortly after a turn ends, which stops background monitors and this command. Its durable receipt remains at ${receiptPath}.`,
|
|
653
840
|
}],
|
|
654
841
|
structuredContent: {
|
|
655
842
|
...receipt.structuredContent,
|
|
@@ -743,11 +930,22 @@ function managedCommandResult(values) {
|
|
|
743
930
|
output_count: values.buildReceipt.outputCount,
|
|
744
931
|
} : null,
|
|
745
932
|
runtime_configuration: managedRuntimeConfiguration(),
|
|
746
|
-
|
|
933
|
+
// The supervising MCP server process. Forge stops a command whose owner has exited.
|
|
934
|
+
owner_pid: process.pid,
|
|
935
|
+
owner_identity: managedCommandOwnerIdentity(),
|
|
936
|
+
launch_requested: values.launchRequested ?? true,
|
|
937
|
+
process_tree_terminated: values.status === "timed_out" ? true : values.timedOut ? false : values.processTreeTerminated,
|
|
938
|
+
...(values.terminationReason ? { termination_reason: values.terminationReason } : {}),
|
|
747
939
|
},
|
|
748
940
|
isError: isTerminal && values.status !== "pass",
|
|
749
941
|
};
|
|
750
942
|
}
|
|
943
|
+
/** This server's birth identity, so a reissued PID is never mistaken for a live owner. */
|
|
944
|
+
function managedCommandOwnerIdentity() {
|
|
945
|
+
// Windows identity capture starts PowerShell; the PID check alone is used there.
|
|
946
|
+
ownerProcessIdentity ??= process.platform === "linux" ? captureHostProcessIdentity(process.pid) : null;
|
|
947
|
+
return ownerProcessIdentity;
|
|
948
|
+
}
|
|
751
949
|
function managedRuntimeConfiguration() {
|
|
752
950
|
const providerOnlySpecs = process.env.FORGE_CI_REPAIR_PROVIDER_ONLY_SPECS?.trim();
|
|
753
951
|
let providerOnlySpecCount = 0;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export declare class ManagedBuildCoordinator {
|
|
2
2
|
private readonly stateRoot;
|
|
3
3
|
constructor(stateRoot?: string);
|
|
4
|
-
withBuildSlot<T>(worktreePath: string, action: (queueWaitMs: number) => Promise<T>, onWaiting?: () => Promise<void
|
|
4
|
+
withBuildSlot<T>(worktreePath: string, action: (queueWaitMs: number) => Promise<T>, onWaiting?: () => Promise<void>, signal?: AbortSignal): Promise<T>;
|
|
5
5
|
}
|
|
@@ -2,6 +2,7 @@ import { createHash, randomUUID } from "node:crypto";
|
|
|
2
2
|
import fs from "node:fs/promises";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { defaultWorktreeCoordinatorStateRoot } from "../worktree/worktree-paths.js";
|
|
5
|
+
import { monotonicNowMs } from "../shared/time/monotonic.js";
|
|
5
6
|
const heartbeatIntervalMs = 30_000;
|
|
6
7
|
const staleAfterMs = 2 * 60_000;
|
|
7
8
|
const acquisitionTimeoutMs = 2 * 60 * 60_000;
|
|
@@ -11,16 +12,19 @@ export class ManagedBuildCoordinator {
|
|
|
11
12
|
constructor(stateRoot = defaultWorktreeCoordinatorStateRoot()) {
|
|
12
13
|
this.stateRoot = stateRoot;
|
|
13
14
|
}
|
|
14
|
-
async withBuildSlot(worktreePath, action, onWaiting) {
|
|
15
|
+
async withBuildSlot(worktreePath, action, onWaiting, signal) {
|
|
15
16
|
const resolved = path.resolve(worktreePath);
|
|
16
17
|
const key = createHash("sha256").update(resolved.toLowerCase()).digest("hex");
|
|
17
18
|
const root = path.join(this.stateRoot, "managed-build-locks");
|
|
18
19
|
const target = path.join(root, `${key}.lock`);
|
|
19
20
|
const token = randomUUID();
|
|
20
|
-
const startedAt =
|
|
21
|
+
const startedAt = monotonicNowMs();
|
|
21
22
|
let waitingReported = false;
|
|
22
23
|
await fs.mkdir(root, { recursive: true, mode: 0o700 });
|
|
23
24
|
while (true) {
|
|
25
|
+
if (signal?.aborted) {
|
|
26
|
+
throw signal.reason instanceof Error ? signal.reason : new Error("managed_build_slot_cancelled: the build-slot wait was cancelled.");
|
|
27
|
+
}
|
|
24
28
|
try {
|
|
25
29
|
const handle = await fs.open(target, "wx", 0o600);
|
|
26
30
|
try {
|
|
@@ -49,7 +53,7 @@ export class ManagedBuildCoordinator {
|
|
|
49
53
|
waitingReported = true;
|
|
50
54
|
await onWaiting?.();
|
|
51
55
|
}
|
|
52
|
-
if (
|
|
56
|
+
if (monotonicNowMs() - startedAt >= acquisitionTimeoutMs) {
|
|
53
57
|
throw new Error("managed_build_slot_timeout: another build held this worktree for more than two hours.", { cause: error });
|
|
54
58
|
}
|
|
55
59
|
await delay(pollIntervalMs);
|
|
@@ -58,7 +62,7 @@ export class ManagedBuildCoordinator {
|
|
|
58
62
|
const heartbeat = setInterval(() => void refreshHeartbeat(target, token), heartbeatIntervalMs);
|
|
59
63
|
heartbeat.unref?.();
|
|
60
64
|
try {
|
|
61
|
-
return await action(
|
|
65
|
+
return await action(Math.round(monotonicNowMs() - startedAt));
|
|
62
66
|
}
|
|
63
67
|
finally {
|
|
64
68
|
clearInterval(heartbeat);
|
|
@@ -8,7 +8,7 @@ import { completionPromptForDebugCycle, completionPromptForDecomposeCycle, compl
|
|
|
8
8
|
import { configuredNativeTestPostgresFallbackPath, nativeTestPostgresFallbackConfigEnvironment, } from "../runtime/native-test-postgres-fallback.js";
|
|
9
9
|
import { toolDescription, toolInputSchema } from "./phase-completion.schemas.js";
|
|
10
10
|
import { writeCompletionArtifact, writeDecomposeGateCompletionArtifact, writeDraftGateCompletionArtifact } from "./phase-completion.artifacts.js";
|
|
11
|
-
import { callManagedAttemptTool, isManagedAttemptTool, managedAttemptToolDefinition, managedAttemptToolNames, } from "./managed-attempt-tools.js";
|
|
11
|
+
import { callManagedAttemptTool, isManagedAttemptTool, managedAttemptToolDefinition, managedAttemptToolNames, runWithOwnerShutdown, } from "./managed-attempt-tools.js";
|
|
12
12
|
export async function prepareCompletionToolRuntime(options) {
|
|
13
13
|
const phase = options.phase ?? completionPhaseFromDispatch(options.dispatch);
|
|
14
14
|
const worktreePath = path.resolve(options.worktree.worktreePath);
|
|
@@ -552,24 +552,29 @@ function managedAttemptToolsAvailable() {
|
|
|
552
552
|
}
|
|
553
553
|
export async function runCompletionMcpServer(config) {
|
|
554
554
|
const session = new CompletionToolServerSession(config);
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
buffer
|
|
563
|
-
|
|
564
|
-
|
|
555
|
+
// This server is the only supervisor of the managed commands it starts, and they run in
|
|
556
|
+
// their own process groups. When the provider closes the connection or stops this server,
|
|
557
|
+
// stop them first so none outlives its supervisor and receipt writer.
|
|
558
|
+
await runWithOwnerShutdown(async () => {
|
|
559
|
+
process.stdin.setEncoding("utf8");
|
|
560
|
+
let buffer = "";
|
|
561
|
+
for await (const chunk of process.stdin) {
|
|
562
|
+
buffer += chunk;
|
|
563
|
+
let newlineIndex = buffer.indexOf("\n");
|
|
564
|
+
while (newlineIndex >= 0) {
|
|
565
|
+
const rawLine = buffer.slice(0, newlineIndex).trim();
|
|
566
|
+
buffer = buffer.slice(newlineIndex + 1);
|
|
567
|
+
if (rawLine.length > 0) {
|
|
568
|
+
await handleJsonRpcLine(session, rawLine);
|
|
569
|
+
}
|
|
570
|
+
newlineIndex = buffer.indexOf("\n");
|
|
565
571
|
}
|
|
566
|
-
newlineIndex = buffer.indexOf("\n");
|
|
567
572
|
}
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
}
|
|
573
|
+
const trailing = buffer.trim();
|
|
574
|
+
if (trailing.length > 0) {
|
|
575
|
+
await handleJsonRpcLine(session, trailing);
|
|
576
|
+
}
|
|
577
|
+
});
|
|
573
578
|
}
|
|
574
579
|
export function parseCompletionMcpArgs(argv) {
|
|
575
580
|
let worktreePath = null;
|
|
@@ -23,6 +23,8 @@ export interface ProviderProcessRunResult {
|
|
|
23
23
|
readonly memorySampleCount?: number;
|
|
24
24
|
readonly memorySource?: string;
|
|
25
25
|
readonly memoryObservedAt?: string;
|
|
26
|
+
/** Present when the caller's cancellation stopped the process before it exited on its own. */
|
|
27
|
+
readonly cancelled?: true;
|
|
26
28
|
}
|
|
27
29
|
export interface ProviderProcessRunner {
|
|
28
30
|
run(request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal): Promise<ProviderProcessRunResult>;
|
|
@@ -70,11 +72,14 @@ interface ProviderChildEnvironmentOptions {
|
|
|
70
72
|
export declare function buildProviderChildEnvironment(requestEnv?: Readonly<Record<string, string>>, options?: ProviderChildEnvironmentOptions): NodeJS.ProcessEnv;
|
|
71
73
|
export declare class StreamingProviderProcessRunner implements ProviderProcessRunner {
|
|
72
74
|
private readonly terminalExitGraceMs;
|
|
73
|
-
|
|
75
|
+
private readonly terminalSuccessCeilingMs;
|
|
76
|
+
constructor(terminalExitGraceMs?: number, terminalSuccessCeilingMs?: number);
|
|
74
77
|
run(request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal): Promise<ProviderProcessRunResult>;
|
|
75
78
|
}
|
|
76
79
|
/** Returns aggregate resident bytes for the exact supervised Unix process group. */
|
|
77
80
|
export declare function processGroupResidentMemoryBytes(processGroupId: number, platform?: NodeJS.Platform, procRoot?: string): number | null;
|
|
81
|
+
export declare const UNIX_PROVIDER_START_GRANT_LINE = "forge-provider-start-granted\n";
|
|
82
|
+
export declare function buildUnixProviderStartGateLaunch(command: string, args: readonly string[]): LaunchCommand;
|
|
78
83
|
export declare function resolveCodexNpmDirectLaunch(commandPath: string, args: readonly string[]): LaunchCommand | null;
|
|
79
84
|
/**
|
|
80
85
|
* npm installs of Claude Code (`npm i -g @anthropic-ai/claude-code`) put a `claude.cmd` shim on
|