Skip to content

Commit b8ddddd

Browse files
authored
feat(media): let agents inspect unsupported local documents (#122408)
Let eligible embedded host runs inspect root-approved unsupported documents after final sandbox, filesystem, provider, owner, and tool-policy gates. Generic ACP, sandboxed, URL-only, and restricted-tool paths retain the plain marker. Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent 77d89b2 commit b8ddddd

10 files changed

Lines changed: 607 additions & 27 deletions

‎docs/nodes/media-understanding.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -260,7 +260,8 @@ When `mode: "all"`, outputs are labeled `[Image 1/2]`, `[Audio 2/2]`, etc.
260260
- Every inbound document attachment ends in a model-visible file block. Attachments routed to image, audio, or video understanding are outside this contract; those stages own their outcomes.
261261
- Extracted file text is wrapped as untrusted external content before it's appended to the media prompt, using boundary markers like `<<<EXTERNAL_UNTRUSTED_CONTENT id="...">>>` / `<<<END_EXTERNAL_UNTRUSTED_CONTENT id="...">>>` plus a `Source: External` metadata line.
262262
- This path intentionally omits the long `SECURITY NOTICE:` banner to keep the media prompt short; the boundary markers and metadata still apply.
263-
- Unsupported files get `[Unsupported document format: <mime>. PDF and plain-text attachments can be read.]`. If the MIME type is unknown, the marker omits it.
263+
- Unsupported files saved on local disk get self-serve guidance only when the reply runtime proves it can read host-local paths (currently non-sandboxed embedded sessions). The path is fenced as untrusted external metadata; the trusted guidance tells the agent to extract the file with its own tools, and modern Office files get an unzip hint. Generic ACP backends, URL-only attachments, and sandboxed sessions keep the plain `[Unsupported document format: <mime>. PDF and plain-text attachments can be read.]` marker.
264+
- Files rejected by an operator-configured allowlist never include the self-serve path; a policy rejection must not coach the agent around the operator's decision.
264265
- Files rejected by an operator-configured `allowedMimes` list get `[Attachment type not allowed: <mime>]` instead, so the prompt never claims support the active configuration disables.
265266
- Read failures get `[Attachment could not be read]`.
266267
- URL attachments get `[Attachment skipped: URL file sources are disabled]` when URL file sources are disabled.

‎src/auto-reply/reply/dispatch-acp.test.ts‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1171,7 +1171,7 @@ describe("tryDispatchAcpReplyCore", () => {
11711171
}
11721172
});
11731173

1174-
it("passes the ACP agent directory to media understanding", async () => {
1174+
it("passes the ACP agent directory without declaring host-path access", async () => {
11751175
setReadyAcpResolution();
11761176
mockVisibleTextTurn("image turn");
11771177
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "dispatch-acp-"));
@@ -1201,12 +1201,12 @@ describe("tryDispatchAcpReplyCore", () => {
12011201
},
12021202
});
12031203

1204-
expect(
1205-
requireRecord(
1206-
mockArg(mediaUnderstandingMocks.applyMediaUnderstanding, 0, 0, "media understanding"),
1207-
"media understanding",
1208-
).agentDir,
1209-
).toBe(agentDir);
1204+
const mediaUnderstandingParams = requireRecord(
1205+
mockArg(mediaUnderstandingMocks.applyMediaUnderstanding, 0, 0, "media understanding"),
1206+
"media understanding",
1207+
);
1208+
expect(mediaUnderstandingParams.agentDir).toBe(agentDir);
1209+
expect(mediaUnderstandingParams.selfServeLocalPaths).toBeUndefined();
12101210
} finally {
12111211
await fs.rm(tempDir, { recursive: true, force: true });
12121212
}

