@loucompanion/forge-bridge 0.1.4-dev.f22f5e3d01fe → 0.2.1-dev.0fedbc5c9ef7

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 (182) hide show
  1. package/README.md +89 -1
  2. package/dist/bridge/bridge-chat-giphy-look.d.ts +48 -0
  3. package/dist/bridge/bridge-chat-giphy-look.js +55 -0
  4. package/dist/bridge/bridge-chat-provider-command.d.ts +27 -3
  5. package/dist/bridge/bridge-chat-provider-command.js +131 -26
  6. package/dist/bridge/bridge-chat.types.d.ts +20 -0
  7. package/dist/bridge/bridge-chat.types.js +28 -1
  8. package/dist/bridge/bridge-state-file.d.ts +161 -0
  9. package/dist/bridge/bridge-state-file.js +376 -0
  10. package/dist/bridge/bridge-state-io.d.ts +11 -0
  11. package/dist/bridge/bridge-state-io.js +50 -0
  12. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  13. package/dist/bridge/bridge-state-lock.js +102 -0
  14. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  15. package/dist/bridge/bridge-state-unpublished.js +111 -0
  16. package/dist/bridge/bridge.service.d.ts +19 -12
  17. package/dist/bridge/bridge.service.js +155 -282
  18. package/dist/bridge/bridge.types.d.ts +5 -0
  19. package/dist/bridge/in-flight-registry.d.ts +62 -0
  20. package/dist/bridge/in-flight-registry.js +207 -0
  21. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  22. package/dist/bridge/readiness-result-outbox.js +20 -0
  23. package/dist/bridge/runner-host-capabilities.js +14 -1
  24. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  25. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  26. package/dist/bridge/windows-bash-resolution.d.ts +31 -0
  27. package/dist/bridge/windows-bash-resolution.js +153 -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 +11 -1
  31. package/dist/cleanup/cleanup.service.js +80 -62
  32. package/dist/cleanup/cleanup.types.d.ts +2 -0
  33. package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
  34. package/dist/cleanup/host-runtime-ledger.js +30 -9
  35. package/dist/cli/cli.help.js +56 -12
  36. package/dist/cli/cli.service.d.ts +3 -10
  37. package/dist/cli/cli.service.js +10 -171
  38. package/dist/cli/idle-status.d.ts +84 -0
  39. package/dist/cli/idle-status.js +181 -0
  40. package/dist/cli/local-config.d.ts +2 -0
  41. package/dist/cli/local-config.js +7 -1
  42. package/dist/cli/provider-cli-detection.d.ts +10 -0
  43. package/dist/cli/provider-cli-detection.js +160 -0
  44. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  45. package/dist/runtime/aspnet-runtime-prebuild.js +104 -26
  46. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  47. package/dist/runtime/attempt-node-runtime-launcher.d.ts +36 -0
  48. package/dist/runtime/attempt-node-runtime-launcher.js +169 -0
  49. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  50. package/dist/runtime/attempt-process-supervisor.js +12 -6
  51. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  52. package/dist/runtime/docker-engine-probe.js +7 -0
  53. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  54. package/dist/runtime/dotnet-build-outputs.js +402 -0
  55. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  56. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  57. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  58. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  59. package/dist/runtime/host-listener-inspector.d.ts +26 -0
  60. package/dist/runtime/host-listener-inspector.js +84 -3
  61. package/dist/runtime/host-load-admission.d.ts +5 -0
  62. package/dist/runtime/host-load-governor-config.d.ts +10 -1
  63. package/dist/runtime/host-load-governor-config.js +4 -1
  64. package/dist/runtime/host-load-governor.d.ts +10 -1
  65. package/dist/runtime/host-load-governor.js +33 -3
  66. package/dist/runtime/host-load-ledger-lock.js +6 -4
  67. package/dist/runtime/host-load-runtime-settings.js +4 -2
  68. package/dist/runtime/host-load-sampler.d.ts +8 -1
  69. package/dist/runtime/host-load-sampler.js +14 -7
  70. package/dist/runtime/host-load-test-slot.js +7 -0
  71. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  72. package/dist/runtime/host-runtime-contract.js +29 -1
  73. package/dist/runtime/host-runtime-lease.d.ts +28 -3
  74. package/dist/runtime/host-runtime-lease.js +140 -296
  75. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  76. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  77. package/dist/runtime/host-runtime-promotion.d.ts +78 -2
  78. package/dist/runtime/host-runtime-promotion.js +307 -14
  79. package/dist/runtime/managed-command-teardown.js +5 -16
  80. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  81. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  82. package/dist/runtime/prepared-runtime-identity.d.ts +4 -0
  83. package/dist/runtime/prepared-runtime-identity.js +130 -9
  84. package/dist/runtime/prepared-runtime-readiness.d.ts +13 -1
  85. package/dist/runtime/prepared-runtime-readiness.js +63 -16
  86. package/dist/runtime/runner-settings.d.ts +4 -0
  87. package/dist/runtime/runner-settings.js +22 -0
  88. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  89. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  90. package/dist/sandbox/host-capacity-broker.d.ts +3 -1
  91. package/dist/sandbox/host-capacity-broker.js +4 -2
  92. package/dist/sandbox/managed-branch.d.ts +13 -0
  93. package/dist/sandbox/managed-branch.js +90 -0
  94. package/dist/sandbox/provider-auth/codex.js +11 -11
  95. package/dist/sandbox/runtime.js +3 -7
  96. package/dist/session/managed-attempt-tools.d.ts +0 -7
  97. package/dist/session/managed-attempt-tools.js +50 -82
  98. package/dist/session/managed-build-coordinator.d.ts +16 -0
  99. package/dist/session/managed-build-coordinator.js +10 -0
  100. package/dist/session/managed-build-receipt.d.ts +5 -0
  101. package/dist/session/managed-build-receipt.js +8 -3
  102. package/dist/session/phase-completion.artifacts.js +2 -1
  103. package/dist/session/phase-completion.d.ts +8 -0
  104. package/dist/session/phase-completion.js +1 -0
  105. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  106. package/dist/session/phase-completion.mcp-args.js +156 -0
  107. package/dist/session/phase-completion.runtime.d.ts +0 -8
  108. package/dist/session/phase-completion.runtime.js +43 -197
  109. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  110. package/dist/session/pre-publication-native-postgres.js +111 -0
  111. package/dist/session/pre-publication-process.js +10 -10
  112. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  113. package/dist/session/pre-publication-step-execution.js +6 -5
  114. package/dist/session/pre-publication-validation.d.ts +7 -3
  115. package/dist/session/pre-publication-validation.js +32 -30
  116. package/dist/session/provider-cli/claude-background-work.d.ts +3 -2
  117. package/dist/session/provider-cli/claude-background-work.js +4 -3
  118. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  119. package/dist/session/provider-cli/host-build-lock.js +30 -0
  120. package/dist/session/provider-cli/pre-publication-repair.d.ts +16 -0
  121. package/dist/session/provider-cli/pre-publication-repair.js +33 -0
  122. package/dist/session/provider-cli/provider-cli.child-environment.js +4 -2
  123. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  124. package/dist/session/provider-cli/provider-cli.merge-integrity.js +28 -8
  125. package/dist/session/provider-cli/provider-cli.process.d.ts +2 -14
  126. package/dist/session/provider-cli/provider-cli.process.js +4 -94
  127. package/dist/session/provider-cli/provider-cli.prompts.d.ts +3 -0
  128. package/dist/session/provider-cli/provider-cli.prompts.js +27 -27
  129. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  130. package/dist/session/provider-cli/provider-cli.runtime.js +23 -2
  131. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  132. package/dist/session/provider-cli/provider-cli.service.js +27 -43
  133. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  134. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  135. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  136. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  137. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  138. package/dist/session/qa-sidecar-validation.js +28 -0
  139. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  140. package/dist/session/sandbox-host-capacity-gate.js +35 -16
  141. package/dist/session/session-redaction.js +31 -181
  142. package/dist/session/session.service.d.ts +6 -0
  143. package/dist/session/session.service.js +131 -88
  144. package/dist/session/session.types.d.ts +1 -0
  145. package/dist/session/session.types.js +3 -3
  146. package/dist/session/sidecar-json-shape.d.ts +31 -0
  147. package/dist/session/sidecar-json-shape.js +217 -0
  148. package/dist/shared/fs/file-identity.d.ts +10 -0
  149. package/dist/shared/fs/file-identity.js +15 -0
  150. package/dist/shared/fs/replace-file.d.ts +7 -0
  151. package/dist/shared/fs/replace-file.js +33 -0
  152. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  153. package/dist/shared/process/host-process-recovery.js +23 -3
  154. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  155. package/dist/shared/process/host-process-supervisor.js +66 -14
  156. package/dist/shared/provider-capabilities.js +9 -1
  157. package/dist/version.d.ts +1 -1
  158. package/dist/version.js +1 -1
  159. package/dist/worktree/orphan-relink.d.ts +19 -0
  160. package/dist/worktree/orphan-relink.js +106 -0
  161. package/dist/worktree/wip-git.d.ts +42 -0
  162. package/dist/worktree/wip-git.js +139 -0
  163. package/dist/worktree/wip-refs.d.ts +77 -0
  164. package/dist/worktree/wip-refs.js +146 -0
  165. package/dist/worktree/wip-restore.d.ts +46 -0
  166. package/dist/worktree/wip-restore.js +280 -0
  167. package/dist/worktree/wip-snapshot.d.ts +53 -0
  168. package/dist/worktree/wip-snapshot.js +270 -0
  169. package/dist/worktree/worktree-inputs.d.ts +8 -0
  170. package/dist/worktree/worktree-inputs.js +134 -0
  171. package/dist/worktree/worktree-origin-sync.d.ts +35 -0
  172. package/dist/worktree/worktree-origin-sync.js +128 -0
  173. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  174. package/dist/worktree/worktree-wip-events.js +115 -0
  175. package/dist/worktree/worktree-wip.d.ts +51 -0
  176. package/dist/worktree/worktree-wip.js +190 -0
  177. package/dist/worktree/worktree.base.d.ts +7 -1
  178. package/dist/worktree/worktree.service.d.ts +27 -5
  179. package/dist/worktree/worktree.service.js +112 -181
  180. package/dist/worktree/worktree.types.d.ts +35 -0
  181. package/package.json +1 -1
  182. package/runtime/windows-listener-owner.ps1 +12 -1
