@loucompanion/forge-bridge 0.1.4-dev.83728c550770 → 0.1.4-dev.866b33be3065

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 (104) hide show
  1. package/README.md +32 -0
  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.service.d.ts +1 -1
  7. package/dist/bridge/bridge.service.js +4 -110
  8. package/dist/bridge/runner-host-capabilities.d.ts +3 -0
  9. package/dist/bridge/runner-host-capabilities.js +13 -0
  10. package/dist/cli/cli.service.d.ts +11 -0
  11. package/dist/cli/cli.service.js +80 -12
  12. package/dist/cli/local-config.d.ts +2 -0
  13. package/dist/cli/local-config.js +19 -3
  14. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  15. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  16. package/dist/runtime/docker-engine-probe.js +7 -0
  17. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  18. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  19. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  20. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  21. package/dist/runtime/host-facts.d.ts +2 -1
  22. package/dist/runtime/host-load-admission.d.ts +9 -2
  23. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  24. package/dist/runtime/host-load-child-environment.js +19 -10
  25. package/dist/runtime/host-load-governor-config.d.ts +10 -1
  26. package/dist/runtime/host-load-governor-config.js +7 -0
  27. package/dist/runtime/host-load-governor.d.ts +10 -0
  28. package/dist/runtime/host-load-governor.js +125 -34
  29. package/dist/runtime/host-load-sampler.d.ts +34 -4
  30. package/dist/runtime/host-load-sampler.js +73 -7
  31. package/dist/runtime/host-load-step-class.d.ts +3 -1
  32. package/dist/runtime/host-load-step-class.js +60 -5
  33. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  34. package/dist/runtime/host-load-test-slot.js +81 -0
  35. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  36. package/dist/runtime/host-load-token-ledger.js +93 -61
  37. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  38. package/dist/runtime/host-load-windows-cpu.js +85 -0
  39. package/dist/runtime/host-runtime-lease.d.ts +2 -2
  40. package/dist/runtime/host-runtime-lease.js +9 -8
  41. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  42. package/dist/runtime/host-runtime-promotion.js +36 -0
  43. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  44. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  45. package/dist/sandbox/host-capacity-broker.d.ts +7 -1
  46. package/dist/sandbox/host-capacity-broker.js +23 -4
  47. package/dist/session/architect-waits.d.ts +2 -0
  48. package/dist/session/architect-waits.js +138 -0
  49. package/dist/session/managed-attempt-tools.d.ts +0 -7
  50. package/dist/session/managed-attempt-tools.js +51 -62
  51. package/dist/session/managed-command-host-load.d.ts +2 -0
  52. package/dist/session/managed-command-host-load.js +2 -1
  53. package/dist/session/phase-completion.artifacts.js +2 -1
  54. package/dist/session/phase-completion.runtime.js +1 -1
  55. package/dist/session/phase-completion.schemas.js +25 -23
  56. package/dist/session/phase-completion.validation.js +3 -1
  57. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  58. package/dist/session/pre-publication-native-postgres.js +111 -0
  59. package/dist/session/pre-publication-pass.d.ts +61 -0
  60. package/dist/session/pre-publication-pass.js +148 -0
  61. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  62. package/dist/session/pre-publication-step-execution.js +6 -5
  63. package/dist/session/pre-publication-validation.d.ts +30 -14
  64. package/dist/session/pre-publication-validation.js +207 -134
  65. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  66. package/dist/session/provider-cli/claude-background-work.js +180 -0
  67. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  68. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  69. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  70. package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
  71. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  72. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  73. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  74. package/dist/session/provider-cli/provider-cli.process.js +39 -430
  75. package/dist/session/provider-cli/provider-cli.prompts.d.ts +2 -0
  76. package/dist/session/provider-cli/provider-cli.prompts.js +45 -8
  77. package/dist/session/provider-cli/provider-cli.runtime.js +7 -0
  78. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -7
  79. package/dist/session/provider-cli/provider-cli.service.js +66 -243
  80. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  81. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  82. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  83. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  84. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  85. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  86. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  87. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  88. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  89. package/dist/session/provider-cli/provider-output-state.js +6 -0
  90. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  91. package/dist/session/qa-sidecar-validation.js +28 -0
  92. package/dist/session/sandbox-host-capacity-gate.js +12 -3
  93. package/dist/session/session-redaction.js +31 -181
  94. package/dist/session/session.types.js +3 -3
  95. package/dist/session/sidecar-json-shape.d.ts +31 -0
  96. package/dist/session/sidecar-json-shape.js +217 -0
  97. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  98. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  99. package/dist/shared/process/windows-launch.d.ts +18 -0
  100. package/dist/shared/process/windows-launch.js +68 -0
  101. package/dist/shared/provider-capabilities.js +5 -6
  102. package/dist/version.d.ts +1 -1
  103. package/dist/version.js +1 -1
  104. package/package.json +2 -2
package/README.md CHANGED
@@ -23,6 +23,16 @@ forge-bridge status
23
23
  forge-bridge connect --server <forge-url> --runner-id <runner-id> --device-token <device-token>
