Skip to content

Commit 2ca1a9d

Browse files
committed
fix(agents): resolve pdf tool models through the canonical resolver
Inside gateway runs the prepared model runtime is a static snapshot whose ModelRegistry is empty on a fresh state dir; configured models are served through the snapshot's prepared facts. The pdf tool resolved candidates via the registry-only resolveModelFromRegistry helper, so every fallback candidate failed with `Unknown model` while the main turn and image tool (already on resolveModelAsync) worked. Resolve each pdf candidate through resolveModelAsync with the prepared stores, matching the image sibling, and delete the registry-only helper. Adds a regression test that acquires a real static prepared runtime on a fresh state dir with a config-inline model. Observed live: Mantis run 32574012855 (both lanes died in the pdf bridge).
1 parent ea1cd39 commit 2ca1a9d

8 files changed

Lines changed: 175 additions & 108 deletions

‎config/assertion-safety-baseline.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2126,7 +2126,7 @@ src/agents/tools/image-tool.helpers.ts 2
21262126
src/agents/tools/image-tool.ts 3
21272127
src/agents/tools/in-process-gateway.ts 1
21282128
src/agents/tools/media-generate-tool-actions-shared.ts 1
2129-
src/agents/tools/media-tool-shared.ts 4
2129+
src/agents/tools/media-tool-shared.ts 2
21302130
src/agents/tools/message-tool-discovery.ts 3
21312131
src/agents/tools/message-tool-execution.ts 4
21322132
src/agents/tools/message-tool-visible-content.ts 9