package/README.md CHANGED
@@ -65,11 +65,13 @@ The bridge auto-detects these provider CLIs on `PATH` and advertises the ones it
65
65
 
66
66
  Claude Code notes:
67
67
 
68
- - Install with the native installer or `npm install -g @anthropic-ai/claude-code`. On Windows, Claude Code needs Git for Windows; set `CLAUDE_CODE_GIT_BASH_PATH` if `bash.exe` is not on `PATH`. `CLAUDE_CONFIG_DIR` is passed through if you keep config outside `~/.claude`.
68
+ - Install with the native installer or `npm install -g @anthropic-ai/claude-code`. On Windows, Claude Code needs Git for Windows; set `CLAUDE_CODE_GIT_BASH_PATH` if `bash.exe` is not on `PATH`. Forge doesn't pass `CLAUDE_CONFIG_DIR` to Claude Code, so it signs in from `~/.claude` (`%USERPROFILE%\.claude` on Windows) or with an Anthropic API key Forge grants; sign in there, not in a custom config directory.
69
69
  - Forge pipes the prompt on stdin, runs with `--permission-mode bypassPermissions` inside the managed worktree, and registers its completion MCP server through a temporary `--mcp-config` file outside the worktree with `--strict-mcp-config`, so user-level MCP servers are not loaded into unattended runs. Forge tools appear to the model as `mcp__forge__<tool>`.
