Skip to content

Commit b65879e

Browse files
fix: deliver requested image artifacts across agent runtimes (#124910)
* fix: distinguish image inspection from delivery Clarify that image-reading tools only load private model context, prefer native Codex image inspection when available, and preserve explicit outbound tool media across Claude CLI loopback runs. Co-authored-by: pash <[email protected]> * fix: propagate CLI vision capability * chore: refresh CI after main fix --------- Co-authored-by: pash <[email protected]>
1 parent 327974f commit b65879e

35 files changed

Lines changed: 299 additions & 38 deletions

‎extensions/codex/src/app-server/dynamic-tool-build.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -420,6 +420,30 @@ describe("Codex app-server dynamic tool build", () => {
420420
]);
421421
});
422422

423+
it.each([
424+
{ nativeToolSurfaceEnabled: true, expected: ["message"] },
425+
{ nativeToolSurfaceEnabled: false, expected: ["image", "message"] },
426+
])(
427+
"uses the active native image loader when native tools are $nativeToolSurfaceEnabled",
428+
async ({ nativeToolSurfaceEnabled, expected }) => {
429+
const workspaceDir = path.join(tempDir, "workspace");
430+
const params = createParams(path.join(tempDir, "session.jsonl"), workspaceDir);
431+
params.disableTools = false;
432+
params.model = createCodexTestModel("codex", ["text", "image"]);
433+
params.runtimePlan = createCodexRuntimePlanFixture();
434+
setOpenClawCodingToolsFactoryForTests(() => [
435+
createRuntimeDynamicTool("image"),
436+
createRuntimeDynamicTool("message"),
437+
]);
438+
439+
const tools = await buildDynamicToolsForTest(params, workspaceDir, {
440+
nativeToolSurfaceEnabled,
441+
});
442+
443+
expect(tools.map((tool) => tool.name)).toEqual(expected);
444+
},
445+
);
446+
423447
it("removes managed web_search when domain-restricted Codex hosted search is active", async () => {
424448
const workspaceDir = path.join(tempDir, "workspace");
425449
const params = createParams(path.join(tempDir, "session.jsonl"), workspaceDir);

‎extensions/codex/src/app-server/dynamic-tool-build.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ import {
4949
createNodeProcessDynamicTool,
5050
isCodexDynamicToolExcluded,
5151
} from "./shell-dynamic-tools.js";
52-
import { filterToolsForVisionInputs } from "./vision-tools.js";
52+
import { filterCodexVisionTools } from "./vision-tools.js";
5353
import { resolveCodexWebSearchPlan, type CodexNativeWebSearchSupport } from "./web-search.js";
5454

5555
type OpenClawCodingToolsOptions = NonNullable<
@@ -402,9 +402,9 @@ export async function buildDynamicTools(input: DynamicToolBuildParams) {
402402
nativeExecutionPolicy,
403403
);
404404
toolBuildStages.mark("codex-filtering");
405-
const visionFilteredTools = filterToolsForVisionInputs(codexFilteredTools, {
405+
const visionFilteredTools = filterCodexVisionTools(codexFilteredTools, {
406406
modelHasVision,
407-
hasInboundImages: (params.images?.length ?? 0) > 0,
407+
nativeImageInspectionEnabled: input.nativeToolSurfaceEnabled === true,
408408
});
409409
toolBuildStages.mark("vision-filtering");
410410
const webSearchPresent = visionFilteredTools.some((tool) => tool.name === "web_search");

‎extensions/codex/src/app-server/run-attempt.vision-tools.test.ts‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
// Codex tests cover run attempt.vision tools plugin behavior.
22
import { describe, expect, it } from "vitest";
3-
import { filterToolsForVisionInputs } from "./vision-tools.js";
3+
import { filterCodexVisionTools } from "./vision-tools.js";
44

55
describe("Codex dynamic tool filtering", () => {
6-
it("drops the image tool when the model already has inbound vision input", () => {
7-
const toolNames = filterToolsForVisionInputs(
6+
it("drops the image tool when native Codex image inspection is active", () => {
7+
const toolNames = filterCodexVisionTools(
88
[{ name: "image" }, { name: "read" }, { name: "write" }],
99
{
1010
modelHasVision: true,
11-
hasInboundImages: true,
11+
nativeImageInspectionEnabled: true,
1212
},
1313
).map((tool) => tool.name);
1414

@@ -17,19 +17,19 @@ describe("Codex dynamic tool filtering", () => {
1717
expect(toolNames).not.toContain("image");
1818
});
1919

20-
it("keeps the image tool unless both model vision and inbound images are present", () => {
20+
it("keeps the image tool when the model lacks vision or native image inspection is disabled", () => {
2121
const tools = [{ name: "image" }, { name: "read" }];
2222

2323
expect(
24-
filterToolsForVisionInputs(tools, {
24+
filterCodexVisionTools(tools, {
2525
modelHasVision: false,
26-
hasInboundImages: true,
26+
nativeImageInspectionEnabled: true,
2727
}),
2828
).toBe(tools);
2929
expect(
30-
filterToolsForVisionInputs(tools, {
30+
filterCodexVisionTools(tools, {
3131
modelHasVision: true,
32-
hasInboundImages: false,
32+
nativeImageInspectionEnabled: false,
3333
}),
3434
).toBe(tools);
3535
});

‎extensions/codex/src/app-server/side-question.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ import {
124124
resolveCodexBindingModelProviderFallback,
125125
resolveReasoningEffort,
126126
} from "./thread-lifecycle.js";
127-
import { filterToolsForVisionInputs } from "./vision-tools.js";
127+
import { filterCodexVisionTools } from "./vision-tools.js";
128128
import {
129129
resolveCodexWebSearchPlan,
130130
type CodexNativeWebSearchSupport,
@@ -1106,9 +1106,9 @@ async function createCodexSideToolBridge(input: {
11061106
requireExplicitMessageTarget: true,
11071107
});
11081108
const codexFilteredTools = filterCodexDynamicTools(allTools, input.pluginConfig);
1109-
tools = filterToolsForVisionInputs(codexFilteredTools, {
1109+
tools = filterCodexVisionTools(codexFilteredTools, {
11101110
modelHasVision: runtimeModel.input?.includes("image") ?? false,
1111-
hasInboundImages: false,
1111+
nativeImageInspectionEnabled: input.nativeToolSurfaceEnabled,
11121112
});
11131113
}
11141114
const requestedWebSearchPlan = resolveCodexWebSearchPlan({

‎extensions/codex/src/app-server/vision-tools.ts‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,15 @@
11
/**
2-
* Filters Codex dynamic tools for turns that already contain image inputs so
3-
* models with native vision do not get redundant image-inspection tools.
2+
* Codex's enabled native surface includes its stable view_image loader. Keep
3+
* OpenClaw's image tool only when that surface or model vision is unavailable.
44
*/
5-
/** Removes the image tool when the model can directly consume inbound images. */
6-
export function filterToolsForVisionInputs<T extends { name?: string }>(
5+
export function filterCodexVisionTools<T extends { name?: string }>(
76
tools: T[],
87
params: {
98
modelHasVision: boolean;
10-
hasInboundImages: boolean;
9+
nativeImageInspectionEnabled: boolean;
1110
},
1211
): T[] {
13-
if (!params.modelHasVision || !params.hasInboundImages) {
12+
if (!params.modelHasVision || !params.nativeImageInspectionEnabled) {
1413
return tools;
1514
}
1615
return tools.filter((tool) => tool.name !== "image");

‎src/agents/cli-output-contracts.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,10 @@ export type CliOutput = {
5454
messagingToolSentMediaUrls?: string[];
5555
messagingToolSentTargets?: MessagingToolSend[];
5656
messagingToolSourceReplyPayloads?: MessagingToolSourceReplyPayload[];
57+
/** Trust-filtered explicit outbound media captured before CLI result normalization. */
58+
toolMediaUrls?: string[];
59+
toolAudioAsVoice?: boolean;
60+
toolTrustedLocalMedia?: boolean;
5761
yielded?: true;
5862
};
5963

‎src/agents/cli-runner.reliability.test.ts‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1033,6 +1033,89 @@ describe("runCliAgent reliability", () => {
10331033
expect(supervisorSpawnMock).toHaveBeenCalledTimes(1);
10341034
});
10351035

1036+
it("projects explicit outbound MCP media without retaining echoed image bytes", async () => {
1037+
const echoedBase64 = "private-echoed-base64";
1038+
const mediaUrls = [
1039+
"https://example.test/one.png",
1040+
"https://example.test/two.png",
1041+
"https://example.test/three.png",
1042+
];
1043+
supervisorSpawnMock.mockImplementationOnce(async (...args: unknown[]) => {
1044+
const input = args[0] as Parameters<ReturnType<typeof getProcessSupervisor>["spawn"]>[0];
1045+
const captureKey = input.env?.OPENCLAW_MCP_CLI_CAPTURE_KEY ?? "";
1046+
for (const [index, mediaUrl] of mediaUrls.entries()) {
1047+
const captureHandle = markMcpLoopbackToolCallStarted({
1048+
captureKey,
1049+
toolName: "image_generate",
1050+
args: { prompt: `image ${index + 1}` },
1051+
});
1052+
if (!captureHandle) {
1053+
throw new Error("Expected outbound media capture");
1054+
}
1055+
recordMcpLoopbackToolCallResult({
1056+
captureHandle,
1057+
toolName: "image_generate",
1058+
args: { prompt: `image ${index + 1}` },
1059+
result: {
1060+
content: [
1061+
{
1062+
type: "image",
1063+
data: echoedBase64,
1064+
mimeType: "image/png",
1065+
},
1066+
],
1067+
details: { media: { mediaUrls: [mediaUrl] } },
1068+
},
1069+
outcome: "completed",
1070+
});
1071+
markMcpLoopbackToolCallFinished(captureHandle);
1072+
}
1073+
for (const [toolName, media] of [
1074+
["image", { mediaUrls: ["/tmp/private.png"], outbound: false }],
1075+
["untrusted_tool", { mediaUrls: ["/tmp/untrusted.png"] }],
1076+
] as const) {
1077+
const captureHandle = markMcpLoopbackToolCallStarted({
1078+
captureKey,
1079+
toolName,
1080+
args: {},
1081+
});
1082+
if (!captureHandle) {
1083+
throw new Error("Expected private media capture");
1084+
}
1085+
recordMcpLoopbackToolCallResult({
1086+
captureHandle,
1087+
toolName,
1088+
args: {},
1089+
result: {
1090+
content: [{ type: "image", data: echoedBase64, mimeType: "image/png" }],
1091+
details: { media },
1092+
},
1093+
outcome: "completed",
1094+
});
1095+
markMcpLoopbackToolCallFinished(captureHandle);
1096+
}
1097+
return makeManagedRun({ stdout: "done" });
1098+
});
1099+
const context = makeClaudePreparedContext({
1100+
sessionKey: "agent:main:outbound-media",
1101+
runId: "run-outbound-media",
1102+
});
1103+
context.mcpDeliveryCapture = true;
1104+
1105+
const result = await runPreparedCliAgent(context);
1106+
1107+
expect(result.payloads).toEqual([
1108+
{
1109+
text: "done",
1110+
mediaUrls,
1111+
mediaUrl: mediaUrls[0],
1112+
},
1113+
]);
1114+
expect(JSON.stringify(result)).not.toContain(echoedBase64);
1115+
expect(JSON.stringify(result)).not.toContain("/tmp/private.png");
1116+
expect(JSON.stringify(result)).not.toContain("/tmp/untrusted.png");
1117+
});
1118+
10361119
it("surfaces a CLI failure after a delivered progress reply", async () => {
10371120
supervisorSpawnMock.mockClear();
10381121
supervisorSpawnMock.mockImplementationOnce(async (...args: unknown[]) => {
@@ -3077,6 +3160,7 @@ describe("runCliAgent reliability", () => {
30773160
expect(result.payloads).toEqual([{ text: "hello from cli" }]);
30783161
expect(getReplyPayloadMetadata(result.payloads?.[0] ?? {})).toMatchObject({
30793162
assistantTranscriptOwned: true,
3163+
assistantTranscriptIdempotencyKey: "cli-assistant:run-persist-cli",
30803164
});
30813165
expect(onUserMessagePersisted).toHaveBeenCalledOnce();
30823166
expect(onUserMessagePersisted).toHaveBeenCalledWith(

‎src/agents/cli-runner.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -575,6 +575,7 @@ export async function runPreparedCliAgent(
575575
effectiveCliSessionId,
576576
bindingFlushOk,
577577
assistantTranscriptOwned: assistantTranscript.owned,
578+
assistantTranscriptIdempotencyKey: assistantTranscript.idempotencyKey,
578579
usedHistoryPrompt,
579580
userTurnHandled,
580581
sessionBindingDisabled,

‎src/agents/cli-runner/cli-run-settlement.ts‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import type { EmbeddedAgentRunResult } from "../embedded-agent-runner.js";
1919
import { resolveExplicitFinalSourceReplyDeliveryEvidence } from "../embedded-agent-runner/delivery-evidence.js";
2020
import { resolveAuthProfileFailureReason } from "../embedded-agent-runner/run/auth-profile-failure-policy.js";
2121
import { buildEmbeddedRunPayloads } from "../embedded-agent-runner/run/payloads.js";
22+
import { mergeAttemptToolMediaPayloads } from "../embedded-agent-runner/run/tool-media-payloads.js";
2223
import { coerceToFailoverError, isFailoverError } from "../failover-error.js";
2324
import { CliAuthProfilePreparationError } from "./auth-profile-preparation-error.js";
2425
import { hashCliReseedPrompt } from "./reseed-envelope.js";
@@ -425,13 +426,15 @@ export function buildCliRunResult(params: {
425426
effectiveCliSessionId?: string;
426427
bindingFlushOk?: boolean;
427428
assistantTranscriptOwned?: boolean;
429+
assistantTranscriptIdempotencyKey?: string;
428430
usedHistoryPrompt: boolean;
429431
userTurnHandled: boolean;
430432
sessionBindingDisabled: boolean;
431433
preparedContextAgentMeta: { contextTokens?: number };
432434
}): EmbeddedAgentRunResult {
433435
const {
434436
assistantTranscriptOwned,
437+
assistantTranscriptIdempotencyKey,
435438
bindingFlushOk,
436439
context,
437440
effectiveCliSessionId,
@@ -460,12 +463,27 @@ export function buildCliRunResult(params: {
460463
: text
461464
? [
462465
assistantTranscriptOwned
463-
? setReplyPayloadMetadata({ text }, { assistantTranscriptOwned: true })
466+
? setReplyPayloadMetadata(
467+
{ text },
468+
{
469+
assistantTranscriptOwned: true,
470+
...(assistantTranscriptIdempotencyKey
471+
? { assistantTranscriptIdempotencyKey }
472+
: {}),
473+
},
474+
)
464475
: { text },
465476
]
466477
: runParams.allowEmptyAssistantReplyAsSilent === true
467478
? [{ text: SILENT_REPLY_TOKEN }]
468479
: undefined;
480+
const payloadsWithToolMedia = mergeAttemptToolMediaPayloads({
481+
payloads,
482+
toolMediaUrls: output.toolMediaUrls,
483+
toolAudioAsVoice: output.toolAudioAsVoice,
484+
toolTrustedLocalMedia: output.toolTrustedLocalMedia,
485+
sourceReplyDeliveryMode: runParams.sourceReplyDeliveryMode,
486+
});
469487
const unflushedCliSessionId =
470488
!sessionBindingDisabled && effectiveCliSessionId && bindingFlushOk === false
471489
? effectiveCliSessionId
@@ -524,7 +542,7 @@ export function buildCliRunResult(params: {
524542
});
525543

526544
return {
527-
payloads,
545+
payloads: payloadsWithToolMedia,
528546
meta: {
529547
durationMs: Date.now() - context.started,
530548
...(output.finalPromptText ? { finalPromptText: output.finalPromptText } : {}),

‎src/agents/cli-runner/cli-run-transcript.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,7 @@ export async function persistCliAssistantTranscript(params: {
146146
};
147147
}): Promise<{
148148
owned: boolean;
149+
idempotencyKey?: string;
149150
terminalAnchor?: import("../../config/sessions/session-accessor.js").TranscriptEntryAnchor;
150151
}> {
151152
const { runParams } = params;
@@ -167,6 +168,7 @@ export async function persistCliAssistantTranscript(params: {
167168
return { owned: false };
168169
}
169170
try {
171+
const idempotencyKey = `cli-assistant:${runParams.runId}`;
170172
const result = await appendExactAssistantMessageToSessionTranscript({
171173
sessionKey: runParams.sessionKey,
172174
agentId: runParams.agentId,
@@ -178,7 +180,7 @@ export async function persistCliAssistantTranscript(params: {
178180
? { expectedWriterRunId: runParams.expectedWriterRunId }
179181
: {}),
180182
storePath: runParams.storePath,
181-
idempotencyKey: `cli-assistant:${runParams.runId}`,
183+
idempotencyKey,
182184
config: runParams.config,
183185
beforeMessageWrite: runAgentHarnessBeforeMessageWriteHook,
184186
message: buildAssistantMessage({
@@ -202,7 +204,11 @@ export async function persistCliAssistantTranscript(params: {
202204
log.warn(`CLI assistant transcript persistence skipped: ${result.reason}`);
203205
return { owned: result.code === "blocked" || result.code === "session-rebound" };
204206
}
205-
return { owned: true, ...(result.anchor ? { terminalAnchor: result.anchor } : {}) };
207+
return {
208+
owned: true,
209+
idempotencyKey,
210+
...(result.anchor ? { terminalAnchor: result.anchor } : {}),
211+
};
206212
} catch (error) {
207213
log.warn(`CLI assistant transcript persistence failed: ${formatErrorMessage(error)}`);
208214
return { owned: false };

0 commit comments

Comments
 (0)