@loucompanion/forge-bridge 0.1.4-dev.c2f22d1dd395 → 0.1.4-dev.ccffca94938b

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/README.md +57 -2
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +16 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +137 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/bridge.base.d.ts +9 -0
  7. package/dist/bridge/bridge.service.d.ts +73 -2
  8. package/dist/bridge/bridge.service.js +312 -119
  9. package/dist/bridge/bridge.types.d.ts +16 -0
  10. package/dist/bridge/local-yield-flag.d.ts +6 -0
  11. package/dist/bridge/local-yield-flag.js +34 -0
  12. package/dist/bridge/runner-host-capabilities.d.ts +5 -0
  13. package/dist/bridge/runner-host-capabilities.js +17 -0
  14. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  15. package/dist/bridge/test-postgres-capability.js +120 -0
  16. package/dist/cleanup/cleanup.service.d.ts +9 -0
  17. package/dist/cleanup/cleanup.service.js +72 -109
  18. package/dist/cleanup/cleanup.types.d.ts +4 -0
  19. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  20. package/dist/cleanup/forge-owned-paths.js +53 -0
  21. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  22. package/dist/cleanup/host-runtime-ledger.js +109 -0
  23. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  24. package/dist/cleanup/managed-branch-sweep.js +111 -0
  25. package/dist/cli/cli.help.js +18 -0
  26. package/dist/cli/cli.service.d.ts +16 -0
  27. package/dist/cli/cli.service.js +142 -16
  28. package/dist/cli/local-config.d.ts +4 -0
  29. package/dist/cli/local-config.js +26 -4
  30. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  31. package/dist/runtime/host-facts.d.ts +2 -1
  32. package/dist/runtime/host-load-admission.d.ts +67 -0
  33. package/dist/runtime/host-load-admission.js +99 -0
  34. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  35. package/dist/runtime/host-load-child-environment.js +76 -0
  36. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  37. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  38. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  39. package/dist/runtime/host-load-governor-config.js +83 -0
  40. package/dist/runtime/host-load-governor.d.ts +184 -0
  41. package/dist/runtime/host-load-governor.js +632 -0
  42. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  43. package/dist/runtime/host-load-ledger-lock.js +185 -0
  44. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  45. package/dist/runtime/host-load-runtime-settings.js +78 -0
  46. package/dist/runtime/host-load-sampler.d.ts +75 -2
  47. package/dist/runtime/host-load-sampler.js +142 -8
  48. package/dist/runtime/host-load-step-class.d.ts +70 -0
  49. package/dist/runtime/host-load-step-class.js +161 -0
  50. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  51. package/dist/runtime/host-load-step-reaper.js +95 -0
  52. package/dist/runtime/host-load-step-run.d.ts +73 -0
  53. package/dist/runtime/host-load-step-run.js +102 -0
  54. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  55. package/dist/runtime/host-load-test-slot.js +81 -0
  56. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  57. package/dist/runtime/host-load-token-ledger.js +453 -0
  58. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  59. package/dist/runtime/host-load-windows-cpu.js +85 -0
  60. package/dist/runtime/host-pressure-stall.d.ts +21 -1
  61. package/dist/runtime/host-pressure-stall.js +48 -1
  62. package/dist/runtime/host-runtime-contract.d.ts +3 -0
  63. package/dist/runtime/host-runtime-contract.js +4 -1
  64. package/dist/runtime/host-runtime-lease.d.ts +74 -4
  65. package/dist/runtime/host-runtime-lease.js +281 -11
  66. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  67. package/dist/runtime/host-runtime-promotion.js +48 -0
  68. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  69. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  70. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  71. package/dist/runtime/host-runtime-requirements.js +117 -0
  72. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  73. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  74. package/dist/runtime/runner-settings.d.ts +100 -0
  75. package/dist/runtime/runner-settings.js +214 -0
  76. package/dist/sandbox/host-capacity-broker.d.ts +113 -0
  77. package/dist/sandbox/host-capacity-broker.js +334 -0
  78. package/dist/sandbox/runtime.d.ts +10 -1
  79. package/dist/sandbox/runtime.js +45 -2
  80. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  81. package/dist/sandbox/sandbox-cgroups.js +42 -0
  82. package/dist/session/architect-waits.d.ts +2 -0
  83. package/dist/session/architect-waits.js +138 -0
  84. package/dist/session/managed-attempt-tools.d.ts +2 -0
  85. package/dist/session/managed-attempt-tools.js +157 -39
  86. package/dist/session/managed-command-host-load.d.ts +47 -0
  87. package/dist/session/managed-command-host-load.js +83 -0
  88. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  89. package/dist/session/mcp-argument-coercion.js +121 -0
  90. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  91. package/dist/session/phase-completion.artifacts.js +94 -25
  92. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  93. package/dist/session/phase-completion.command-validation.js +77 -0
  94. package/dist/session/phase-completion.d.ts +4 -0
  95. package/dist/session/phase-completion.helpers.js +13 -12
  96. package/dist/session/phase-completion.js +4 -0
  97. package/dist/session/phase-completion.prompts.js +6 -1
  98. package/dist/session/phase-completion.runtime.d.ts +5 -3
  99. package/dist/session/phase-completion.runtime.js +49 -19
  100. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  101. package/dist/session/phase-completion.schema-parts.js +188 -0
  102. package/dist/session/phase-completion.schemas.d.ts +3 -3
  103. package/dist/session/phase-completion.schemas.js +208 -231
  104. package/dist/session/phase-completion.validation.d.ts +2 -3
  105. package/dist/session/phase-completion.validation.js +49 -93
  106. package/dist/session/pre-publication-host-load.d.ts +27 -0
  107. package/dist/session/pre-publication-host-load.js +111 -0
  108. package/dist/session/pre-publication-pass.d.ts +61 -0
  109. package/dist/session/pre-publication-pass.js +148 -0
  110. package/dist/session/pre-publication-process.d.ts +3 -0
  111. package/dist/session/pre-publication-process.js +23 -11
  112. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  113. package/dist/session/pre-publication-step-execution.js +49 -0
  114. package/dist/session/pre-publication-validation.d.ts +32 -20
  115. package/dist/session/pre-publication-validation.js +195 -158
  116. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  117. package/dist/session/provider-cli/claude-background-work.js +180 -0
  118. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  119. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  120. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  121. package/dist/session/provider-cli/provider-cli.artifacts.js +20 -7
  122. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  123. package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
  124. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  125. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  126. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  127. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  128. package/dist/session/provider-cli/provider-cli.process.d.ts +39 -17
  129. package/dist/session/provider-cli/provider-cli.process.js +136 -345
  130. package/dist/session/provider-cli/provider-cli.prompts.d.ts +7 -0
  131. package/dist/session/provider-cli/provider-cli.prompts.js +65 -10
  132. package/dist/session/provider-cli/provider-cli.runtime.js +7 -0
  133. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  134. package/dist/session/provider-cli/provider-cli.service.js +142 -162
  135. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  136. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  137. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  138. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  139. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  140. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  141. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  142. package/dist/session/provider-cli/provider-output-state.d.ts +8 -0
  143. package/dist/session/provider-cli/provider-output-state.js +15 -0
  144. package/dist/session/publishable-worktree-changes.d.ts +10 -1
  145. package/dist/session/publishable-worktree-changes.js +21 -5
  146. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  147. package/dist/session/sandbox-host-capacity-gate.js +238 -0
  148. package/dist/session/session.base.d.ts +9 -1
  149. package/dist/session/session.service.d.ts +9 -2
  150. package/dist/session/session.service.js +120 -5
  151. package/dist/session/session.types.d.ts +3 -0
  152. package/dist/session/session.types.js +12 -3
  153. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  154. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  155. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  156. package/dist/shared/process/host-process-supervisor.js +1 -1
  157. package/dist/shared/process/process-tree.d.ts +52 -0
  158. package/dist/shared/process/process-tree.js +144 -0
  159. package/dist/shared/process/process.d.ts +67 -0
  160. package/dist/shared/process/process.js +213 -11
  161. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  162. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  163. package/dist/shared/process/windows-launch.d.ts +18 -0
  164. package/dist/shared/process/windows-launch.js +68 -0
  165. package/dist/shared/provider-capabilities.js +5 -6
  166. package/dist/version.d.ts +1 -1
  167. package/dist/version.js +1 -1
  168. package/dist/worktree/dependency-warmer.d.ts +25 -0
  169. package/dist/worktree/dependency-warmer.js +46 -10
  170. package/dist/worktree/worktree.service.d.ts +10 -1
  171. package/dist/worktree/worktree.service.js +42 -2
  172. package/dist/worktree/worktree.types.d.ts +7 -0
  173. package/package.json +2 -2
