@loucompanion/forge-bridge 0.2.1-dev.c3166221b6e7 → 0.2.1-dev.eac6976df5e9

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 (39) hide show
  1. package/dist/bridge/bridge-chat-giphy-look.d.ts +48 -0
  2. package/dist/bridge/bridge-chat-giphy-look.js +55 -0
  3. package/dist/bridge/bridge-chat-provider-command.d.ts +22 -1
  4. package/dist/bridge/bridge-chat-provider-command.js +102 -4
  5. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  6. package/dist/bridge/bridge-chat.types.js +12 -0
  7. package/dist/bridge/bridge.service.d.ts +2 -0
  8. package/dist/bridge/bridge.service.js +11 -31
  9. package/dist/runtime/host-load-admission.d.ts +5 -0
  10. package/dist/runtime/host-load-governor-config.d.ts +10 -1
  11. package/dist/runtime/host-load-governor-config.js +4 -1
  12. package/dist/runtime/host-load-governor.d.ts +8 -1
  13. package/dist/runtime/host-load-governor.js +33 -3
  14. package/dist/runtime/host-load-test-slot.js +7 -0
  15. package/dist/sandbox/runtime.js +1 -1
  16. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  17. package/dist/session/provider-cli/provider-cli.merge-integrity.js +28 -8
  18. package/dist/session/sandbox-host-capacity-gate.js +1 -1
  19. package/dist/session/session.service.js +8 -4
  20. package/dist/session/session.types.d.ts +1 -0
  21. package/dist/session/session.types.js +2 -2
  22. package/dist/version.d.ts +1 -1
  23. package/dist/version.js +1 -1
  24. package/dist/worktree/wip-git.d.ts +9 -0
  25. package/dist/worktree/wip-git.js +21 -4
  26. package/dist/worktree/wip-refs.d.ts +15 -0
  27. package/dist/worktree/wip-refs.js +29 -2
  28. package/dist/worktree/wip-restore.d.ts +8 -0
  29. package/dist/worktree/wip-restore.js +115 -25
  30. package/dist/worktree/wip-snapshot.d.ts +5 -2
  31. package/dist/worktree/wip-snapshot.js +15 -13
  32. package/dist/worktree/worktree-origin-sync.d.ts +1 -0
  33. package/dist/worktree/worktree-origin-sync.js +1 -0
  34. package/dist/worktree/worktree-wip-events.js +19 -2
  35. package/dist/worktree/worktree-wip.d.ts +1 -0
  36. package/dist/worktree/worktree-wip.js +6 -1
  37. package/dist/worktree/worktree.service.js +2 -0
  38. package/dist/worktree/worktree.types.d.ts +4 -0
  39. package/package.json +1 -1
@@ -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,4 +1,6 @@
1
1
  import type { ProviderCliCommand, ProviderProcessRunResult } from "../session/provider-cli/provider-cli.process.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";
2
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";
@@ -16,4 +18,23 @@ export interface ChatProviderCommandPlan {
16
18
  */
17
19
  readonly env?: Readonly<Record<string, string>>;
18
20
  }
19
- 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,10 +3,14 @@
3
3
  * and the prompt that carries the conversation, its context references and its bounded handoff
4
4
  * metadata.
5
5
  */
6
+ import fs from "node:fs";
7
+ import path from "node:path";
6
8
  import { claudeHeadlessEnvironment, providerTurnEndedWithBackgroundWorkFailure } from "../session/provider-cli/claude-background-work.js";
7
9
  import { hostDotnetBuildLockEnvironment, hostDotnetBuildLockInstruction } from "../session/provider-cli/host-build-lock.js";
8
10
  import { claudeIsolatedLaunchArgs, providerUserConfigIsolationUnsupported, providerUserConfigIsolationEnv } from "../session/provider-cli/provider-user-config-isolation.js";
9
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";
10
14
  import { chatProviderKind } from "./bridge-chat.types.js";
11
15
  /** The turn-scoped handoff metadata file the bridge writes into the chat workspace. */
12
16
  export const chatTurnMetadataFileName = "forge-chat-metadata.json";
@@ -19,11 +23,12 @@ export function assertChatTurnFinished(result) {
19
23
  throw providerTurnEndedWithBackgroundWorkFailure("The Bridge Chat turn did not finish.");
20
24
  }
21
25
  }