70
70
  - Claude Code has no model-listing command, so the bridge advertises the `sonnet`, `opus`, and `haiku` aliases. Set `FORGE_CLAUDE_MODELS` to advertise specific model ids instead.
71
71
  - Claude runs in host mode only. Docker sandbox placement currently supports Codex only.
72
72
 
73
+ On Windows the bridge's `bash` capability is Git for Windows' `bash.exe`, resolved to an absolute path: `FORGE_BRIDGE_BASH_PATH` (then `CLAUDE_CODE_GIT_BASH_PATH`) if set, otherwise the Git install found from `git --exec-path` or `git.exe` on `PATH`, then `bash.exe` on `PATH`, then the standard Program Files locations. WSL's `System32\bash.exe` and Store aliases are never accepted. A bare `bash` is not used because Windows' executable search checks the current directory before `PATH`, and a scheduled task with no working directory starts in `System32`.
74
+
73
75
  Show or change the saved server without editing `bridge.json`:
74
76
 
75
77
  ```bash
@@ -175,6 +177,92 @@ While yielding, the bridge takes no new attempts and heavy steps of running atte
175
177
  budget. Yield is on when this local flag or the runner's Yield toggle in Forge is on. The flag is stored
176
178
  in `bridge.yield.json` next to `bridge.json`, and a running bridge notices it within one heartbeat.
177
179
 
180
+ ## Restarting or updating the bridge safely
181
+
182
+ Restarting `forge-bridge connect` kills everything it is running, including work that has no agent
183
+ process yet: an accepted offer waiting for Start, host-runtime admission, worktree and dependency
184
+ preparation, prepared-runtime probes, pre-publication validation and teardown. Forge then records the
185
+ attempt's outcome as unknown. Checking for agent processes is not enough, so the running bridge
186
+ publishes its in-flight work to `bridge.state.json` next to `bridge.json` (pid, runner instance, a
187
+ heartbeat refreshed every 5 seconds, and each in-flight item with its ids, phase and start time), and
188
+ `forge-bridge status --idle` reads it. Each bridge reads and rewrites the file while it holds a lock
189
+ the operating system owns and frees when the bridge exits (an abstract socket on Linux, a named pipe
190
+ on Windows, a flock on `bridge.state.json.lock` on macOS), so a second bridge on the same config always
191
+ sees the first one's record and reports the conflict, and a stopping bridge never writes its "stopped"
192
+ record over a newer bridge's. A bridge that can't publish (a failed write, or the lock held by another
193
+ process for more than 5 seconds) leaves `bridge.state.json.unpublished.<id>.json` instead of touching
194
+ the shared record, and a record missing any field reads as unknown, so neither can read as idle:
195
+
196
+ | Exit code | Verdict | Meaning |
197
+ |---:|---|---|
198
+ | 0 | `idle` | A live bridge reported a fresh heartbeat with nothing in flight. |
199
+ | 1 | `busy` | Work is in flight; restarting now would kill it. |
200
+ | 2 | | Usage error. |
201
+ | 3 | `stale` / `unknown` | Old heartbeat (hung bridge or reused pid), missing or unreadable state file, two bridge processes publishing to one config, or the bridge is shutting down. Idle can't be confirmed. A bridge older than this check writes no state file, so it reads as `unknown`. |
202
+ | 4 | `not_running` | The recorded bridge process has exited. Nothing to interrupt, but it is not an idle report. |
203
+ | 5 | `not_yielding` | With `--require-yield`: nothing in flight, but Forge has not acknowledged yield from this bridge, so placement can still pick it. |
204
+
205
+ `--json` prints the verdict, the reason, the heartbeat age, the pid check, the yield state (`yielding`:
206
+ acknowledged by Forge; `yieldApplied`: applied by the bridge) and the in-flight list. `--wait <seconds>`
207
+ keeps checking until the bridge is idle, its process has exited, or the time is up, so a file briefly
208
+ held by antivirus or the indexer doesn't end the wait; `--wait 0` checks once, like no `--wait`.
209
+ Against a bridge older than this check (no state file) it waits out the full time; check once without
210
+ `--wait` first.
211
+
212
+ What yield does and doesn't stop:
213
+
214
+ - It stops new attempts: the bridge refuses Offers while yielding (Forge re-places them), and Forge
215
+ stops placing work on the runner once it has acknowledged the yield (the next heartbeat or settings
216
+ report, at most about 30 seconds). `--require-yield` waits for that acknowledgement.
217
+ - It defers background runtime-readiness probes; Forge retries them after yield is off.
218
+ - It doesn't stop a Bridge Chat turn whose chat lease is already bound to this runner: Forge has no
219
+ retry for a refused turn, so the bridge runs it, and `status --idle` reports it as busy until it ends.
220
+ - It doesn't stop a legacy `Dispatch`, which Forge sends only to protocol-1 bridges. This bridge
221
+ registers a newer protocol, so it receives Offer and Start instead. A legacy dispatch is still
222
+ counted as busy.
223
+ - Attempts already running finish normally.
224
+
225
+ Restart procedure: yield, wait for idle, restart, then turn yield off once the new bridge has connected
226
+ (the flag file survives the restart, so the new bridge starts yielded and takes no work until then).
227
+ If the wait fails, turn yield off again so the runner doesn't stay out of placement, or leave it on
228
+ deliberately and retry later.
229
+ Run the commands as the same user and with the same `FORGE_BRIDGE_CONFIG` as the bridge so they use its
230
+ `bridge.json`, `bridge.yield.json` and `bridge.state.json`. On Windows, a shell inside an MSIX-packaged
231
+ app can have `%APPDATA%` writes virtualized away from the bridge; `--require-yield` catches that, because
232
+ the yield has to be applied by the bridge and acknowledged by Forge.
233
+
234
+ Linux or macOS:
235
+
236
+ ```bash
237
+ forge-bridge yield on
238
+ if forge-bridge status --idle --require-yield --wait 3600; then
239
+ # Stop forge-bridge connect, update it (npm install -g @loucompanion/forge-bridge@next), start it again.
240
+ forge-bridge yield off # once the new bridge has connected
241
+ else
242
+ code=$?
243
+ forge-bridge yield off # don't leave the runner out of placement
244
+ echo "Bridge is not idle (exit $code); not restarting." >&2
245
+ fi
246
+ ```
247
+
248
+ Windows PowerShell:
249
+
250
+ ```powershell
251
+ forge-bridge yield on
252
+ forge-bridge status --idle --require-yield --wait 3600
253
+ $code = $LASTEXITCODE
254
+ if ($code -eq 0) {
255
+ # Stop forge-bridge connect, update it (npm install -g @loucompanion/forge-bridge@next), start it again.
256
+ forge-bridge yield off # once the new bridge has connected
257
+ } else {
258
+ forge-bridge yield off # don't leave the runner out of placement
259
+ Write-Error "Bridge is not idle (exit $code); not restarting."
260
+ }
261
+ ```
262
+
263
+ The bridge also logs each accepted offer, each accepted dispatch and the start and end of each run,
264
+ with the dispatch attempt, lease, session and cycle ids.
265
+
178
266
  ## Pre-publication repair
179
267
 
180
268
  Before Forge commits and pushes an agent's work, the bridge runs the CI parity checks in
@@ -0,0 +1,48 @@
1
+ /**
2
+ * The AI's one look at the GIFs a user sent (GIPHY in Chat). Frames never ride in the dispatch packet,
3
+ * which goes through Forge's database outbox: at turn start the bridge takes them once from the API's
4
+ * in-memory store, shows them to a throwaway Claude call that keeps no session and has no tools, and gives
5
+ * the main turn only that call's short description. The main turn never gets the frames, and nothing the
6
+ * look call saw is written to disk by the bridge. The look call is built and run with the other provider
7
+ * launches, in `bridge-chat-provider-command.ts`.
8
+ */
9
+ import type { ProviderProcessRunner } from "../session/provider-cli/provider-cli.process.js";
10
+ /** The hub method that hands a turn its GIF frames, once. */
11
+ export declare const chatTurnGiphyFramesMethod = "ChatTurnGiphyFrames";
12
+ /** The API hands out at most four stills a GIF; any more are ignored. */
13
+ export declare const maxChatGiphyLookFrames = 4;
14
+ export interface ChatTurnGiphyFrameSet {
15
+ readonly giphyId: string;
16
+ readonly title: string;
17
+ readonly altText?: string | null;
18
+ /** Base64 JPEG stills. */
19
+ readonly frames: readonly string[];
20
+ }
21
+ export interface ChatTurnGiphyFramesResponse {
22
+ readonly accepted: boolean;
23
+ readonly gifs?: readonly ChatTurnGiphyFrameSet[] | null;
24
+ readonly code?: string | null;
25
+ }
26
+ export interface ChatGiphyLook {
27
+ readonly title: string;
28
+ readonly description: string;
29
+ }
30
+ export interface ChatGiphyLookDependencies {
31
+ /** Calls the hub's frames method. */
32
+ readonly takeFrames: (request: {
33
+ leaseId: string;
34
+ fencingToken: string;
35
+ turnId: string;
36
+ /** The packet's `giphyFramesThroughSeq`: frames only for GIFs sent at or before it. */
37
+ throughSeq: number;
38
+ }) => Promise<ChatTurnGiphyFramesResponse>;
39
+ readonly runner: ProviderProcessRunner;
40
+ readonly signal?: AbortSignal;
41
+ readonly log?: (message: string) => void;
42
+ }
43
+ /** One stream-json user message: what to do, then the frames as base64 JPEG image blocks. */
44
+ export declare function chatGiphyLookStdin(title: string, altText: string | null, frames: readonly string[]): string;
45
+ /** The look call's answer, from its stream-json `result` event, as one short line. */
46
+ export declare function chatGiphyLookDescription(stdoutLines: readonly string[]): string | null;
47
+ /** What the main turn reads about the GIFs, after the conversation. It never gets the frames. */
48
+ export declare function chatGiphyLookPromptSection(looks: readonly ChatGiphyLook[]): string;
@@ -0,0 +1,55 @@
1
+ /** The hub method that hands a turn its GIF frames, once. */
2
+ export const chatTurnGiphyFramesMethod = "ChatTurnGiphyFrames";
3
+ const maxDescriptionChars = 600;
4
+ /** The API hands out at most four stills a GIF; any more are ignored. */
5
+ export const maxChatGiphyLookFrames = 4;
6
+ /** One stream-json user message: what to do, then the frames as base64 JPEG image blocks. */
7
+ export function chatGiphyLookStdin(title, altText, frames) {
8
+ const about = altText ? `"${oneLine(title)}" (alt text: "${oneLine(altText)}")` : `"${oneLine(title)}"`;
9
+ const text = `These are ${frames.length} evenly spaced frames of a GIF from GIPHY, ${about}, that a user sent in a chat. `
10
+ + "Describe what happens in the GIF in one or two plain sentences, for someone who can't see it. "
11
+ + "Reply with the description only.";
12
+ return `${JSON.stringify({
13
+ type: "user",
14
+ message: {
15
+ role: "user",
16
+ content: [
17
+ { type: "text", text },
18
+ ...frames.map(data => ({ type: "image", source: { type: "base64", media_type: "image/jpeg", data } })),
19
+ ],
20
+ },
21
+ })}\n`;
22
+ }
23
+ /** The look call's answer, from its stream-json `result` event, as one short line. */
24
+ export function chatGiphyLookDescription(stdoutLines) {
25
+ for (const line of [...stdoutLines].reverse()) {
26
+ if (!line.trim().startsWith("{"))
27
+ continue;
28
+ try {
29
+ const event = JSON.parse(line);
30
+ if (event.type !== "result")
31
+ continue;
32
+ if (event.is_error === true || typeof event.result !== "string")
33
+ return null;
34
+ const text = oneLine(event.result);
35
+ return text ? clip(text, maxDescriptionChars) : null;
36
+ }
37
+ catch {
38
+ continue;
39
+ }
40
+ }
41
+ return null;
42
+ }
43
+ /** What the main turn reads about the GIFs, after the conversation. It never gets the frames. */
44
+ export function chatGiphyLookPromptSection(looks) {
45
+ if (looks.length === 0)
46
+ return "";
47
+ const lines = looks.map(look => `- "${oneLine(look.title)}": ${look.description}`);
48
+ return `\n\n# What the sent GIFs show\n\nA separate look at frames of the GIFs sent since your last reply:\n${lines.join("\n")}`;
49
+ }
50
+ function oneLine(value) {
51
+ return value.replace(/\s+/g, " ").replaceAll("\"", "'").trim();
52
+ }
53
+ function clip(value, max) {
54
+ return value.length <= max ? value : `${value.slice(0, max - 1).trimEnd()}…`;
55
+ }
@@ -1,5 +1,7 @@
1
1
  import type { ProviderCliCommand, ProviderProcessRunResult } from "../session/provider-cli/provider-cli.process.js";