‎scripts/e2e/telegram-mantis-sut.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -209,8 +209,8 @@ export function writeSutConfig(params: {
209209
models: {
210210
"openai/gpt-5.6-luna": { params: { openaiWsWarmup: false, transport: "sse" } },
211211
},
212-
// Auto-resolution walks plugin manifest defaults (gpt-5.5), which this
213-
// catalog does not define; pin the pdf tool to the only harness model.
212+
// Keep the pdf tool on the one catalog model instead of walking fallback
213+
// candidates the mock never scripted.
214214
pdfModel: { primary: "openai/gpt-5.6-luna" },
215215
},
216216
entries: {

‎src/agents/tools/media-tool-shared.test.ts‎

Lines changed: 0 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ import {
1212
resolveMediaToolInboundRoots,
1313
resolveCapabilityModelConfigForTool,
1414
resolveMediaToolReferenceAccess,
15-
resolveModelFromRegistry,
1615
} from "./media-tool-shared.js";
1716

1817
// Keep media-tool-shared tests focused on root separation; channel-inbound
@@ -44,22 +43,6 @@ function normalizeHostPath(value: string): string {
4443
return path.normalize(path.resolve(value));
4544
}
4645

47-
function createModelRegistryStub(resolve: (provider: string, modelId: string) => unknown): {
48-
calls: Array<[string, string]>;
49-
registry: { find: (provider: string, modelId: string) => unknown };
50-
} {
51-
const calls: Array<[string, string]> = [];
52-
return {
53-
calls,
54-
registry: {
55-
find(provider, modelId) {
56-
calls.push([provider, modelId]);
57-
return resolve(provider, modelId);
58-
},
59-
},
60-
};
61-
}
62-
6346
describe("readBooleanToolParam", () => {
6447
it("parses booleans and true/false string tokens", () => {
6548
expect(readBooleanToolParam({ audio: true }, "audio")).toBe(true);
@@ -194,55 +177,6 @@ describe("resolveMediaToolReferenceAccess", () => {
194177
});
195178
});
196179

197-
describe("resolveModelFromRegistry", () => {
198-
it("normalizes provider and model refs before registry lookup", () => {
199-
const foundModel = { provider: "ollama", id: "qwen3.5:397b-cloud" };
200-
const { calls, registry } = createModelRegistryStub(() => foundModel);
201-
202-
const result = resolveModelFromRegistry({
203-
modelRegistry: registry,
204-
provider: " OLLAMA ",
205-
modelId: " qwen3.5:397b-cloud ",
206-
});
207-
208-
expect(calls).toEqual([["ollama", "qwen3.5:397b-cloud"]]);
209-
expect(result).toBe(foundModel);
210-
});
211-
212-
it("reports the normalized ref when the registry lookup misses", () => {
213-
const { registry } = createModelRegistryStub(() => null);
214-
215-
expect(() =>
216-
resolveModelFromRegistry({
217-
modelRegistry: registry,
218-
provider: " OLLAMA ",
219-
modelId: " qwen3.5:397b-cloud ",
220-
}),
221-
).toThrow("Unknown model: ollama/qwen3.5:397b-cloud");
222-
});
223-
224-
it("falls back to provider-prefixed custom model IDs", () => {
225-
// Custom providers can store ids with provider prefixes; try both forms so
226-
// callers can pass the short local model id.
227-
const foundModel = { provider: "kimchi", id: "kimchi/claude-opus-4-6" };
228-
const { calls, registry } = createModelRegistryStub((_, modelId) =>
229-
modelId === "kimchi/claude-opus-4-6" ? foundModel : null,
230-
);
231-
232-
const result = resolveModelFromRegistry({
233-
modelRegistry: registry,
234-
provider: "kimchi",
235-
modelId: "claude-opus-4-6",
236-
});
237-
238-
expect(calls).toEqual([
239-
["kimchi", "claude-opus-4-6"],
240-
["kimchi", "kimchi/claude-opus-4-6"],
241-
]);
242-
expect(result).toBe(foundModel);
243-
}, 180_000);
244-
});
245-
246180
describe("hasGenerationToolAvailability", () => {
247181
it("accepts config-backed custom provider auth for generation providers", () => {
248182
const cfg = {

‎src/agents/tools/media-tool-shared.ts‎

Lines changed: 0 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ import { readSnakeCaseParamRaw } from "../../param-key.js";
2323
import { loadCapabilityManifestSnapshot } from "../../plugins/capability-provider-runtime.js";
2424
import { listAvailableManifestContractValues } from "../../plugins/manifest-contract-eligibility.js";
2525
import type { AuthProfileStore } from "../auth-profiles/types.js";
26-
import { normalizeModelRef } from "../model-selection.js";
2726
import {
2827
resolveSandboxedBridgeMediaPath,
2928
type SandboxedBridgeMediaPathConfig,
@@ -696,30 +695,6 @@ export function buildTextToolResult(
696695
};
697696
}
698697

699-
/**
700-
* Resolves a catalog model while supporting registries that index model ids with provider prefixes.
701-
*/
702-
export function resolveModelFromRegistry(params: {
703-
modelRegistry: { find: (provider: string, modelId: string) => unknown };
704-
provider: string;
705-
modelId: string;
706-
}): Model {
707-
const resolvedRef = normalizeModelRef(params.provider, params.modelId, {
708-
allowPluginNormalization: false,
709-
});
710-
let model = params.modelRegistry.find(resolvedRef.provider, resolvedRef.model) as Model | null;
711-
if (!model && !resolvedRef.model.includes("/")) {
712-
model = params.modelRegistry.find(
713-
resolvedRef.provider,
714-
`${resolvedRef.provider}/${resolvedRef.model}`,
715-
) as Model | null;
716-
}
717-
if (!model) {
718-
throw new Error(`Unknown model: ${resolvedRef.provider}/${resolvedRef.model}`);
719-
}
720-
return model;
721-
}
722-
723698
/**
724699
* Loads the runtime API key for a resolved model and caches it in per-run auth storage.
725700
*/
Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
// PDF model resolution must consume configured facts from static prepared runtimes.
2+
import fs from "node:fs/promises";
3+
import { afterEach, describe, expect, it, vi } from "vitest";
4+
import { loadConfig } from "../../config/config.js";
5+
import * as pdfExtractModule from "../../media/pdf-extract.js";
6+
import * as webMedia from "../../media/web-media.js";
7+
import { withOpenClawTestState } from "../../test-utils/openclaw-test-state.js";
8+
import { acquireAgentRunPreparedModelRuntime } from "../prepared-model-runtime.js";
9+
10+
const completeMock = vi.hoisted(() => vi.fn());
11+
12+
vi.mock("../../llm/stream.js", async () => {
13+
const actual = await vi.importActual<typeof import("../../llm/stream.js")>("../../llm/stream.js");
14+
return { ...actual, complete: completeMock };
15+
});
16+
17+
vi.mock("../provider-stream.js", () => ({
18+
registerProviderStreamForModel: vi.fn(),
19+
}));
20+
21+
describe("PDF tool static prepared runtime", () => {
22+
afterEach(() => {
23+
completeMock.mockReset();
24+
vi.restoreAllMocks();
25+
});
26+
27+
it("resolves a config-inline model when the static registry is empty", async () => {
28+
await withOpenClawTestState(
29+
{
30+
label: "pdf-static-inline-model",
31+
env: { OPENAI_API_KEY: "test-key" },
32+
},
33+
async (state) => {
34+
const modelId = "gpt-5.6-luna";
35+
const modelRef = `openai/${modelId}`;
36+
await state.writeConfig({
37+
models: {
38+
mode: "replace",
39+
providers: {
40+
openai: {
41+
api: "openai-responses",
42+
baseUrl: "http://127.0.0.1:9/v1",
43+
models: [
44+
{
45+
id: modelId,
46+
name: "GPT-5.6 Luna inline fixture",
47+
reasoning: true,
48+
input: ["text"],
49+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
50+
contextWindow: 128_000,
51+
maxTokens: 8_192,
52+
},
53+
],
54+
},
55+
},
56+
},
57+
agents: {
58+
defaults: {
59+
model: { primary: modelRef },
60+
pdfModel: { primary: modelRef },
61+
},
62+
},
63+
});
64+
const config = loadConfig({
65+
pin: false,
66+
skipPluginValidation: true,
67+
skipShellEnvFallback: true,
68+
});
69+
const agentDir = state.agentDir();
70+
await fs.mkdir(agentDir, { recursive: true });
71+
const lease = await acquireAgentRunPreparedModelRuntime(
72+
{ agentDir, config },
73+
{ catalogMode: "static" },
74+
);
75+
76+
try {
77+
const stores = lease.snapshot.createStores();
78+
expect(stores.modelRegistry.find("openai", modelId)).toBeUndefined();
79+
expect(
80+
lease.snapshot.configuredRuntimeModels.map((entry) => ({
81+
provider: entry.provider,
82+
modelId: entry.modelId,
83+
})),
84+
).toContainEqual({ provider: "openai", modelId });
85+
86+
vi.spyOn(webMedia, "loadWebMediaRaw").mockResolvedValue({
87+
kind: "document",
88+
buffer: Buffer.from("%PDF-1.4 inline model fixture"),
89+
contentType: "application/pdf",
90+
fileName: "inline-model.pdf",
91+
});
92+
vi.spyOn(pdfExtractModule, "extractPdfContent").mockResolvedValue({
93+
text: "Inline model regression fixture",
94+
images: [],
95+
});
96+
completeMock.mockResolvedValue({
97+
role: "assistant",
98+
stopReason: "stop",
99+
content: [{ type: "text", text: "resolved inline model" }],
100+
});
101+
102+
const { createPdfTool } = await import("./pdf-tool.js");
103+
const tool = createPdfTool({
104+
config,
105+
agentDir,
106+
preparedModelRuntime: lease.snapshot,
107+
});
108+
if (!tool) {
109+
throw new Error("expected PDF tool");
110+
}
111+
112+
const result = await tool.execute("pdf-static-inline", {
113+
prompt: "Summarize",
114+
pdf: "/tmp/inline-model.pdf",
115+
});
116+
117+
expect(completeMock).toHaveBeenCalledWith(
118+
expect.objectContaining({ provider: "openai", id: modelId }),
119+
expect.any(Object),
120+
expect.any(Object),
121+
);
122+
expect(result.details).toMatchObject({ model: modelRef, native: false });
123+
} finally {
124+
lease.release();
125+
}
126+
},
127+
);
128+
}, 180_000);
129+
});

‎src/agents/tools/pdf-tool.test-support.ts‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import fs from "node:fs/promises";
44
import os from "node:os";
55
import path from "node:path";
66
import { type Mock, vi } from "vitest";
7+
import type { OpenClawConfig } from "../../config/config.js";
78
import * as webMedia from "../../media/web-media.js";
89
import * as modelAuth from "../model-auth.js";
910
import * as modelsConfig from "../models-config.js";
@@ -12,6 +13,25 @@ import {
1213
getModelRegistryRuntime,
1314
initializeModelRegistryRuntime,
1415
} from "../sessions/model-registry-runtime.js";
16+
import { createEmptyPluginMetadataSnapshot } from "../test-helpers/embedded-agent-runner-e2e-mocks.js";
17+
18+
type StubPreparedRuntimeSnapshot = {
19+
agentDir: string;
20+
config: OpenClawConfig;
21+
workspaceDir?: string;
22+
createStores: () => { authStorage: unknown; modelRegistry: unknown };
23+
};
24+
25+
// The canonical resolver reads prepared facts before the registry; stub snapshots
26+
// carry empty facts so registry-driven fixtures keep deciding resolution.
27+
export function withPreparedRuntimeFacts(snapshot: StubPreparedRuntimeSnapshot) {
28+
return {
29+
...snapshot,
30+
metadataSnapshot: createEmptyPluginMetadataSnapshot(snapshot.workspaceDir),
31+
configuredRuntimeModels: [],
32+
inlineProviderModels: [],
33+
};
34+
}
1535

1636
export async function withTempPdfAgentDir<T>(run: (agentDir: string) => Promise<T>): Promise<T> {
1737
const agentDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-pdf-"));
@@ -95,12 +115,12 @@ export function createPdfToolInfraStub(completeMock: Mock) {
95115
vi.spyOn(preparedModelRuntime, "acquireAgentRunPreparedModelRuntime").mockImplementation(
96116
async (input) =>
97117
({
98-
snapshot: {
118+
snapshot: withPreparedRuntimeFacts({
99119
agentDir: input.agentDir,
100120
config: input.config,
101121
workspaceDir: input.workspaceDir,
102122
createStores: () => ({ authStorage, modelRegistry }),
103-
},
123+
}),
104124
release,
105125
}) as never,
106126
);

‎src/agents/tools/pdf-tool.test.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
createPdfToolInfraStub,
1919
FAKE_PDF_MEDIA,
2020
resetPdfToolAuthEnv,
21+
withPreparedRuntimeFacts,
2122
withTempPdfAgentDir,
2223
} from "./pdf-tool.test-support.js";
2324

@@ -603,11 +604,11 @@ describe("createPdfTool", () => {
603604
);
604605
vi.spyOn(pdfNativeProviders, "anthropicAnalyzePdf").mockResolvedValue("parent summary");
605606
const cfg = withPdfModel(ANTHROPIC_PDF_MODEL);
606-
const parentPreparedModelRuntime = {
607+
const parentPreparedModelRuntime = withPreparedRuntimeFacts({
607608
agentDir,
608609
config: cfg,
609610
createStores: () => ({ authStorage, modelRegistry }),
610-
} as never;
611+
}) as never;
611612
const tool = requirePdfTool(
612613
(await loadCreatePdfTool())({
613614
config: cfg,
@@ -642,12 +643,12 @@ describe("createPdfTool", () => {
642643
const modelRegistry = createPdfModelRegistry(find);
643644
const release = vi.fn();
644645
vi.mocked(preparedModelRuntime.acquireAgentRunPreparedModelRuntime).mockResolvedValueOnce({
645-
snapshot: {
646+
snapshot: withPreparedRuntimeFacts({
646647
agentDir: "/tmp/committed-pdf-agent",
647648
workspaceDir: committedWorkspace,
648649
config: withPdfModel(GOOGLE_PDF_MODEL),
649650
createStores: () => ({ authStorage, modelRegistry }),
650-
},
651+
}),
651652
release,
652653
} as never);
653654
const geminiSpy = vi

0 commit comments

Comments
 (0)