@loucompanion/forge-bridge 0.1.4-dev.138b79c6feb3 → 0.1.4-dev.176dfdaf5020
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 +142 -1
- package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
- package/dist/bridge/bridge-chat-provider-command.js +132 -0
- package/dist/bridge/bridge-chat.types.d.ts +10 -0
- package/dist/bridge/bridge-chat.types.js +16 -1
- package/dist/bridge/bridge-state-file.d.ts +161 -0
- package/dist/bridge/bridge-state-file.js +376 -0
- package/dist/bridge/bridge-state-io.d.ts +11 -0
- package/dist/bridge/bridge-state-io.js +50 -0
- package/dist/bridge/bridge-state-lock.d.ts +11 -0
- package/dist/bridge/bridge-state-lock.js +102 -0
- package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
- package/dist/bridge/bridge-state-unpublished.js +111 -0
- package/dist/bridge/bridge.base.d.ts +9 -0
- package/dist/bridge/bridge.service.d.ts +87 -14
- package/dist/bridge/bridge.service.js +393 -337
- package/dist/bridge/bridge.types.d.ts +16 -0
- package/dist/bridge/in-flight-registry.d.ts +62 -0
- package/dist/bridge/in-flight-registry.js +207 -0
- package/dist/bridge/local-yield-flag.d.ts +6 -0
- package/dist/bridge/local-yield-flag.js +34 -0
- package/dist/bridge/readiness-result-outbox.d.ts +5 -1
- package/dist/bridge/readiness-result-outbox.js +20 -0
- package/dist/bridge/runner-host-capabilities.d.ts +3 -0
- package/dist/bridge/runner-host-capabilities.js +13 -0
- package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
- package/dist/bridge/sandbox-resource-accounting.js +150 -0
- package/dist/cleanup/cleanup-wip.d.ts +12 -0
- package/dist/cleanup/cleanup-wip.js +66 -0
- package/dist/cleanup/cleanup.service.d.ts +11 -1
- package/dist/cleanup/cleanup.service.js +80 -62
- package/dist/cleanup/cleanup.types.d.ts +2 -0
- package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
- package/dist/cleanup/host-runtime-ledger.js +30 -9
- package/dist/cli/cli.help.js +74 -12
- package/dist/cli/cli.service.d.ts +19 -10
- package/dist/cli/cli.service.js +142 -185
- package/dist/cli/idle-status.d.ts +84 -0
- package/dist/cli/idle-status.js +181 -0
- package/dist/cli/local-config.d.ts +6 -0
- package/dist/cli/local-config.js +32 -4
- package/dist/cli/provider-cli-detection.d.ts +10 -0
- package/dist/cli/provider-cli-detection.js +160 -0
- package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
- package/dist/runtime/aspnet-runtime-prebuild.js +104 -26
- package/dist/runtime/attempt-database-broker.d.ts +1 -1
- package/dist/runtime/attempt-node-runtime-launcher.js +9 -0
- package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
- package/dist/runtime/attempt-process-supervisor.js +12 -6
- package/dist/runtime/docker-engine-probe.d.ts +5 -0
- package/dist/runtime/docker-engine-probe.js +7 -0
- package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
- package/dist/runtime/dotnet-build-outputs.js +402 -0
- package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
- package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
- package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
- package/dist/runtime/ephemeral-test-postgres.js +303 -0
- package/dist/runtime/host-facts.d.ts +2 -1
- package/dist/runtime/host-load-admission.d.ts +18 -3
- package/dist/runtime/host-load-admission.js +19 -4
- package/dist/runtime/host-load-child-environment.d.ts +11 -6
- package/dist/runtime/host-load-child-environment.js +22 -11
- package/dist/runtime/host-load-governor-config.d.ts +19 -1
- package/dist/runtime/host-load-governor-config.js +37 -0
- package/dist/runtime/host-load-governor.d.ts +14 -0
- package/dist/runtime/host-load-governor.js +139 -26
- package/dist/runtime/host-load-ledger-lock.js +6 -4
- package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
- package/dist/runtime/host-load-runtime-settings.js +80 -0
- package/dist/runtime/host-load-sampler.d.ts +34 -4
- package/dist/runtime/host-load-sampler.js +73 -7
- package/dist/runtime/host-load-step-class.d.ts +3 -1
- package/dist/runtime/host-load-step-class.js +60 -5
- package/dist/runtime/host-load-test-slot.d.ts +43 -0
- package/dist/runtime/host-load-test-slot.js +81 -0
- package/dist/runtime/host-load-token-ledger.d.ts +26 -0
- package/dist/runtime/host-load-token-ledger.js +93 -61
- package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
- package/dist/runtime/host-load-windows-cpu.js +85 -0
- package/dist/runtime/host-runtime-contract.d.ts +12 -0
- package/dist/runtime/host-runtime-contract.js +29 -1
- package/dist/runtime/host-runtime-lease.d.ts +32 -4
- package/dist/runtime/host-runtime-lease.js +109 -173
- package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
- package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
- package/dist/runtime/host-runtime-promotion.d.ts +23 -0
- package/dist/runtime/host-runtime-promotion.js +36 -0
- package/dist/runtime/managed-command-teardown.js +5 -16
- package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
- package/dist/runtime/native-test-postgres-fallback.js +60 -8
- package/dist/runtime/runner-settings.d.ts +104 -0
- package/dist/runtime/runner-settings.js +236 -0
- package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
- package/dist/runtime/supervised-runtime-build-guard.js +112 -0
- package/dist/sandbox/host-capacity-broker.d.ts +10 -2
- package/dist/sandbox/host-capacity-broker.js +27 -6
- package/dist/sandbox/managed-branch.d.ts +13 -0
- package/dist/sandbox/managed-branch.js +90 -0
- package/dist/sandbox/provider-auth/codex.js +11 -11
- package/dist/sandbox/runtime.js +2 -6
- package/dist/session/architect-waits.d.ts +2 -0
- package/dist/session/architect-waits.js +138 -0
- package/dist/session/managed-attempt-tools.d.ts +0 -7
- package/dist/session/managed-attempt-tools.js +58 -91
- package/dist/session/managed-build-coordinator.d.ts +16 -0
- package/dist/session/managed-build-coordinator.js +10 -0
- package/dist/session/managed-build-receipt.d.ts +5 -0
- package/dist/session/managed-build-receipt.js +8 -3
- package/dist/session/managed-command-host-load.d.ts +2 -0
- package/dist/session/managed-command-host-load.js +2 -1
- package/dist/session/phase-completion.artifacts.js +2 -1
- package/dist/session/phase-completion.d.ts +8 -0
- package/dist/session/phase-completion.js +1 -0
- package/dist/session/phase-completion.mcp-args.d.ts +9 -0
- package/dist/session/phase-completion.mcp-args.js +156 -0
- package/dist/session/phase-completion.runtime.d.ts +0 -8
- package/dist/session/phase-completion.runtime.js +43 -197
- package/dist/session/phase-completion.schemas.js +25 -23
- package/dist/session/phase-completion.validation.js +3 -1
- package/dist/session/pre-publication-native-postgres.d.ts +30 -0
- package/dist/session/pre-publication-native-postgres.js +111 -0
- package/dist/session/pre-publication-pass.d.ts +61 -0
- package/dist/session/pre-publication-pass.js +148 -0
- package/dist/session/pre-publication-process.js +10 -10
- package/dist/session/pre-publication-step-execution.d.ts +2 -1
- package/dist/session/pre-publication-step-execution.js +6 -5
- package/dist/session/pre-publication-validation.d.ts +30 -14
- package/dist/session/pre-publication-validation.js +207 -134
- package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
- package/dist/session/provider-cli/claude-background-work.js +181 -0
- package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
- package/dist/session/provider-cli/host-build-lock.js +30 -0
- package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
- package/dist/session/provider-cli/pre-publication-repair.js +276 -0
- package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
- package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
- package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
- package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
- package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
- package/dist/session/provider-cli/provider-cli.process.js +39 -430
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +68 -31
- package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
- package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
- package/dist/session/provider-cli/provider-cli.service.d.ts +5 -5
- package/dist/session/provider-cli/provider-cli.service.js +70 -263
- package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
- package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
- package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
- package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
- package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
- package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
- package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
- package/dist/session/provider-cli/provider-output-pipes.js +67 -0
- package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
- package/dist/session/provider-cli/provider-output-state.js +6 -0
- package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
- package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
- package/dist/session/qa-sidecar-validation.d.ts +6 -0
- package/dist/session/qa-sidecar-validation.js +28 -0
- package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
- package/dist/session/sandbox-host-capacity-gate.js +42 -14
- package/dist/session/session-redaction.js +31 -181
- package/dist/session/session.base.d.ts +6 -1
- package/dist/session/session.service.d.ts +6 -1
- package/dist/session/session.service.js +75 -64
- package/dist/session/session.types.js +3 -3
- package/dist/session/sidecar-json-shape.d.ts +31 -0
- package/dist/session/sidecar-json-shape.js +217 -0
- package/dist/shared/fs/file-identity.d.ts +10 -0
- package/dist/shared/fs/file-identity.js +15 -0
- package/dist/shared/fs/replace-file.d.ts +7 -0
- package/dist/shared/fs/replace-file.js +33 -0
- package/dist/shared/process/host-process-recovery.d.ts +14 -3
- package/dist/shared/process/host-process-recovery.js +23 -3
- package/dist/shared/process/host-process-supervisor.d.ts +13 -1
- package/dist/shared/process/host-process-supervisor.js +66 -14
- package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
- package/dist/shared/process/windows-app-execution-alias.js +45 -0
- package/dist/shared/process/windows-launch.d.ts +18 -0
- package/dist/shared/process/windows-launch.js +68 -0
- package/dist/shared/provider-capabilities.js +14 -7
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/orphan-relink.d.ts +19 -0
- package/dist/worktree/orphan-relink.js +106 -0
- package/dist/worktree/wip-git.d.ts +33 -0
- package/dist/worktree/wip-git.js +122 -0
- package/dist/worktree/wip-refs.d.ts +62 -0
- package/dist/worktree/wip-refs.js +119 -0
- package/dist/worktree/wip-restore.d.ts +38 -0
- package/dist/worktree/wip-restore.js +190 -0
- package/dist/worktree/wip-snapshot.d.ts +50 -0
- package/dist/worktree/wip-snapshot.js +268 -0
- package/dist/worktree/worktree-inputs.d.ts +8 -0
- package/dist/worktree/worktree-inputs.js +134 -0
- package/dist/worktree/worktree-origin-sync.d.ts +34 -0
- package/dist/worktree/worktree-origin-sync.js +127 -0
- package/dist/worktree/worktree-wip-events.d.ts +18 -0
- package/dist/worktree/worktree-wip-events.js +98 -0
- package/dist/worktree/worktree-wip.d.ts +50 -0
- package/dist/worktree/worktree-wip.js +185 -0
- package/dist/worktree/worktree.base.d.ts +7 -1
- package/dist/worktree/worktree.service.d.ts +27 -5
- package/dist/worktree/worktree.service.js +110 -181
- package/dist/worktree/worktree.types.d.ts +31 -0
- package/package.json +2 -2
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Headless Claude Code runs must not start work that outlives the turn.
|
|
3
|
+
*
|
|
4
|
+
* Forge runs `claude -p` and treats the turn's terminal `result` event as the end of the run.
|
|
5
|
+
* When background work is still live at the end of a turn (a background subagent or shell, a
|
|
6
|
+
* Monitor watch, a scheduled wakeup), Claude Code withholds that `result` and keeps the process
|
|
7
|
+
* open for the work, so Forge sees a silent provider instead of a finished one. The launch
|
|
8
|
+
* restrictions below remove the ways to start such work; `ClaudeBackgroundTurnEndWatch` is the
|
|
9
|
+
* backstop for anything that still gets through.
|
|
10
|
+
*/
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
import { ForgeFailureError } from "../session.types.js";
|
|
13
|
+
/**
|
|
14
|
+
* Removes the `run_in_background` parameter from Bash, PowerShell and the Agent tool, runs
|
|
15
|
+
* forked subagents and forked skills in the foreground, and stops Claude Code from moving long
|
|
16
|
+
* shell commands, subagents and MCP calls to the background on its own. Cron disables the
|
|
17
|
+
* session-scoped scheduled tasks (`CronCreate`, `/loop`). Applied last, so a project's runtime
|
|
18
|
+
* environment cannot turn them back on.
|
|
19
|
+
*/
|
|
20
|
+
export const claudeHeadlessEnvironment = Object.freeze({
|
|
21
|
+
CLAUDE_CODE_DISABLE_BACKGROUND_TASKS: "1",
|
|
22
|
+
CLAUDE_CODE_DISABLE_CRON: "1",
|
|
23
|
+
});
|
|
24
|
+
/**
|
|
25
|
+
* Tools whose only purpose is work that reports after the turn. `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS`
|
|
26
|
+
* leaves Monitor running in the background, so it is removed here, together with self-paced
|
|
27
|
+
* wakeups, workflows (which run their agents in the background), cloud routines, cron
|
|
28
|
+
* (also disabled by environment), SendMessage, which resumes an earlier subagent in the
|
|
29
|
+
* background, and agent teams, whose teammates run alongside the turn. Foreground subagents
|
|
30
|
+
* stay available: they block the turn until they finish.
|
|
31
|
+
*/
|
|
32
|
+
export const claudeHeadlessDisallowedTools = Object.freeze([
|
|
33
|
+
"Monitor",
|
|
34
|
+
"ScheduleWakeup",
|
|
35
|
+
"Workflow",
|
|
36
|
+
"RemoteTrigger",
|
|
37
|
+
"CronCreate",
|
|
38
|
+
"SendMessage",
|
|
39
|
+
"TeamCreate",
|
|
40
|
+
]);
|
|
41
|
+
/**
|
|
42
|
+
* The Claude Code arguments that apply the restrictions: the tool deny list, and the environment
|
|
43
|
+
* again as flag settings, which outrank a user's or repository's settings `env` block. Other flag
|
|
44
|
+
* settings (`provider-user-config-isolation.ts`) share the one `--settings` value.
|
|
45
|
+
*/
|
|
46
|
+
export function claudeHeadlessToolArgs(additionalSettings = {}) {
|
|
47
|
+
return [
|
|
48
|
+
"--disallowedTools", claudeHeadlessDisallowedTools.join(","),
|
|
49
|
+
"--settings", JSON.stringify({ ...additionalSettings, env: claudeHeadlessEnvironment }),
|
|
50
|
+
];
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* The provider ended its turn while background work it started (a background subagent or
|
|
54
|
+
* shell, a Monitor watch, a wakeup) was still live. Claude Code withholds the turn's terminal
|
|
55
|
+
* result for such work, and nothing started in the background reports to Forge, so Forge stops
|
|
56
|
+
* the provider at once instead of waiting for an idle watchdog. Retryable: the harness, not the
|
|
57
|
+
* task, ended the run.
|
|
58
|
+
*/
|
|
59
|
+
export function providerTurnEndedWithBackgroundWorkFailure(message) {
|
|
60
|
+
return new ForgeFailureError("provider_turn_ended_with_background_work", `${message} The provider ended its turn while background work it started was still running, so it never delivered a terminal result; Forge stopped it instead of waiting.`);
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Fails every provider run Forge stopped because its turn ended with background work still live,
|
|
64
|
+
* whether or not the turn recorded a completion first: the stop cut that work short, so nothing
|
|
65
|
+
* may validate, commit or publish the worktree it left behind.
|
|
66
|
+
*/
|
|
67
|
+
export class BackgroundWorkStopFailingRunner {
|
|
68
|
+
inner;
|
|
69
|
+
constructor(inner) {
|
|
70
|
+
this.inner = inner;
|
|
71
|
+
}
|
|
72
|
+
async run(request, handlers, signal) {
|
|
73
|
+
const result = await this.inner.run(request, handlers, signal);
|
|
74
|
+
if (result.terminalStopReason === "turn_ended_with_background_work") {
|
|
75
|
+
throw providerTurnEndedWithBackgroundWorkFailure("The provider turn did not finish.");
|
|
76
|
+
}
|
|
77
|
+
return result;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Recognizes a main-conversation turn that ended while background tasks it started were still
|
|
82
|
+
* live, the case in which Claude Code withholds the turn's `result`. The turn end is Claude
|
|
83
|
+
* Code's `post_turn_summary` event; the live set is the documented `background_tasks_changed`
|
|
84
|
+
* event (Claude Code's own `ambient` tasks and `awaited` ones do not count). After `graceMs`
|
|
85
|
+
* without the result or new main-conversation activity, it calls `onTurnEndedWithBackgroundWork`
|
|
86
|
+
* once, so the runner can stop the provider instead of waiting on work no one will collect.
|
|
87
|
+
*/
|
|
88
|
+
export class ClaudeBackgroundTurnEndWatch {
|
|
89
|
+
graceMs;
|
|
90
|
+
onTurnEndedWithBackgroundWork;
|
|
91
|
+
liveBackgroundTasks = 0;
|
|
92
|
+
terminalSinceMainActivity = false;
|
|
93
|
+
mainTurnEnded = false;
|
|
94
|
+
timer = null;
|
|
95
|
+
stopped = false;
|
|
96
|
+
enabled;
|
|
97
|
+
/** Watches only Claude Code, by its executable `command`; other output is left alone. */
|
|
98
|
+
constructor(command, graceMs, onTurnEndedWithBackgroundWork) {
|
|
99
|
+
this.graceMs = graceMs;
|
|
100
|
+
this.onTurnEndedWithBackgroundWork = onTurnEndedWithBackgroundWork;
|
|
101
|
+
this.enabled = path.parse(command).name.toLowerCase() === "claude";
|
|
102
|
+
}
|
|
103
|
+
consume(line) {
|
|
104
|
+
if (!this.enabled || this.stopped)
|
|
105
|
+
return;
|
|
106
|
+
const event = parseStreamEvent(line);
|
|
107
|
+
if (!event)
|
|
108
|
+
return;
|
|
109
|
+
if (isTerminalEvent(event)) {
|
|
110
|
+
this.terminalSinceMainActivity = true;
|
|
111
|
+
this.cancel();
|
|
112
|
+
}
|
|
113
|
+
else if (event.type === "system" && event.subtype === "background_tasks_changed") {
|
|
114
|
+
this.liveBackgroundTasks = liveBackgroundTaskCount(event.tasks);
|
|
115
|
+
// The work settled: Claude Code now delivers the result or starts a turn for it, and a
|
|
116
|
+
// follow-up turn can think for a while before its first event.
|
|
117
|
+
if (this.liveBackgroundTasks === 0)
|
|
118
|
+
this.cancel();
|
|
119
|
+
// A task can be reported just after the turn summary, as the turn ends.
|
|
120
|
+
else if (this.mainTurnEnded)
|
|
121
|
+
this.armIfTurnEndedWithBackgroundWork();
|
|
122
|
+
}
|
|
123
|
+
else if (event.type === "system" && event.subtype === "post_turn_summary") {
|
|
124
|
+
this.mainTurnEnded = true;
|
|
125
|
+
this.armIfTurnEndedWithBackgroundWork();
|
|
126
|
+
}
|
|
127
|
+
else if ((event.type === "assistant" || event.type === "user") && !event.parent_tool_use_id) {
|
|
128
|
+
// The main conversation is working again (a new turn, or a turn that is still going).
|
|
129
|
+
this.terminalSinceMainActivity = false;
|
|
130
|
+
this.mainTurnEnded = false;
|
|
131
|
+
this.cancel();
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
stop() {
|
|
135
|
+
this.stopped = true;
|
|
136
|
+
this.cancel();
|
|
137
|
+
}
|
|
138
|
+
armIfTurnEndedWithBackgroundWork() {
|
|
139
|
+
if (this.timer || this.terminalSinceMainActivity || this.liveBackgroundTasks === 0)
|
|
140
|
+
return;
|
|
141
|
+
this.timer = setTimeout(() => {
|
|
142
|
+
this.timer = null;
|
|
143
|
+
this.stopped = true;
|
|
144
|
+
this.onTurnEndedWithBackgroundWork();
|
|
145
|
+
}, this.graceMs);
|
|
146
|
+
this.timer.unref?.();
|
|
147
|
+
}
|
|
148
|
+
cancel() {
|
|
149
|
+
if (!this.timer)
|
|
150
|
+
return;
|
|
151
|
+
clearTimeout(this.timer);
|
|
152
|
+
this.timer = null;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
function parseStreamEvent(line) {
|
|
156
|
+
const trimmed = line.trim();
|
|
157
|
+
if (!trimmed.startsWith("{"))
|
|
158
|
+
return null;
|
|
159
|
+
try {
|
|
160
|
+
const parsed = JSON.parse(trimmed);
|
|
161
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
return null;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
function isTerminalEvent(event) {
|
|
168
|
+
return event.type === "result" || event.type === "error";
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Tasks that keep the turn's result back: not Claude Code's own `ambient` tasks, and not
|
|
172
|
+
* `awaited` ones, which a still-running tool call of the turn waits for.
|
|
173
|
+
*/
|
|
174
|
+
function liveBackgroundTaskCount(tasks) {
|
|
175
|
+
if (!Array.isArray(tasks))
|
|
176
|
+
return 0;
|
|
177
|
+
return tasks.filter(task => {
|
|
178
|
+
const entry = task && typeof task === "object" ? task : {};
|
|
179
|
+
return entry.ambient !== true && entry.awaited !== true;
|
|
180
|
+
}).length;
|
|
181
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A runner host can allow only one local .NET build or test at a time across everything that runs
|
|
3
|
+
* on it: Forge agents, the owner's own sessions and their tools. Parallel builds there exhaust
|
|
4
|
+
* memory and break each other's shared test output. The host's owner names the lock wrapper in the
|
|
5
|
+
* bridge's own environment; Forge passes it to every host-mode agent turn and Bridge Chat turn and
|
|
6
|
+
* tells the agent to run its .NET builds and tests through it. The rule reaches agents only from Forge, never from a
|
|
7
|
+
* user-level instruction file (provider-user-config-isolation.ts).
|
|
8
|
+
*/
|
|
9
|
+
export declare const hostDotnetBuildLockVariable = "FORGE_HOST_DOTNET_BUILD_LOCK";
|
|
10
|
+
/** The host's .NET build lock wrapper, when the bridge's environment names one. */
|
|
11
|
+
export declare function hostDotnetBuildLock(environment?: NodeJS.ProcessEnv): string | null;
|
|
12
|
+
export declare function hostDotnetBuildLockEnvironment(environment?: NodeJS.ProcessEnv): Readonly<Record<string, string>>;
|
|
13
|
+
/**
|
|
14
|
+
* The runtime-context instruction for a host that names a .NET build lock, or an empty string.
|
|
15
|
+
* Session turns also hear that the commands Forge runs for them are scheduled by Forge; Bridge
|
|
16
|
+
* Chat turns have no Forge tools.
|
|
17
|
+
*/
|
|
18
|
+
export declare function hostDotnetBuildLockInstruction(environment?: NodeJS.ProcessEnv, turn?: "session" | "chat"): string;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A runner host can allow only one local .NET build or test at a time across everything that runs
|
|
3
|
+
* on it: Forge agents, the owner's own sessions and their tools. Parallel builds there exhaust
|
|
4
|
+
* memory and break each other's shared test output. The host's owner names the lock wrapper in the
|
|
5
|
+
* bridge's own environment; Forge passes it to every host-mode agent turn and Bridge Chat turn and
|
|
6
|
+
* tells the agent to run its .NET builds and tests through it. The rule reaches agents only from Forge, never from a
|
|
7
|
+
* user-level instruction file (provider-user-config-isolation.ts).
|
|
8
|
+
*/
|
|
9
|
+
export const hostDotnetBuildLockVariable = "FORGE_HOST_DOTNET_BUILD_LOCK";
|
|
10
|
+
/** The host's .NET build lock wrapper, when the bridge's environment names one. */
|
|
11
|
+
export function hostDotnetBuildLock(environment = process.env) {
|
|
12
|
+
return environment[hostDotnetBuildLockVariable]?.trim() || null;
|
|
13
|
+
}
|
|
14
|
+
export function hostDotnetBuildLockEnvironment(environment = process.env) {
|
|
15
|
+
const lock = hostDotnetBuildLock(environment);
|
|
16
|
+
return lock ? { [hostDotnetBuildLockVariable]: lock } : {};
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* The runtime-context instruction for a host that names a .NET build lock, or an empty string.
|
|
20
|
+
* Session turns also hear that the commands Forge runs for them are scheduled by Forge; Bridge
|
|
21
|
+
* Chat turns have no Forge tools.
|
|
22
|
+
*/
|
|
23
|
+
export function hostDotnetBuildLockInstruction(environment = process.env, turn = "session") {
|
|
24
|
+
if (!hostDotnetBuildLock(environment))
|
|
25
|
+
return "";
|
|
26
|
+
const forgeScheduled = turn === "session"
|
|
27
|
+
? " Commands Forge runs for you (`forge.start_managed_verification`, pre-publication checks) are scheduled by Forge."
|
|
28
|
+
: "";
|
|
29
|
+
return `\n- This host runs one local .NET build or test at a time. Run every \`dotnet build\` and \`dotnet test\` you start yourself through the host lock in \`${hostDotnetBuildLockVariable}\`, for example \`"$${hostDotnetBuildLockVariable}" dotnet test <project> --filter <tests>\`. It waits while another build or test holds the lock and exits 75 if the wait times out; wait and retry rather than running without it.${forgeScheduled}`;
|
|
30
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { PrePublicationValidationError, type PrePublicationProfile, type PrePublicationValidator } from "../pre-publication-validation.js";
|
|
2
|
+
import { prepareCompletionToolRuntime } from "../phase-completion.js";
|
|
3
|
+
import { type RunOnceDispatchPacket } from "../session.types.js";
|
|
4
|
+
import type { ProviderProcessRunner } from "./provider-cli.process.js";
|
|
5
|
+
import { buildProviderCliCommand } from "./provider-cli.prompts.js";
|
|
6
|
+
import type { ProviderCliRunContext } from "./provider-cli.types.js";
|
|
7
|
+
import { type ProviderOutputState } from "./provider-output-state.js";
|
|
8
|
+
/**
|
|
9
|
+
* The in-place repair budget: FORGE_PREPUBLICATION_REPAIR_TURNS when it is a whole number from 1
|
|
10
|
+
* (capped at 10), otherwise 4.
|
|
11
|
+
*/
|
|
12
|
+
export declare function prePublicationRepairTurnsFromEnvironment(environment?: Readonly<Record<string, string | undefined>>): number;
|
|
13
|
+
export interface PrePublicationRepairOptions {
|
|
14
|
+
readonly context: ProviderCliRunContext;
|
|
15
|
+
readonly validationProfile: PrePublicationProfile;
|
|
16
|
+
readonly repairEnvironment: Readonly<Record<string, string>> | undefined;
|
|
17
|
+
readonly outputState: ProviderOutputState;
|
|
18
|
+
readonly preparedHeadSha: string;
|
|
19
|
+
readonly repairScope: "implementation" | "pull_request";
|
|
20
|
+
/**
|
|
21
|
+
* Derives the repair environment from a refreshed runtime environment. CI repair
|
|
22
|
+
* rewrites its readiness manifest so the attempt URLs it records stay current.
|
|
23
|
+
*/
|
|
24
|
+
readonly onRuntimeEnvironmentRefreshed?: (runtimeEnvironment: Readonly<Record<string, string>>) => Promise<Readonly<Record<string, string>>>;
|
|
25
|
+
}
|
|
26
|
+
/** One resumed provider turn that repairs a failed pass in place. */
|
|
27
|
+
export interface PrePublicationRepairTurn {
|
|
28
|
+
readonly prompt: string;
|
|
29
|
+
readonly repairTurn: number;
|
|
30
|
+
readonly maxRepairTurns: number;
|
|
31
|
+
readonly providerThreadId: string;
|
|
32
|
+
readonly repairEnvironment: Readonly<Record<string, string>> | undefined;
|
|
33
|
+
readonly environment: Readonly<Record<string, string>>;
|
|
34
|
+
readonly failure: PrePublicationValidationError;
|
|
35
|
+
}
|
|
36
|
+
export interface PrePublicationRepairDependencies {
|
|
37
|
+
readonly validator: PrePublicationValidator;
|
|
38
|
+
readonly defaultProcessRunner: ProviderProcessRunner;
|
|
39
|
+
readonly maxRepairTurns: number;
|
|
40
|
+
readonly runRepairTurn: (turn: PrePublicationRepairTurn) => Promise<void>;
|
|
41
|
+
}
|
|
42
|
+
export declare function validatePrePublicationWithRepair(options: PrePublicationRepairOptions, dependencies: PrePublicationRepairDependencies): Promise<void>;
|
|
43
|
+
/**
|
|
44
|
+
* The resumed command for one pre-publication repair turn. The main turn's Forge MCP server was
|
|
45
|
+
* cleaned up when that turn exited, so the repair turn gets its own: the managed-attempt tools its
|
|
46
|
+
* prompt directs long checks to, without the completion tools whose artifacts are already recorded.
|
|
47
|
+
* The caller owns the returned runtime and cleans it up when the turn exits.
|
|
48
|
+
*/
|
|
49
|
+
export declare function prepareRepairTurnLaunch(context: ProviderCliRunContext, turn: PrePublicationRepairTurn): Promise<{
|
|
50
|
+
readonly repairDispatch: RunOnceDispatchPacket;
|
|
51
|
+
readonly providerPrompt: string;
|
|
52
|
+
readonly pipePromptToStdin: boolean;
|
|
53
|
+
readonly completionTools: Awaited<ReturnType<typeof prepareCompletionToolRuntime>>;
|
|
54
|
+
readonly command: ReturnType<typeof buildProviderCliCommand>;
|
|
55
|
+
}>;
|
|
56
|
+
export declare function buildPrePublicationRepairPrompt(error: PrePublicationValidationError, repairTurn: number, maxRepairTurns: number, repairScope: "implementation" | "pull_request"): string;
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import { HostPortCollisionError } from "../../runtime/host-port-broker.js";
|
|
2
|
+
import { runtimeAdmissionPriority } from "../../runtime/host-runtime-lease.js";
|
|
3
|
+
import { runtimeRestartCheckId } from "../pre-publication-pass.js";
|
|
4
|
+
import { PrePublicationValidationError, } from "../pre-publication-validation.js";
|
|
5
|
+
import { prepareCompletionToolRuntime } from "../phase-completion.js";
|
|
6
|
+
import { ForgeFailureError } from "../session.types.js";
|
|
7
|
+
import { buildProviderCliCommand, buildProviderCliPrompt, shouldPipePromptToStdin, usesManagedWindowsHost, } from "./provider-cli.prompts.js";
|
|
8
|
+
import { prePublicationValidationEnv, providerProcessEnv } from "./provider-cli.runtime.js";
|
|
9
|
+
import { clip } from "./provider-output-state.js";
|
|
10
|
+
// Pre-publication validation with bounded in-place repair: each pass restarts the attempt's runtime
|
|
11
|
+
// stack when the workspace changed, runs every check that can still meaningfully run, and hands all
|
|
12
|
+
// of the pass's failures to one resumed provider turn, up to the repair budget.
|
|
13
|
+
const defaultRepairTurns = 4;
|
|
14
|
+
const maximumRepairTurns = 10;
|
|
15
|
+
const repairTurnsEnvironment = "FORGE_PREPUBLICATION_REPAIR_TURNS";
|
|
16
|
+
// The repair prompt's diagnostics: each failed check gets an equal share of the total, between the
|
|
17
|
+
// floor and the ceiling (validation already clips each check's own output to the ceiling). The
|
|
18
|
+
// total keeps a prompt passed as a command-line argument within Windows' 32,767-character limit.
|
|
19
|
+
const repairPromptDetailBudget = 18_000;
|
|
20
|
+
const repairPromptDetailCeiling = 6000;
|
|
21
|
+
const repairPromptDetailFloor = 1500;
|
|
22
|
+
/**
|
|
23
|
+
* The in-place repair budget: FORGE_PREPUBLICATION_REPAIR_TURNS when it is a whole number from 1
|
|
24
|
+
* (capped at 10), otherwise 4.
|
|
25
|
+
*/
|
|
26
|
+
export function prePublicationRepairTurnsFromEnvironment(environment = process.env) {
|
|
27
|
+
const configured = environment[repairTurnsEnvironment]?.trim() ?? "";
|
|
28
|
+
return /^\d+$/u.test(configured) && Number(configured) >= 1
|
|
29
|
+
? Math.min(Number(configured), maximumRepairTurns)
|
|
30
|
+
: defaultRepairTurns;
|
|
31
|
+
}
|
|
32
|
+
/** The environments a pass and its repair turn use; a runtime restart assigns new ports, so all move together. */
|
|
33
|
+
class RepairEnvironments {
|
|
34
|
+
options;
|
|
35
|
+
repair;
|
|
36
|
+
constructor(options) {
|
|
37
|
+
this.options = options;
|
|
38
|
+
this.repair = options.repairEnvironment;
|
|
39
|
+
}
|
|
40
|
+
get provider() {
|
|
41
|
+
return providerProcessEnv(this.options.context.dispatch, this.repair);
|
|
42
|
+
}
|
|
43
|
+
get validation() {
|
|
44
|
+
return prePublicationValidationEnv(this.options.context.dispatch, this.repair);
|
|
45
|
+
}
|
|
46
|
+
async refresh(runtimeEnvironment) {
|
|
47
|
+
this.repair = this.options.onRuntimeEnvironmentRefreshed
|
|
48
|
+
? await this.options.onRuntimeEnvironmentRefreshed(runtimeEnvironment)
|
|
49
|
+
: runtimeEnvironment;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* The restart stopped the stack and released its ports before it failed, so the URLs the pass and
|
|
53
|
+
* repair turn would inherit name ports another attempt may now hold. Both run without them; the
|
|
54
|
+
* next pass restarts the stack and supplies fresh ones.
|
|
55
|
+
*/
|
|
56
|
+
async withdrawRuntimeStack() {
|
|
57
|
+
await this.refresh(withoutRuntimeStack(this.repair, this.options.context.runtimeStackEnvironmentKeys ?? []));
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
export async function validatePrePublicationWithRepair(options, dependencies) {
|
|
61
|
+
const { context, outputState } = options;
|
|
62
|
+
const { maxRepairTurns } = dependencies;
|
|
63
|
+
const environments = new RepairEnvironments(options);
|
|
64
|
+
for (let repairTurn = 0;; repairTurn += 1) {
|
|
65
|
+
const failure = await runValidationPass(options, dependencies, environments, repairTurn);
|
|
66
|
+
if (!failure) {
|
|
67
|
+
if (repairTurn > 0) {
|
|
68
|
+
await context.emit(repairEvent("checkpoint", "prepublication_repair_completed", `Pre-publication validation passed after ${repairTurn} in-place repair turn${repairTurn === 1 ? "" : "s"}.`, { repairTurn, maxRepairTurns }));
|
|
69
|
+
}
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
if (repairTurn >= maxRepairTurns) {
|
|
73
|
+
await context.emit(repairEvent("error", "prepublication_repair_exhausted", `Pre-publication validation still fails after ${maxRepairTurns} in-place repair turns: ${clip(failure.message, 4000)}`, { checkId: failure.checkId, checkIds: failure.checkIds, repairTurns: repairTurn, maxRepairTurns }));
|
|
74
|
+
throw failure;
|
|
75
|
+
}
|
|
76
|
+
const providerThreadId = outputState.providerThreadId?.trim();
|
|
77
|
+
if (!providerThreadId) {
|
|
78
|
+
throw new Error(`prepublication_repair_unavailable: ${failure.message}; provider did not report a resumable thread id, so Forge preserved the dirty worktree without starting a blind replacement run.`, { cause: failure });
|
|
79
|
+
}
|
|
80
|
+
const nextRepairTurn = repairTurn + 1;
|
|
81
|
+
await context.emit(repairEvent("checkpoint", "prepublication_repair_started", `Resuming ${context.dispatch.execution.provider} ${outputState.sessionLabel ?? "provider thread"} for bounded pre-publication repair ${nextRepairTurn}/${maxRepairTurns} after ${describeFailedChecks(failure.checkIds)} failed.`, { checkId: failure.checkId, checkIds: failure.checkIds, repairTurn: nextRepairTurn, maxRepairTurns }));
|
|
82
|
+
await dependencies.runRepairTurn({
|
|
83
|
+
prompt: buildPrePublicationRepairPrompt(failure, nextRepairTurn, maxRepairTurns, options.repairScope),
|
|
84
|
+
repairTurn: nextRepairTurn,
|
|
85
|
+
maxRepairTurns,
|
|
86
|
+
providerThreadId,
|
|
87
|
+
repairEnvironment: environments.repair,
|
|
88
|
+
environment: environments.provider,
|
|
89
|
+
failure,
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* The resumed command for one pre-publication repair turn. The main turn's Forge MCP server was
|
|
95
|
+
* cleaned up when that turn exited, so the repair turn gets its own: the managed-attempt tools its
|
|
96
|
+
* prompt directs long checks to, without the completion tools whose artifacts are already recorded.
|
|
97
|
+
* The caller owns the returned runtime and cleans it up when the turn exits.
|
|
98
|
+
*/
|
|
99
|
+
export async function prepareRepairTurnLaunch(context, turn) {
|
|
100
|
+
const { dispatch, worktree } = context;
|
|
101
|
+
const { prompt: focusedPrompt, repairEnvironment } = turn;
|
|
102
|
+
const repairDispatch = {
|
|
103
|
+
...dispatch,
|
|
104
|
+
session: { ...dispatch.session, resumeProviderThreadId: turn.providerThreadId },
|
|
105
|
+
};
|
|
106
|
+
const providerPrompt = buildProviderCliPrompt(repairDispatch, focusedPrompt, repairEnvironment);
|
|
107
|
+
const pipePromptToStdin = shouldPipePromptToStdin(repairDispatch.execution.provider, providerPrompt, usesManagedWindowsHost(repairDispatch));
|
|
108
|
+
const completionTools = await prepareCompletionToolRuntime({
|
|
109
|
+
dispatch: repairDispatch,
|
|
110
|
+
worktree,
|
|
111
|
+
runtimeEnvironment: repairEnvironment,
|
|
112
|
+
hostLoadEnvironment: context.hostLoadEnvironment,
|
|
113
|
+
managedToolsOnly: true,
|
|
114
|
+
});
|
|
115
|
+
const command = buildProviderCliCommand(repairDispatch, {
|
|
116
|
+
worktreePath: worktree.worktreePath,
|
|
117
|
+
prompt: focusedPrompt,
|
|
118
|
+
promptFromStdin: pipePromptToStdin,
|
|
119
|
+
completionTools,
|
|
120
|
+
runtimeEnvironment: repairEnvironment,
|
|
121
|
+
});
|
|
122
|
+
return { repairDispatch, providerPrompt, pipePromptToStdin, completionTools, command };
|
|
123
|
+
}
|
|
124
|
+
/** Restarts the runtime stack if needed, then validates; returns every failure of the pass, or null. */
|
|
125
|
+
async function runValidationPass(options, dependencies, environments, repairTurn) {
|
|
126
|
+
const { context, validationProfile, preparedHeadSha } = options;
|
|
127
|
+
let runtimeRestartFailure;
|
|
128
|
+
try {
|
|
129
|
+
const refreshed = await refreshPrePublicationRuntime(context, validationProfile, repairTurn);
|
|
130
|
+
if (refreshed)
|
|
131
|
+
await environments.refresh(refreshed);
|
|
132
|
+
}
|
|
133
|
+
catch (error) {
|
|
134
|
+
if (!(error instanceof PrePublicationValidationError))
|
|
135
|
+
throw error;
|
|
136
|
+
// The pass still runs the checks that do not need the stack, so the repair turn sees them too.
|
|
137
|
+
runtimeRestartFailure = error;
|
|
138
|
+
await environments.withdrawRuntimeStack();
|
|
139
|
+
}
|
|
140
|
+
try {
|
|
141
|
+
await dependencies.validator.validate(context.worktree.worktreePath, validationProfile, publicationCapabilities(context, environments.repair), context.emit, context.signal, {
|
|
142
|
+
...prePublicationExecution(context, environments.validation, dependencies.defaultProcessRunner, preparedHeadSha),
|
|
143
|
+
runtimeRestartFailure,
|
|
144
|
+
});
|
|
145
|
+
// The validator reports the restart failure with its own; the restart failed either way.
|
|
146
|
+
return runtimeRestartFailure ?? null;
|
|
147
|
+
}
|
|
148
|
+
catch (error) {
|
|
149
|
+
if (!(error instanceof PrePublicationValidationError))
|
|
150
|
+
throw error;
|
|
151
|
+
return runtimeRestartFailure && !error.checkIds.includes(runtimeRestartCheckId)
|
|
152
|
+
? new PrePublicationValidationError(runtimeRestartFailure.checkId, runtimeRestartFailure.exitCode, runtimeRestartFailure.command, runtimeRestartFailure.args, runtimeRestartFailure.detail, error.failures)
|
|
153
|
+
: error;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
function describeFailedChecks(checkIds) {
|
|
157
|
+
const quoted = checkIds.map(checkId => `'${checkId}'`);
|
|
158
|
+
return quoted.length <= 1
|
|
159
|
+
? quoted.join("")
|
|
160
|
+
: `${quoted.slice(0, -1).join(", ")} and ${quoted.at(-1)}`;
|
|
161
|
+
}
|
|
162
|
+
function repairEvent(kind, eventType, content, data) {
|
|
163
|
+
return { role: "runner", kind, content, eventType, data: JSON.stringify(data) };
|
|
164
|
+
}
|
|
165
|
+
export function buildPrePublicationRepairPrompt(error, repairTurn, maxRepairTurns, repairScope) {
|
|
166
|
+
const { failures } = error;
|
|
167
|
+
const several = failures.length > 1;
|
|
168
|
+
const detailLimit = Math.min(repairPromptDetailCeiling, Math.max(repairPromptDetailFloor, Math.floor(repairPromptDetailBudget / failures.length)));
|
|
169
|
+
const priorWork = repairScope === "implementation"
|
|
170
|
+
? "Keep the completed implementation and its Forge-owned completion artifacts intact."
|
|
171
|
+
: "Keep the existing PR-comment or CI repairs intact.";
|
|
172
|
+
const sections = failures.map((failure, index) => [
|
|
173
|
+
several ? `Failed check ${index + 1}/${failures.length}: ${failure.checkId}` : `Failed check: ${failure.checkId}`,
|
|
174
|
+
`Command: ${[failure.command, ...failure.args].join(" ")}`,
|
|
175
|
+
`Exit code: ${failure.exitCode}`,
|
|
176
|
+
"Diagnostics:",
|
|
177
|
+
clip(failure.detail, detailLimit) || "The validation command returned no diagnostic output.",
|
|
178
|
+
].join("\n\n"));
|
|
179
|
+
return [
|
|
180
|
+
`Forge pre-publication validation failed after your ${repairScope === "implementation" ? "implementation" : "PR repair"} turn.`,
|
|
181
|
+
`This is bounded in-place repair turn ${repairTurn}/${maxRepairTurns}.`,
|
|
182
|
+
...(several
|
|
183
|
+
? [`${failures.length} checks failed in the same validation pass: ${error.checkIds.join(", ")}. Fix every one of them in this turn.`]
|
|
184
|
+
: []),
|
|
185
|
+
...sections,
|
|
186
|
+
several
|
|
187
|
+
? "Fix the root cause of each failed check in the current worktree and run each focused failing check."
|
|
188
|
+
: "Fix the root cause in the current worktree and run the focused failing check.",
|
|
189
|
+
`${priorWork} Do not commit, push, rebase, or modify Forge-owned protocol artifacts.`,
|
|
190
|
+
`When the focused check${several ? "s pass" : " passes"}, stop; Bridge will rerun the complete required pre-publication profile and owns commit/push.`,
|
|
191
|
+
].join("\n\n");
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Restarts the attempt's runtime stack when the workspace changed since it was
|
|
195
|
+
* launched, before a validation pass runs against it. A build of the changed
|
|
196
|
+
* source that fails is a validation failure the bounded repair turn can fix.
|
|
197
|
+
*/
|
|
198
|
+
async function refreshPrePublicationRuntime(context, validationProfile, repairTurn) {
|
|
199
|
+
if (!context.refreshRuntimeEnvironment)
|
|
200
|
+
return null;
|
|
201
|
+
let refreshed;
|
|
202
|
+
try {
|
|
203
|
+
refreshed = await context.refreshRuntimeEnvironment(context.signal);
|
|
204
|
+
}
|
|
205
|
+
catch (error) {
|
|
206
|
+
// A restart that fails to build, start or become ready reflects the changed source, which a
|
|
207
|
+
// bounded repair turn can fix; the next pass restarts again. Cancellation, a released lease
|
|
208
|
+
// and a changed runtime contract still end the attempt.
|
|
209
|
+
if (restartFailureForRepair(error)) {
|
|
210
|
+
throw new PrePublicationValidationError(runtimeRestartCheckId, 1, "forge-host-runtime-restart", [],
|
|
211
|
+
// The session's host_runtime_restart_started event records why it restarted.
|
|
212
|
+
`Forge restarted the attempt runtime stack before validation, and the restart failed: ${error.message}`);
|
|
213
|
+
}
|
|
214
|
+
throw error;
|
|
215
|
+
}
|
|
216
|
+
if (!refreshed)
|
|
217
|
+
return null;
|
|
218
|
+
const { environment: restarted, reason, changes } = refreshed;
|
|
219
|
+
const apiUrl = restarted.FORGE_E2E_API_URL ?? restarted.FORGE_API_URL ?? null;
|
|
220
|
+
const webUrl = restarted.FORGE_E2E_WEB_URL ?? restarted.FORGE_WEB_URL ?? restarted.FORGE_PLAYWRIGHT_BASE_URL ?? null;
|
|
221
|
+
await context.emit(repairEvent("checkpoint", "prepublication_runtime_restarted", `Restarted the attempt runtime stack before pre-publication validation because ${restartReasonText[reason]}; validation${repairTurn > 0 ? " and repair turns" : ""} now use${apiUrl ? ` API ${apiUrl}` : " the refreshed runtime URLs"}${webUrl ? ` and web ${webUrl}` : ""}.`, { reason, changes, validationProfile, repairTurn, apiUrl, webUrl }));
|
|
222
|
+
return restarted;
|
|
223
|
+
}
|
|
224
|
+
const restartReasonText = {
|
|
225
|
+
previous_restart_incomplete: "the previous restart did not complete",
|
|
226
|
+
fingerprint_unavailable: "the workspace state could not be compared with the stack's",
|
|
227
|
+
workspace_changed: "the workspace changed since it was launched",
|
|
228
|
+
};
|
|
229
|
+
/** The environment with the runtime stack's URLs and ports withheld and the stack marked unavailable. */
|
|
230
|
+
function withoutRuntimeStack(environment, stackKeys) {
|
|
231
|
+
const remaining = { ...(environment ?? {}) };
|
|
232
|
+
for (const key of stackKeys)
|
|
233
|
+
delete remaining[key];
|
|
234
|
+
remaining.FORGE_RUNTIME_STACK = "unavailable";
|
|
235
|
+
return remaining;
|
|
236
|
+
}
|
|
237
|
+
const restartFailuresForRepair = new Set([
|
|
238
|
+
"host_runtime_project_start_failed",
|
|
239
|
+
"host_runtime_process_exited",
|
|
240
|
+
"host_runtime_listener_timeout",
|
|
241
|
+
"host_runtime_http_readiness_timeout",
|
|
242
|
+
"host_port_collision",
|
|
243
|
+
]);
|
|
244
|
+
function restartFailureForRepair(error) {
|
|
245
|
+
if (error instanceof ForgeFailureError)
|
|
246
|
+
return restartFailuresForRepair.has(error.failureCode);
|
|
247
|
+
// The port broker throws an untyped collision once its launch retries are exhausted.
|
|
248
|
+
return error instanceof HostPortCollisionError;
|
|
249
|
+
}
|
|
250
|
+
function publicationCapabilities(context, runtimeEnvironment) {
|
|
251
|
+
const capabilities = new Set();
|
|
252
|
+
const launchTarget = context.dispatch.qaBrowser?.launchTarget;
|
|
253
|
+
if (runtimeEnvironment?.FORGE_PLAYWRIGHT_CONFIG
|
|
254
|
+
|| launchTarget?.url
|
|
255
|
+
|| launchTarget?.command
|
|
256
|
+
|| launchTarget?.managed_runtime_port) {
|
|
257
|
+
capabilities.add("browser_launch");
|
|
258
|
+
}
|
|
259
|
+
return capabilities;
|
|
260
|
+
}
|
|
261
|
+
function prePublicationExecution(context, environment, defaultRunner, baselineRevision) {
|
|
262
|
+
const hostLoadOwner = {
|
|
263
|
+
dispatchAttemptId: context.dispatch.sandbox?.dispatchAttemptId ?? null,
|
|
264
|
+
priority: runtimeAdmissionPriority(context.dispatch),
|
|
265
|
+
};
|
|
266
|
+
if (context.processRunner)
|
|
267
|
+
return { baselineRevision, environment, processRunner: context.processRunner, hostLoadOwner };
|
|
268
|
+
if (context.dispatch.sandbox?.executionMode !== "docker")
|
|
269
|
+
return { baselineRevision, environment, hostLoadOwner };
|
|
270
|
+
const expectedSandboxId = context.dispatch.sandbox.dispatchAttemptId;
|
|
271
|
+
const observedSandboxId = context.runtimeEnvironment?.FORGE_SANDBOX_ID ?? process.env.FORGE_SANDBOX_ID;
|
|
272
|
+
if (observedSandboxId !== expectedSandboxId) {
|
|
273
|
+
throw new ForgeFailureError("prepublication_execution_scope_invalid", `prepublication_execution_scope_invalid: Docker attempt ${expectedSandboxId} has no runner proven to execute inside that sandbox.`, "bridge");
|
|
274
|
+
}
|
|
275
|
+
return { baselineRevision, environment, processRunner: defaultRunner, hostLoadOwner };
|
|
276
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export interface ProviderChildEnvironmentOptions {
|
|
2
|
+
readonly parentEnv?: NodeJS.ProcessEnv;
|
|
3
|
+
readonly platform?: NodeJS.Platform;
|
|
4
|
+
readonly homeDir?: string;
|
|
5
|
+
readonly arch?: string;
|
|
6
|
+
}
|
|
7
|
+
export declare function buildProviderChildEnvironment(requestEnv?: Readonly<Record<string, string>>, options?: ProviderChildEnvironmentOptions): NodeJS.ProcessEnv;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import os from "node:os";
|
|
2
|
+
import { normalizeWindowsProviderEnvironment, windowsAllowedProviderParentEnvNames } from "./provider-cli.windows-environment.js";
|
|
3
|
+
// The environment a provider child process starts with: an allowlist of the Bridge's own
|
|
4
|
+
// variables, the request's values, the Windows defaults, then the .NET build-server settings.
|
|
5
|
+
// CLAUDE_CONFIG_DIR is not passed: it would point Claude Code at a user configuration directory
|
|
6
|
+
// of the host's choosing (provider-user-config-isolation.ts). Claude signs in from the provider
|
|
7
|
+
// home's default `.claude` directory under HOME or USERPROFILE, or with a Forge-granted API key.
|
|
8
|
+
const allowedProviderParentEnvNames = [
|
|
9
|
+
"PATH",
|
|
10
|
+
"HOME",
|
|
11
|
+
"USERPROFILE",
|
|
12
|
+
"TMPDIR",
|
|
13
|
+
"TEMP",
|
|
14
|
+
"TMP",
|
|
15
|
+
"LANG"
|
|
16
|
+
];
|
|
17
|
+
export function buildProviderChildEnvironment(requestEnv, options = {}) {
|
|
18
|
+
const parentEnv = options.parentEnv ?? process.env;
|
|
19
|
+
const platform = options.platform ?? process.platform;
|
|
20
|
+
const env = {};
|
|
21
|
+
for (const [key, value] of Object.entries(parentEnv)) {
|
|
22
|
+
if (typeof value === "string" && isAllowedProviderParentEnv(key, platform)) {
|
|
23
|
+
env[key] = value;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
if (requestEnv) {
|
|
27
|
+
for (const [key, value] of Object.entries(requestEnv)) {
|
|
28
|
+
const trimmedKey = key.trim();
|
|
29
|
+
if (trimmedKey.length > 0) {
|
|
30
|
+
env[trimmedKey] = value;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
if (platform === "win32") {
|
|
35
|
+
normalizeWindowsProviderEnvironment(env, parentEnv, options.homeDir ?? os.homedir(), options.arch ?? os.arch());
|
|
36
|
+
}
|
|
37
|
+
normalizeProviderBuildEnvironment(env);
|
|
38
|
+
return env;
|
|
39
|
+
}
|
|
40
|
+
function normalizeProviderBuildEnvironment(env) {
|
|
41
|
+
// Provider sessions are long lived and commonly run many dotnet builds. Persistent
|
|
42
|
+
// MSBuild and Roslyn compiler servers otherwise survive individual commands and can
|
|
43
|
+
// retain more memory than the active Forge lane. Keep those caches process-scoped by
|
|
44
|
+
// default on every runner OS; an explicitly supplied request value still wins.
|
|
45
|
+
setCanonicalProviderBuildEnvironmentValue(env, "DOTNET_CLI_USE_MSBUILD_SERVER", "0");
|
|
46
|
+
setCanonicalProviderBuildEnvironmentValue(env, "MSBUILDDISABLENODEREUSE", "1");
|
|
47
|
+
setCanonicalProviderBuildEnvironmentValue(env, "UseSharedCompilation", "false");
|
|
48
|
+
}
|
|
49
|
+
function setCanonicalProviderBuildEnvironmentValue(env, name, value) {
|
|
50
|
+
// The dotnet CLI uses case-sensitive environment lookup on POSIX, while MSBuild
|
|
51
|
+
// property names are case-insensitive on every OS. Collapse request aliases to
|
|
52
|
+
// one canonical key so the explicit value wins without producing ambiguity.
|
|
53
|
+
const exact = env[name];
|
|
54
|
+
const alias = Object.entries(env).find(([key, candidate]) => key !== name
|
|
55
|
+
&& key.toLowerCase() === name.toLowerCase()
|
|
56
|
+
&& typeof candidate === "string"
|
|
57
|
+
&& candidate.trim().length > 0)?.[1];
|
|
58
|
+
const resolved = typeof exact === "string" && exact.trim().length > 0
|
|
59
|
+
? exact
|
|
60
|
+
: alias ?? value;
|
|
61
|
+
for (const key of Object.keys(env)) {
|
|
62
|
+
if (key !== name && key.toLowerCase() === name.toLowerCase()) {
|
|
63
|
+
delete env[key];
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
env[name] = resolved;
|
|
67
|
+
}
|
|
68
|
+
function isAllowedProviderParentEnv(key, platform = process.platform) {
|
|
69
|
+
return isAllowedProviderParentEnvName(key, allowedProviderParentEnvNames)
|
|
70
|
+
|| key.toUpperCase().startsWith("LC_")
|
|
71
|
+
|| (platform === "win32" && isAllowedProviderParentEnvName(key, windowsAllowedProviderParentEnvNames));
|
|
72
|
+
}
|
|
73
|
+
function isAllowedProviderParentEnvName(key, allowedNames) {
|
|
74
|
+
return allowedNames.some((allowed) => allowed.toLowerCase() === key.toLowerCase());
|
|
75
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { ProviderProcessRunResult } from "./provider-cli.process.js";
|
|
2
|
+
export declare function isCodexModelsCacheSchemaFailure(result: ProviderProcessRunResult): boolean;
|
|
3
|
+
export declare function quarantineIncompatibleCodexModelsCache(requestEnv?: Readonly<Record<string, string>>): Promise<boolean>;
|