Skip to content

Commit 16a6470

Browse files
committed
fix(providers): load trusted external thinking policies
1 parent 43634f6 commit 16a6470

11 files changed

Lines changed: 449 additions & 72 deletions

‎extensions/zai/index.ts‎

Lines changed: 2 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ import { detectZaiEndpoint, type ZaiEndpointId } from "./detect.js";
3636
import { zaiMediaUnderstandingProvider } from "./media-understanding-provider.js";
3737
import { buildZaiModelDefinition, resolveZaiBaseUrl } from "./model-definitions.js";
3838
import { applyZaiConfig, applyZaiProviderConfig, resolveZaiModelId } from "./onboard.js";
39+
import { isGlm52ModelId, resolveThinkingProfile } from "./provider-policy-api.js";
3940

4041
const PROVIDER_ID = "zai";
4142
const GLM5_TEMPLATE_MODEL_ID = "glm-4.7";
@@ -128,10 +129,6 @@ function isDisabledThinkingLevel(thinkingLevel: ProviderWrapStreamFnContext["thi
128129
return thinkingLevel === "off";
129130
}
130131

131-
function isGlm52ModelId(modelId?: string | null): boolean {
132-
return normalizeLowercaseStringOrEmpty(modelId).startsWith("glm-5.2");
133-
}
134-
135132
function mapThinkingLevelToZaiReasoningEffort(
136133
thinkingLevel: ProviderWrapStreamFnContext["thinkingLevel"],
137134
): "high" | "max" | undefined {
@@ -394,24 +391,7 @@ export default definePluginEntry({
394391
}),
395392
prepareExtraParams: (ctx) => defaultToolStreamExtraParams(ctx.extraParams),
396393
wrapStreamFn: (ctx) => wrapZaiStreamFn(ctx),
397-
resolveThinkingProfile: (ctx) =>
398-
isGlm52ModelId(ctx.modelId)
399-
? {
400-
levels: [
401-
{ id: "off", label: "off" },
402-
{ id: "low", label: "low" },
403-
{ id: "high", label: "high" },
404-
{ id: "max", label: "max" },
405-
],
406-
defaultLevel: "off",
407-
}
408-
: {
409-
levels: [
410-
{ id: "off", label: "off" },
411-
{ id: "low", label: "on" },
412-
],
413-
defaultLevel: "off",
414-
},
394+
resolveThinkingProfile,
415395
isModernModelRef: ({ modelId }) => {
416396
const lower = normalizeLowercaseStringOrEmpty(modelId);
417397
return (
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// Z.AI tests cover its cold provider thinking policy.
2+
import { describe, expect, it } from "vitest";
3+
import { resolveThinkingProfile } from "./provider-policy-api.js";
4+
5+
describe("zai provider thinking policy", () => {
6+
it.each(["glm-5.2", "glm-5.2-flash"])("exposes full GLM 5.2 levels for %s", (modelId) => {
7+
expect(resolveThinkingProfile({ provider: "zai", modelId })).toEqual({
8+
levels: [
9+
{ id: "off", label: "off" },
10+
{ id: "low", label: "low" },
11+
{ id: "high", label: "high" },
12+
{ id: "max", label: "max" },
13+
],
14+
defaultLevel: "off",
15+
});
16+
});
17+
18+
it.each(["glm-5.1", "glm-4.7"])("keeps older GLM models binary for %s", (modelId) => {
19+
expect(resolveThinkingProfile({ provider: "zai", modelId })).toEqual({
20+
levels: [
21+
{ id: "off", label: "off" },
22+
{ id: "low", label: "on" },
23+
],
24+
defaultLevel: "off",
25+
});
26+
});
27+
});
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Z.AI public policy surface shared by cold selection and the provider runtime.
2+
import type {
3+
ProviderDefaultThinkingPolicyContext,
4+
ProviderThinkingProfile,
5+
} from "openclaw/plugin-sdk/plugin-entry";
6+
import { normalizeLowercaseStringOrEmpty } from "openclaw/plugin-sdk/string-coerce-runtime";
7+
8+
export function isGlm52ModelId(modelId?: string | null): boolean {
9+
return normalizeLowercaseStringOrEmpty(modelId).startsWith("glm-5.2");
10+
}
11+
12+
export function resolveThinkingProfile(
13+
ctx: ProviderDefaultThinkingPolicyContext,
14+
): ProviderThinkingProfile {
15+
if (isGlm52ModelId(ctx.modelId)) {
16+
return {
17+
levels: [
18+
{ id: "off", label: "off" },
19+
{ id: "low", label: "low" },
20+
{ id: "high", label: "high" },
21+
{ id: "max", label: "max" },
22+
],
23+
defaultLevel: "off",
24+
};
25+
}
26+
return {
27+
levels: [
28+
{ id: "off", label: "off" },
29+
{ id: "low", label: "on" },
30+
],
31+
defaultLevel: "off",
32+
};
33+
}

‎src/plugins/provider-policy-surface.ts‎

Lines changed: 49 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,10 @@ import type {
1616
ProviderDefaultThinkingPolicyContext,
1717
ProviderThinkingProfile,
1818
} from "./provider-thinking.types.js";
19-
import { loadBundledPluginPublicArtifactModuleSync } from "./public-surface-loader.js";
19+
import {
20+
loadBundledPluginPublicArtifactModuleSync,
21+
loadPluginPublicArtifactModuleSync,
22+
} from "./public-surface-loader.js";
2023

2124
const PROVIDER_POLICY_ARTIFACT_CANDIDATES = ["provider-policy-api.js"] as const;
2225
const providerPolicySurfaceByPluginId = new Map<string, BundledProviderPolicySurface | null>();
@@ -52,35 +55,64 @@ function hasProviderPolicyHook(
5255
);
5356
}
5457

55-
/** Loads policy hooks directly by canonical bundled plugin id. */
56-
export function resolveDirectBundledProviderPolicySurface(
57-
pluginId: string,
58-
): BundledProviderPolicySurface | null {
59-
const cacheKey = `${resolveBundledPluginsDir() ?? ""}\0${pluginId}`;
60-
const cached = providerPolicySurfaceByPluginId.get(cacheKey);
58+
function resolveCachedProviderPolicySurface(params: {
59+
cacheKey: string;
60+
loadModule: (artifactBasename: string) => Record<string, unknown>;
61+
missingSurfacePrefix: string;
62+
}): BundledProviderPolicySurface | null {
63+
const cached = providerPolicySurfaceByPluginId.get(params.cacheKey);
6164
if (cached !== undefined) {
6265
return cached;
6366
}
6467
for (const artifactBasename of PROVIDER_POLICY_ARTIFACT_CANDIDATES) {
6568
try {
66-
const mod = loadBundledPluginPublicArtifactModuleSync<Record<string, unknown>>({
67-
dirName: pluginId,
68-
artifactBasename,
69-
});
69+
const mod = params.loadModule(artifactBasename);
7070
if (hasProviderPolicyHook(mod)) {
71-
providerPolicySurfaceByPluginId.set(cacheKey, mod);
71+
providerPolicySurfaceByPluginId.set(params.cacheKey, mod);
7272
return mod;
7373
}
7474
} catch (error) {
75-
if (
76-
error instanceof Error &&
77-
error.message.startsWith("Unable to resolve bundled plugin public surface ")
78-
) {
75+
if (error instanceof Error && error.message.startsWith(params.missingSurfacePrefix)) {
7976
continue;
8077
}
8178
throw error;
8279
}
8380
}
84-
providerPolicySurfaceByPluginId.set(cacheKey, null);
81+
providerPolicySurfaceByPluginId.set(params.cacheKey, null);
8582
return null;
8683
}
84+
85+
/** Loads policy hooks directly by canonical bundled plugin id. */
86+
export function resolveDirectBundledProviderPolicySurface(
87+
pluginId: string,
88+
): BundledProviderPolicySurface | null {
89+
return resolveCachedProviderPolicySurface({
90+
cacheKey: `${resolveBundledPluginsDir() ?? ""}\0${pluginId}`,
91+
loadModule: (artifactBasename) =>
92+
loadBundledPluginPublicArtifactModuleSync<Record<string, unknown>>({
93+
dirName: pluginId,
94+
artifactBasename,
95+
}),
96+
missingSurfacePrefix: "Unable to resolve bundled plugin public surface ",
97+
});
98+
}
99+
100+
/** Loads policy hooks from a host-verified official external plugin install. */
101+
export function resolveTrustedExternalProviderPolicySurface(params: {
102+
pluginId: string;
103+
pluginRoot: string;
104+
trustedOfficialInstall?: boolean;
105+
}): BundledProviderPolicySurface | null {
106+
if (params.trustedOfficialInstall !== true) {
107+
return null;
108+
}
109+
return resolveCachedProviderPolicySurface({
110+
cacheKey: `${params.pluginRoot}\0${params.pluginId}`,
111+
loadModule: (artifactBasename) =>
112+
loadPluginPublicArtifactModuleSync<Record<string, unknown>>({
113+
pluginRoot: params.pluginRoot,
114+
artifactBasename,
115+
}),
116+
missingSurfacePrefix: "Unable to resolve plugin public surface ",
117+
});
118+
}

‎src/plugins/provider-public-artifacts.test.ts‎

Lines changed: 87 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,33 @@ import path from "node:path";
55
import { importFreshModule } from "openclaw/plugin-sdk/test-fixtures";
66
import { afterEach, describe, expect, it, vi } from "vitest";
77
import type { ModelProviderConfig } from "../config/types.models.js";
8-
import { resolveBundledProviderPolicySurface } from "./provider-public-artifacts.js";
8+
import {
9+
resolveBundledProviderPolicySurface,
10+
resolveProviderPolicySurface,
11+
} from "./provider-public-artifacts.js";
12+
13+
function writeExternalPolicyFixture(): string {
14+
const pluginRoot = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-provider-policy-external-"));
15+
fs.writeFileSync(
16+
path.join(pluginRoot, "provider-policy-api.js"),
17+
[
18+
"export function resolveThinkingProfile({ modelId }) {",
19+
' return modelId === "full"',
20+
' ? { levels: [{ id: "off" }, { id: "high" }, { id: "max" }], defaultLevel: "off" }',
21+
' : { levels: [{ id: "off" }, { id: "low", label: "on" }], defaultLevel: "off" };',
22+
"}",
23+
"",
24+
].join("\n"),
25+
"utf8",
26+
);
27+
return pluginRoot;
28+
}
929

1030
describe("provider public artifacts", () => {
1131
const originalBundledPluginsDir = process.env.OPENCLAW_BUNDLED_PLUGINS_DIR;
1232
const originalTrustBundledPluginsDir = process.env.OPENCLAW_TEST_TRUST_BUNDLED_PLUGINS_DIR;
1333

14-
afterEach(() => {
34+
function restoreBundledPluginEnv() {
1535
if (originalBundledPluginsDir === undefined) {
1636
delete process.env.OPENCLAW_BUNDLED_PLUGINS_DIR;
1737
} else {
@@ -22,6 +42,10 @@ describe("provider public artifacts", () => {
2242
} else {
2343
process.env.OPENCLAW_TEST_TRUST_BUNDLED_PLUGINS_DIR = originalTrustBundledPluginsDir;
2444
}
45+
}
46+
47+
afterEach(() => {
48+
restoreBundledPluginEnv();
2549
vi.doUnmock("./bundled-dir.js");
2650
vi.doUnmock("./manifest-registry.js");
2751
vi.doUnmock("./public-surface-loader.js");
@@ -98,6 +122,67 @@ describe("provider public artifacts", () => {
98122
});
99123
});
100124

125+
it("loads trusted official external provider policy before runtime registration", () => {
126+
const bundledPluginsDir = fs.mkdtempSync(
127+
path.join(os.tmpdir(), "openclaw-empty-bundled-plugins-"),
128+
);
129+
const pluginRoot = writeExternalPolicyFixture();
130+
131+
try {
132+
process.env.OPENCLAW_BUNDLED_PLUGINS_DIR = bundledPluginsDir;
133+
process.env.OPENCLAW_TEST_TRUST_BUNDLED_PLUGINS_DIR = "1";
134+
const fixturePlugin = {
135+
id: "fixture-provider",
136+
origin: "external",
137+
trustedOfficialInstall: true,
138+
rootDir: pluginRoot,
139+
providers: ["fixture-provider"],
140+
cliBackends: [],
141+
} as const;
142+
const surface = resolveProviderPolicySurface("fixture-provider", {
143+
manifestRegistry: { plugins: [fixturePlugin as never] },
144+
});
145+
146+
expect(
147+
surface
148+
?.resolveThinkingProfile?.({ provider: "fixture-provider", modelId: "full" })
149+
?.levels.map((level) => level.id),
150+
).toEqual(["off", "high", "max"]);
151+
expect(
152+
surface
153+
?.resolveThinkingProfile?.({ provider: "fixture-provider", modelId: "legacy" })
154+
?.levels.map((level) => level.label),
155+
).toEqual([undefined, "on"]);
156+
} finally {
157+
restoreBundledPluginEnv();
158+
fs.rmSync(pluginRoot, { recursive: true, force: true });
159+
fs.rmSync(bundledPluginsDir, { recursive: true, force: true });
160+
}
161+
});
162+
163+
it("does not load public policy code from untrusted external plugins", () => {
164+
const pluginRoot = writeExternalPolicyFixture();
165+
try {
166+
expect(
167+
resolveProviderPolicySurface("fixture-provider", {
168+
manifestRegistry: {
169+
plugins: [
170+
{
171+
id: "fixture-provider",
172+
origin: "external",
173+
rootDir: pluginRoot,
174+
providers: ["fixture-provider"],
175+
cliBackends: [],
176+
} as never,
177+
],
178+
},
179+
}),
180+
).toBeNull();
181+
} finally {
182+
fs.rmSync(pluginRoot, { recursive: true, force: true });
183+
}
184+
});
185+
101186
it("resolves multi-provider policy artifacts by manifest-owned provider id", async () => {
102187
const bundledPluginsDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-provider-policy-"));
103188
const pluginDir = path.join(bundledPluginsDir, "openai");

‎src/plugins/provider-public-artifacts.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { resolveBundledPluginsDir } from "./bundled-dir.js";
44
import { loadPluginManifestRegistry, type PluginManifestRegistry } from "./manifest-registry.js";
55
import {
66
resolveDirectBundledProviderPolicySurface,
7+
resolveTrustedExternalProviderPolicySurface,
78
type BundledProviderPolicySurface,
89
} from "./provider-policy-surface.js";
910

@@ -78,3 +79,36 @@ export function resolveBundledProviderPolicySurface(
7879
}
7980
return resolveDirectBundledProviderPolicySurface(ownerPluginId);
8081
}
82+
83+
/** Resolves provider policy hooks from bundled or trusted official plugin artifacts. */
84+
export function resolveProviderPolicySurface(
85+
providerId: string,
86+
options: { manifestRegistry?: Pick<PluginManifestRegistry, "plugins"> } = {},
87+
): BundledProviderPolicySurface | null {
88+
const bundledSurface = resolveBundledProviderPolicySurface(providerId, options);
89+
if (bundledSurface) {
90+
return bundledSurface;
91+
}
92+
const normalizedProviderId = normalizeProviderId(providerId);
93+
if (!normalizedProviderId || !options.manifestRegistry) {
94+
return null;
95+
}
96+
for (const plugin of options.manifestRegistry.plugins.toSorted((left, right) =>
97+
left.id.localeCompare(right.id),
98+
)) {
99+
if (
100+
pluginOwnsProviderPolicyRef(plugin, normalizedProviderId) &&
101+
plugin.trustedOfficialInstall === true
102+
) {
103+
const surface = resolveTrustedExternalProviderPolicySurface({
104+
pluginId: plugin.id,
105+
pluginRoot: plugin.rootDir,
106+
trustedOfficialInstall: plugin.trustedOfficialInstall,
107+
});
108+
if (surface) {
109+
return surface;
110+
}
111+
}
112+
}
113+
return null;
114+
}

0 commit comments

Comments
 (0)