@loucompanion/forge-bridge 0.2.1-dev.17ad6c965e41 → 0.2.1-dev.4f11ffc822f9

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.
@@ -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 = [
@@ -1,7 +1,13 @@
1
+ import { ForgeFailureError } from "../session/session.types.js";
1
2
  import type { AttemptProcessChildHandle, AttemptProcessSupervisor } from "./attempt-process-supervisor.js";
2
3
  import type { HostPortLeaseOwner } from "./host-port-broker.js";
3
4
  import { HostListenerInspector } from "./host-listener-inspector.js";
5
+ import type { ProviderProcessHandlers, ProviderProcessRunner, ProviderProcessRunRequest, ProviderProcessRunResult } from "../session/provider-cli/provider-cli.process.js";
4
6
  import type { HostListenerOwnership, NodeRuntimeCommandLauncher, NodeRuntimeLaunchRequest, NodeRuntimeReadinessDiagnostics } from "./node-host-runtime-adapter.js";
7
+ export declare function brokeredHostPorts(ports: readonly {
8
+ readonly hostPort: number;
9
+ }[]): ReadonlySet<number>;
10
+ export declare function isolationViolationError(detail: string): ForgeFailureError;
5
11
  /** Launches one explicitly configured HTTP project beneath the attempt coordinator. */
6
12
  export declare class AttemptNodeRuntimeLauncher implements NodeRuntimeCommandLauncher<AttemptProcessChildHandle> {
7
13
  private readonly supervisor;
@@ -10,9 +16,39 @@ export declare class AttemptNodeRuntimeLauncher implements NodeRuntimeCommandLau
10
16
  private readonly listenerInspector;
11
17
  private readonly exactSecrets;
12
18
  private readonly diagnosticsByChild;
19
+ private readonly launchedChildren;
13
20
  constructor(supervisor: AttemptProcessSupervisor, owner: HostPortLeaseOwner, logDirectory: string, listenerInspector?: HostListenerInspector, exactSecrets?: readonly string[]);
14
21
  launch(request: NodeRuntimeLaunchRequest, signal?: AbortSignal): Promise<AttemptProcessChildHandle>;
15
22
  inspectListener(child: AttemptProcessChildHandle, request: NodeRuntimeLaunchRequest): Promise<HostListenerOwnership>;
23
+ /**
24
+ * Every loopback TCP port held by the process trees this launcher started that are still
25
+ * running, brokered or not. A launch the port broker retried leaves an exited child behind;
26
+ * it holds nothing and is skipped.
27
+ */
28
+ ownedListenerPorts(): Promise<readonly number[]>;
29
+ /**
30
+ * Why these process trees break isolation, or null when they do not: a listener the port
31
+ * broker did not assign, or listeners that could not be inspected (unproven isolation).
32
+ */
33
+ unbrokeredListenerViolation(brokered: ReadonlySet<number>): Promise<string | null>;
34
+ /**
35
+ * Re-audits these process trees on an interval until stopped, so a listener opened after
36
+ * readiness (say, a fixed admin port bound once a database connects) is caught within one
37
+ * interval. `brokered` returning null skips a tick. The first violation is reported once and
38
+ * ends the monitor. Returns the function that stops it.
39
+ */
40
+ monitorListeners(brokered: () => ReadonlySet<number> | null, onViolation: (detail: string) => Promise<void>): () => void;
16
41
  stop(child: AttemptProcessChildHandle): Promise<void>;
17
42
  readinessDiagnostics(child: AttemptProcessChildHandle): Promise<NodeRuntimeReadinessDiagnostics>;
18
43
  }
44
+ /** Runs a provider process beneath an attempt supervisor; an analysis-only provider may open no loopback listener. */
45
+ export declare class AttemptSupervisedProviderProcessRunner implements ProviderProcessRunner {
46
+ private readonly supervisor;
47
+ private readonly owner;
48
+ private readonly listenerInspector;
49
+ private readonly enforceNoListeners;
50
+ private readonly onProcessTreeStarted;
51
+ constructor(supervisor: AttemptProcessSupervisor, owner: HostPortLeaseOwner, listenerInspector: HostListenerInspector, enforceNoListeners: boolean, onProcessTreeStarted: () => void);
52
+ run(request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal): Promise<ProviderProcessRunResult>;
53
+ private awaitProviderResult;
54
+ }
@@ -6,6 +6,12 @@ import { ForgeFailureError, sanitizeFailureError } from "../session/session.type
6
6
  import { HostListenerInspector } from "./host-listener-inspector.js";
7
7
  import { writeSupervisedRuntimeDescriptor } from "./supervised-runtime-build-guard.js";
8
8
  const diagnosticTailLength = 4_000;
9
+ export function brokeredHostPorts(ports) {
10
+ return new Set(ports.map(port => port.hostPort));
11
+ }
12
+ export function isolationViolationError(detail) {
13
+ return new ForgeFailureError("host_runtime_isolation_violation", `host_runtime_isolation_violation: ${detail}; the repository's parallel promotion was revoked and its runs are serialized until isolation is proven again.`);
14
+ }
9
15
  /** Launches one explicitly configured HTTP project beneath the attempt coordinator. */
10
16
  export class AttemptNodeRuntimeLauncher {
11
17
  supervisor;
@@ -14,6 +20,7 @@ export class AttemptNodeRuntimeLauncher {
14
20
  listenerInspector;
15
21
  exactSecrets;
16
22
  diagnosticsByChild = new WeakMap();
23
+ launchedChildren = [];
17
24
  constructor(supervisor, owner, logDirectory, listenerInspector = new HostListenerInspector(), exactSecrets = []) {
18
25
  this.supervisor = supervisor;
19
26
  this.owner = owner;
@@ -63,6 +70,7 @@ export class AttemptNodeRuntimeLauncher {
63
70
  }
64
71
  const exposedChild = sanitizedChildHandle(child, this.exactSecrets);
65
72
  this.diagnosticsByChild.set(exposedChild, diagnostics);
73
+ this.launchedChildren.push(exposedChild);
66
74
  void exposedChild.result.then(result => {
67
75
  diagnostics.exited = true;
68
76
  diagnostics.exitCode = result.exitCode;
@@ -79,6 +87,65 @@ export class AttemptNodeRuntimeLauncher {
79
87
  async inspectListener(child, request) {
80
88
  return await this.listenerInspector.inspect(child, request.port, this.owner);
81
89
  }
90
+ /**
91
+ * Every loopback TCP port held by the process trees this launcher started that are still
92
+ * running, brokered or not. A launch the port broker retried leaves an exited child behind;
93
+ * it holds nothing and is skipped.
94
+ */
95
+ async ownedListenerPorts() {
96
+ const ports = new Set();
97
+ for (const child of this.launchedChildren) {
98
+ if (this.diagnosticsByChild.get(child)?.exited)
99
+ continue;
100
+ for (const port of await this.listenerInspector.inspectOwnedTcpListeners(child, this.owner))
101
+ ports.add(port);
102
+ }
103
+ return [...ports].sort((left, right) => left - right);
104
+ }
105
+ /**
106
+ * Why these process trees break isolation, or null when they do not: a listener the port
107
+ * broker did not assign, or listeners that could not be inspected (unproven isolation).
108
+ */
109
+ async unbrokeredListenerViolation(brokered) {
110
+ try {
111
+ const stray = (await this.ownedListenerPorts()).filter(port => !brokered.has(port));
112
+ return stray.length === 0
113
+ ? null
114
+ : `the launched runtime listens on port(s) the port broker did not assign (${stray.join(", ")})`;
115
+ }
116
+ catch (error) {
117
+ return `the launched runtime's listeners could not be inspected (${error instanceof Error ? error.message : String(error)})`;
118
+ }
119
+ }
120
+ /**
121
+ * Re-audits these process trees on an interval until stopped, so a listener opened after
122
+ * readiness (say, a fixed admin port bound once a database connects) is caught within one
123
+ * interval. `brokered` returning null skips a tick. The first violation is reported once and
124
+ * ends the monitor. Returns the function that stops it.
125
+ */
126
+ monitorListeners(brokered, onViolation) {
127
+ let stopped = false;
128
+ let timer;
129
+ const schedule = () => {
130
+ timer = setTimeout(() => void tick(), this.listenerInspector.ownedListenerAuditIntervalMs);
131
+ timer.unref();
132
+ };
133
+ const tick = async () => {
134
+ const ports = stopped ? null : brokered();
135
+ const violation = ports === null ? null : await this.unbrokeredListenerViolation(ports);
136
+ if (stopped)
137
+ return;
138
+ if (violation === null)
139
+ return schedule();
140
+ stopped = true;
141
+ await onViolation(violation).catch(() => undefined);
142
+ };
143
+ schedule();
144
+ return () => {
145
+ stopped = true;
146
+ clearTimeout(timer);
147
+ };
148
+ }
82
149
  async stop(child) {
83
150
  await child.stop(this.owner.fencingToken);
84
151
  }
@@ -147,3 +214,96 @@ function replaceSanitizedErrorMessage(error, message) {
147
214
  function boundedDiagnostic(value) {
148
215
  return value.replaceAll(/[\r\n\t]+/gu, " ").trim().slice(-1_000);
149
216
  }
217
+ /** Runs a provider process beneath an attempt supervisor; an analysis-only provider may open no loopback listener. */
218
+ export class AttemptSupervisedProviderProcessRunner {
219
+ supervisor;
220
+ owner;
221
+ listenerInspector;
222
+ enforceNoListeners;
223
+ onProcessTreeStarted;
224
+ constructor(supervisor, owner, listenerInspector, enforceNoListeners, onProcessTreeStarted) {
225
+ this.supervisor = supervisor;
226
+ this.owner = owner;
227
+ this.listenerInspector = listenerInspector;
228
+ this.enforceNoListeners = enforceNoListeners;
229
+ this.onProcessTreeStarted = onProcessTreeStarted;
230
+ }
231
+ async run(request, handlers = {}, signal) {
232
+ const baselineListeners = this.enforceNoListeners
233
+ ? new Set(await this.listenerInspector.inspectLoopbackListeners())
234
+ : new Set();
235
+ const child = await this.supervisor.startChildReady("provider", request, handlers, signal, { maxStartAttempts: request.stdin === undefined ? 1 : 3, retryDelayMs: 100 });
236
+ this.onProcessTreeStarted();
237
+ try {
238
+ return await this.awaitProviderResult(child, baselineListeners, signal);
239
+ }
240
+ finally {
241
+ // The provider tree, and the MCP server inside it, is gone. A managed command that
242
+ // server started now has no supervisor and no receipt writer, so it must not keep
243
+ // running into the next provider generation. This never rejects; a command it
244
+ // cannot prove stopped is left to attempt teardown, which fails closed.
245
+ await this.supervisor.stopOrphanedManagedCommands();
246
+ }
247
+ }
248
+ async awaitProviderResult(child, baselineListeners, signal) {
249
+ if (!this.enforceNoListeners)
250
+ return await child.result;
251
+ let settled = false;
252
+ let inspectionFailure;
253
+ const monitor = (async () => {
254
+ while (!settled) {
255
+ try {
256
+ const ports = (await this.listenerInspector.inspectOwnedLoopbackListeners(child, this.owner))
257
+ .filter(port => !baselineListeners.has(port));
258
+ if (ports.length > 0) {
259
+ inspectionFailure = new Error(`host_analysis_listener_violation: analysis-only provider opened undeclared loopback listener(s): ${ports.join(", ")}.`);
260
+ await child.stop(this.owner.fencingToken).catch(() => undefined);
261
+ return;
262
+ }
263
+ }
264
+ catch (error) {
265
+ inspectionFailure = error;
266
+ await child.stop(this.owner.fencingToken).catch(() => undefined);
267
+ return;
268
+ }
269
+ await waitForAnalysisInspection(250, signal).catch(error => {
270
+ if (!settled && !signal?.aborted)
271
+ inspectionFailure = error;
272
+ });
273
+ }
274
+ })();
275
+ try {
276
+ const result = await child.result;
277
+ settled = true;
278
+ await monitor;
279
+ if (inspectionFailure)
280
+ throw inspectionFailure;
281
+ return result;
282
+ }
283
+ catch (error) {
284
+ settled = true;
285
+ await monitor.catch(() => undefined);
286
+ if (inspectionFailure)
287
+ throw inspectionFailure;
288
+ throw error;
289
+ }
290
+ }
291
+ }
292
+ function waitForAnalysisInspection(milliseconds, signal) {
293
+ if (signal?.aborted)
294
+ return Promise.reject(cancellationError(signal));
295
+ return new Promise((resolve, reject) => {
296
+ const timer = setTimeout(() => {
297
+ signal?.removeEventListener("abort", abort);
298
+ resolve();
299
+ }, milliseconds);
300
+ const abort = () => {
301
+ clearTimeout(timer);
302
+ reject(cancellationError(signal));
303
+ };
304
+ signal?.addEventListener("abort", abort, { once: true });
305
+ });
306
+ }
307
+ function cancellationError(signal) {
308
+ return new Error(String(signal?.reason ?? "Dispatch cancelled while waiting for host runtime singleton ownership."));
309
+ }