@@ -1,38 +1,240 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import readline from "node:readline";
3
+ import { systemWindowsProcessTable, windowsTicksFromEpochMs, WindowsProcessTree } from "./process-tree.js";
4
+ /**
5
+ * A command's process tree could not be proven gone after it was stopped.
6
+ * Whatever reserved capacity for it must keep that reservation.
7
+ */
8
+ export class ProcessTreeTerminationError extends Error {
9
+ rootPid;
10
+ command;
11
+ stillGone;
12
+ code = "process_tree_termination_unconfirmed";
13
+ /**
14
+ * `stillGone` resolves true once the tree is proven gone (Unix: an existence
15
+ * check only, since its members were already SIGKILLed; Windows: another
16
+ * tracked stop), for callers that hold the reservation until then.
17
+ */
18
+ constructor(rootPid, command, stillGone) {
19
+ super(`process_tree_termination_unconfirmed: ${command} (pid ${rootPid}) left processes that did not stop after SIGKILL; its host capacity stays reserved until they are gone.`);
20
+ this.rootPid = rootPid;
21
+ this.command = command;
22
+ this.stillGone = stillGone;
23
+ this.name = "ProcessTreeTerminationError";
24
+ }
25
+ }
26
+ /** Codes of every failure that means a process tree may still be running. */
27
+ const unprovenTerminationCodes = ["process_tree_termination_unconfirmed", "host_process_supervisor_termination_failed"];
28
+ /**
29
+ * True when `error`, or anything it wraps (an AggregateError's errors, a cause
30
+ * chain, a sanitized copy that kept only the message), says a process tree
31
+ * could not be proven gone. Whoever holds capacity for that tree must keep it.
32
+ */
33
+ export function isProcessTreeTerminationUnproven(error, depth = 0) {
34
+ if (depth > 8 || error === null || error === undefined)
35
+ return false;
36
+ if (error instanceof ProcessTreeTerminationError)
37
+ return true;
38
+ const message = error instanceof Error ? error.message : typeof error === "string" ? error : "";
39
+ if (unprovenTerminationCodes.some(code => message.includes(code)))
40
+ return true;
41
+ if (error instanceof AggregateError && error.errors.some(inner => isProcessTreeTerminationUnproven(inner, depth + 1)))
42
+ return true;
43
+ return error instanceof Error && isProcessTreeTerminationUnproven(error.cause, depth + 1);
44
+ }
3
45
  export class NodeProcessRunner {
46
+ graceMs;
47
+ killWaitMs;
48
+ platform;
49
+ windowsProcesses;
50
+ windowsTrackIntervalMs;
51
+ groupAlive;
52
+ constructor(options = {}) {
53
+ this.graceMs = options.terminationGraceMs ?? 5_000;
54
+ this.killWaitMs = options.killWaitMs ?? 10_000;
55
+ this.platform = options.platform ?? process.platform;
56
+ this.windowsProcesses = options.windowsProcesses ?? systemWindowsProcessTable;
57
+ this.windowsTrackIntervalMs = options.windowsTrackIntervalMs ?? 2_000;
58
+ this.groupAlive = options.groupAlive ?? groupExists;
59
+ }
4
60
  async run(request) {
61
+ if (request.signal?.aborted)
62
+ throw abortError(request.signal);
63
+ const tree = request.processGroup === true ? (this.platform === "win32" ? "windows" : "unix") : null;
64
+ // Taken before the spawn: the root is created no earlier than this (less clock and
65
+ // precision slack), which anchors its Windows tree even if it exits before a snapshot.
66
+ const spawnedNotBefore = windowsTicksFromEpochMs(Date.now() - 2_000);
5
67
  return await new Promise((resolve, reject) => {
6
68
  const child = spawn(request.command, request.args, {
7
69
  cwd: request.cwd,
8
70
  env: request.env,
9
71
  stdio: ["ignore", "pipe", "pipe"],
10
72
  windowsVerbatimArguments: request.windowsVerbatimArguments,
73
+ detached: tree === "unix",
74
+ });
75
+ const stdout = new OutputTail(request.maxOutputChars);
76
+ const stderr = new OutputTail(request.maxOutputChars);
77
+ let aborted = false;
78
+ let escalation = null;
79
+ let tracking = null;
80
+ // Resolves true once the tree is proven gone (trivially true without a tree).
81
+ let treeGone = Promise.resolve(true);
82
+ const windowsTree = tree === "windows" && child.pid
83
+ ? new WindowsProcessTree(child.pid, this.windowsProcesses, { notBefore: spawnedNotBefore })
84
+ : null;
85
+ const signalChild = (signal) => {
86
+ if (!child.pid)
87
+ return;
88
+ try {
89
+ process.kill(tree === "unix" ? -child.pid : child.pid, signal);
90
+ }
91
+ catch {
92
+ // ESRCH: already gone. Anything else surfaces as the child's own exit.
93
+ }
94
+ };
95
+ const onAbort = () => {
96
+ aborted = true;
97
+ if (windowsTree) {
98
+ // No signals on Windows: the tracked tree is stopped once the root exits.
99
+ void this.windowsProcesses.killTree(child.pid);
100
+ return;
101
+ }
102
+ signalChild("SIGTERM");
103
+ escalation = setTimeout(() => signalChild("SIGKILL"), this.graceMs);
104
+ escalation.unref?.();
105
+ };
106
+ const cleanup = () => {
107
+ request.signal?.removeEventListener("abort", onAbort);
108
+ if (escalation)
109
+ clearTimeout(escalation);
110
+ if (tracking)
111
+ clearInterval(tracking);
112
+ };
113
+ if (request.onSpawn)
114
+ child.once("spawn", () => { if (child.pid)
115
+ request.onSpawn(child.pid); });
116
+ if (windowsTree) {
117
+ void windowsTree.track();
118
+ tracking = setInterval(() => void windowsTree.track(), this.windowsTrackIntervalMs);
119
+ tracking.unref?.();
120
+ }
121
+ request.signal?.addEventListener("abort", onAbort, { once: true });
122
+ child.on("error", error => {
123
+ // A launch failure (ENOENT and the like): nothing is running.
124
+ if (child.pid === undefined) {
125
+ cleanup();
126
+ reject(error);
127
+ }
128
+ });
129
+ // The command itself ended. Members of its tree that outlive it (a daemon or an
130
+ // orphaned script holding the pipes open) are stopped, so "close" can follow.
131
+ child.once("exit", () => {
132
+ if (!child.pid)
133
+ return;
134
+ if (tree === "unix")
135
+ treeGone = stopUnixGroup(child.pid, this.graceMs, this.killWaitMs, this.groupAlive);
136
+ if (windowsTree) {
137
+ windowsTree.markRootExited();
138
+ treeGone = windowsTree.stop(Date.now() + this.graceMs + this.killWaitMs);
139
+ }
11
140
  });
12
- let stdout = "";
13
- let stderr = "";
14
- child.on("error", reject);
15
141
  const stdoutReader = request.rawOutput ? undefined : readline.createInterface({ input: child.stdout });
16
142
  const stderrReader = request.rawOutput ? undefined : readline.createInterface({ input: child.stderr });
17
143
  if (request.rawOutput) {
18
- child.stdout.setEncoding("utf8").on("data", chunk => { stdout += chunk; });
19
- child.stderr.setEncoding("utf8").on("data", chunk => { stderr += chunk; });
144
+ child.stdout.setEncoding("utf8").on("data", chunk => { stdout.append(chunk); });
145
+ child.stderr.setEncoding("utf8").on("data", chunk => { stderr.append(chunk); });
20
146
  }
21
147
  stdoutReader?.on("line", (line) => {
22
- stdout += `${line}\n`;
148
+ stdout.append(`${line}\n`);
23
149
  });
24
150
  stderrReader?.on("line", (line) => {
25
- stderr += `${line}\n`;
151
+ stderr.append(`${line}\n`);
26
152
  });
27
153
  child.on("close", (code) => {
28
154
  stdoutReader?.close();
29
155
  stderrReader?.close();
30
- resolve({
31
- exitCode: code ?? 1,
32
- stdout,
33
- stderr
156
+ void treeGone.then(gone => {
157
+ cleanup();
158
+ // Never settle as finished while part of the tree may still run.
159
+ if (!gone) {
160
+ const pid = child.pid;
161
+ reject(new ProcessTreeTerminationError(pid, request.command, windowsTree
162
+ ? async () => await windowsTree.stop(Date.now() + this.graceMs)
163
+ : async () => !this.groupAlive(pid)));
164
+ return;
165
+ }
166
+ if (aborted) {
167
+ reject(abortError(request.signal));
168
+ return;
169
+ }
170
+ const truncated = stdout.truncated || stderr.truncated;
171
+ resolve({
172
+ exitCode: code ?? 1,
173
+ stdout: stdout.value(),
174
+ stderr: stderr.value(),
175
+ ...truncated ? { outputTruncated: true } : {},
176
+ });
34
177
  });
35
178
  });
36
179
  });
37
180
  }
38
181
  }
182
+ /** Keeps the last `limit` characters of a stream; unbounded without a limit. */
183
+ class OutputTail {
184
+ limit;
185
+ text = "";
186
+ truncated = false;
187
+ constructor(limit) {
188
+ this.limit = limit;
189
+ }
190
+ append(chunk) {
191
+ this.text += chunk;
192
+ // Trimmed in batches, so a noisy stream costs amortized linear time.
193
+ if (this.limit !== undefined && this.text.length > 2 * this.limit)
194
+ this.trim();
195
+ }
196
+ value() {
197
+ if (this.limit !== undefined && this.text.length > this.limit)
198
+ this.trim();
199
+ return this.truncated
200
+ ? `[output truncated: only the last ${this.limit} characters are kept]\n${this.text}`
201
+ : this.text;
202
+ }
203
+ trim() {
204
+ this.text = this.text.slice(-this.limit);
205
+ this.truncated = true;
206
+ }
207
+ }
208
+ /**
209
+ * SIGTERM, then SIGKILL, to what is left of a process group. True once the
210
+ * group is empty; false when members survive the SIGKILL wait.
211
+ */
212
+ async function stopUnixGroup(groupId, graceMs, killWaitMs, alive) {
213
+ for (const [signal, waitMs] of [["SIGTERM", graceMs], ["SIGKILL", killWaitMs]]) {
214
+ if (!alive(groupId))
215
+ return true;
216
+ try {
217
+ process.kill(-groupId, signal);
218
+ }
219
+ catch {
220
+ // ESRCH: the group emptied meanwhile; checked below.
221
+ }
222
+ const deadline = Date.now() + waitMs;
223
+ while (alive(groupId) && Date.now() < deadline)
224
+ await new Promise(resolve => setTimeout(resolve, 20));
225
+ }
226
+ // The deadline is a failed proof, not a success: a member may still run.
227
+ return !alive(groupId);
228
+ }
229
+ function groupExists(groupId) {
230
+ try {
231
+ process.kill(-groupId, 0);
232
+ return true;
233
+ }
234
+ catch (error) {
235
+ return error.code === "EPERM";
236
+ }
237
+ }
238
+ function abortError(signal) {
239
+ return Object.assign(new Error("The operation was aborted", { cause: signal.reason }), { name: "AbortError", code: "ABORT_ERR" });
240
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Tools an agent commonly starts by bare name. When one of them resolves to a Microsoft Store
3
+ * app-execution alias (`%LOCALAPPDATA%\Microsoft\WindowsApps\pwsh.exe` and the like), Windows
4
+ * creates the process it starts outside the provider's Job Object: it survives the job, keeps the
5
+ * pipe handles it inherited, and holds the attempt's output open until it exits on its own.
6
+ */
7
+ export declare const APP_EXECUTION_ALIAS_SENSITIVE_TOOLS: readonly ["pwsh", "node", "dotnet"];
8
+ export interface AppExecutionAliasFinding {
9
+ readonly tool: string;
10
+ /** The alias the tool's bare name resolves to. */
11
+ readonly aliasPath: string;
12
+ /** The first regular install later on PATH, or null when the alias is the only one. */
13
+ readonly nextInstallPath: string | null;
14
+ }
15
+ /** The sensitive tools whose bare name resolves, on this PATH, to an app-execution alias. */
16
+ export declare function findAppExecutionAliasTools(pathValue: string, pathExtValue?: string, tools?: readonly string[]): AppExecutionAliasFinding[];
17
+ export declare function describeAppExecutionAliasFindings(findings: readonly AppExecutionAliasFinding[]): string | null;
18
+ /** Reads PATH and PATHEXT from an environment whose key case is not normalized (Windows: "Path"). */
19
+ export declare function appExecutionAliasWarning(env: Readonly<Record<string, string | undefined>>, platform?: NodeJS.Platform): string | null;
@@ -0,0 +1,45 @@
1
+ import { isWindowsAppExecutionAliasPath, resolveWindowsCommandFromPath } from "./windows-launch.js";
2
+ /**
3
+ * Tools an agent commonly starts by bare name. When one of them resolves to a Microsoft Store
4
+ * app-execution alias (`%LOCALAPPDATA%\Microsoft\WindowsApps\pwsh.exe` and the like), Windows
5
+ * creates the process it starts outside the provider's Job Object: it survives the job, keeps the
6
+ * pipe handles it inherited, and holds the attempt's output open until it exits on its own.
7
+ */
8
+ export const APP_EXECUTION_ALIAS_SENSITIVE_TOOLS = ["pwsh", "node", "dotnet"];
9
+ /** The sensitive tools whose bare name resolves, on this PATH, to an app-execution alias. */
10
+ export function findAppExecutionAliasTools(pathValue, pathExtValue, tools = APP_EXECUTION_ALIAS_SENSITIVE_TOOLS) {
11
+ const findings = [];
12
+ for (const tool of tools) {
13
+ const aliasPath = resolveWindowsCommandFromPath(tool, pathValue, pathExtValue);
14
+ if (!aliasPath || !isWindowsAppExecutionAliasPath(aliasPath))
15
+ continue;
16
+ const nextInstallPath = resolveWindowsCommandFromPath(tool, pathValue, pathExtValue, { skipAppExecutionAliases: true });
17
+ findings.push({ tool, aliasPath, nextInstallPath });
18
+ }
19
+ return findings;
20
+ }
21
+ export function describeAppExecutionAliasFindings(findings) {
22
+ if (findings.length === 0)
23
+ return null;
24
+ const tools = findings.map(finding => `${finding.tool} -> ${finding.aliasPath}${finding.nextInstallPath
25
+ ? ` (a regular install later on PATH: ${finding.nextInstallPath})`
26
+ : " (no regular install on PATH)"}`);
27
+ return "Host readiness warning: on the provider PATH, "
28
+ + `${tools.join("; ")} resolve${findings.length === 1 ? "s" : ""} to a Microsoft Store app-execution alias under WindowsApps. `
29
+ + "A process started through an alias is created outside the provider's Windows Job Object, survives it, "
30
+ + "and can hold the attempt's output pipes open until it exits. Install the tool normally "
31
+ + "(for PowerShell, the MSI under C:\\Program Files\\PowerShell\\7) and put it ahead of WindowsApps on PATH.";
32
+ }
33
+ /** Reads PATH and PATHEXT from an environment whose key case is not normalized (Windows: "Path"). */
34
+ export function appExecutionAliasWarning(env, platform = process.platform) {
35
+ if (platform !== "win32")
36
+ return null;
37
+ const pathValue = environmentValue(env, "PATH");
38
+ if (!pathValue)
39
+ return null;
40
+ return describeAppExecutionAliasFindings(findAppExecutionAliasTools(pathValue, environmentValue(env, "PATHEXT")));
41
+ }
42
+ function environmentValue(env, name) {
43
+ const key = Object.keys(env).find(candidate => candidate.toUpperCase() === name);
44
+ return key === undefined ? undefined : env[key];
45
+ }
@@ -6,3 +6,21 @@ export declare function buildWindowsCmdLaunch(command: string, args: readonly st
6
6
  export declare function buildWindowsLaunchCommand(commandPath: string, args: readonly string[]): LaunchCommand;
7
7
  export declare function windowsCommandLine(command: string, args: readonly string[]): string;
8
8
  export declare function quoteWindowsCommandLineArg(value: string): string;
9
+ export interface WindowsCommandPathOptions {
10
+ /**
11
+ * Skip candidates under a `WindowsApps` directory. Those are Microsoft Store app-execution
12
+ * aliases: the process they start is created outside the caller's Job Object, so it survives the
13
+ * job and keeps any inherited pipe open. Resolve the next real install on PATH instead.
14
+ */
15
+ readonly skipAppExecutionAliases?: boolean;
16
+ }
17
+ /**
18
+ * Resolves Windows commands without spawning where.exe. Runtime launches can
19
+ * happen while the machine is under enough process pressure for where.exe to
20
+ * miss its timeout; returning the unresolved package-manager name in that case
21
+ * makes Node fall back to a shell shim that cannot survive Job Object wrapping.
22
+ */
23
+ export declare function resolveWindowsCommandFromPath(command: string, pathValue?: string, pathExtValue?: string, options?: WindowsCommandPathOptions): string | null;
24
+ export declare function chooseWindowsCommandCandidate(candidates: readonly string[]): string | null;
25
+ /** True for a path inside a `WindowsApps` directory, where Store app-execution aliases live. */
26
+ export declare function isWindowsAppExecutionAliasPath(candidate: string): boolean;
@@ -1,3 +1,4 @@
1
+ import fs from "node:fs";
1
2
  import path from "node:path";
2
3
  export function buildWindowsCmdLaunch(command, args, comSpec = process.env.ComSpec) {
3
4
  const resolvedComSpec = comSpec?.trim();
@@ -39,3 +40,70 @@ function powershellExecutable() {
39
40
  ? path.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
40
41
  : "powershell.exe";
41
42
  }
43
+ /**
44
+ * Resolves Windows commands without spawning where.exe. Runtime launches can
45
+ * happen while the machine is under enough process pressure for where.exe to
46
+ * miss its timeout; returning the unresolved package-manager name in that case
47
+ * makes Node fall back to a shell shim that cannot survive Job Object wrapping.
48
+ */
49
+ export function resolveWindowsCommandFromPath(command, pathValue = process.env.PATH ?? "", pathExtValue = process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD", options = {}) {
50
+ if (!command || path.isAbsolute(command) || command.includes("/") || command.includes("\\")) {
51
+ return null;
52
+ }
53
+ const hasExtension = path.extname(command).length > 0;
54
+ const extensions = hasExtension
55
+ ? [""]
56
+ : [...new Set([
57
+ "",
58
+ ".exe",
59
+ ".ps1",
60
+ ".cmd",
61
+ ".bat",
62
+ ...pathExtValue.split(";").map(value => value.trim().toLowerCase()).filter(Boolean),
63
+ ])];
64
+ for (const rawDirectory of pathValue.split(path.delimiter)) {
65
+ const directory = rawDirectory.trim().replace(/^"|"$/gu, "");
66
+ if (!directory)
67
+ continue;
68
+ const candidates = [];
69
+ for (const extension of extensions) {
70
+ const candidate = path.join(directory, `${command}${extension}`);
71
+ if (options.skipAppExecutionAliases && isWindowsAppExecutionAliasPath(candidate))
72
+ continue;
73
+ if (pathEntryExists(candidate))
74
+ candidates.push(candidate);
75
+ }
76
+ const resolved = chooseWindowsCommandCandidate(candidates);
77
+ if (resolved)
78
+ return resolved;
79
+ }
80
+ return null;
81
+ }
82
+ export function chooseWindowsCommandCandidate(candidates) {
83
+ const normalized = candidates
84
+ .map((candidate) => candidate.trim())
85
+ .filter((candidate) => candidate.length > 0);
86
+ if (normalized.length === 0) {
87
+ return null;
88
+ }
89
+ const preferredExtensions = [".exe", ".ps1", ".cmd", ".bat", ""];
90
+ for (const extension of preferredExtensions) {
91
+ const candidate = normalized.find((entry) => path.extname(entry).toLowerCase() === extension);
92
+ if (candidate) {
93
+ return candidate;
94
+ }
95
+ }
96
+ return normalized[0];
97
+ }
98
+ /** True for a path inside a `WindowsApps` directory, where Store app-execution aliases live. */
99
+ export function isWindowsAppExecutionAliasPath(candidate) {
100
+ return candidate.split(/[\\/]+/u).some(segment => segment.toLowerCase() === "windowsapps");
101
+ }
102
+ // An app-execution alias is a reparse point that stat() may not open, so an
103
+ // alias is also accepted when only lstat() can see it.
104
+ function pathEntryExists(candidate) {
105
+ if (fs.existsSync(candidate))
106
+ return true;
107
+ return isWindowsAppExecutionAliasPath(candidate)
108
+ && fs.lstatSync(candidate, { throwIfNoEntry: false }) !== undefined;
109
+ }
@@ -40,8 +40,12 @@ function chatProviderEntries(cliProviders, providerStatuses) {
40
40
  const providerKind = provider.trim().toLowerCase();
41
41
  if (providerKind.length === 0)
42
42
  continue;
43
- statuses.set(providerKind, { providerKind, status });
43
+ statuses.set(providerKind, { status });
44
44
  }
45
+ // Only configured CLI providers can run a Bridge Chat turn. A status entry for a
46
+ // provider that is not in cliProviders (for example a leftover entry in
47
+ // bridge.json for a CLI that is no longer installed) annotates nothing and must
48
+ // not be advertised as a chat provider.
45
49
  const providers = new Map();
46
50
  for (const provider of cliProviders) {
47
51
  const providerKind = provider.trim().toLowerCase();
@@ -52,11 +56,6 @@ function chatProviderEntries(cliProviders, providerStatuses) {
52
56
  status: statuses.get(providerKind)?.status,
53
57
  });
54
58
  }
55
- for (const [providerKind, entry] of statuses) {
56
- if (!providers.has(providerKind)) {
57
- providers.set(providerKind, entry);
58
- }
59
- }
60
59
  return [...providers.values()].sort((left, right) => compareStable(left.providerKind, right.providerKind));
61
60
  }
62
61
  function sortedUniqueStrings(values, lower) {
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const forgeBridgeVersion = "0.1.4-dev.c2f22d1dd395";
1
+ export declare const forgeBridgeVersion = "0.1.4-dev.ccffca94938b";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const forgeBridgeVersion = "0.1.4-dev.c2f22d1dd395";
1
+ export const forgeBridgeVersion = "0.1.4-dev.ccffca94938b";
@@ -1,3 +1,5 @@
1
+ import type { HostLoadStepGate } from "../runtime/host-load-governor.js";
2
+ import type { HostLoadTokenPriority } from "../runtime/host-load-token-ledger.js";
1
3
  export type DependencyEcosystem = "node" | "dotnet" | "python";
2
4
  export interface WarmPathEntry {
3
5
  readonly relativePath: string;
@@ -10,6 +12,18 @@ export interface WarmDependenciesRequest {
10
12
  readonly allowedRoot: string;
11
13
  readonly warmPathOverrides?: readonly string[];
12
14
  readonly preparationPolicy?: DependencyPreparationPolicy;
15
+ /** Install fallbacks wait for host capacity first (decision 0013). */
16
+ readonly hostLoad?: DependencyInstallHostLoad;
17
+ /**
18
+ * The attempt's cancellation: a queued install stops waiting and a running one
19
+ * is stopped (its whole process group) before its host capacity is returned.
20
+ */
21
+ readonly signal?: AbortSignal;
22
+ }
23
+ export interface DependencyInstallHostLoad {
24
+ readonly gate: HostLoadStepGate;
25
+ readonly dispatchAttemptId: string | null;
26
+ readonly priority: HostLoadTokenPriority;
13
27
  }
14
28
  export interface DependencyPreparationPolicy {
15
29
  readonly isolation?: string;
@@ -45,6 +59,15 @@ export interface CommandExecutor {
45
59
  export interface CommandExecutionOptions {
46
60
  readonly env?: NodeJS.ProcessEnv;
47
61
  readonly windowsVerbatimArguments?: boolean;
62
+ /** Stops the install (a reclaimed host load token, decision 0013). */
63
+ readonly signal?: AbortSignal;
64
+ /** Called with the install's pid once it starts, so its token records the process. */
65
+ readonly onSpawn?: (pid: number) => void;
66
+ /**
67
+ * Unix: the install leads its own process group, which is stopped as a whole
68
+ * (on abort, and anything left once the install exits) before the run settles.
69
+ */
70
+ readonly processGroup?: boolean;
48
71
  }
49
72
  export declare function detectWarmPaths(repoRoot: string, warmPathOverrides?: readonly string[]): Promise<WarmPathEntry[]>;
50
73
  export declare function warmWorktreeDependencies(request: WarmDependenciesRequest, executor?: CommandExecutor): Promise<WarmDependenciesResult>;
@@ -82,3 +105,5 @@ export declare function unattendedDependencyEnvironment(env?: NodeJS.ProcessEnv)
82
105
  export declare function compactWindowsPackageManagerPath(pathValue: string, env?: NodeJS.ProcessEnv, options?: PackageManagerEnvironmentOptions): string;
83
106
  export declare function windowsPackageManagerLifecyclePathPrefix(packageRoot: string): string;
84
107
  export declare function windowsPackageManagerPathBudget(packageRoot: string): number;
108
+ /** Runs dependency installs; exported for tests. */
109
+ export declare const defaultCommandExecutor: CommandExecutor;
@@ -9,6 +9,9 @@ import { NodeProcessRunner } from "../shared/process/process.js";
9
9
  import { buildWindowsCmdLaunch } from "../shared/process/windows-launch.js";
10
10
  import { isSubPath } from "../shared/path/path.js";
11
11
  import { defaultWorktreeCoordinatorStateRoot } from "./worktree-paths.js";
12
+ import { dependencyInstallStepClass } from "../runtime/host-load-step-class.js";
13
+ import { runHostGovernedStep } from "../runtime/host-load-step-run.js";
14
+ import { captureHostProcessIdentity } from "../shared/process/host-process-supervisor.js";
12
15
  const SKIP_DIR_NAMES = new Set([
13
16
  ".git",
14
17
  "node_modules",
@@ -78,7 +81,7 @@ export async function warmWorktreeDependencies(request, executor = defaultComman
78
81
  continue;
79
82
  }
80
83
  installedNodeRoots.add(packageKey);
81
- const preparation = await ensureInstallFallback({ ...entry, packageRoot: installPackageRoot }, worktreePath, "Managed worktrees require isolated Node dependencies.", executor, request.preparationPolicy);
84
+ const preparation = await ensureInstallFallback({ ...entry, packageRoot: installPackageRoot }, worktreePath, "Managed worktrees require isolated Node dependencies.", executor, request.preparationPolicy, request.hostLoad, request.signal);
82
85
  receipts.push(preparation.receipt);
83
86
  if (preparation.install)
84
87
  fallbacks.push(preparation.install);
@@ -93,7 +96,7 @@ export async function warmWorktreeDependencies(request, executor = defaultComman
93
96
  continue;
94
97
  }
95
98
  restoredDotNetRoots.add(packageKey);
96
- const preparation = await ensureInstallFallback(entry, worktreePath, "Managed worktrees require isolated .NET build outputs.", executor, request.preparationPolicy);
99
+ const preparation = await ensureInstallFallback(entry, worktreePath, "Managed worktrees require isolated .NET build outputs.", executor, request.preparationPolicy, request.hostLoad, request.signal);
97
100
  receipts.push(preparation.receipt);
98
101
  if (preparation.install)
99
102
  fallbacks.push(preparation.install);
@@ -102,7 +105,7 @@ export async function warmWorktreeDependencies(request, executor = defaultComman
102
105
  const sourceExists = await directoryExists(sourcePath);
103
106
  const fallbackReason = await resolveFallbackReason(entry, baseCheckoutPath, worktreePath, sourceExists);
104
107
  if (fallbackReason) {
105
- const preparation = await ensureInstallFallback(entry, worktreePath, fallbackReason, executor, request.preparationPolicy);
108
+ const preparation = await ensureInstallFallback(entry, worktreePath, fallbackReason, executor, request.preparationPolicy, request.hostLoad, request.signal);
106
109
  receipts.push(preparation.receipt);
107
110
  if (preparation.install)
108
111
  fallbacks.push(preparation.install);
@@ -242,7 +245,7 @@ export async function lockfilesDiffer(baseCheckoutPath, worktreePath, packageRoo
242
245
  }
243
246
  return false;
244
247
  }
245
- async function ensureInstallFallback(entry, worktreePath, reason, executor, policy) {
248
+ async function ensureInstallFallback(entry, worktreePath, reason, executor, policy, hostLoad, signal) {
246
249
  const startedAt = performance.now();
247
250
  const cwd = path.resolve(worktreePath, entry.packageRoot === "." ? "" : entry.packageRoot);
248
251
  assertWithinRoot(path.resolve(worktreePath), cwd, "Dependency package root");
@@ -271,7 +274,32 @@ async function ensureInstallFallback(entry, worktreePath, reason, executor, poli
271
274
  },
272
275
  };
273
276
  }
274
- const install = await runInstallFallback(entry, worktreePath, reason, executor);
277
+ // Inside the per-root lock, and only on a real install: a verified receipt never queues.
278
+ const install = await runHostGovernedStep(hostLoad?.gate, {
279
+ classification: dependencyInstallStepClass,
280
+ label: `${command} (${entry.packageRoot})`,
281
+ dispatchAttemptId: hostLoad?.dispatchAttemptId ?? null,
282
+ priority: hostLoad?.priority ?? "foreground",
283
+ // Attempt cancellation ends the wait for capacity too.
284
+ signal,
285
+ }, async (_waitMs, hostLoadControl) => {
286
+ // The install stops when the attempt is cancelled, its token is lost, or its
287
+ // process group cannot be recorded on the token. The runner settles only once
288
+ // the whole group is gone, so the token is never returned while it still runs.
289
+ const unrecorded = new AbortController();
290
+ const stop = [signal, hostLoadControl.fenced, unrecorded.signal].filter((value) => value !== undefined);
291
+ return await runInstallFallback(entry, worktreePath, reason, executor, {
292
+ signal: AbortSignal.any(stop),
293
+ processGroup: true,
294
+ onSpawn: hostLoadControl.attachProcess
295
+ ? pid => void hostLoadControl.attachProcess({
296
+ rootPid: pid,
297
+ rootIdentity: captureHostProcessIdentity(pid),
298
+ processGroup: process.platform !== "win32",
299
+ }).catch((error) => unrecorded.abort(error))
300
+ : undefined,
301
+ });
302
+ });
275
303
  // npm is allowed to omit node_modules when the package graph is empty. Keep
276
304
  // an isolated, ignored output directory so the durable receipt still has a
277
305
  // concrete marker whose removal invalidates reuse.
@@ -449,7 +477,7 @@ async function persistDependencyPreparationReceipt(receiptPath, receipt) {
449
477
  function sha256Text(value) {
450
478
  return createHash("sha256").update(value).digest("hex");
451
479
  }
452
- async function runInstallFallback(entry, worktreePath, reason, executor) {
480
+ async function runInstallFallback(entry, worktreePath, reason, executor, control = {}) {
453
481
  assertHostDatabaseCapabilityBoundary();
454
482
  const cwd = path.join(worktreePath, entry.packageRoot === "." ? "" : entry.packageRoot);
455
483
  if (entry.ecosystem === "node") {
@@ -463,6 +491,7 @@ async function runInstallFallback(entry, worktreePath, reason, executor) {
463
491
  requiredPathDirectories: launch.requiredPathDirectories,
464
492
  }),
465
493
  windowsVerbatimArguments: launch.windowsVerbatimArguments,
494
+ ...control,
466
495
  });
467
496
  return { ecosystem: entry.ecosystem, packageRoot: entry.packageRoot, reason, command: `pnpm ${args.join(" ")}` };
468
497
  }
@@ -475,16 +504,17 @@ async function runInstallFallback(entry, worktreePath, reason, executor) {
475
504
  requiredPathDirectories: launch.requiredPathDirectories,
476
505
  }),
477
506
  windowsVerbatimArguments: launch.windowsVerbatimArguments,
507
+ ...control,
478
508
  });
479
509
  return { ecosystem: entry.ecosystem, packageRoot: entry.packageRoot, reason, command: `npm ${args.join(" ")}` };
480
510
  }
481
511
  if (entry.ecosystem === "python") {
482
512
  const environment = unattendedDependencyEnvironment();
483
- await executor.run(cwd, "python", ["-m", "venv", ".venv"], { env: environment });
513
+ await executor.run(cwd, "python", ["-m", "venv", ".venv"], { env: environment, ...control });
484
514
  const requirements = path.join(cwd, "requirements.txt");
485
515
  if (await pathExists(requirements)) {
486
516
  const pip = process.platform === "win32" ? path.join(".venv", "Scripts", "pip") : path.join(".venv", "bin", "pip");
487
- await executor.run(cwd, pip, ["install", "-r", "requirements.txt"], { env: environment });
517
+ await executor.run(cwd, pip, ["install", "-r", "requirements.txt"], { env: environment, ...control });
488
518
  return {
489
519
  ecosystem: entry.ecosystem,
490
520
  packageRoot: entry.packageRoot,
@@ -499,7 +529,7 @@ async function runInstallFallback(entry, worktreePath, reason, executor) {
499
529
  command: "python -m venv .venv"
500
530
  };
501
531
  }
502
- await executor.run(cwd, "dotnet", ["restore"], { env: unattendedDependencyEnvironment() });
532
+ await executor.run(cwd, "dotnet", ["restore"], { env: unattendedDependencyEnvironment(), ...control });
503
533
  return {
504
534
  ecosystem: entry.ecosystem,
505
535
  packageRoot: entry.packageRoot,
@@ -960,7 +990,8 @@ function defaultNpmCliCandidates(execPath, homeDir) {
960
990
  candidates.push("/usr/bin/npm", "/usr/local/bin/npm", path.join(homeDir, ".npm-global", "bin", "npm"), path.join(homeDir, ".npm-global", "lib", "node_modules", "npm", "bin", "npm-cli.js"));
961
991
  return candidates;
962
992
  }
963
- const defaultCommandExecutor = {
993
+ /** Runs dependency installs; exported for tests. */
994
+ export const defaultCommandExecutor = {
964
995
  async run(cwd, command, args, options) {
965
996
  const result = await defaultProcessRunner.run({
966
997
  command,
@@ -968,6 +999,11 @@ const defaultCommandExecutor = {
968
999
  args,
969
1000
  env: options?.env,
970
1001
  windowsVerbatimArguments: options?.windowsVerbatimArguments,
1002
+ signal: options?.signal,
1003
+ onSpawn: options?.onSpawn,
1004
+ processGroup: options?.processGroup,
1005
+ // Only a failure excerpt is ever reported; a noisy install keeps its last 1 MiB.
1006
+ maxOutputChars: 1024 * 1024,
971
1007
  });
972
1008
  if (result.exitCode !== 0) {
973
1009
  const output = formatCommandFailureOutput(result.stdout, result.stderr);