24
24
  ```
25
25
 
26
+ To pair, open **Settings → Runners → Connect a bridge** in Forge and run the command it shows:
27
+
28
+ ```bash
29
+ forge-bridge pair <code> --server <forge-url>
30
+ ```
31
+
32
+ The runner name, provider CLIs and repo folder chosen in that dialog come back with the claim
33
+ and are saved to `bridge.json`; `--repo-root` and `--cli-provider` on the command line win over
34
+ them. `bridge.json` holds the device token, so the bridge writes it with mode `0600`.
35
+
26
36
  The bridge can also read connection settings from environment variables:
27
37
 
28
38
  - `FORGE_URL`
@@ -139,6 +149,19 @@ capacity (`FORGE_HOST_MAX_CONCURRENT_ATTEMPTS`, `FORGE_HOST_CPU_BUDGET_PERCENT`,
139
149
  `FORGE_HOST_LOAD_CPU_BUDGET_FRACTION`, `FORGE_HOST_MAX_HEAVY_STEPS`) and a floor on the reserve
140
150
  (`FORGE_HOST_MEMORY_RESERVE_BYTES`). Without a server value, the env var or the bridge default applies.
141
151
  The CPU budget, yield budget and heavy-step limit take effect only with `FORGE_HOST_LOAD_GOVERNOR=on`.
152
+ They gate on Linux PSI. Windows has no PSI, so a Windows bridge estimates CPU pressure from whole-host
153
+ CPU use and reports it with `pressureSource: "windows_estimate"` (decision 0021). Forge's Load column
154
+ and the budgets then work there too. Without either signal, the governor falls back to one heavy step at a time.
155
+
156
+ Two or more attempts on one host take turns at the host test slot (decision 0018): builds, test runs,
157
+ Playwright, pre-publication checks and the ASP.NET runtime build each wait for it in one host-wide queue,
158
+ foreground first, then first come, first served, across the bridge and every completion MCP server. Plain
159
+ managed commands and dependency installs never wait for it. A waiting step reports who holds the slot
160
+ (`prepublication_host_capacity_waiting`, `host_runtime_build_waiting_for_host_capacity`, or
161
+ `host_load_wait_detail` on a managed command's receipt), and its own timeout starts only once it runs.
162
+ A holder that crashes or stalls keeps the slot only until the host load ledger takes its token back (its
163
+ process tree stopped, its lease fenced, or attempt teardown). `FORGE_HOST_LOAD_TEST_SLOTS` sets how many
164
+ run at once (default 1; `0` turns the slot off).
142
165
 
143
166
  Yield this machine to foreground work (for example while gaming) from the host itself:
144
167
 
@@ -152,6 +175,15 @@ While yielding, the bridge takes no new attempts and heavy steps of running atte
152
175
  budget. Yield is on when this local flag or the runner's Yield toggle in Forge is on. The flag is stored
153
176
  in `bridge.yield.json` next to `bridge.json`, and a running bridge notices it within one heartbeat.
154
177
 
178
+ ## Pre-publication repair
179
+
180
+ Before Forge commits and pushes an agent's work, the bridge runs the CI parity checks in
181
+ `.forge/validation/ci-parity.v1.json`. A failed check does not stop the pass: the other checks still
182
+ run, except those that need what failed (the OpenAPI export and E2E after a .NET compile failure, E2E
183
+ after a failed runtime restart). The provider thread then gets one in-place repair turn that lists
184
+ every failed check. A Work Order holds after `FORGE_PREPUBLICATION_REPAIR_TURNS` repair turns (a whole
185
+ number from 1, capped at 10; default 4) if validation still fails.
186
+
155
187
  ## Docker sandbox runners
156
188
 
157
189
  Protocol-v2 bridges preflight Docker before advertising the `docker` sandbox runtime. Validate a repository contract and the local runner before enabling a project's `sandbox_required` policy:
@@ -0,0 +1,16 @@
1
+ import type { ProviderCliCommand, ProviderProcessRunResult } from "../session/provider-cli/provider-cli.process.js";
2
+ import { type ChatTurnDispatchPacket } from "./bridge-chat.types.js";
3
+ /** The turn-scoped handoff metadata file the bridge writes into the chat workspace. */
4
+ export declare const chatTurnMetadataFileName = "forge-chat-metadata.json";
5
+ /**
6
+ * Fails a Bridge Chat turn Forge stopped because it ended with background work still live: the
7
+ * turn never delivered its answer, so it must not be reported as one.
8
+ */
9
+ export declare function assertChatTurnFinished(result: Pick<ProviderProcessRunResult, "terminalStopReason">): void;
10
+ export interface ChatProviderCommandPlan {
11
+ readonly command: ProviderCliCommand;
12
+ readonly stdin?: string;
13
+ /** Provider environment, such as the headless background-work restrictions for Claude. */
14
+ readonly env?: Readonly<Record<string, string>>;
15
+ }
16
+ export declare function buildChatProviderCommand(packet: ChatTurnDispatchPacket, cwd: string): ChatProviderCommandPlan;
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Builds the provider command for a Bridge Chat turn: the CLI invocation for the turn's provider
3
+ * and the prompt that carries the conversation, its context references and its bounded handoff
4
+ * metadata.
5
+ */
6
+ import { claudeHeadlessEnvironment, claudeHeadlessToolArgs, providerTurnEndedWithBackgroundWorkFailure } from "../session/provider-cli/claude-background-work.js";
7
+ import { codexSandboxModeForPlatform, providerEffort } from "../session/provider-cli/provider-cli.prompts.js";
8
+ import { chatProviderKind } from "./bridge-chat.types.js";
9
+ /** The turn-scoped handoff metadata file the bridge writes into the chat workspace. */
10
+ export const chatTurnMetadataFileName = "forge-chat-metadata.json";
11
+ /**
12
+ * Fails a Bridge Chat turn Forge stopped because it ended with background work still live: the
13
+ * turn never delivered its answer, so it must not be reported as one.
14
+ */
15
+ export function assertChatTurnFinished(result) {
16
+ if (result.terminalStopReason === "turn_ended_with_background_work") {
17
+ throw providerTurnEndedWithBackgroundWorkFailure("The Bridge Chat turn did not finish.");
18
+ }
19
+ }
20
+ export function buildChatProviderCommand(packet, cwd) {
21
+ // The provider kind picks the CLI and its effort levels; an auth-path suffix such as `:bridge` does not.
22
+ const provider = chatProviderKind(packet.providerKind);
23
+ const model = packet.model.trim();
24
+ const prompt = buildChatPrompt(packet);
25
+ const resumeThreadId = packet.providerThreadId?.trim() || null;
26
+ // Levels the provider does not accept are dropped, so the CLI keeps its own default.
27
+ const effort = providerEffort(provider, packet.effort);
28
+ if (provider === "codex") {
29
+ const args = ["-s", codexSandboxModeForPlatform(process.platform, "host"), "-a", "never", "exec"];
30
+ if (resumeThreadId) {
31
+ args.push("--cd", cwd, "resume");
32
+ }
33
+ args.push("--model", model);
34
+ if (effort) {
35
+ args.push("-c", `model_reasoning_effort=${JSON.stringify(effort)}`);
36
+ }
37
+ args.push("--json");
38
+ if (!resumeThreadId) {
39
+ args.push("--cd", cwd);
40
+ }
41
+ args.push("--skip-git-repo-check");
42
+ if (resumeThreadId) {
43
+ args.push(resumeThreadId);
44
+ }
45
+ args.push("-");
46
+ return { command: { command: "codex", args }, stdin: prompt };
47
+ }
48
+ if (provider === "cursor") {
49
+ const args = ["--print", "--output-format", "stream-json", "--model", model, "--workspace", cwd];
50
+ if (resumeThreadId) {
51
+ args.push("--resume", resumeThreadId);
52
+ }
53
+ args.push("--yolo", "--approve-mcps", "--trust", prompt);
54
+ return { command: { command: "cursor-agent", args } };
55
+ }
56
+ if (provider === "claude") {
57
+ const args = ["-p", "--output-format", "stream-json", "--verbose", "--model", model];
58
+ if (effort) {
59
+ args.push("--effort", effort);
60
+ }
61
+ args.push("--permission-mode", "bypassPermissions", ...claudeHeadlessToolArgs());
62
+ if (resumeThreadId) {
63
+ args.push("--resume", resumeThreadId);
64
+ }
65
+ return { command: { command: "claude", args }, stdin: prompt, env: claudeHeadlessEnvironment };
66
+ }
67
+ return {
68
+ command: {
69
+ command: provider,
70
+ args: ["--model", model, prompt],
71
+ },
72
+ };
73
+ }
74
+ function buildChatPrompt(packet) {
75
+ const messages = packet.messages
76
+ .map((message, index) => {
77
+ const role = message.role.trim() || `message-${index + 1}`;
78
+ return `[${role}]\n${message.content}`;
79
+ })
80
+ .join("\n\n");
81
+ const contextRefs = packet.contextRefs.length === 0
82
+ ? ""
83
+ : `\n\n# Context References\n\n${packet.contextRefs.map((ref, index) => {
84
+ const title = ref.title?.trim() ? `\nTitle: ${ref.title.trim()}` : "";
85
+ const summary = ref.summary?.trim() ? `\nSummary: ${ref.summary.trim()}` : "";
86
+ return `${index + 1}. ${ref.kind}:${ref.refId}${title}${summary}`;
87
+ }).join("\n\n")}`;
88
+ const continuation = packet.providerThreadId
89
+ ? "\n\nContinue the existing provider thread identified by the bridge; do not restart the conversation context."
90
+ : "";
91
+ const boundedMetadata = buildChatBoundedMetadataPrompt(packet);
92
+ return `You are handling a Forge Bridge Chat turn.
93
+
94
+ Conversation ID: ${packet.conversationId}
95
+ Turn ID: ${packet.turnId}
96
+ Provider: ${packet.providerKind}
97
+ Model: ${packet.model}${continuation}${boundedMetadata}
98
+
99
+ # Conversation
100
+
101
+ ${messages}${contextRefs}
102
+ `;
103
+ }
104
+ function buildChatBoundedMetadataPrompt(packet) {
105
+ if (packet.attachmentHandoffs.length === 0 && packet.actionBrokerGrants.length === 0) {
106
+ return "";
107
+ }
108
+ const sections = [
109
+ `\n\n# Bounded Handoff Metadata\n\nMetadata file: ${chatTurnMetadataFileName}\n\nThe metadata file is turn-scoped and cleaned up by the bridge when the turn ends. It contains opaque handles only; attachment content, raw paths, and grant nonces are not included.`,
110
+ ];
111
+ if (packet.attachmentHandoffs.length > 0) {
112
+ sections.push(`Attachment handoffs:\n${packet.attachmentHandoffs.map((handoff, index) => [
113
+ `${index + 1}. turnId: ${handoff.turnId}`,
114
+ ` attachmentId: ${handoff.attachmentId}`,
115
+ ` tempFileToken: ${handoff.tempFileToken}`,
116
+ ` mimeType: ${handoff.mimeType}`,
117
+ ` sizeBytes: ${handoff.sizeBytes}`,
118
+ ` sha256: ${handoff.sha256}`,
119
+ ` fileNameDisplay: ${handoff.fileNameDisplay}`,
120
+ ` expiresAt: ${handoff.expiresAt}`,
121
+ ` status: ${handoff.status}`,
122
+ ].join("\n")).join("\n\n")}`);
123
+ }
124
+ if (packet.actionBrokerGrants.length > 0) {
125
+ sections.push(`Action-broker grants:\n${packet.actionBrokerGrants.map((grant, index) => [
126
+ `${index + 1}. grantId: ${grant.grantId}`,
127
+ ` turnId: ${grant.turnId}`,
128
+ ` leaseId: ${grant.leaseId}`,
129
+ ` fencingToken: ${grant.fencingToken}`,
130
+ ` allowedScopes: ${grant.allowedScopes.join(", ")}`,
131
+ ` expiresAt: ${grant.expiresAt}`,
132
+ ` redactionStatus: ${grant.redactionStatus}`,
133
+ " nonce: held by bridge",
134
+ ].join("\n")).join("\n\n")}`);
135
+ }
136
+ return sections.join("\n\n");
137
+ }
@@ -35,6 +35,11 @@ export interface ChatTurnDispatchPacket {
35
35
  readonly contextRefs: readonly ChatTurnContextRef[];
36
36
  readonly idempotencyKey: string;
37
37
  readonly providerThreadId?: string | null;
38
+ /**
39
+ * The Chat role's reasoning effort for this provider and model, or null for the provider default.
40
+ * Older servers omit it. The command builder drops levels the provider does not accept.
41
+ */
42
+ readonly effort?: string | null;
38
43
  readonly protocolVersion: typeof bridgeChatProtocolVersion;
39
44
  readonly requestedCapabilities: readonly BridgeChatRequestedCapability[];
40
45
  readonly attachmentHandoffs: readonly ChatAttachmentHandoffHandle[];
@@ -107,5 +112,10 @@ export interface ChatTurnCancelPacket {
107
112
  export declare function unavailableBridgeChatCapability(protocolVersion?: string, unavailableCode?: string | null, unavailableReason?: string | null): BridgeChatCapability;
108
113
  export declare function normalizeBridgeChatCapability(value: BridgeChatCapability | null | undefined): BridgeChatCapability;
109
114
  export declare function parseChatTurnDispatchPacket(value: unknown, capability?: BridgeChatCapability): ChatTurnDispatchPacket;
115
+ /**
116
+ * The provider kind of a saved provider selection: `codex:bridge` and `codex` are both `codex`.
117
+ * Forge stores the Chat role's provider with its auth-path suffix and may send it as is.
118
+ */
119
+ export declare function chatProviderKind(provider: string): string;
110
120
  export declare function isTerminalChatTurnCallbackKind(kind: ChatTurnCallbackKind): boolean;
111
121
  export declare function assertBridgeChatCallbackPayload(value: unknown, label?: string): void;
@@ -87,18 +87,26 @@ export function parseChatTurnDispatchPacket(value, capability = unavailableBridg
87
87
  leaseId,
88
88
  fencingToken,
89
89
  runnerInstanceId: requiredUuid(packet, "runnerInstanceId"),
90
- providerKind: requiredString(packet, "providerKind").trim().toLowerCase(),
90
+ providerKind: requiredProviderKind(packet),
91
91
  model: requiredString(packet, "model").trim(),
92
92
  messages,
93
93
  contextRefs,
94
94
  idempotencyKey: requiredString(packet, "idempotencyKey").trim(),
95
95
  providerThreadId: optionalString(packet, "providerThreadId", bridgeChatMaxProviderThreadIdChars),
96
+ effort: optionalString(packet, "effort")?.toLowerCase() ?? null,
96
97
  protocolVersion: bridgeChatProtocolVersion,
97
98
  requestedCapabilities,
98
99
  attachmentHandoffs,
99
100
  actionBrokerGrants,
100
101
  };
101
102
  }
103
+ /**
104
+ * The provider kind of a saved provider selection: `codex:bridge` and `codex` are both `codex`.
105
+ * Forge stores the Chat role's provider with its auth-path suffix and may send it as is.
106
+ */
107
+ export function chatProviderKind(provider) {
108
+ return (provider.split(":", 1)[0] ?? "").trim().toLowerCase();
109
+ }
102
110
  export function isTerminalChatTurnCallbackKind(kind) {
103
111
  return kind === "output_completed" || kind === "failed" || kind === "cancelled" || kind === "expired";
104
112
  }
@@ -304,6 +312,13 @@ function requiredUuid(source, key) {
304
312
  }
305
313
  return value;
306
314
  }