22
- export function buildChatProviderCommand(packet, cwd) {
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 = []) {
23
28
  // The provider kind picks the CLI and its effort levels; an auth-path suffix such as `:bridge` does not.
24
29
  const provider = chatProviderKind(packet.providerKind);
25
30
  const model = packet.model.trim();
26
- const prompt = buildChatPrompt(packet);
31
+ const prompt = buildChatPrompt(packet, giphyLooks);
27
32
  const resumeThreadId = packet.providerThreadId?.trim() || null;
28
33
  // Levels the provider does not accept are dropped, so the CLI keeps its own default.
29
34
  const effort = providerEffort(provider, packet.effort);
@@ -63,7 +68,7 @@ export function buildChatProviderCommand(packet, cwd) {
63
68
  // cursor-agent and other CLIs can't be kept from the host user's own configuration.
64
69
  throw providerUserConfigIsolationUnsupported(packet.providerKind);
65
70
  }
66
- function buildChatPrompt(packet) {
71
+ function buildChatPrompt(packet, giphyLooks) {
67
72
  const messages = packet.messages
68
73
  .map((message, index) => {
69
74
  const role = message.role.trim() || `message-${index + 1}`;
@@ -93,7 +98,7 @@ Model: ${packet.model}${continuation}${boundedMetadata}${hostRules}
93
98
 
94
99
  # Conversation
95
100
 
96
- ${messages}${contextRefs}
101
+ ${messages}${chatGiphyLookPromptSection(giphyLooks)}${contextRefs}
97
102
  `;
98
103
  }
99
104
  function buildChatBoundedMetadataPrompt(packet) {
@@ -130,3 +135,96 @@ function buildChatBoundedMetadataPrompt(packet) {
130
135
  }
131
136
  return sections.join("\n\n");
132
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
+ }
@@ -44,6 +44,16 @@ export interface ChatTurnDispatchPacket {
44
44
  readonly requestedCapabilities: readonly BridgeChatRequestedCapability[];
45
45
  readonly attachmentHandoffs: readonly ChatAttachmentHandoffHandle[];
46
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;
47
57
  }
48
58
  export interface ChatTurnMessage {
49
59
  readonly role: string;
@@ -98,6 +98,7 @@ export function parseChatTurnDispatchPacket(value, capability = unavailableBridg
98
98
  requestedCapabilities,
99
99
  attachmentHandoffs,
100
100
  actionBrokerGrants,
101
+ ...giphyFramesPending(packet),
101
102
  };
102
103
  }
103
104
  /**
@@ -333,6 +334,17 @@ function boundedRequiredString(source, key, maxLength) {
333
334
  }
334
335
  return clean;
335
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
+ }
336
348
  function requiredNonNegativeInteger(source, key) {
337
349
  const value = source[key];
338
350
  if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
@@ -140,6 +140,8 @@ export declare class ForgeBridgeService implements BridgeService {
140
140
  stop(): Promise<void>;
141
141
  private handleChatTurn;
142
142
  private createChatTurnWorkspace;
143
+ /** Has Claude look at the turn's sent GIFs once, pulling their frames from the hub; no looks means text only. */
144
+ private lookAtChatGiphyFrames;
143
145
  private runChatProviderProcess;
144
146
  private sendChatProviderEvent;
145
147
  private sendChatAbortTerminal;
@@ -9,7 +9,7 @@ import { bridgeChatCapabilityFor, supportsDraftImageAttachmentsFor } from "../sh
9
9
  import { redactText } from "../shared/redaction/redaction.js";
10
10
  import { BridgeSessionService } from "../session/session.service.js";
11
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";
12
+ import { assertChatTurnFinished, buildChatProviderCommand, chatTurnGiphyFramesMethod, lookAtChatGiphyFrames, materializeChatTurnMetadata, } 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";
@@ -704,9 +704,18 @@ export class ForgeBridgeService {
704
704
  await fs.promises.mkdir(root, { recursive: true });
705
705
  return await fs.promises.mkdtemp(path.join(root, `${safePathComponent(packet.turnId)}-`));
706
706
  }
707
+ /** Has Claude look at the turn's sent GIFs once, pulling their frames from the hub; no looks means text only. */
708
+ async lookAtChatGiphyFrames(packet, active, cwd) {
709
+ return await lookAtChatGiphyFrames(packet, cwd, {
710
+ runner: this.chatProcessRunner,
711
+ signal: active.controller.signal,
712
+ log: logBridgeStatus,
713
+ takeFrames: async (request) => await this.connection?.invoke(chatTurnGiphyFramesMethod, request) ?? { accepted: false },
714
+ });
715
+ }
707
716
  async runChatProviderProcess(packet, active, cwd) {
708
717
  const output = createProviderOutputState(packet.providerKind);
709
- const plan = buildChatProviderCommand(packet, cwd);
718
+ const plan = buildChatProviderCommand(packet, cwd, await this.lookAtChatGiphyFrames(packet, active, cwd));
710
719
  const redactionSecrets = chatRedactionSecrets(packet);
711
720
  let started = false;
712
721
  const result = await this.chatProcessRunner.run({
@@ -2748,35 +2757,6 @@ const defaultChatTurnLeaseMs = 60 * 60 * 1000;
2748
2757
  const maxChatEventContentChars = 4000;
2749
2758
  const maxChatTerminalTextChars = 120_000;
2750
2759
  const maxChatExactSecretChars = 8 * 1024;
2751
- async function materializeChatTurnMetadata(packet, workspacePath) {
2752
- if (packet.attachmentHandoffs.length === 0 && packet.actionBrokerGrants.length === 0) {
2753
- return;
2754
- }
2755
- await fs.promises.writeFile(path.join(workspacePath, chatTurnMetadataFileName), `${JSON.stringify({
2756
- schemaVersion: 1,
2757
- attachmentHandoffs: packet.attachmentHandoffs.map((handoff) => ({
2758
- turnId: handoff.turnId,
2759
- attachmentId: handoff.attachmentId,
2760
- tempFileToken: handoff.tempFileToken,
2761
- mimeType: handoff.mimeType,
2762
- sizeBytes: handoff.sizeBytes,
2763
- sha256: handoff.sha256,
2764
- fileNameDisplay: handoff.fileNameDisplay,
2765
- expiresAt: handoff.expiresAt,
2766
- status: handoff.status,
2767
- })),
2768
- actionBrokerGrants: packet.actionBrokerGrants.map((grant) => ({
2769
- grantId: grant.grantId,
2770
- turnId: grant.turnId,
2771
- leaseId: grant.leaseId,
2772
- fencingToken: grant.fencingToken,
2773
- allowedScopes: grant.allowedScopes,
2774
- expiresAt: grant.expiresAt,
2775
- redactionStatus: grant.redactionStatus,
2776
- nonceHeldByBridge: true,
2777
- })),
2778
- }, null, 2)}\n`, "utf8");
2779
- }
2780
2760
  function chatTurnLeaseExpiresAt(packet, nowMs = Date.now()) {
2781
2761
  const defaultExpiresAtMs = nowMs + defaultChatTurnLeaseMs;
2782
2762
  const metadataExpiresAtMs = [
@@ -55,6 +55,11 @@ export interface HostLoadAdmissionDecision {
55
55
  readonly reservedCpuCores: number;
56
56
  readonly reservedMemoryBytes: number;
57
57
  readonly detail: string;
58
+ /**
59
+ * Set on a host test slot wait whose holders are all healthy (owner alive, lease renewed, not retained):
60
+ * the queue is moving, so the wait does not count toward the stalled-wait limit.
61
+ */
62
+ readonly progressing?: boolean;
58
63
  }
59
64
  /**
60
65
  * Decision 0013 admission rule. A step is admitted when the reserved cost of
@@ -18,8 +18,17 @@ export interface HostLoadGovernorConfig {
18
18
  readonly backpressureSamples: number;
19
19
  /** Host memory PSI `full avg10` (percent) above which admission is a hard stop. */
20
20
  readonly memoryFullThreshold: number;
21
- /** Maximum queue wait before a retryable host_capacity_timeout. */
21
+ /**
22
+ * FORGE_HOST_LOAD_MAX_WAIT_MS: the longest a step waits while its queue is stalled before a retryable
23
+ * host_capacity_timeout. Time spent behind holders of the host test slot that are all healthy (owner
24
+ * alive, lease renewed, not retained) does not count: their steps are making progress.
25
+ */
22
26
  readonly maxWaitMs: number;
27
+ /**
28
+ * FORGE_HOST_LOAD_MAX_TOTAL_WAIT_MS: the longest a step may queue in all, healthy holders or not; the
29
+ * backstop for a holder that is alive but never finishes. Never below maxWaitMs.
30
+ */
31
+ readonly maxTotalWaitMs: number;
23
32
  /** Steps allowed at once when PSI is unavailable (the per-host semaphore fallback). */
24
33
  readonly fallbackSlots: number;
25
34
  /** After this long at the head of the queue, later waiters may no longer overtake it. */
@@ -9,6 +9,7 @@ export const defaultHostLoadGovernorConfig = {
9
9
  backpressureSamples: 2,
10
10
  memoryFullThreshold: 5,
11
11
  maxWaitMs: 30 * 60_000,
12
+ maxTotalWaitMs: 4 * 60 * 60_000,
12
13
  fallbackSlots: 1,
13
14
  antiStarvationMs: 2 * 60_000,
14
15
  leaseMs: 2 * 60_000,
@@ -27,6 +28,7 @@ export function hostLoadGovernorEnabled(config) {
27
28
  }
28
29
  export function loadHostLoadGovernorConfig(environment = process.env) {
29
30
  const defaults = defaultHostLoadGovernorConfig;
31
+ const maxWaitMs = bounded(environment.FORGE_HOST_LOAD_MAX_WAIT_MS, defaults.maxWaitMs, 1_000, 24 * 60 * 60_000);
30
32
  return {
31
33
  mode: parseHostLoadGovernorMode(environment.FORGE_HOST_LOAD_GOVERNOR),
32
34
  testSlots: Math.round(bounded(environment.FORGE_HOST_LOAD_TEST_SLOTS, defaults.testSlots, 0, 8)),
@@ -35,7 +37,8 @@ export function loadHostLoadGovernorConfig(environment = process.env) {
35
37
  cpuPressureThreshold: bounded(environment.FORGE_HOST_LOAD_CPU_PRESSURE_THRESHOLD, defaults.cpuPressureThreshold, 1, 100),
36
38
  backpressureSamples: Math.round(bounded(environment.FORGE_HOST_LOAD_BACKPRESSURE_SAMPLES, defaults.backpressureSamples, 1, 60)),
37
39
  memoryFullThreshold: bounded(environment.FORGE_HOST_LOAD_MEMORY_FULL_THRESHOLD, defaults.memoryFullThreshold, 0, 100),
38
- maxWaitMs: bounded(environment.FORGE_HOST_LOAD_MAX_WAIT_MS, defaults.maxWaitMs, 1_000, 24 * 60 * 60_000),
40
+ maxWaitMs,
41
+ maxTotalWaitMs: Math.max(maxWaitMs, bounded(environment.FORGE_HOST_LOAD_MAX_TOTAL_WAIT_MS, defaults.maxTotalWaitMs, 1_000, 24 * 60 * 60_000)),
39
42
  fallbackSlots: Math.round(bounded(environment.FORGE_HOST_LOAD_FALLBACK_SLOTS, defaults.fallbackSlots, 1, 64)),
40
43
  antiStarvationMs: defaults.antiStarvationMs,
41
44
  leaseMs: defaults.leaseMs,
@@ -51,7 +51,7 @@ export interface HostLoadAdmission {
51
51
  /** The gate heavy steps call before launching. */
52
52
  export interface HostLoadStepGate {
53
53
  readonly enabled: boolean;
54
- /** The longest a step may queue before host_capacity_timeout, when the gate knows it. */
54
+ /** The longest a step may queue in all before host_capacity_timeout, when the gate knows it. */
55
55
  readonly maxWaitMs?: number;
56
56
  acquire(request: HostLoadStepRequest, options?: HostLoadAcquireOptions): Promise<HostLoadAdmission>;
57
57
  }
@@ -150,6 +150,13 @@ export declare class HostLoadGovernor implements HostLoadStepGate {
150
150
  */
151
151
  private runningStepsMemoryBytes;
152
152
  private logicalCpus;
153
+ /**
154
+ * Waiting behind healthy holders of the host test slot is progress: their steps run, and the slot passes
155
+ * down the queue as they finish. Any other wait (a holder past its lease or whose owner is gone, the
156
+ * budget, a recovering ledger) counts toward maxWaitMs from the last time the queue made progress.
157
+ */
158
+ private checkStalled;
159
+ private timeOut;
153
160
  private settle;
154
161
  /** Renewed tokens reset their lease clock; fenced ones stop their steps (they keep their cost until released). */
155
162
  private applyHeldOutcome;
@@ -66,7 +66,7 @@ export class HostLoadGovernor {
66
66
  });
67
67
  }
68
68
  get maxWaitMs() {
69
- return this.config.maxWaitMs;
69
+ return this.config.maxTotalWaitMs;
70
70
  }
71
71
  async acquire(request, options = {}) {
72
72
  if (!this.enabled) {
@@ -85,15 +85,17 @@ export class HostLoadGovernor {
85
85
  if (signal?.aborted)
86
86
  throw abortError(signal);
87
87
  return await new Promise((resolve, reject) => {
88
+ const enqueuedAtMs = monotonicNowMs();
88
89
  const waiter = {
89
90
  request,
90
- enqueuedAtMs: monotonicNowMs(),
91
+ enqueuedAtMs,
91
92
  signal,
92
93
  onWaiting: options.onWaiting,
93
94
  resolve,
94
95
  reject,
95
96
  abort: () => this.settle(waiter, () => reject(abortError(signal))),
96
97
  deadline: null,
98
+ progressAtMs: enqueuedAtMs,
97
99
  lastDecision: null,
98
100
  settled: false,
99
101
  ticket: this.config.testSlots > 0 && takesHostTestSlot(request.stepClass)
@@ -107,7 +109,8 @@ export class HostLoadGovernor {
107
109
  }
108
110
  : null,
109
111
  };
110
- waiter.deadline = setTimeout(() => this.settle(waiter, () => reject(new HostCapacityTimeoutError(request.stepClass, request.label, monotonicNowMs() - waiter.enqueuedAtMs, waiter.lastDecision?.detail ?? "the host stayed at capacity."))), this.config.maxWaitMs);
112
+ // The backstop: even behind healthy holders, a step queues no longer than maxTotalWaitMs.
113
+ waiter.deadline = setTimeout(() => this.timeOut(waiter, `${waiter.lastDecision?.detail ?? "The host stayed at capacity."} It reached the longest a step may queue (${minutes(this.config.maxTotalWaitMs)}).`), this.config.maxTotalWaitMs);
111
114
  waiter.deadline.unref?.();
112
115
  signal?.addEventListener("abort", waiter.abort, { once: true });
113
116
  // Foreground goes ahead of background, except background that has already
@@ -233,6 +236,7 @@ export class HostLoadGovernor {
233
236
  waiter.lastDecision = decision;
234
237
  if (first && !waiter.settled)
235
238
  void Promise.resolve(waiter.onWaiting?.(decision)).catch(() => undefined);
239
+ this.checkStalled(waiter, decision);
236
240
  continue;
237
241
  }
238
242
  const entry = {
@@ -310,6 +314,7 @@ export class HostLoadGovernor {
310
314
  return {
311
315
  ...decision,
312
316
  admitted: false,
317
+ progressing: false,
313
318
  reason: "ledger_recovering",
314
319
  detail: `The host load ledger was corrupt and was quarantined; admissions resume at ${transaction.recoveringUntil}, once running steps have restored their reservations.`,
315
320
  };
@@ -387,6 +392,26 @@ export class HostLoadGovernor {
387
392
  return reported;
388
393
  return Math.max(1, typeof os.availableParallelism === "function" ? os.availableParallelism() : os.cpus().length);
389
394
  }
395
+ /**
396
+ * Waiting behind healthy holders of the host test slot is progress: their steps run, and the slot passes
397
+ * down the queue as they finish. Any other wait (a holder past its lease or whose owner is gone, the
398
+ * budget, a recovering ledger) counts toward maxWaitMs from the last time the queue made progress.
399
+ */
400
+ checkStalled(waiter, decision) {
401
+ if (waiter.settled)
402
+ return;
403
+ const nowMs = monotonicNowMs();
404
+ if (decision.reason === "host_test_slot" && decision.progressing === true) {
405
+ waiter.progressAtMs = nowMs;
406
+ return;
407
+ }
408
+ if (nowMs - waiter.progressAtMs < this.config.maxWaitMs)
409
+ return;
410
+ this.timeOut(waiter, `${decision.detail} The queue made no progress for ${minutes(nowMs - waiter.progressAtMs)}.`);
411
+ }
412
+ timeOut(waiter, detail) {
413
+ this.settle(waiter, () => waiter.reject(new HostCapacityTimeoutError(waiter.request.stepClass, waiter.request.label, monotonicNowMs() - waiter.enqueuedAtMs, detail)));
414
+ }
390
415
  settle(waiter, complete) {
391
416
  if (waiter.settled)
392
417
  return;
@@ -592,6 +617,11 @@ function tighterMemory(hostAvailable, cgroupHeadroom) {
592
617
  return hostAvailable;
593
618
  return hostAvailable === null ? cgroupHeadroom : Math.min(hostAvailable, cgroupHeadroom);
594
619
  }
620
+ /** Whole minutes for messages (at least 1); sub-minute limits only occur in tests and tuning. */
621
+ function minutes(ms) {
622
+ const whole = Math.max(1, Math.round(ms / 60_000));
623
+ return whole === 1 ? "1 minute" : `${whole} minutes`;
624
+ }
595
625
  function abortError(signal) {
596
626
  if (signal.reason instanceof Error)
597
627
  return signal.reason;
@@ -55,8 +55,15 @@ export function decideHostTestSlot(input) {
55
55
  admitted,
56
56
  reason: "host_test_slot",
57
57
  detail: `Waiting for the host test slot (${input.testSlots} at once): ${heldBy}; ${ahead} step(s) ahead in the host queue.`,
58
+ // Only a running, healthy holder is progress. With no holder the steps ahead are waiting too (for
59
+ // the budget, say), and that wait must count as stalled, not reset the clock.
60
+ progressing: holders.length > 0 && holders.every(healthyHolder),
58
61
  };
59
62
  }
63
+ /** A holder whose step is still running under a live, renewed lease; the ledger reclaims the rest. */
64
+ function healthyHolder(token) {
65
+ return !token.degradedAt && !token.fencedAt && !token.retainedAt;
66
+ }
60
67
  function describeHolder(token) {
61
68
  const attempt = token.dispatchAttemptId ? `, attempt ${token.dispatchAttemptId}` : "";
62
69
  const state = token.degradedAt
@@ -170,7 +170,7 @@ export class DockerSandboxRuntime {
170
170
  const brokered = this.hostLoadGate?.enabled === true;
171
171
  const workerArgs = workerCreateArgs(runtimeDispatch, validated, resources, labels, imageDigest, securityOptions);
172
172
  const createArgs = brokered
173
- ? withSandboxHostCapacityBroker(workerArgs, imageDigest, this.hostLoadGate.maxWaitMs ?? defaultHostLoadGovernorConfig.maxWaitMs)
173
+ ? withSandboxHostCapacityBroker(workerArgs, imageDigest, this.hostLoadGate.maxWaitMs ?? defaultHostLoadGovernorConfig.maxTotalWaitMs)
174
174
  : workerArgs;
175
175
  const createdContainer = await this.docker(createArgs, 60_000, runtimeSignal);
176
176
  const containerId = dockerObjectId(createdContainer.stdout, "container");
@@ -57,17 +57,20 @@ export declare class MergeResolutionUnresolvedConflictError extends ForgeFailure
57
57
  export declare function isMergeInProgress(git: GitRunner, worktreePath: string): Promise<boolean>;
58
58
  export declare function readInProgressMerge(git: GitRunner, worktreePath: string): Promise<InProgressMerge | null>;
59
59
  /**
60
- * Fails before `git add -A` can silently resolve a conflict:
60
+ * Fails before `git add -A` can silently resolve a conflict, during a merge or whenever the index
61
+ * holds unmerged paths without one (a WIP snapshot re-applied across a branch move that conflicted,
62
+ * see wip-restore.ts):
61
63
  * - a modify/delete conflict, by keeping whatever is on disk;
62
64
  * - a binary (or other marker-less) conflict, by staging whichever side is on disk;
63
65
  * - a content conflict, by staging its conflict markers. This includes markers
64
66
  * the provider already staged, which clears the unmerged stages, so every path
65
- * both sides changed is checked too.
67
+ * both sides of the merge changed is checked too, or without a merge every path
68
+ * the worktree's WIP re-apply conflict record lists.
66
69
  * A text conflict the agent resolved in the working tree without `git add` is
67
70
  * still unmerged here and is accepted once its markers are gone.
68
71
  */
69
72
  export declare function assertNoUnresolvedMergeConflicts(git: GitRunner, worktreePath: string): Promise<void>;
70
- export declare function readUnresolvedMergeConflicts(git: GitRunner, worktreePath: string, merge: InProgressMerge): Promise<readonly UnresolvedMergeConflict[]>;
73
+ export declare function readUnresolvedMergeConflicts(git: GitRunner, worktreePath: string, merge: InProgressMerge | null): Promise<readonly UnresolvedMergeConflict[]>;
71
74
  /**
72
75
  * Staging excludes some worktree changes (Forge runtime output) by unstaging them
73
76
  * back to HEAD. During a merge HEAD is the story side, so an excluded path the merge