2
- import type { ChatTurnDispatchPacket } from "./bridge-chat.types.js";
2
+ import { type ChatGiphyLook, type ChatGiphyLookDependencies } from "./bridge-chat-giphy-look.js";
3
+ export { chatTurnGiphyFramesMethod, type ChatGiphyLook, type ChatTurnGiphyFramesResponse } from "./bridge-chat-giphy-look.js";
4
+ import { type ChatTurnDispatchPacket } from "./bridge-chat.types.js";
3
5
  /** The turn-scoped handoff metadata file the bridge writes into the chat workspace. */
4
6
  export declare const chatTurnMetadataFileName = "forge-chat-metadata.json";
5
7
  /**
@@ -10,7 +12,29 @@ export declare function assertChatTurnFinished(result: Pick<ProviderProcessRunRe
10
12
  export interface ChatProviderCommandPlan {
11
13
  readonly command: ProviderCliCommand;
12
14
  readonly stdin?: string;
13
- /** Provider environment, such as the headless background-work restrictions for Claude. */
15
+ /**
16
+ * Provider environment: the host's .NET build lock (host-build-lock.ts), Codex's own home, and
17
+ * the headless background-work restrictions for Claude.
18
+ */
14
19
  readonly env?: Readonly<Record<string, string>>;
15
20
  }
