@loucompanion/forge-bridge 0.1.4-dev.8901ba056f68 → 0.1.4-dev.894bcbd53d64

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 (225) hide show
  1. package/README.md +142 -1
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +132 -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-state-file.d.ts +161 -0
  7. package/dist/bridge/bridge-state-file.js +376 -0
  8. package/dist/bridge/bridge-state-io.d.ts +11 -0
  9. package/dist/bridge/bridge-state-io.js +50 -0
  10. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  11. package/dist/bridge/bridge-state-lock.js +102 -0
  12. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  13. package/dist/bridge/bridge-state-unpublished.js +111 -0
  14. package/dist/bridge/bridge.base.d.ts +9 -0
  15. package/dist/bridge/bridge.service.d.ts +87 -14
  16. package/dist/bridge/bridge.service.js +394 -338
  17. package/dist/bridge/bridge.types.d.ts +16 -0
  18. package/dist/bridge/in-flight-registry.d.ts +62 -0
  19. package/dist/bridge/in-flight-registry.js +207 -0
  20. package/dist/bridge/local-yield-flag.d.ts +6 -0
  21. package/dist/bridge/local-yield-flag.js +34 -0
  22. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  23. package/dist/bridge/readiness-result-outbox.js +20 -0
  24. package/dist/bridge/runner-host-capabilities.d.ts +3 -0
  25. package/dist/bridge/runner-host-capabilities.js +13 -0
  26. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  27. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  28. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  29. package/dist/cleanup/cleanup-wip.js +66 -0
  30. package/dist/cleanup/cleanup.service.d.ts +20 -1
  31. package/dist/cleanup/cleanup.service.js +150 -169
  32. package/dist/cleanup/cleanup.types.d.ts +6 -0
  33. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  34. package/dist/cleanup/forge-owned-paths.js +53 -0
  35. package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
  36. package/dist/cleanup/host-runtime-ledger.js +130 -0
  37. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  38. package/dist/cleanup/managed-branch-sweep.js +111 -0
  39. package/dist/cli/cli.help.js +74 -12
  40. package/dist/cli/cli.service.d.ts +19 -10
  41. package/dist/cli/cli.service.js +149 -186
  42. package/dist/cli/idle-status.d.ts +84 -0
  43. package/dist/cli/idle-status.js +181 -0
  44. package/dist/cli/local-config.d.ts +6 -0
  45. package/dist/cli/local-config.js +32 -4
  46. package/dist/cli/provider-cli-detection.d.ts +10 -0
  47. package/dist/cli/provider-cli-detection.js +160 -0
  48. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  49. package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
  50. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  51. package/dist/runtime/attempt-node-runtime-launcher.js +9 -0
  52. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  53. package/dist/runtime/attempt-process-supervisor.js +12 -6
  54. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  55. package/dist/runtime/docker-engine-probe.js +7 -0
  56. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  57. package/dist/runtime/dotnet-build-outputs.js +402 -0
  58. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  59. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  60. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  61. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  62. package/dist/runtime/host-facts.d.ts +2 -1
  63. package/dist/runtime/host-load-admission.d.ts +18 -3
  64. package/dist/runtime/host-load-admission.js +19 -4
  65. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  66. package/dist/runtime/host-load-child-environment.js +22 -11
  67. package/dist/runtime/host-load-governor-config.d.ts +19 -1
  68. package/dist/runtime/host-load-governor-config.js +37 -0
  69. package/dist/runtime/host-load-governor.d.ts +14 -0
  70. package/dist/runtime/host-load-governor.js +139 -26
  71. package/dist/runtime/host-load-ledger-lock.js +6 -4
  72. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  73. package/dist/runtime/host-load-runtime-settings.js +80 -0
  74. package/dist/runtime/host-load-sampler.d.ts +34 -4
  75. package/dist/runtime/host-load-sampler.js +73 -7
  76. package/dist/runtime/host-load-step-class.d.ts +3 -1
  77. package/dist/runtime/host-load-step-class.js +60 -5
  78. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  79. package/dist/runtime/host-load-test-slot.js +81 -0
  80. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  81. package/dist/runtime/host-load-token-ledger.js +93 -61
  82. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  83. package/dist/runtime/host-load-windows-cpu.js +85 -0
  84. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  85. package/dist/runtime/host-runtime-contract.js +29 -1
  86. package/dist/runtime/host-runtime-lease.d.ts +59 -3
  87. package/dist/runtime/host-runtime-lease.js +212 -61
  88. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  89. package/dist/runtime/host-runtime-promotion.js +36 -0
  90. package/dist/runtime/managed-command-teardown.js +5 -16
  91. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  92. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  93. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  94. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  95. package/dist/runtime/runner-settings.d.ts +104 -0
  96. package/dist/runtime/runner-settings.js +236 -0
  97. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  98. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  99. package/dist/sandbox/host-capacity-broker.d.ts +10 -2
  100. package/dist/sandbox/host-capacity-broker.js +27 -6
  101. package/dist/sandbox/managed-branch.d.ts +13 -0
  102. package/dist/sandbox/managed-branch.js +90 -0
  103. package/dist/sandbox/provider-auth/codex.js +11 -11
  104. package/dist/sandbox/runtime.js +2 -6
  105. package/dist/session/architect-waits.d.ts +2 -0
  106. package/dist/session/architect-waits.js +138 -0
  107. package/dist/session/managed-attempt-tools.d.ts +2 -7
  108. package/dist/session/managed-attempt-tools.js +94 -104
  109. package/dist/session/managed-build-coordinator.d.ts +16 -0
  110. package/dist/session/managed-build-coordinator.js +10 -0
  111. package/dist/session/managed-build-receipt.d.ts +5 -0
  112. package/dist/session/managed-build-receipt.js +8 -3
  113. package/dist/session/managed-command-host-load.d.ts +2 -0
  114. package/dist/session/managed-command-host-load.js +2 -1
  115. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  116. package/dist/session/mcp-argument-coercion.js +121 -0
  117. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  118. package/dist/session/phase-completion.artifacts.js +96 -26
  119. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  120. package/dist/session/phase-completion.command-validation.js +77 -0
  121. package/dist/session/phase-completion.d.ts +10 -0
  122. package/dist/session/phase-completion.helpers.js +13 -12
  123. package/dist/session/phase-completion.js +5 -0
  124. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  125. package/dist/session/phase-completion.mcp-args.js +156 -0
  126. package/dist/session/phase-completion.prompts.js +6 -1
  127. package/dist/session/phase-completion.runtime.d.ts +4 -10
  128. package/dist/session/phase-completion.runtime.js +77 -209
  129. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  130. package/dist/session/phase-completion.schema-parts.js +188 -0
  131. package/dist/session/phase-completion.schemas.d.ts +3 -3
  132. package/dist/session/phase-completion.schemas.js +208 -231
  133. package/dist/session/phase-completion.validation.d.ts +2 -3
  134. package/dist/session/phase-completion.validation.js +49 -93
  135. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  136. package/dist/session/pre-publication-native-postgres.js +111 -0
  137. package/dist/session/pre-publication-pass.d.ts +61 -0
  138. package/dist/session/pre-publication-pass.js +148 -0
  139. package/dist/session/pre-publication-process.js +10 -10
  140. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  141. package/dist/session/pre-publication-step-execution.js +6 -5
  142. package/dist/session/pre-publication-validation.d.ts +30 -14
  143. package/dist/session/pre-publication-validation.js +207 -134
  144. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  145. package/dist/session/provider-cli/claude-background-work.js +181 -0
  146. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  147. package/dist/session/provider-cli/host-build-lock.js +30 -0
  148. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  149. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  150. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  151. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  152. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  153. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  154. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  155. package/dist/session/provider-cli/provider-cli.process.js +39 -430
  156. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  157. package/dist/session/provider-cli/provider-cli.prompts.js +72 -32
  158. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  159. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  160. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  161. package/dist/session/provider-cli/provider-cli.service.js +78 -171
  162. package/dist/session/provider-cli/provider-cli.types.d.ts +26 -0
  163. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  164. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  165. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  166. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  167. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  168. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  169. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  170. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  171. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  172. package/dist/session/provider-cli/provider-output-state.js +6 -0
  173. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  174. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  175. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  176. package/dist/session/qa-sidecar-validation.js +28 -0
  177. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  178. package/dist/session/sandbox-host-capacity-gate.js +42 -14
  179. package/dist/session/session-redaction.js +31 -181
  180. package/dist/session/session.base.d.ts +6 -1
  181. package/dist/session/session.service.d.ts +9 -2
  182. package/dist/session/session.service.js +169 -66
  183. package/dist/session/session.types.js +4 -4
  184. package/dist/session/sidecar-json-shape.d.ts +31 -0
  185. package/dist/session/sidecar-json-shape.js +217 -0
  186. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  187. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  188. package/dist/shared/fs/file-identity.d.ts +10 -0
  189. package/dist/shared/fs/file-identity.js +15 -0
  190. package/dist/shared/fs/replace-file.d.ts +7 -0
  191. package/dist/shared/fs/replace-file.js +33 -0
  192. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  193. package/dist/shared/process/host-process-recovery.js +23 -3
  194. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  195. package/dist/shared/process/host-process-supervisor.js +66 -14
  196. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  197. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  198. package/dist/shared/process/windows-launch.d.ts +18 -0
  199. package/dist/shared/process/windows-launch.js +68 -0
  200. package/dist/shared/provider-capabilities.js +14 -7
  201. package/dist/version.d.ts +1 -1
  202. package/dist/version.js +1 -1
  203. package/dist/worktree/orphan-relink.d.ts +19 -0
  204. package/dist/worktree/orphan-relink.js +106 -0
  205. package/dist/worktree/wip-git.d.ts +33 -0
  206. package/dist/worktree/wip-git.js +122 -0
  207. package/dist/worktree/wip-refs.d.ts +62 -0
  208. package/dist/worktree/wip-refs.js +119 -0
  209. package/dist/worktree/wip-restore.d.ts +38 -0
  210. package/dist/worktree/wip-restore.js +190 -0
  211. package/dist/worktree/wip-snapshot.d.ts +50 -0
  212. package/dist/worktree/wip-snapshot.js +268 -0
  213. package/dist/worktree/worktree-inputs.d.ts +8 -0
  214. package/dist/worktree/worktree-inputs.js +134 -0
  215. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  216. package/dist/worktree/worktree-origin-sync.js +127 -0
  217. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  218. package/dist/worktree/worktree-wip-events.js +98 -0
  219. package/dist/worktree/worktree-wip.d.ts +50 -0
  220. package/dist/worktree/worktree-wip.js +185 -0
  221. package/dist/worktree/worktree.base.d.ts +7 -1
  222. package/dist/worktree/worktree.service.d.ts +31 -5
  223. package/dist/worktree/worktree.service.js +120 -163
  224. package/dist/worktree/worktree.types.d.ts +31 -0
  225. package/package.json +2 -2