315
+ function requiredProviderKind(source) {
316
+ const kind = chatProviderKind(requiredString(source, "providerKind"));
317
+ if (kind.length === 0) {
318
+ throw new Error("providerKind must be a non-empty string.");
319
+ }
320
+ return kind;
321
+ }
307
322
  function requiredString(source, key) {
308
323
  const value = source[key];
309
324
  if (typeof value !== "string" || value.trim().length === 0) {
@@ -1,5 +1,5 @@
1
1
  import type { SessionService } from "../session/session.base.js";
2
- import type { ProviderProcessRunner } from "../session/provider-cli/provider-cli.process.js";
2
+ import { type ProviderProcessRunner } from "../session/provider-cli/provider-cli.service.js";
3
3
  import { type RunnerSettingsReport } from "../runtime/runner-settings.js";
4
4
  import { DockerEngineProbe, type DockerEngineCapabilitySnapshot } from "../runtime/docker-engine-probe.js";
5
5
  import { type DispatchSandboxResourceRequest, type RunOnceDispatchPacket, type RunOnceResultPacket } from "../session/session.types.js";
@@ -8,8 +8,8 @@ import { defaultForgeBridgeConfig } from "../config.js";
8
8
  import { bridgeChatCapabilityFor, supportsDraftImageAttachmentsFor } from "../shared/provider-capabilities.js";
9
9
  import { redactText } from "../shared/redaction/redaction.js";
10
10
  import { BridgeSessionService } from "../session/session.service.js";
11
- import { ProcessBackedProviderCliService, RoutingProviderCliService, StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.service.js";
12
- import { codexSandboxModeForPlatform, formatProviderCliCommandForCheckpoint } from "../session/provider-cli/provider-cli.prompts.js";
11
+ import { formatProviderCliCommandForCheckpoint, ProcessBackedProviderCliService, RoutingProviderCliService, StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.service.js";
12
+ import { assertChatTurnFinished, buildChatProviderCommand, chatTurnMetadataFileName } from "./bridge-chat-provider-command.js";
13
13
  import { clip, createProviderOutputState } from "../session/provider-cli/provider-output-state.js";
14
14
  import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "../session/session-redaction.js";
15
15
  import { PrePublicationValidator } from "../session/pre-publication-validation.js";
@@ -681,6 +681,7 @@ export class ForgeBridgeService {
681
681
  env: {
682
682
  FORGE_BRIDGE_CHAT_RUN_ID: packet.chatRunId,
683
683
  FORGE_BRIDGE_CHAT_TURN_ID: packet.turnId,
684
+ ...plan.env,
684
685
  },
685
686
  stdin: plan.stdin,
686
687
  }, {
@@ -707,6 +708,7 @@ export class ForgeBridgeService {
707
708
  content: "Bridge Chat provider process exited.",
708
709
  }).catch(() => undefined);
709
710
  }
711
+ assertChatTurnFinished(result);
710
712
  return { command: plan.command, output, result };
711
713
  }
712
714
  async sendChatProviderEvent(packet, active, event, providerThreadId) {
@@ -2690,7 +2692,6 @@ const defaultChatTurnLeaseMs = 60 * 60 * 1000;
2690
2692
  const maxChatEventContentChars = 4000;
2691
2693
  const maxChatTerminalTextChars = 120_000;
2692
2694
  const maxChatExactSecretChars = 8 * 1024;
2693
- const chatTurnMetadataFileName = "forge-chat-metadata.json";
2694
2695
  async function materializeChatTurnMetadata(packet, workspacePath) {
2695
2696
  if (packet.attachmentHandoffs.length === 0 && packet.actionBrokerGrants.length === 0) {
2696
2697
  return;
@@ -2750,113 +2751,6 @@ async function cleanupChatTurnWorkspace(workspacePath, redactionSecrets) {
2750
2751
  };
2751
2752
  }
2752
2753
  }
2753
- function buildChatProviderCommand(packet, cwd) {
2754
- const provider = packet.providerKind.trim().toLowerCase();
2755
- const model = packet.model.trim();
2756
- const prompt = buildChatPrompt(packet);
2757
- const resumeThreadId = packet.providerThreadId?.trim() || null;
2758
- if (provider === "codex") {
2759
- const args = ["-s", codexSandboxModeForPlatform(process.platform, "host"), "-a", "never", "exec"];
2760
- if (resumeThreadId) {
2761
- args.push("--cd", cwd, "resume");
2762
- }
2763
- args.push("--model", model, "--json");
2764
- if (!resumeThreadId) {
2765
- args.push("--cd", cwd);
2766
- }
2767
- args.push("--skip-git-repo-check");
2768
- if (resumeThreadId) {
2769
- args.push(resumeThreadId);
2770
- }
2771
- args.push("-");
2772
- return { command: { command: "codex", args }, stdin: prompt };
2773
- }
2774
- if (provider === "cursor") {
2775
- const args = ["--print", "--output-format", "stream-json", "--model", model, "--workspace", cwd];
2776
- if (resumeThreadId) {
2777
- args.push("--resume", resumeThreadId);
2778
- }
2779
- args.push("--yolo", "--approve-mcps", "--trust", prompt);
2780
- return { command: { command: "cursor-agent", args } };
2781
- }
2782
- if (provider === "claude") {
2783
- const args = ["-p", "--output-format", "stream-json", "--verbose", "--model", model, "--permission-mode", "bypassPermissions"];
2784
- if (resumeThreadId) {
2785
- args.push("--resume", resumeThreadId);
2786
- }
2787
- return { command: { command: "claude", args }, stdin: prompt };
2788
- }
2789
- return {
2790
- command: {
2791
- command: provider,
2792
- args: ["--model", model, prompt],
2793
- },
2794
- };
2795
- }
2796
- function buildChatPrompt(packet) {
2797
- const messages = packet.messages
2798
- .map((message, index) => {
2799
- const role = message.role.trim() || `message-${index + 1}`;
2800
- return `[${role}]\n${message.content}`;
2801
- })
2802
- .join("\n\n");
2803
- const contextRefs = packet.contextRefs.length === 0
2804
- ? ""
2805
- : `\n\n# Context References\n\n${packet.contextRefs.map((ref, index) => {
2806
- const title = ref.title?.trim() ? `\nTitle: ${ref.title.trim()}` : "";
2807
- const summary = ref.summary?.trim() ? `\nSummary: ${ref.summary.trim()}` : "";
2808
- return `${index + 1}. ${ref.kind}:${ref.refId}${title}${summary}`;
2809
- }).join("\n\n")}`;
2810
- const continuation = packet.providerThreadId
2811
- ? "\n\nContinue the existing provider thread identified by the bridge; do not restart the conversation context."
2812
- : "";
2813
- const boundedMetadata = buildChatBoundedMetadataPrompt(packet);
2814
- return `You are handling a Forge Bridge Chat turn.
2815
-
2816
- Conversation ID: ${packet.conversationId}
2817
- Turn ID: ${packet.turnId}
2818
- Provider: ${packet.providerKind}
2819
- Model: ${packet.model}${continuation}${boundedMetadata}
2820
-
2821
- # Conversation
2822
-
2823
- ${messages}${contextRefs}
2824
- `;
2825
- }
2826
- function buildChatBoundedMetadataPrompt(packet) {
2827
- if (packet.attachmentHandoffs.length === 0 && packet.actionBrokerGrants.length === 0) {
2828
- return "";
2829
- }
2830
- const sections = [
2831
- `\n\n# Bounded Handoff Metadata\n\nMetadata file: ${chatTurnMetadataFileName}\n\nThe metadata file is turn-scoped and cleaned up by the bridge when the turn ends. It contains opaque handles only; attachment content, raw paths, and grant nonces are not included.`,
2832
- ];
2833
- if (packet.attachmentHandoffs.length > 0) {
2834
- sections.push(`Attachment handoffs:\n${packet.attachmentHandoffs.map((handoff, index) => [
2835
- `${index + 1}. turnId: ${handoff.turnId}`,
2836
- ` attachmentId: ${handoff.attachmentId}`,
2837
- ` tempFileToken: ${handoff.tempFileToken}`,
2838
- ` mimeType: ${handoff.mimeType}`,
2839
- ` sizeBytes: ${handoff.sizeBytes}`,
2840
- ` sha256: ${handoff.sha256}`,
2841
- ` fileNameDisplay: ${handoff.fileNameDisplay}`,
2842
- ` expiresAt: ${handoff.expiresAt}`,
2843
- ` status: ${handoff.status}`,
2844
- ].join("\n")).join("\n\n")}`);
2845
- }
2846
- if (packet.actionBrokerGrants.length > 0) {
2847
- sections.push(`Action-broker grants:\n${packet.actionBrokerGrants.map((grant, index) => [
2848
- `${index + 1}. grantId: ${grant.grantId}`,
2849
- ` turnId: ${grant.turnId}`,
2850
- ` leaseId: ${grant.leaseId}`,
2851
- ` fencingToken: ${grant.fencingToken}`,
2852
- ` allowedScopes: ${grant.allowedScopes.join(", ")}`,
2853
- ` expiresAt: ${grant.expiresAt}`,
2854
- ` redactionStatus: ${grant.redactionStatus}`,
2855
- " nonce: held by bridge",
2856
- ].join("\n")).join("\n\n")}`);
2857
- }
2858
- return sections.join("\n\n");
2859
- }
2860
2754
  function chatProviderExitFailure(command, result, redactionSecrets) {
2861
2755
  const commandText = redactText(formatProviderCliCommandForCheckpoint(command), redactionSecrets);
2862
2756
  const stderr = clip(redactText(result.stderr.trim(), redactionSecrets), 1000);
@@ -11,6 +11,9 @@ export interface RunnerHostCapabilityProbe {
11
11
  detect(config: BridgeServiceConfig): Promise<RunnerHostCapabilitySnapshot>;
12
12
  }
13
13
  export declare class ProcessRunnerHostCapabilityProbe implements RunnerHostCapabilityProbe {
14
+ private readonly warn;
15
+ private readonly providerEnvironment;
16
+ constructor(warn?: (message: string) => void, providerEnvironment?: () => NodeJS.ProcessEnv);
14
17
  detect(config: BridgeServiceConfig): Promise<RunnerHostCapabilitySnapshot>;
15
18
  }
16
19
  export declare function isUnavailablePlaywrightConfigError(error: unknown): boolean;
@@ -3,9 +3,22 @@ import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { promisify } from "node:util";
5
5
  import { probeTestPostgresCapability } from "./test-postgres-capability.js";
6
+ import { appExecutionAliasWarning } from "../shared/process/windows-app-execution-alias.js";
7
+ import { buildProviderChildEnvironment } from "../session/provider-cli/provider-cli.process.js";
6
8
  const execFileAsync = promisify(execFile);
7
9
  export class ProcessRunnerHostCapabilityProbe {
10
+ warn;
11
+ providerEnvironment;
12
+ constructor(warn = message => process.stderr.write(`[${new Date().toISOString()}] ${message}\n`), providerEnvironment = () => buildProviderChildEnvironment()) {
13
+ this.warn = warn;
14
+ this.providerEnvironment = providerEnvironment;
15
+ }
8
16
  async detect(config) {
17
+ // Readiness, not a capability: the bridge still settles an attempt whose descendant escaped
18
+ // the Job Object (see OutputPipeRelease), but the host should not hand out aliases.
19
+ const aliasWarning = appExecutionAliasWarning(this.providerEnvironment());
20
+ if (aliasWarning)
21
+ this.warn(aliasWarning);
9
22
  const [pnpm, dotnet, git, bash, pwsh, windowsPowerShell] = await Promise.all([
10
23
  probe("pnpm", ["--version"]),
11
24
  probe("dotnet", ["--version"]),
@@ -109,13 +109,24 @@ interface PairArgs {
109
109
  readonly repoRoot?: string;
110
110
  readonly cleanupWorktrees: boolean;
111
111
  readonly cliProviders: readonly string[];
112
+ /** True when `--cli-provider` named the providers, which then win over the Connect dialog's choice. */
113
+ readonly cliProvidersFromFlag?: boolean;
112
114
  readonly projectLabels: readonly string[];
113
115
  }
116
+ /** Decision 0014 §5: what the Connect dialog's pairing intent set for this host, echoed by the claim. */
117
+ export interface PairRunnerHost {
118
+ readonly name?: string;
119
+ readonly repoRoot?: string;
120
+ readonly cliProviders?: readonly string[];
121
+ }
114
122
  interface PairRunnerClaim {
115
123
  readonly runnerId: string;
116
124
  readonly deviceToken: string;
125
+ readonly host?: PairRunnerHost;
117
126
  }
118
127
  type PairRunnerClient = (args: PairArgs) => Promise<PairRunnerClaim>;
128
+ /** Expands `~` in a repo folder chosen in Forge and rejects one shaped for another OS. */
129
+ export declare function resolveHostRepoRoot(value: string, platform?: NodeJS.Platform, home?: string): string | undefined;
119
130
  export declare const claudeDefaultModels: readonly string[];
120
131
  export declare function parseCodexModelCatalog(raw: string): string[];
121
132
  export declare function parseCursorModelList(raw: string): string[];
@@ -131,13 +131,22 @@ export class ForgeBridgeCliService {
131
131
  const current = readLocalConfigSync();
132
132
  io.stdout.write(`Pairing with server: ${args.serverUrl}\n`);
133
133
  const code = await resolvePairingCode(args.code);
134
- const repoRoot = await resolvePairRepoRoot(args.repoRoot, current.defaultRepoRoot);
135
- await fs.mkdir(repoRoot, { recursive: true });
136
- const pairArgs = await withDetectedPairCliProviders({ ...args, code, repoRoot });
134
+ const provisionalRoot = path.resolve(args.repoRoot ?? current.defaultRepoRoot ?? path.join(os.homedir(), "ForgeRepos"));
135
+ const pairArgs = await withDetectedPairCliProviders({ ...args, code, repoRoot: provisionalRoot });
137
136
  const claim = await this.pairRunner(pairArgs);
138
- const next = pairedConfig(current, pairArgs, claim);
139
- await writeLocalConfig(next);
140
- io.stdout.write(`Paired runner ${claim.runnerId}.\n`);
137
+ // The code is spent now: save the credentials before anything else can fail or prompt.
138
+ const applied = applyPairHost(pairArgs, claim.host, args.repoRoot !== undefined, io);
139
+ await writeLocalConfig(pairedConfig(current, applied.args, claim));
140
+ let repoRoot = applied.args.repoRoot;
141
+ if (!args.repoRoot && !applied.repoRootFromHost) {
142
+ const answered = await promptPairRepoRoot(repoRoot);
143
+ if (answered !== repoRoot) {
144
+ repoRoot = answered;
145
+ await writeLocalConfig(pairedConfig(current, { ...applied.args, repoRoot }, claim));
146
+ }
147
+ }
148
+ await fs.mkdir(repoRoot, { recursive: true });
149
+ io.stdout.write(`Paired runner ${claim.runnerId}${applied.args.name ? ` (${applied.args.name})` : ""}.\n`);
141
150
  io.stdout.write(`Repo folder: ${repoRoot}\n`);
142
151
  io.stdout.write(`Config: ${resolveLocalConfigPath()}\n`);
143
152
  io.stdout.write("Start the bridge with: forge-bridge connect\n");
@@ -813,6 +822,7 @@ function parsePairArgs(argv) {
813
822
  repoRoot: repoRoot?.trim() ? path.resolve(repoRoot) : undefined,
814
823
  cleanupWorktrees: cleanupWorktrees ?? defaultConfig.cleanupWorktrees,
815
824
  cliProviders: cliProviders.length > 0 ? cliProviders : localConfig.cliProviders && localConfig.cliProviders.length > 0 ? [...localConfig.cliProviders] : ["codex"],
825
+ cliProvidersFromFlag: cliProviders.length > 0,
816
826
  projectLabels: projectLabels.length > 0 ? projectLabels : localConfig.projectLabels ? [...localConfig.projectLabels] : []
817
827
  };
818
828
  }
@@ -875,9 +885,71 @@ async function claimBridgeRunner(args) {
875
885
  }
876
886
  return {
877
887
  runnerId: value.runnerId,
878
- deviceToken: value.deviceToken
888
+ deviceToken: value.deviceToken,
889
+ host: parsePairRunnerHost(value.host)
890
+ };
891
+ }
892
+ function parsePairRunnerHost(value) {
893
+ if (!value || typeof value !== "object") {
894
+ return undefined;
895
+ }
896
+ const host = value;
897
+ const name = typeof host.name === "string" && host.name.trim() ? host.name.trim() : undefined;
898
+ const repoRoot = typeof host.repoRoot === "string" && host.repoRoot.trim() ? host.repoRoot.trim() : undefined;
899
+ const cliProviders = Array.isArray(host.cliProviders)
900
+ ? host.cliProviders.filter((provider) => typeof provider === "string" && provider.trim().length > 0)
901
+ : [];
902
+ return { name, repoRoot, cliProviders: cliProviders.length > 0 ? cliProviders : undefined };
903
+ }
904
+ /**
905
+ * Decision 0014 §5: the claim's host block carries what the Connect dialog chose. The runner name
906
+ * is the server's; providers and the repo folder apply unless a flag named them on this command line.
907
+ */
908
+ function applyPairHost(args, host, repoRootFromFlag, io) {
909
+ if (!host) {
910
+ return { args, repoRootFromHost: false };
911
+ }
912
+ let repoRoot = args.repoRoot;
913
+ let repoRootFromHost = false;
914
+ if (host.repoRoot && !repoRootFromFlag) {
915
+ const resolved = resolveHostRepoRoot(host.repoRoot);
916
+ if (!resolved) {
917
+ io.stderr.write(`Ignoring the repo folder chosen in Forge (${host.repoRoot}): it is not a path on this machine.\n`);
918
+ }
919
+ else {
920
+ repoRootFromHost = true;
921
+ repoRoot = resolved;
922
+ }
923
+ }
924
+ return {
925
+ args: {
926
+ ...args,
927
+ name: host.name ?? args.name,
928
+ cliProviders: host.cliProviders && !args.cliProvidersFromFlag ? [...host.cliProviders] : args.cliProviders,
929
+ repoRoot
930
+ },
931
+ repoRootFromHost
879
932
  };
880
933
  }
934
+ /** Expands `~` in a repo folder chosen in Forge and rejects one shaped for another OS. */
935
+ export function resolveHostRepoRoot(value, platform = process.platform, home = os.homedir()) {
936
+ const trimmed = value.trim();
937
+ if (!trimmed) {
938
+ return undefined;
939
+ }
940
+ const pathApi = platform === "win32" ? path.win32 : path.posix;
941
+ if (trimmed === "~") {
942
+ return home;
943
+ }
944
+ if (/^~[\\/]/.test(trimmed)) {
945
+ return pathApi.resolve(home, trimmed.slice(2));
946
+ }
947
+ const windowsShaped = /^[A-Za-z]:[\\/]/.test(trimmed) || trimmed.startsWith("\\\\");
948
+ if (platform === "win32") {
949
+ return windowsShaped || trimmed.startsWith("/") ? pathApi.resolve(trimmed) : undefined;
950
+ }
951
+ return !windowsShaped && trimmed.startsWith("/") ? pathApi.resolve(trimmed) : undefined;
952
+ }
881
953
  function pairedConfig(current, args, claim) {
882
954
  return {
883
955
  ...current,
@@ -922,11 +994,7 @@ async function resolvePairingCode(code) {
922
994
  prompt.close();
923
995
  }
924
996
  }
925
- async function resolvePairRepoRoot(repoRoot, configuredRoot) {
926
- const fallback = path.resolve(repoRoot ?? configuredRoot ?? path.join(os.homedir(), "ForgeRepos"));
927
- if (repoRoot?.trim()) {
928
- return fallback;
929
- }
997
+ async function promptPairRepoRoot(fallback) {
930
998
  if (!process.stdin.isTTY || !process.stdout.isTTY) {
931
999
  return fallback;
932
1000
  }
@@ -30,6 +30,8 @@ export interface LocalRepoMapping extends BridgeRepoMapping {
30
30
  export declare function resolveLocalConfigPath(): string;
31
31
  export declare function readLocalConfig(): Promise<BridgeLocalConfig>;
32
32
  export declare function readLocalConfigSync(): BridgeLocalConfig;
33
+ /** Decision 0014 §5: `bridge.json` holds the device token, so only its owner may read it. */
34
+ export declare const localConfigFileMode = 384;
33
35
  export declare function writeLocalConfig(config: BridgeLocalConfig): Promise<void>;
34
36
  export declare function applyLocalConfigDefaults(config: BridgeServiceConfig, local: BridgeLocalConfig): BridgeServiceConfig;
35
37
  /** Decision 0014: the `forge-bridge yield` flag, beside the bridge config and never inside it. */
@@ -29,12 +29,28 @@ export function readLocalConfigSync() {
29
29
  }
30
30
  return parseLocalConfig(fsSync.readFileSync(configPath, "utf8"));
31
31
  }
32
+ /** Decision 0014 §5: `bridge.json` holds the device token, so only its owner may read it. */
33
+ export const localConfigFileMode = 0o600;
34
+ const localConfigDirectoryMode = 0o700;
32
35
  export async function writeLocalConfig(config) {
33
36
  const configPath = resolveLocalConfigPath();
34
- await fs.mkdir(path.dirname(configPath), { recursive: true });
37
+ await fs.mkdir(path.dirname(configPath), { recursive: true, mode: localConfigDirectoryMode });
35
38
  const tempPath = `${configPath}.${process.pid}.${Date.now()}.tmp`;
36
- await fs.writeFile(tempPath, `${JSON.stringify(normalizeLocalConfig(config), null, 2)}\n`, "utf8");
37
- await fs.rename(tempPath, configPath);
39
+ try {
40
+ await fs.writeFile(tempPath, `${JSON.stringify(normalizeLocalConfig(config), null, 2)}\n`, {
41
+ encoding: "utf8",
42
+ mode: localConfigFileMode
43
+ });
44
+ if (process.platform !== "win32") {
45
+ // The create mode is masked by the umask; set it exactly before the file becomes visible.
46
+ await fs.chmod(tempPath, localConfigFileMode);
47
+ }
48
+ await fs.rename(tempPath, configPath);
49
+ }
50
+ catch (error) {
51
+ await fs.rm(tempPath, { force: true }).catch(() => undefined);
52
+ throw error;
53
+ }
38
54
  }
39
55
  export function applyLocalConfigDefaults(config, local) {
40
56
  const cliProviders = local.cliProviders && local.cliProviders.length > 0 ? [...local.cliProviders] : config.cliProviders;