16
- export declare function buildChatProviderCommand(packet: ChatTurnDispatchPacket, cwd: string): ChatProviderCommandPlan;
21
+ /** `giphyLooks` are the descriptions of the turn's sent GIFs from the look call; never their frames. */
22
+ export declare function buildChatProviderCommand(packet: ChatTurnDispatchPacket, cwd: string, giphyLooks?: readonly ChatGiphyLook[]): ChatProviderCommandPlan;
23
+ /** Writes the turn-scoped handoff metadata file: opaque handles only, no attachment content or grant nonces. */
24
+ export declare function materializeChatTurnMetadata(packet: ChatTurnDispatchPacket, workspacePath: string): Promise<void>;
25
+ /**
26
+ * Looks at the turn's sent GIFs. Returns no looks, so the turn goes ahead with the GIFs as text only, when
27
+ * none are waiting, the turn's provider is not Claude (Codex has no image input over stdin), the frames are
28
+ * gone, or a look fails.
29
+ */
30
+ export declare function lookAtChatGiphyFrames(packet: ChatTurnDispatchPacket, cwd: string, dependencies: ChatGiphyLookDependencies): Promise<readonly ChatGiphyLook[]>;
31
+ /**
32
+ * `claude -p` that keeps no session (`--no-session-persistence`), reads one stream-json user message with
33
+ * the frames as image blocks on stdin, and has no tools (`--tools ""`), no MCP servers and none of the host
34
+ * user's settings.
35
+ */
36
+ export declare function buildChatGiphyLookCommand(model: string, cwd: string): {
37
+ readonly command: string;
38
+ readonly args: readonly string[];
39
+ readonly env: Readonly<Record<string, string>>;
40
+ };
@@ -3,8 +3,15 @@
3
3
  * and the prompt that carries the conversation, its context references and its bounded handoff