@@ -1,18 +1,14 @@
1
1
  import fs from "node:fs/promises";
2
- import { execFile } from "node:child_process";
3
2
  import os from "node:os";
4
3
  import path from "node:path";
5
4
  import { createInterface } from "node:readline/promises";
6
- import { promisify } from "node:util";
7
- import { resolveCursorAgentDirectLaunch } from "../shared/cursor-agent/cursor-agent.launch.js";
8
- import { buildWindowsCmdLaunch } from "../shared/process/windows-launch.js";
9
5
  import { configureDotNetToolchain } from "../shared/process/dotnet-toolchain.js";
10
6
  import { supportsDraftImageAttachmentsFor } from "../shared/provider-capabilities.js";
11
7
  import { redactText } from "../shared/redaction/redaction.js";
12
- import { defaultBridgeServiceConfig, ForgeBridgeService } from "../bridge/bridge.service.js";
8
+ import { BridgeRevokedError, bridgeRevokedExitCode, defaultBridgeServiceConfig, ForgeBridgeService, } from "../bridge/bridge.service.js";
13
9
  import { forgeBridgeVersion } from "../version.js";
14
10
  import { ManagedWorktreeCleanupService } from "../cleanup/cleanup.service.js";
15
- import { addRepoMapping, applyLocalConfigDefaults, providerStatusesFor, readLocalConfigSync, removeRepoMapping, resolveLocalConfigPath, setSandboxPolicy, setServerUrl, writeLocalConfig } from "./local-config.js";
11
+ import { addRepoMapping, applyLocalConfigDefaults, providerStatusesFor, readLocalConfigSync, removeRepoMapping, resolveLocalConfigPath, resolveLocalYieldFlagPath, setSandboxPolicy, setServerUrl, writeLocalConfig } from "./local-config.js";
16
12
  import { BridgeSessionService } from "../session/session.service.js";
17
13
  import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "../session/session-redaction.js";
18
14
  import { validateDockerfilePolicy, validateSandboxContract } from "../sandbox/contract.js";
@@ -22,8 +18,11 @@ import { DockerSandboxSmoke } from "../sandbox/smoke.js";
22
18
  import { parseCompletionMcpArgs, runCompletionMcpServer } from "../session/phase-completion.js";
23
19
  import { failureFactsFromError, failureResult, parseRunOnceDispatchPacket } from "../session/session.types.js";
24
20
  import { commandHelpText, helpText } from "./cli.help.js";
21
+ import { readLocalYieldFlag, writeLocalYieldFlag } from "../bridge/local-yield-flag.js";
22
+ import { detectCliProviders } from "./provider-cli-detection.js";
23
+ import { idleSummaryLine, parseStatusArgs, runIdleStatusCommand } from "./idle-status.js";
24
+ export { claudeDefaultModels, parseCodexModelCatalog, parseCursorModelList } from "./provider-cli-detection.js";
25
25
  const apiKeySecretGrantEnv = "FORGE_API_KEY_SECRET_GRANT";
26
- const execFileAsync = promisify(execFile);
27
26
  export class ForgeBridgeCliService {
28
27
  sessions;
29
28
  bridgeFactory;
@@ -91,11 +90,22 @@ export class ForgeBridgeCliService {
91
90
  if (config.cleanupWorktrees && config.repoMappings.some(mapping => mapping.localPath?.trim())) {
92
91
  io.stdout.write("Cleaning stale managed worktrees before accepting dispatches.\n");
93
92
  await cleanupRepos(config, "stale", true, this.cleanupFactory(config.sandboxStateRoot), io);
93
+ // Forge branches on this device whose work has merged since the bridge last ran.
94
+ await cleanupRepos(config, "merged", true, this.cleanupFactory(config.sandboxStateRoot), io);
94
95
  }
95
96
  io.stdout.write(connectStartupText(config));
96
97
  await this.bridgeFactory(config).run(controller.signal);
97
98
  return 0;
98
99
  }
100
+ catch (error) {
101
+ if (error instanceof BridgeRevokedError) {
102
+ // Decision 0014: removed from Forge. Exit with a distinct code so a supervisor can
103
+ // tell "pair again" apart from a crash.
104
+ io.stderr.write(`${error.message}\n`);
105
+ return bridgeRevokedExitCode;
106
+ }
107
+ throw error;
108
+ }
99
109
  finally {
100
110
  process.off("SIGINT", stop);
101
111
  process.off("SIGTERM", stop);
@@ -119,13 +129,22 @@ export class ForgeBridgeCliService {
119
129
  const current = readLocalConfigSync();
120
130
  io.stdout.write(`Pairing with server: ${args.serverUrl}\n`);
121
131
  const code = await resolvePairingCode(args.code);
122
- const repoRoot = await resolvePairRepoRoot(args.repoRoot, current.defaultRepoRoot);
123
- await fs.mkdir(repoRoot, { recursive: true });
124
- const pairArgs = await withDetectedPairCliProviders({ ...args, code, repoRoot });
132
+ const provisionalRoot = path.resolve(args.repoRoot ?? current.defaultRepoRoot ?? path.join(os.homedir(), "ForgeRepos"));
133
+ const pairArgs = await withDetectedPairCliProviders({ ...args, code, repoRoot: provisionalRoot });
125
134
  const claim = await this.pairRunner(pairArgs);
126
- const next = pairedConfig(current, pairArgs, claim);
127
- await writeLocalConfig(next);
128
- io.stdout.write(`Paired runner ${claim.runnerId}.\n`);
135
+ // The code is spent now: save the credentials before anything else can fail or prompt.
136
+ const applied = applyPairHost(pairArgs, claim.host, args.repoRoot !== undefined, io);
137
+ await writeLocalConfig(pairedConfig(current, applied.args, claim));
138
+ let repoRoot = applied.args.repoRoot;
139
+ if (!args.repoRoot && !applied.repoRootFromHost) {
140
+ const answered = await promptPairRepoRoot(repoRoot);
141
+ if (answered !== repoRoot) {
142
+ repoRoot = answered;
143
+ await writeLocalConfig(pairedConfig(current, { ...applied.args, repoRoot }, claim));
144
+ }
145
+ }
146
+ await fs.mkdir(repoRoot, { recursive: true });
147
+ io.stdout.write(`Paired runner ${claim.runnerId}${applied.args.name ? ` (${applied.args.name})` : ""}.\n`);
129
148
  io.stdout.write(`Repo folder: ${repoRoot}\n`);
130
149
  io.stdout.write(`Config: ${resolveLocalConfigPath()}\n`);
131
150
  io.stdout.write("Start the bridge with: forge-bridge connect\n");
@@ -174,8 +193,7 @@ export class ForgeBridgeCliService {
174
193
  }
175
194
  }
176
195
  if (args.command === "status") {
177
- await writeStatus(args.config, args.checkUpdates, io);
178
- return 0;
196
+ return await runStatus(args, io);
179
197
  }
180
198
  if (args.command === "cleanup") {
181
199
  return await cleanupRepos(args.config, args.mode, args.force, this.cleanupFactory(args.config.sandboxStateRoot), io);
@@ -208,6 +226,9 @@ export class ForgeBridgeCliService {
208
226
  writeSandboxPolicyStatus(readLocalConfigSync(), io);
209
227
  return 0;
210
228
  }
229
+ if (args.command === "yield") {
230
+ return await runYieldCommand(args.action, io);
231
+ }
211
232
  if (args.command === "mcp") {
212
233
  const parsed = parseCompletionMcpArgs(args.argv);
213
234
  if (!parsed.ok) {
@@ -245,6 +266,36 @@ export class ForgeBridgeCliService {
245
266
  }
246
267
  }
247
268
  }
269
+ /**
270
+ * Decision 0014 `forge-bridge yield`: the host's own yield switch. It writes a
271
+ * flag file next to the bridge config (never bridge.json); a running bridge
272
+ * polls it and stops taking new attempts without a restart.
273
+ */
274
+ async function runYieldCommand(action, io) {
275
+ const flagPath = resolveLocalYieldFlagPath();
276
+ try {
277
+ if (action !== "status") {
278
+ await writeLocalYieldFlag(flagPath, action === "on");
279
+ }
280
+ const on = await readLocalYieldFlag(flagPath);
281
+ if (action === "on") {
282
+ io.stdout.write("Local yield to foreground is on. A running bridge takes no new attempts within one heartbeat; running attempts finish.\n");
283
+ }
284
+ else if (action === "off") {
285
+ io.stdout.write("Local yield to foreground is off. The bridge takes new attempts again unless yield is on in Forge.\n");
286
+ }
287
+ else {
288
+ io.stdout.write(`Local yield to foreground: ${on ? "on" : "off"}\n`);
289
+ }
290
+ io.stdout.write(`Flag file: ${flagPath}\n`);
291
+ io.stdout.write("The effective state also depends on Forge: the runner yields when this flag or its Yield toggle in Forge is on.\n");
292
+ return 0;
293
+ }
294
+ catch (error) {
295
+ io.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
296
+ return 1;
297
+ }
298
+ }
248
299
  function attachEnvSecretGrant(dispatch) {
249
300
  if (!dispatch.execution.requiresApiKeySecretGrant) {
250
301
  delete process.env[apiKeySecretGrantEnv];
@@ -327,17 +378,7 @@ export function parseArgs(argv) {
327
378
  return { ok: false, error: "Usage: forge-bridge server <show|set <url>>" };
328
379
  }
329
380
  if (argv[0] === "status") {
330
- let checkUpdates = false;
331
- for (let index = 1; index < argv.length; index += 1) {
332
- const arg = argv[index];
333
- if (arg === "--check-updates") {
334
- checkUpdates = true;
335
- }
336
- else {
337
- return { ok: false, error: `Unknown argument: ${arg}` };
338
- }
339
- }
340
- return { ok: true, command: "status", config: configuredBridgeServiceConfig(), checkUpdates };
381
+ return parseStatusArgs(argv, configuredBridgeServiceConfig);
341
382
  }
342
383
  if (argv[0] === "cleanup") {
343
384
  return parseCleanupArgs(argv);
@@ -348,6 +389,13 @@ export function parseArgs(argv) {
348
389
  if (argv[0] === "sandbox") {
349
390
  return parseSandboxArgs(argv);
350
391
  }
392
+ if (argv[0] === "yield") {
393
+ const action = argv[1] ?? "status";
394
+ if (argv.length > 2 || (action !== "on" && action !== "off" && action !== "status")) {
395
+ return { ok: false, error: "Usage: forge-bridge yield [on|off|status]" };
396
+ }
397
+ return { ok: true, command: "yield", action };
398
+ }
351
399
  if (argv[0] !== "run-once") {
352
400
  return {
353
401
  ok: false,
@@ -761,6 +809,7 @@ function parsePairArgs(argv) {
761
809
  repoRoot: repoRoot?.trim() ? path.resolve(repoRoot) : undefined,
762
810
  cleanupWorktrees: cleanupWorktrees ?? defaultConfig.cleanupWorktrees,
763
811
  cliProviders: cliProviders.length > 0 ? cliProviders : localConfig.cliProviders && localConfig.cliProviders.length > 0 ? [...localConfig.cliProviders] : ["codex"],
812
+ cliProvidersFromFlag: cliProviders.length > 0,
764
813
  projectLabels: projectLabels.length > 0 ? projectLabels : localConfig.projectLabels ? [...localConfig.projectLabels] : []
765
814
  };
766
815
  }
@@ -823,9 +872,71 @@ async function claimBridgeRunner(args) {
823
872
  }
824
873
  return {
825
874
  runnerId: value.runnerId,
826
- deviceToken: value.deviceToken
875
+ deviceToken: value.deviceToken,
876
+ host: parsePairRunnerHost(value.host)
827
877
  };
828
878
  }
879
+ function parsePairRunnerHost(value) {
880
+ if (!value || typeof value !== "object") {
881
+ return undefined;
882
+ }
883
+ const host = value;
884
+ const name = typeof host.name === "string" && host.name.trim() ? host.name.trim() : undefined;
885
+ const repoRoot = typeof host.repoRoot === "string" && host.repoRoot.trim() ? host.repoRoot.trim() : undefined;
886
+ const cliProviders = Array.isArray(host.cliProviders)
887
+ ? host.cliProviders.filter((provider) => typeof provider === "string" && provider.trim().length > 0)
888
+ : [];
889
+ return { name, repoRoot, cliProviders: cliProviders.length > 0 ? cliProviders : undefined };
890
+ }
891
+ /**
892
+ * Decision 0014 §5: the claim's host block carries what the Connect dialog chose. The runner name
893
+ * is the server's; providers and the repo folder apply unless a flag named them on this command line.
894
+ */
895
+ function applyPairHost(args, host, repoRootFromFlag, io) {
896
+ if (!host) {
897
+ return { args, repoRootFromHost: false };
898
+ }
899
+ let repoRoot = args.repoRoot;
900
+ let repoRootFromHost = false;
901
+ if (host.repoRoot && !repoRootFromFlag) {
902
+ const resolved = resolveHostRepoRoot(host.repoRoot);
903
+ if (!resolved) {
904
+ io.stderr.write(`Ignoring the repo folder chosen in Forge (${host.repoRoot}): it is not a path on this machine.\n`);
905
+ }
906
+ else {
907
+ repoRootFromHost = true;
908
+ repoRoot = resolved;
909
+ }
910
+ }
911
+ return {
912
+ args: {
913
+ ...args,
914
+ name: host.name ?? args.name,
915
+ cliProviders: host.cliProviders && !args.cliProvidersFromFlag ? [...host.cliProviders] : args.cliProviders,
916
+ repoRoot
917
+ },
918
+ repoRootFromHost
919
+ };
920
+ }
921
+ /** Expands `~` in a repo folder chosen in Forge and rejects one shaped for another OS. */
922
+ export function resolveHostRepoRoot(value, platform = process.platform, home = os.homedir()) {
923
+ const trimmed = value.trim();
924
+ if (!trimmed) {
925
+ return undefined;
926
+ }
927
+ const pathApi = platform === "win32" ? path.win32 : path.posix;
928
+ if (trimmed === "~") {
929
+ return home;
930
+ }
931
+ if (/^~[\\/]/.test(trimmed)) {
932
+ return pathApi.resolve(home, trimmed.slice(2));
933
+ }
934
+ const windowsShaped = /^[A-Za-z]:[\\/]/.test(trimmed) || trimmed.startsWith("\\\\");
935
+ if (platform === "win32") {
936
+ return windowsShaped || trimmed.startsWith("/") ? pathApi.resolve(trimmed) : undefined;
937
+ }
938
+ return !windowsShaped && trimmed.startsWith("/") ? pathApi.resolve(trimmed) : undefined;
939
+ }
829
940
  function pairedConfig(current, args, claim) {
830
941
  return {
831
942
  ...current,
@@ -870,11 +981,7 @@ async function resolvePairingCode(code) {
870
981
  prompt.close();
871
982
  }
872
983
  }
873
- async function resolvePairRepoRoot(repoRoot, configuredRoot) {
874
- const fallback = path.resolve(repoRoot ?? configuredRoot ?? path.join(os.homedir(), "ForgeRepos"));
875
- if (repoRoot?.trim()) {
876
- return fallback;
877
- }
984
+ async function promptPairRepoRoot(fallback) {
878
985
  if (!process.stdin.isTTY || !process.stdout.isTTY) {
879
986
  return fallback;
880
987
  }
@@ -945,6 +1052,9 @@ async function writeJsonAtomic(outputPath, value) {
945
1052
  await fs.writeFile(tempPath, `${JSON.stringify(value, null, 2)}\n`, "utf8");
946
1053
  await fs.rename(tempPath, outputPath);
947
1054
  }
1055
+ async function runStatus(args, io) {
1056
+ return args.idle ? await runIdleStatusCommand(args.idle, io) : await writeStatus(args.config, args.checkUpdates, io);
1057
+ }
948
1058
  async function writeStatus(config, checkUpdates, io) {
949
1059
  const detected = await detectCliProviders([...new Set([...config.cliProviders, "codex", "cursor", "claude"])]);
950
1060
  const repos = config.repoMappings.filter((mapping) => mapping.localPath?.trim());
@@ -953,7 +1063,7 @@ async function writeStatus(config, checkUpdates, io) {
953
1063
  io.stdout.write(`Server: ${config.serverUrl || "not configured"}\n`);
954
1064
  io.stdout.write(`Device: ${config.runnerId || "not configured"}${config.deviceName ? ` (${config.deviceName})` : ""}\n`);
955
1065
  io.stdout.write(`Device token: ${config.deviceToken ? "configured" : "missing"}\n`);
956
- io.stdout.write(`Active sessions: 0\n`);
1066
+ io.stdout.write(`${await idleSummaryLine()}\n`);
957
1067
  io.stdout.write("Repos:\n");
958
1068
  if (repos.length === 0) {
959
1069
  io.stdout.write(" none\n");
@@ -971,6 +1081,7 @@ async function writeStatus(config, checkUpdates, io) {
971
1081
  if (checkUpdates) {
972
1082
  io.stdout.write("Update check: no update channel configured.\n");
973
1083
  }
1084
+ return 0;
974
1085
  }
975
1086
  async function cleanupRepos(config, mode, force, cleanup, io) {
976
1087
  const repos = config.repoMappings.filter((mapping) => mapping.localPath?.trim());
@@ -1003,7 +1114,11 @@ async function cleanupRepos(config, mode, force, cleanup, io) {
1003
1114
  io.stdout.write(`Removed ${result.removedWorktrees} stale managed ${result.removedWorktrees === 1 ? "worktree" : "worktrees"} from ${result.worktreeRoot}\n`);
1004
1115
  }
1005
1116
  else {
1006
- io.stdout.write(`Pruned stale worktree metadata for ${repoPath}\n`);
1117
+ const deleted = result.deletedBranches ?? 0;
1118
+ io.stdout.write(`Pruned stale worktree metadata and deleted ${deleted} Forge ${deleted === 1 ? "branch" : "branches"} (merged work and leftover readiness probes) in ${repoPath}\n`);
1119
+ if (result.mergedBaseUnresolved) {
1120
+ io.stderr.write(`${repoPath}: merged work branches were kept because the base branch couldn't be determined: origin/HEAD is unset or names a branch that no longer exists, and origin has none or more than one of develop, main and master. Run \`git fetch origin && git remote set-head origin --auto\`.\n`);
1121
+ }
1007
1122
  }
1008
1123
  }
1009
1124
  catch (error) {
@@ -1013,158 +1128,6 @@ async function cleanupRepos(config, mode, force, cleanup, io) {
1013
1128
  }
1014
1129
  return failures === 0 ? 0 : 1;
1015
1130
  }
1016
- async function detectCliProviders(providers) {
1017
- const results = [];
1018
- for (const provider of providers) {
1019
- let detected = null;
1020
- for (const probe of cliProbeCommandsFor(provider)) {
1021
- try {
1022
- detected = await execVersionCommand(probe, probe.timeoutMs);
1023
- break;
1024
- }
1025
- catch {
1026
- // Try the next provider-specific probe.
1027
- }
1028
- }
1029
- results.push({
1030
- provider,
1031
- found: detected !== null,
1032
- version: detected ? versionLine(`${detected.stdout || detected.stderr}`) : "",
1033
- models: detected ? await detectCliModels(provider) : []
1034
- });
1035
- }
1036
- return results;
1037
- }
1038
- function cliProbeCommandsFor(provider) {
1039
- const normalized = provider.toLowerCase();
1040
- if (normalized === "codex") {
1041
- return [
1042
- { command: "codex", args: ["-V"] },
1043
- { command: "codex", args: ["--version"] }
1044
- ];
1045
- }
1046
- if (normalized === "claude") {
1047
- return [
1048
- // Claude Code's Node startup can exceed the default 2s probe on a cold Windows host.
1049
- { command: "claude", args: ["--version"], timeoutMs: 8000 },
1050
- { command: "claude", args: ["-v"], timeoutMs: 8000 }
1051
- ];
1052
- }
1053
- if (normalized === "cursor") {
1054
- return [
1055
- { command: "cursor-agent", args: ["-v"] },
1056
- { command: "agent", args: ["-v"] },
1057
- { command: "cursor-agent", args: ["--version"] },
1058
- { command: "agent", args: ["--version"] }
1059
- ];
1060
- }
1061
- return [
1062
- { command: provider, args: ["--version"] },
1063
- { command: provider, args: ["-V"] }
1064
- ];
1065
- }
1066
- async function execVersionCommand(probe, timeout = 2000, maxBuffer) {
1067
- const directLaunch = process.platform === "win32"
1068
- ? await resolveCursorAgentDirectLaunch(probe.command, probe.args)
1069
- : null;
1070
- if (directLaunch) {
1071
- return await execFileAsync(directLaunch.command, [...directLaunch.args], { timeout, maxBuffer });
1072
- }
1073
- try {
1074
- return await execFileAsync(probe.command, probe.args, { timeout, maxBuffer });
1075
- }
1076
- catch (error) {
1077
- if (process.platform !== "win32") {
1078
- throw error;
1079
- }
1080
- const launch = buildWindowsCmdLaunch(probe.command, probe.args);
1081
- return await execFileAsync(launch.command, [...launch.args], { timeout, maxBuffer });
1082
- }
1083
- }
1084
- function versionLine(output) {
1085
- const lines = output
1086
- .trim()
1087
- .split(/\r?\n/)
1088
- .map((line) => line.trim())
1089
- .filter((line) => line.length > 0);
1090
- return lines.at(-1) ?? "";
1091
- }
1092
- async function detectCliModels(provider) {
1093
- const normalized = provider.toLowerCase();
1094
- try {
1095
- if (normalized === "codex") {
1096
- // Windows installs codex as a .cmd shim, which execFile cannot launch directly.
1097
- const result = await execVersionCommand({ command: "codex", args: ["debug", "models"] }, 10_000, 10 * 1024 * 1024);
1098
- return parseCodexModelCatalog(result.stdout);
1099
- }
1100
- if (normalized === "cursor") {
1101
- const result = await execVersionCommand({ command: "cursor-agent", args: ["models"] }, 10_000);
1102
- return parseCursorModelList(`${result.stdout || result.stderr}`);
1103
- }
1104
- if (normalized === "claude") {
1105
- // Claude Code has no model-listing command; it accepts these aliases and full model IDs.
1106
- const configured = splitCsv(process.env.FORGE_CLAUDE_MODELS ?? "");
1107
- return configured.length > 0 ? configured : [...claudeDefaultModels];
1108
- }
1109
- }
1110
- catch {
1111
- return [];
1112
- }
1113
- return [];
1114
- }
1115
- export const claudeDefaultModels = ["sonnet", "opus", "haiku"];
1116
- export function parseCodexModelCatalog(raw) {
1117
- try {
1118
- const parsed = JSON.parse(raw);
1119
- if (!isRecord(parsed) || !Array.isArray(parsed.models)) {
1120
- return [];
1121
- }
1122
- const entries = parsed.models
1123
- .map((entry, index) => {
1124
- if (!isRecord(entry) || typeof entry.slug !== "string") {
1125
- return null;
1126
- }
1127
- const visibility = typeof entry.visibility === "string" ? entry.visibility.toLowerCase() : "list";
1128
- if (visibility !== "list") {
1129
- return null;
1130
- }
1131
- const priority = typeof entry.priority === "number" && Number.isFinite(entry.priority) ? entry.priority : index;
1132
- return { slug: entry.slug, priority, index };
1133
- })
1134
- .filter((entry) => entry !== null)
1135
- .sort((left, right) => left.priority - right.priority || left.index - right.index)
1136
- .map((entry) => entry.slug);
1137
- return uniqueModels(entries);
1138
- }
1139
- catch {
1140
- return [];
1141
- }
1142
- }
1143
- export function parseCursorModelList(raw) {
1144
- return uniqueModels(raw
1145
- .split(/\r?\n/)
1146
- .map((line) => line.trim())
1147
- .filter((line) => line.length > 0 && !line.toLowerCase().startsWith("available models"))
1148
- .map((line) => line.split(/\s+-\s+/, 1)[0]?.trim() ?? "")
1149
- .filter((model) => model.length > 0));
1150
- }
1151
- function uniqueModels(models) {
1152
- const seen = new Set();
1153
- const result = [];
1154
- for (const model of models) {
1155
- const trimmed = model.trim();
1156
- const key = trimmed.toLowerCase();
1157
- if (!trimmed || seen.has(key)) {
1158
- continue;
1159
- }
1160
- seen.add(key);
1161
- result.push(trimmed);
1162
- }
1163
- return result;
1164
- }
1165
- function isRecord(value) {
1166
- return typeof value === "object" && value !== null;
1167
- }
1168
1131
  async function withDetectedCliProviders(config, candidates = config.cliProviders) {
1169
1132
  const detected = await detectCliProviders(uniqueProviders(candidates));
1170
1133
  const found = detected.filter((result) => result.found);
@@ -0,0 +1,84 @@
1
+ import { type BridgeIdleEvaluation, type BridgeStateRead } from "../bridge/bridge-state-file.js";
2
+ import { type InFlightEntry } from "../bridge/in-flight-registry.js";
3
+ import type { BridgeServiceConfig } from "../bridge/bridge.types.js";
4
+ import type { CliIo } from "./cli.base.js";
5
+ export interface IdleStatusOptions {
6
+ readonly json: boolean;
7
+ /** Seconds to keep polling while the bridge is busy, stale or not yet yielding; 0 (or no --wait) checks once. */
8
+ readonly waitSeconds: number;
9
+ /** Idle counts only once the bridge itself reports yield (exit 5 until then). */
10
+ readonly requireYield: boolean;
11
+ }
12
+ export type StatusArgs = {
13
+ readonly ok: true;
14
+ readonly command: "status";
15
+ readonly config: BridgeServiceConfig;
16
+ readonly checkUpdates: boolean;
17
+ readonly idle: IdleStatusOptions | null;
18
+ } | {
19
+ readonly ok: false;
20
+ readonly error: string;
21
+ };
22
+ export declare function parseStatusArgs(argv: readonly string[], config: () => BridgeServiceConfig): StatusArgs;
23
+ export interface IdleStatusDependencies {
24
+ readonly statePath: string;
25
+ readonly now: () => number;
26
+ readonly pidAlive: (pid: number) => boolean;
27
+ readonly read: (statePath: string) => Promise<BridgeStateRead>;
28
+ readonly localYield: () => Promise<boolean>;
29
+ readonly sleep: (ms: number) => Promise<void>;
30
+ readonly pollMs: number;
31
+ }
32
+ export declare function defaultIdleStatusDependencies(): IdleStatusDependencies;
33
+ export declare function runIdleStatusCommand(options: IdleStatusOptions, io: CliIo, deps?: IdleStatusDependencies): Promise<number>;
34
+ /** One line for plain `forge-bridge status`. */
35
+ export declare function idleSummaryLine(deps?: IdleStatusDependencies): Promise<string>;
36
+ export declare function idleStatusJson(evaluation: BridgeIdleEvaluation, deps: Pick<IdleStatusDependencies, "statePath" | "now">, localYield: boolean): {
37
+ pid: null;
38
+ runnerId: null;
39
+ runnerInstanceId: null;
40
+ version: null;
41
+ state: null;
42
+ startedAt: null;
43
+ updatedAt: null;
44
+ connected: null;
45
+ yielding: null;
46
+ yieldApplied: null;
47
+ conflict: null;
48
+ inFlight: readonly InFlightEntry[];
49
+ schemaVersion: number;
50
+ verdict: import("../bridge/bridge-state-file.js").BridgeIdleVerdict;
51
+ idle: boolean;
52
+ exitCode: number;
53
+ reason: string;
54
+ statePath: string;
55
+ checkedAt: string;
56
+ pidAlive: boolean | null;
57
+ heartbeatAgeMs: number | null;
58
+ staleAfterMs: number;
59
+ localYield: boolean;
60
+ } | {
61
+ pid: number;
62
+ runnerId: string;
63
+ runnerInstanceId: string;
64
+ version: string;
65
+ state: "running" | "stopped";
66
+ startedAt: string;
67
+ updatedAt: string;
68
+ connected: boolean;
69
+ yielding: boolean;
70
+ yieldApplied: boolean;
71
+ conflict: import("../bridge/bridge-state-file.js").BridgeStateConflict | null;
72
+ inFlight: readonly InFlightEntry[];
73
+ schemaVersion: number;
74
+ verdict: import("../bridge/bridge-state-file.js").BridgeIdleVerdict;
75
+ idle: boolean;
76
+ exitCode: number;
77
+ reason: string;
78
+ statePath: string;
79
+ checkedAt: string;
80
+ pidAlive: boolean | null;
81
+ heartbeatAgeMs: number | null;
82
+ staleAfterMs: number;
83
+ localYield: boolean;
84
+ };