‎src/auto-reply/reply/get-reply.message-hooks.test.ts‎

Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Tests get-reply message hooks before and after agent execution.
22
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
3+
import type { OpenClawConfig } from "../../config/types.openclaw.js";
34
import { logVerbose } from "../../globals.js";
45
import type { ApplyMediaUnderstandingResult } from "../../media-understanding/apply.js";
56
import { AGENT_HARNESS_SESSION_KEY_RESERVED_MESSAGE } from "../../sessions/agent-harness-session-key.js";
@@ -187,6 +188,52 @@ async function resetMessageHookTestState() {
187188
);
188189
}
189190

191+
async function runLocalPathSelfServeCase(params: {
192+
ctx: Partial<MsgContext>;
193+
cfg: OpenClawConfig;
194+
opts?: Parameters<typeof getReplyFromConfig>[1];
195+
provider?: string;
196+
model?: string;
197+
senderIsOwner?: boolean;
198+
}) {
199+
const ctx = buildCtx(params.ctx);
200+
const enableLocalPathSelfServe = vi.fn();
201+
mocks.applyMediaUnderstanding.mockResolvedValueOnce({
202+
outputs: [],
203+
decisions: [],
204+
extractedFileImages: [],
205+
appliedImage: false,
206+
appliedAudio: false,
207+
appliedVideo: false,
208+
appliedFile: true,
209+
enableLocalPathSelfServe,
210+
});
211+
mocks.initSessionState.mockResolvedValueOnce(
212+
createGetReplySessionState({
213+
sessionCtx: ctx,
214+
sessionKey: ctx.SessionKey,
215+
isGroup: false,
216+
}),
217+
);
218+
mocks.resolveReplyDirectives.mockResolvedValueOnce(
219+
createGetReplyContinueDirectivesResult({
220+
body: ctx.BodyForAgent ?? "read the document",
221+
abortKey: ctx.SessionKey ?? "agent:main:main",
222+
from: ctx.From ?? "webchat:operator",
223+
to: ctx.To ?? "webchat:local",
224+
senderId: ctx.SenderId ?? "operator",
225+
commandSource: "message",
226+
senderIsOwner: params.senderIsOwner ?? false,
227+
resetHookTriggered: false,
228+
provider: params.provider,
229+
model: params.model,
230+
}),
231+
);
232+
233+
await getReplyFromConfig(ctx, params.opts, withFastReplyConfig(params.cfg));
234+
return enableLocalPathSelfServe;
235+
}
236+
190237
describe("getReplyFromConfig message hooks", () => {
191238
let enrichedHookCase: {
192239
transcribed: ReturnType<typeof hookEventCall>;
@@ -367,6 +414,89 @@ describe("getReplyFromConfig message hooks", () => {
367414
);
368415
});
369416

417+
const hostDocumentCtx = {
418+
SessionKey: "agent:main:main",
419+
OriginatingChannel: undefined,
420+
Provider: "webchat",
421+
Surface: "webchat",
422+
ChatType: "direct",
423+
SenderId: "operator",
424+
} as const;
425+
426+
it("promotes local document self-service for a host main session", async () => {
427+
const enable = await runLocalPathSelfServeCase({ ctx: hostDocumentCtx, cfg: {} });
428+
expect(enable).toHaveBeenCalledOnce();
429+
});
430+
431+
it("withholds local document self-service from a sandboxed external conversation", async () => {
432+
const enable = await runLocalPathSelfServeCase({
433+
ctx: {
434+
...hostDocumentCtx,
435+
OriginatingChannel: "telegram",
436+
AccountId: "default",
437+
SenderId: "42",
438+
},
439+
cfg: {
440+
agents: {
441+
defaults: { sandbox: { mode: "non-main", scope: "agent" } },
442+
list: [{ id: "main", default: true }],
443+
},
444+
},
445+
});
446+
expect(enable).not.toHaveBeenCalled();
447+
});
448+
449+
it("withholds local document self-service when the turn cannot read files", async () => {
450+
const enable = await runLocalPathSelfServeCase({
451+
ctx: hostDocumentCtx,
452+
cfg: {},
453+
opts: { toolsAllow: ["message"] },
454+
});
455+
expect(enable).not.toHaveBeenCalled();
456+
});
457+
458+
it("withholds local document self-service from workspace-only file tools", async () => {
459+
const enable = await runLocalPathSelfServeCase({
460+
ctx: hostDocumentCtx,
461+
cfg: { tools: { fs: { workspaceOnly: true } } },
462+
});
463+
expect(enable).not.toHaveBeenCalled();
464+
});
465+
466+
it("projects local document self-service against the final provider", async () => {
467+
const cfg = { tools: { byProvider: { anthropic: { deny: ["read"] } } } };
468+
const denied = await runLocalPathSelfServeCase({
469+
ctx: hostDocumentCtx,
470+
cfg,
471+
provider: "anthropic",
472+
model: "claude-sonnet",
473+
});
474+
expect(denied).not.toHaveBeenCalled();
475+
476+
await resetMessageHookTestState();
477+
const unrelated = await runLocalPathSelfServeCase({
478+
ctx: hostDocumentCtx,
479+
cfg,
480+
provider: "openai",
481+
model: "gpt-5",
482+
});
483+
expect(unrelated).toHaveBeenCalledOnce();
484+
});
485+
486+
it("applies wildcard sender policy only to non-owner turns", async () => {
487+
const cfg = { tools: { toolsBySender: { "*": { deny: ["read"] } } } };
488+
const nonOwner = await runLocalPathSelfServeCase({ ctx: hostDocumentCtx, cfg });
489+
expect(nonOwner).not.toHaveBeenCalled();
490+
491+
await resetMessageHookTestState();
492+
const owner = await runLocalPathSelfServeCase({
493+
ctx: hostDocumentCtx,
494+
cfg,
495+
senderIsOwner: true,
496+
});
497+
expect(owner).toHaveBeenCalledOnce();
498+
});
499+
370500
it("keeps unconfigured audio with a model-locked harness", async () => {
371501
const sessionKey = "agent:main:harness:claude-cli:locked-unconfigured-audio";
372502
const sessionEntry = {

‎src/auto-reply/reply/get-reply.ts‎

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,18 @@ import {
1010
resolveSessionAgentId,
1111
resolveAgentSkillsFilter,
1212
} from "../../agents/agent-scope.js";
13+
import { resolveConversationCapabilityProfile } from "../../agents/conversation-capability-profile.js";
14+
import { projectConversationToolNames } from "../../agents/conversation-tool-policy-pipeline.js";
1315
import type { ModelCatalogSnapshot } from "../../agents/model-catalog.types.js";
1416
import { resolveModelRefFromString } from "../../agents/model-selection.js";
1517
import { publishedModelCatalogOwnerMatchesAgent } from "../../agents/prepared-model-catalog-owner.js";
18+
import { resolveSandboxRuntimeStatus } from "../../agents/sandbox.js";
1619
import { resolveAgentTimeoutMs } from "../../agents/timeout.js";
20+
import { resolveEffectiveToolFsRootExpansionAllowed } from "../../agents/tool-fs-policy.js";
1721
import { DEFAULT_AGENT_WORKSPACE_DIR, ensureAgentWorkspace } from "../../agents/workspace.js";
1822
import { resolveChannelModelOverride } from "../../channels/model-overrides.js";
1923
import { type OpenClawConfig, getRuntimeConfig } from "../../config/config.js";
24+
import { resolveGroupSessionKey } from "../../config/sessions/group.js";
2025
import { isSessionWorkStartInvalidatedError } from "../../config/sessions/lifecycle.js";
2126
import { logVerbose } from "../../globals.js";
2227
import { measureDiagnosticsTimelineSpan } from "../../infra/diagnostics-timeline.js";
@@ -71,13 +76,15 @@ import {
7176
} from "./inbound-media.js";
7277
import { emitPreAgentMessageHooks } from "./message-preprocess-hooks.js";
7378
import { createFastTestModelSelectionState, createModelSelectionState } from "./model-selection.js";
79+
import { resolveOriginMessageProvider } from "./origin-routing.js";
7480
import {
7581
PENDING_FINAL_DELIVERY_CLEAR_PATCH,
7682
sanitizePendingFinalDeliveryText,
7783
} from "./pending-final-delivery.js";
7884
import { getPreparedReplyDispatchRuntime } from "./prepared-reply-dispatch-context.js";
7985
import { attachProgressNarratorToReplyOptions } from "./progress-narrator.js";
8086
import { createReplyTimingTracker } from "./reply-timing-tracker.js";
87+
import { resolveRuntimePolicySessionKey } from "./runtime-policy-session-key.js";
8188
import { initSessionState, resolveReplySessionPreprocessingState } from "./session.js";
8289
import { mergeSkillFilters } from "./skill-filter.js";
8390
import { stageRemoteInboundMediaIfNeeded } from "./stage-remote-inbound-media.js";
@@ -162,6 +169,7 @@ async function applyMediaUnderstandingIfNeeded(params: {
162169
workspaceDir?: string;
163170
activeModel: { provider: string; model: string };
164171
processingMode?: "audio-only";
172+
selfServeLocalPaths?: boolean;
165173
}): Promise<ApplyMediaUnderstandingResult | undefined> {
166174
if (!hasInboundMediaForUnderstanding(params.ctx)) {
167175
return undefined;
@@ -183,6 +191,74 @@ function hasExplicitAudioUnderstandingConfig(cfg: OpenClawConfig): boolean {
183191
return audio !== undefined && audio.enabled !== false;
184192
}
185193

194+
function canSelfServeLocalPaths(params: {
195+
ctx: MsgContext;
196+
cfg: OpenClawConfig;
197+
agentId: string;
198+
agentDir?: string;
199+
sessionKey?: string;
200+
workspaceDir: string;
201+
provider: string;
202+
model: string;
203+
opts?: GetReplyOptions;
204+
senderIsOwner: boolean;
205+
spawnedBy?: string;
206+
}): boolean {
207+
if (
208+
params.opts?.disableTools === true ||
209+
!resolveEffectiveToolFsRootExpansionAllowed({ cfg: params.cfg, agentId: params.agentId })
210+
) {
211+
return false;
212+
}
213+
const policySessionKey = resolveRuntimePolicySessionKey({
214+
cfg: params.cfg,
215+
ctx: params.ctx,
216+
sessionKey: params.sessionKey,
217+
});
218+
if (resolveSandboxRuntimeStatus({ cfg: params.cfg, sessionKey: policySessionKey }).sandboxed) {
219+
return false;
220+
}
221+
const capabilityProfile = resolveConversationCapabilityProfile({
222+
config: params.cfg,
223+
sessionKey: policySessionKey,
224+
runSessionKey: policySessionKey === params.sessionKey ? undefined : params.sessionKey,
225+
agentId: params.agentId,
226+
agentDir: params.agentDir,
227+
agentAccountId: params.ctx.AccountId,
228+
messageProvider: resolveOriginMessageProvider({
229+
originatingChannel: params.ctx.OriginatingChannel,
230+
provider: params.ctx.Provider ?? params.ctx.Surface,
231+
}),
232+
chatType: params.ctx.ChatType,
233+
conversationToolPolicy: params.ctx.ConversationToolPolicy,
234+
groupId: resolveGroupSessionKey(params.ctx)?.id,
235+
groupChannel:
236+
normalizeOptionalString(params.ctx.GroupChannel) ??
237+
normalizeOptionalString(params.ctx.GroupSubject),
238+
groupSpace: normalizeOptionalString(params.ctx.GroupSpace),
239+
memberRoleIds: params.ctx.MemberRoleIds,
240+
spawnedBy: params.spawnedBy,
241+
senderId: normalizeOptionalString(params.ctx.SenderId),
242+
senderName: normalizeOptionalString(params.ctx.SenderName),
243+
senderUsername: normalizeOptionalString(params.ctx.SenderUsername),
244+
senderE164: normalizeOptionalString(params.ctx.SenderE164),
245+
senderIsOwner: params.senderIsOwner,
246+
modelProvider: params.provider,
247+
modelId: params.model,
248+
workspaceDir: params.workspaceDir,
249+
runtimeToolAllowlist: params.opts?.toolsAllow,
250+
inheritRuntimeToolAllowlist: true,
251+
inputProvenance: params.ctx.InputProvenance,
252+
});
253+
return (
254+
projectConversationToolNames({
255+
capabilityProfile,
256+
toolNames: ["read"],
257+
warn: () => {},
258+
}).length === 1
259+
);
260+
}
261+
186262
function withExtractedFileImages(
187263
opts: RuntimeInternalGetReplyOptions | undefined,
188264
extractedFileImages: ExtractedFileImage[] | undefined,
@@ -318,6 +394,7 @@ export async function getReplyFromConfig(
318394
| RuntimeInternalGetReplyOptions
319395
| undefined;
320396
let extractedFileImages: ExtractedFileImage[] | undefined;
397+
let enableLocalPathSelfServe: ApplyMediaUnderstandingResult["enableLocalPathSelfServe"];
321398
const agentCfg = cfg.agents?.defaults;
322399
const agentEntry = resolveAgentConfig(cfg, agentId);
323400
const configuredThinkingDefault =
@@ -467,12 +544,16 @@ export async function getReplyFromConfig(
467544
agentDir,
468545
workspaceDir,
469546
activeModel: { provider, model },
547+
// Cache and classify now; the final provider and owner policy are
548+
// resolved later, immediately before the embedded turn starts.
549+
selfServeLocalPaths: false,
470550
...(shouldApplyLockedAudio ? { processingMode: "audio-only" as const } : {}),
471551
}),
472552
);
473553
if (mediaResult?.extractedFileImages.length) {
474554
extractedFileImages = mediaResult.extractedFileImages;
475555
}
556+
enableLocalPathSelfServe = mediaResult?.enableLocalPathSelfServe;
476557
}
477558
}
478559
if (linkUnderstandingRequested && !utilityModelSelectionLocked) {
@@ -776,6 +857,24 @@ export async function getReplyFromConfig(
776857
triggerBodyNormalized,
777858
commandAuthorized,
778859
});
860+
if (
861+
enableLocalPathSelfServe &&
862+
canSelfServeLocalPaths({
863+
ctx: sessionCtx,
864+
cfg,
865+
agentId,
866+
agentDir,
867+
sessionKey,
868+
workspaceDir,
869+
provider: autoFallbackPrimaryProbe?.provider ?? provider,
870+
model: autoFallbackPrimaryProbe?.model ?? model,
871+
opts: resolvedOpts,
872+
senderIsOwner: fastCommand.senderIsOwner,
873+
spawnedBy: normalizeOptionalString(sessionEntry.spawnedBy),
874+
})
875+
) {
876+
enableLocalPathSelfServe(finalized, sessionCtx);
877+
}
779878
logResolverTiming("milestone", "before_fast_directive_prepared_reply");
780879
const fastReplyResult = await traceGetReplyPhase("reply.run_prepared_reply", () =>
781880
runPreparedReply({
@@ -1072,6 +1171,25 @@ export async function getReplyFromConfig(
10721171
}
10731172
}
10741173

1174+
if (
1175+
enableLocalPathSelfServe &&
1176+
canSelfServeLocalPaths({
1177+
ctx: sessionCtx,
1178+
cfg,
1179+
agentId,
1180+
agentDir,
1181+
sessionKey,
1182+
workspaceDir,
1183+
provider: runProvider,
1184+
model: runModel,
1185+
opts: resolvedOpts,
1186+
senderIsOwner: command.senderIsOwner,
1187+
spawnedBy: normalizeOptionalString(sessionEntry.spawnedBy),
1188+
})
1189+
) {
1190+
enableLocalPathSelfServe(finalized, sessionCtx);
1191+
}
1192+
10751193
// Already-staged facts or SDK projections must remain a single-stage contract.
10761194
if (
10771195
!useFastTestBootstrap &&

0 commit comments

Comments
 (0)