4
4
  * metadata.
5
5
  */
6
- import { claudeHeadlessEnvironment, claudeHeadlessToolArgs, providerTurnEndedWithBackgroundWorkFailure } from "../session/provider-cli/claude-background-work.js";
7
- import { codexSandboxModeForPlatform } from "../session/provider-cli/provider-cli.prompts.js";
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+ import { claudeHeadlessEnvironment, providerTurnEndedWithBackgroundWorkFailure } from "../session/provider-cli/claude-background-work.js";
9
+ import { hostDotnetBuildLockEnvironment, hostDotnetBuildLockInstruction } from "../session/provider-cli/host-build-lock.js";
10
+ import { claudeIsolatedLaunchArgs, providerUserConfigIsolationUnsupported, providerUserConfigIsolationEnv } from "../session/provider-cli/provider-user-config-isolation.js";
11
+ import { codexSandboxModeForPlatform, providerEffort } from "../session/provider-cli/provider-cli.prompts.js";
12
+ import { chatGiphyLookDescription, chatGiphyLookPromptSection, chatGiphyLookStdin, maxChatGiphyLookFrames, } from "./bridge-chat-giphy-look.js";
13
+ export { chatTurnGiphyFramesMethod } from "./bridge-chat-giphy-look.js";
14
+ import { chatProviderKind } from "./bridge-chat.types.js";
8
15
  /** The turn-scoped handoff metadata file the bridge writes into the chat workspace. */
9
16
  export const chatTurnMetadataFileName = "forge-chat-metadata.json";
10
17
  /**
@@ -16,17 +23,25 @@ export function assertChatTurnFinished(result) {
16
23
  throw providerTurnEndedWithBackgroundWorkFailure("The Bridge Chat turn did not finish.");
17
24
  }
18
25
  }
19
- export function buildChatProviderCommand(packet, cwd) {
20
- const provider = packet.providerKind.trim().toLowerCase();
26
+ /** `giphyLooks` are the descriptions of the turn's sent GIFs from the look call; never their frames. */
27
+ export function buildChatProviderCommand(packet, cwd, giphyLooks = []) {
28
+ // The provider kind picks the CLI and its effort levels; an auth-path suffix such as `:bridge` does not.
29
+ const provider = chatProviderKind(packet.providerKind);
21
30
  const model = packet.model.trim();
22
- const prompt = buildChatPrompt(packet);
31
+ const prompt = buildChatPrompt(packet, giphyLooks);
23
32
  const resumeThreadId = packet.providerThreadId?.trim() || null;
33
+ // Levels the provider does not accept are dropped, so the CLI keeps its own default.
34
+ const effort = providerEffort(provider, packet.effort);
24
35
  if (provider === "codex") {
25
36
  const args = ["-s", codexSandboxModeForPlatform(process.platform, "host"), "-a", "never", "exec"];
26
37
  if (resumeThreadId) {
27
38
  args.push("--cd", cwd, "resume");
28
39
  }
29
- args.push("--model", model, "--json");
40
+ args.push("--model", model);
41
+ if (effort) {
42
+ args.push("-c", `model_reasoning_effort=${JSON.stringify(effort)}`);
43
+ }
44
+ args.push("--json");
30
45
  if (!resumeThreadId) {
31
46
  args.push("--cd", cwd);
32
47
  }
@@ -35,31 +50,25 @@ export function buildChatProviderCommand(packet, cwd) {
35
50
  args.push(resumeThreadId);
36
51
  }
37
52
  args.push("-");
38
- return { command: { command: "codex", args }, stdin: prompt };
39
- }
40
- if (provider === "cursor") {
41
- const args = ["--print", "--output-format", "stream-json", "--model", model, "--workspace", cwd];
42
- if (resumeThreadId) {
43
- args.push("--resume", resumeThreadId);
44
- }
45
- args.push("--yolo", "--approve-mcps", "--trust", prompt);
46
- return { command: { command: "cursor-agent", args } };
53
+ // Codex runs with Forge's own CODEX_HOME, not the user's ~/.codex (provider-user-config-isolation.ts).
54
+ return { command: { command: "codex", args }, stdin: prompt, env: { ...hostDotnetBuildLockEnvironment(), ...providerUserConfigIsolationEnv("codex") } };
47
55
  }
48
56
  if (provider === "claude") {
49
- const args = ["-p", "--output-format", "stream-json", "--verbose", "--model", model, "--permission-mode", "bypassPermissions", ...claudeHeadlessToolArgs()];
57
+ const args = ["-p", "--output-format", "stream-json", "--verbose", "--model", model];
58
+ if (effort) {
59
+ args.push("--effort", effort);
60
+ }
61
+ // Only Forge's context and no MCP servers (provider-user-config-isolation.ts).
62
+ args.push("--permission-mode", "bypassPermissions", ...claudeIsolatedLaunchArgs({ workingDirectory: cwd, forgeMcpConfigPath: null, headless: true }));
50
63
  if (resumeThreadId) {
51
64
  args.push("--resume", resumeThreadId);
52
65
  }
53
- return { command: { command: "claude", args }, stdin: prompt, env: claudeHeadlessEnvironment };
66
+ return { command: { command: "claude", args }, stdin: prompt, env: { ...hostDotnetBuildLockEnvironment(), ...claudeHeadlessEnvironment } };
54
67
  }
55
- return {
56
- command: {
57
- command: provider,
58
- args: ["--model", model, prompt],
59
- },
60
- };
68
+ // cursor-agent and other CLIs can't be kept from the host user's own configuration.
69
+ throw providerUserConfigIsolationUnsupported(packet.providerKind);
61
70
  }
62
- function buildChatPrompt(packet) {
71
+ function buildChatPrompt(packet, giphyLooks) {
63
72
  const messages = packet.messages
64
73
  .map((message, index) => {
65
74
  const role = message.role.trim() || `message-${index + 1}`;
@@ -77,16 +86,19 @@ function buildChatPrompt(packet) {
77
86
  ? "\n\nContinue the existing provider thread identified by the bridge; do not restart the conversation context."
78
87
  : "";
79
88
  const boundedMetadata = buildChatBoundedMetadataPrompt(packet);
89
+ // Chat turns run on the bridge's host, so they follow its .NET build lock like session turns.
90
+ const buildLock = hostDotnetBuildLockInstruction(process.env, "chat");
91
+ const hostRules = buildLock ? `\n\n# Host rules\n${buildLock}` : "";
80
92
  return `You are handling a Forge Bridge Chat turn.
81
93
 
82
94
  Conversation ID: ${packet.conversationId}
83
95
  Turn ID: ${packet.turnId}
84
96
  Provider: ${packet.providerKind}
85
- Model: ${packet.model}${continuation}${boundedMetadata}
97
+ Model: ${packet.model}${continuation}${boundedMetadata}${hostRules}
86
98
 
87
99
  # Conversation
88
100
 
89
- ${messages}${contextRefs}
101
+ ${messages}${chatGiphyLookPromptSection(giphyLooks)}${contextRefs}
90
102
  `;
91
103
  }
92
104
  function buildChatBoundedMetadataPrompt(packet) {
@@ -123,3 +135,96 @@ function buildChatBoundedMetadataPrompt(packet) {
123
135
  }
124
136
  return sections.join("\n\n");
125
137
  }
138
+ /** Writes the turn-scoped handoff metadata file: opaque handles only, no attachment content or grant nonces. */
139
+ export async function materializeChatTurnMetadata(packet, workspacePath) {
140
+ if (packet.attachmentHandoffs.length === 0 && packet.actionBrokerGrants.length === 0) {
141
+ return;
142
+ }
143
+ await fs.promises.writeFile(path.join(workspacePath, chatTurnMetadataFileName), `${JSON.stringify({
144
+ schemaVersion: 1,
145
+ attachmentHandoffs: packet.attachmentHandoffs.map((handoff) => ({
146
+ turnId: handoff.turnId,
147
+ attachmentId: handoff.attachmentId,
148
+ tempFileToken: handoff.tempFileToken,
149
+ mimeType: handoff.mimeType,
150
+ sizeBytes: handoff.sizeBytes,
151
+ sha256: handoff.sha256,
152
+ fileNameDisplay: handoff.fileNameDisplay,
153
+ expiresAt: handoff.expiresAt,
154
+ status: handoff.status,
155
+ })),
156
+ actionBrokerGrants: packet.actionBrokerGrants.map((grant) => ({
157
+ grantId: grant.grantId,
158
+ turnId: grant.turnId,
159
+ leaseId: grant.leaseId,
160
+ fencingToken: grant.fencingToken,
161
+ allowedScopes: grant.allowedScopes,
162
+ expiresAt: grant.expiresAt,
163
+ redactionStatus: grant.redactionStatus,
164
+ nonceHeldByBridge: true,
165
+ })),
166
+ }, null, 2)}\n`, "utf8");
167
+ }
168
+ /**
169
+ * Looks at the turn's sent GIFs. Returns no looks, so the turn goes ahead with the GIFs as text only, when
170
+ * none are waiting, the turn's provider is not Claude (Codex has no image input over stdin), the frames are
171
+ * gone, or a look fails.
172
+ */
173
+ export async function lookAtChatGiphyFrames(packet, cwd, dependencies) {
174
+ if (!packet.giphyFramesPending || packet.giphyFramesThroughSeq === undefined || chatProviderKind(packet.providerKind) !== "claude") {
175
+ return [];
176
+ }
177
+ let response;
178
+ try {
179
+ response = await dependencies.takeFrames({
180
+ leaseId: packet.leaseId,
181
+ fencingToken: packet.fencingToken,
182
+ turnId: packet.turnId,
183
+ throughSeq: packet.giphyFramesThroughSeq,
184
+ });
185
+ }
186
+ catch (error) {
187
+ dependencies.log?.(`GIF frames for turn ${packet.turnId} were not available: ${error instanceof Error ? error.message : String(error)}`);
188
+ return [];
189
+ }
190
+ const looks = [];
191
+ for (const gif of response.accepted ? response.gifs ?? [] : []) {
192
+ if (dependencies.signal?.aborted)
193
+ break;
194
+ const frames = gif.frames.slice(0, maxChatGiphyLookFrames);
195
+ if (frames.length === 0)
196
+ continue;
197
+ const plan = buildChatGiphyLookCommand(packet.model, cwd);
198
+ const lines = [];
199
+ const result = await dependencies.runner.run({ command: plan.command, args: plan.args, cwd, env: plan.env, stdin: chatGiphyLookStdin(gif.title, gif.altText ?? null, frames), captureOutput: false }, { onStdoutLine: line => { lines.push(line); } }, dependencies.signal).catch(() => null);
200
+ const description = result?.exitCode === 0 ? chatGiphyLookDescription(lines) : null;
201
+ if (description) {
202
+ looks.push({ title: gif.title, description });
203
+ }
204
+ else {
205
+ dependencies.log?.(`The look at a GIF for turn ${packet.turnId} gave no description; it stays text only.`);
206
+ }
207
+ }
208
+ return looks;
209
+ }
210
+ /**
211
+ * `claude -p` that keeps no session (`--no-session-persistence`), reads one stream-json user message with
212
+ * the frames as image blocks on stdin, and has no tools (`--tools ""`), no MCP servers and none of the host
213
+ * user's settings.
214
+ */
215
+ export function buildChatGiphyLookCommand(model, cwd) {
216
+ return {
217
+ command: "claude",
218
+ args: [
219
+ "-p",
220
+ "--no-session-persistence",
221
+ "--input-format", "stream-json",
222
+ "--output-format", "stream-json",
223
+ "--verbose",
224
+ "--model", model.trim(),
225
+ "--tools", "",
226
+ ...claudeIsolatedLaunchArgs({ workingDirectory: cwd, forgeMcpConfigPath: null, headless: true }),
227
+ ],
228
+ env: { ...claudeHeadlessEnvironment },
229
+ };
230
+ }
@@ -35,10 +35,25 @@ 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[];
41
46
  readonly actionBrokerGrants: readonly ChatActionBrokerGrant[];
47
+ /**
48
+ * How many sent GIFs have frames waiting for the AI's one look; absent when none or from older servers.
49
+ * The frames never ride in the packet: the bridge takes them once through the hub's `ChatTurnGiphyFrames`.
50
+ */
51
+ readonly giphyFramesPending?: number;
52
+ /**
53
+ * The newest message `Seq` the packet's messages read, present with `giphyFramesPending`. It goes back with
54
+ * `ChatTurnGiphyFrames` so the API hands out only frames of GIFs this turn's messages include.
55
+ */
56
+ readonly giphyFramesThroughSeq?: number;
42
57
  }
43
58
  export interface ChatTurnMessage {
44
59
  readonly role: string;
@@ -107,5 +122,10 @@ export interface ChatTurnCancelPacket {
107
122
  export declare function unavailableBridgeChatCapability(protocolVersion?: string, unavailableCode?: string | null, unavailableReason?: string | null): BridgeChatCapability;
108
123
  export declare function normalizeBridgeChatCapability(value: BridgeChatCapability | null | undefined): BridgeChatCapability;
109
124
  export declare function parseChatTurnDispatchPacket(value: unknown, capability?: BridgeChatCapability): ChatTurnDispatchPacket;
125
+ /**
126
+ * The provider kind of a saved provider selection: `codex:bridge` and `codex` are both `codex`.
127
+ * Forge stores the Chat role's provider with its auth-path suffix and may send it as is.
128
+ */
129
+ export declare function chatProviderKind(provider: string): string;
110
130
  export declare function isTerminalChatTurnCallbackKind(kind: ChatTurnCallbackKind): boolean;
111
131
  export declare function assertBridgeChatCallbackPayload(value: unknown, label?: string): void;
@@ -87,18 +87,27 @@ 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,
101
+ ...giphyFramesPending(packet),
100
102
  };
101
103
  }
104
+ /**
105
+ * The provider kind of a saved provider selection: `codex:bridge` and `codex` are both `codex`.
106
+ * Forge stores the Chat role's provider with its auth-path suffix and may send it as is.
107
+ */
108
+ export function chatProviderKind(provider) {
109
+ return (provider.split(":", 1)[0] ?? "").trim().toLowerCase();
110
+ }
102
111
  export function isTerminalChatTurnCallbackKind(kind) {
103
112
  return kind === "output_completed" || kind === "failed" || kind === "cancelled" || kind === "expired";
104
113
  }
@@ -304,6 +313,13 @@ function requiredUuid(source, key) {
304
313
  }
305
314
  return value;
306
315
  }
316
+ function requiredProviderKind(source) {
317
+ const kind = chatProviderKind(requiredString(source, "providerKind"));
318
+ if (kind.length === 0) {
319
+ throw new Error("providerKind must be a non-empty string.");
320
+ }
321
+ return kind;
322
+ }
307
323
  function requiredString(source, key) {
308
324
  const value = source[key];
309
325
  if (typeof value !== "string" || value.trim().length === 0) {
@@ -318,6 +334,17 @@ function boundedRequiredString(source, key, maxLength) {
318
334
  }
319
335
  return clean;
320
336
  }
337
+ function giphyFramesPending(packet) {
338
+ if (packet.giphyFramesPending === undefined || packet.giphyFramesPending === null)
339
+ return {};
340
+ const pending = requiredNonNegativeInteger(packet, "giphyFramesPending");
341
+ if (pending === 0)
342
+ return {};
343
+ // Without the cutoff the API would hand out nothing, so a packet without one asks for no frames.
344
+ if (packet.giphyFramesThroughSeq === undefined || packet.giphyFramesThroughSeq === null)
345
+ return {};
346
+ return { giphyFramesPending: pending, giphyFramesThroughSeq: requiredNonNegativeInteger(packet, "giphyFramesThroughSeq") };
347
+ }
321
348
  function requiredNonNegativeInteger(source, key) {
322
349
  const value = source[key];
323
350
  if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {