Skip to content

Commit 1399ca5

Browse files
authored
fix(plugins): forward plugin subagent overrides (#48277)
Merged via squash. Prepared head SHA: ffa4589 Co-authored-by: jalehman <[email protected]> Co-authored-by: jalehman <[email protected]> Reviewed-by: @jalehman
1 parent 1561c6a commit 1399ca5

32 files changed

Lines changed: 1203 additions & 65 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ Docs: https://docs.openclaw.ai
117117
- Agents/compaction: trigger overflow recovery from the tool-result guard once post-compaction context still exceeds the safe threshold, so long tool loops compact before the next model call hard-fails. (#29371) thanks @keshav55.
118118
- macOS/exec approvals: harden exec-host request HMAC verification to use a timing-safe compare and keep malformed or truncated signatures fail-closed in focused IPC auth coverage.
119119
- Gateway/exec approvals: surface requested env override keys in gateway-host approval prompts so operators can review surviving env context without inheriting noisy base host env.
120+
- Plugins/subagents: forward per-run provider and model overrides through gateway plugin subagent dispatch so plugin-launched agent delegations honor explicit model selection again. (#48277) Thanks @jalehman.
120121

121122
### Fixes
122123

‎apps/macos/Sources/OpenClawProtocol/GatewayModels.swift‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -515,6 +515,8 @@ public struct PollParams: Codable, Sendable {
515515
public struct AgentParams: Codable, Sendable {
516516
public let message: String
517517
public let agentid: String?
518+
public let provider: String?
519+
public let model: String?
518520
public let to: String?
519521
public let replyto: String?
520522
public let sessionid: String?
@@ -542,6 +544,8 @@ public struct AgentParams: Codable, Sendable {
542544
public init(
543545
message: String,
544546
agentid: String?,
547+
provider: String?,
548+
model: String?,
545549
to: String?,
546550
replyto: String?,
547551
sessionid: String?,
@@ -568,6 +572,8 @@ public struct AgentParams: Codable, Sendable {
568572
{
569573
self.message = message
570574
self.agentid = agentid
575+
self.provider = provider
576+
self.model = model
571577
self.to = to
572578
self.replyto = replyto
573579
self.sessionid = sessionid
@@ -596,6 +602,8 @@ public struct AgentParams: Codable, Sendable {
596602
private enum CodingKeys: String, CodingKey {
597603
case message
598604
case agentid = "agentId"
605+
case provider
606+
case model
599607
case to
600608
case replyto = "replyTo"
601609
case sessionid = "sessionId"

‎apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -515,6 +515,8 @@ public struct PollParams: Codable, Sendable {
515515
public struct AgentParams: Codable, Sendable {
516516
public let message: String
517517
public let agentid: String?
518+
public let provider: String?
519+
public let model: String?
518520
public let to: String?
519521
public let replyto: String?
520522
public let sessionid: String?
@@ -542,6 +544,8 @@ public struct AgentParams: Codable, Sendable {
542544
public init(
543545
message: String,
544546
agentid: String?,
547+
provider: String?,
548+
model: String?,
545549
to: String?,
546550
replyto: String?,
547551
sessionid: String?,
@@ -568,6 +572,8 @@ public struct AgentParams: Codable, Sendable {
568572
{
569573
self.message = message
570574
self.agentid = agentid
575+
self.provider = provider
576+
self.model = model
571577
self.to = to
572578
self.replyto = replyto
573579
self.sessionid = sessionid
@@ -596,6 +602,8 @@ public struct AgentParams: Codable, Sendable {
596602
private enum CodingKeys: String, CodingKey {
597603
case message
598604
case agentid = "agentId"
605+
case provider
606+
case model
599607
case to
600608
case replyto = "replyTo"
601609
case sessionid = "sessionId"

‎docs/gateway/configuration-reference.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2419,6 +2419,8 @@ See [Local Models](/gateway/local-models). TL;DR: run MiniMax M2.5 via LM Studio
24192419
- `plugins.entries.<id>.apiKey`: plugin-level API key convenience field (when supported by the plugin).
24202420
- `plugins.entries.<id>.env`: plugin-scoped env var map.
24212421
- `plugins.entries.<id>.hooks.allowPromptInjection`: when `false`, core blocks `before_prompt_build` and ignores prompt-mutating fields from legacy `before_agent_start`, while preserving legacy `modelOverride` and `providerOverride`. Applies to native plugin hooks and supported bundle-provided hook directories.
2422+
- `plugins.entries.<id>.subagent.allowModelOverride`: explicitly trust this plugin to request per-run `provider` and `model` overrides for background subagent runs.
2423+
- `plugins.entries.<id>.subagent.allowedModels`: optional allowlist of canonical `provider/model` targets for trusted subagent overrides. Use `"*"` only when you intentionally want to allow any model.
24222424
- `plugins.entries.<id>.config`: plugin-defined config object (validated by native OpenClaw plugin schema when available).
24232425
- Enabled Claude bundle plugins can also contribute embedded Pi defaults from `settings.json`; OpenClaw applies those as sanitized agent settings, not as raw OpenClaw config patches.
24242426
- `plugins.slots.memory`: pick the active memory plugin id, or `"none"` to disable memory plugins.

‎docs/tools/plugin.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -862,6 +862,26 @@ Notes:
862862
- Returns `{ text: undefined }` when no transcription output is produced (for example skipped/unsupported input).
863863
- `api.runtime.stt.transcribeAudioFile(...)` remains as a compatibility alias.
864864

865+
Plugins can also launch background subagent runs through `api.runtime.subagent`:
866+
867+
```ts
868+
const result = await api.runtime.subagent.run({
869+
sessionKey: "agent:main:subagent:search-helper",
870+
message: "Expand this query into focused follow-up searches.",
871+
provider: "openai",
872+
model: "gpt-4.1-mini",
873+
deliver: false,
874+
});
875+
```
876+
877+
Notes:
878+
879+
- `provider` and `model` are optional per-run overrides, not persistent session changes.
880+
- OpenClaw only honors those override fields for trusted callers.
881+
- For plugin-owned fallback runs, operators must opt in with `plugins.entries.<id>.subagent.allowModelOverride: true`.
882+
- Use `plugins.entries.<id>.subagent.allowedModels` to restrict trusted plugins to specific canonical `provider/model` targets, or `"*"` to allow any target explicitly.
883+
- Untrusted plugin subagent runs still work, but override requests are rejected instead of silently falling back.
884+
865885
For web search, plugins can consume the shared runtime helper instead of
866886
reaching into the agent tool wiring:
867887

‎extensions/discord/src/voice/manager.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -623,6 +623,7 @@ export class DiscordVoiceManager {
623623
agentId: entry.route.agentId,
624624
messageChannel: "discord",
625625
senderIsOwner: speaker.senderIsOwner,
626+
allowModelOverride: false,
626627
deliver: false,
627628
},
628629
this.params.runtime,

‎src/acp/translator.session-rate-limit.test.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -308,7 +308,6 @@ describe("acp session UX bridge behavior", () => {
308308
"low",
309309
"medium",
310310
"high",
311-
"xhigh",
312311
"adaptive",
313312
]);
314313
expect(result.configOptions).toEqual(

‎src/agents/agent-command.ts‎

Lines changed: 82 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ import { applyVerboseOverride } from "../sessions/level-overrides.js";
5151
import { applyModelOverrideToSessionEntry } from "../sessions/model-overrides.js";
5252
import { resolveSendPolicy } from "../sessions/send-policy.js";
5353
import { emitSessionTranscriptUpdate } from "../sessions/transcript-events.js";
54+
import { sanitizeForLog } from "../terminal/ansi.js";
5455
import { resolveMessageChannel } from "../utils/message-channel.js";
5556
import {
5657
listAgentIds,
@@ -82,6 +83,7 @@ import {
8283
modelKey,
8384
normalizeModelRef,
8485
normalizeProviderId,
86+
parseModelRef,
8587
resolveConfiguredModelRef,
8688
resolveDefaultModelForAgent,
8789
resolveThinkingDefault,
@@ -124,6 +126,36 @@ const OVERRIDE_FIELDS_CLEARED_BY_DELETE: OverrideFieldClearedByDelete[] = [
124126
"claudeCliSessionId",
125127
];
126128

129+
const OVERRIDE_VALUE_MAX_LENGTH = 256;
130+
131+
function containsControlCharacters(value: string): boolean {
132+
for (const char of value) {
133+
const code = char.codePointAt(0);
134+
if (code === undefined) {
135+
continue;
136+
}
137+
if (code <= 0x1f || (code >= 0x7f && code <= 0x9f)) {
138+
return true;
139+
}
140+
}
141+
return false;
142+
}
143+
144+
function normalizeExplicitOverrideInput(raw: string, kind: "provider" | "model"): string {
145+
const trimmed = raw.trim();
146+
const label = kind === "provider" ? "Provider" : "Model";
147+
if (!trimmed) {
148+
throw new Error(`${label} override must be non-empty.`);
149+
}
150+
if (trimmed.length > OVERRIDE_VALUE_MAX_LENGTH) {
151+
throw new Error(`${label} override exceeds ${String(OVERRIDE_VALUE_MAX_LENGTH)} characters.`);
152+
}
153+
if (containsControlCharacters(trimmed)) {
154+
throw new Error(`${label} override contains invalid control characters.`);
155+
}
156+
return trimmed;
157+
}
158+
127159
async function persistSessionEntry(params: PersistSessionEntryParams): Promise<void> {
128160
const persisted = await updateSessionStore(params.storePath, (store) => {
129161
const merged = mergeSessionEntry(store[params.sessionKey], params.entry);
@@ -340,7 +372,7 @@ function runAgentAttempt(params: {
340372
resolvedVerboseLevel: VerboseLevel | undefined;
341373
agentDir: string;
342374
onAgentEvent: (evt: { stream: string; data?: Record<string, unknown> }) => void;
343-
primaryProvider: string;
375+
authProfileProvider: string;
344376
sessionStore?: Record<string, SessionEntry>;
345377
storePath?: string;
346378
allowTransientCooldownProbe?: boolean;
@@ -388,7 +420,7 @@ function runAgentAttempt(params: {
388420
params.storePath
389421
) {
390422
log.warn(
391-
`CLI session expired, clearing from session store: provider=${params.providerOverride} sessionKey=${params.sessionKey}`,
423+
`CLI session expired, clearing from session store: provider=${sanitizeForLog(params.providerOverride)} sessionKey=${params.sessionKey}`,
392424
);
393425

394426
// Clear the expired session ID from the session store
@@ -452,7 +484,7 @@ function runAgentAttempt(params: {
452484
}
453485

454486
const authProfileId =
455-
params.providerOverride === params.primaryProvider
487+
params.providerOverride === params.authProfileProvider
456488
? params.sessionEntry?.authProfileOverride
457489
: undefined;
458490
return runEmbeddedPiAgent({
@@ -937,7 +969,19 @@ async function agentCommandInternal(
937969
const hasStoredOverride = Boolean(
938970
sessionEntry?.modelOverride || sessionEntry?.providerOverride,
939971
);
940-
const needsModelCatalog = hasAllowlist || hasStoredOverride;
972+
const explicitProviderOverride =
973+
typeof opts.provider === "string"
974+
? normalizeExplicitOverrideInput(opts.provider, "provider")
975+
: undefined;
976+
const explicitModelOverride =
977+
typeof opts.model === "string"
978+
? normalizeExplicitOverrideInput(opts.model, "model")
979+
: undefined;
980+
const hasExplicitRunOverride = Boolean(explicitProviderOverride || explicitModelOverride);
981+
if (hasExplicitRunOverride && opts.allowModelOverride !== true) {
982+
throw new Error("Model override is not authorized for this caller.");
983+
}
984+
const needsModelCatalog = hasAllowlist || hasStoredOverride || hasExplicitRunOverride;
941985
let allowedModelKeys = new Set<string>();
942986
let allowedModelCatalog: Awaited<ReturnType<typeof loadModelCatalog>> = [];
943987
let modelCatalog: Awaited<ReturnType<typeof loadModelCatalog>> | null = null;
@@ -1000,13 +1044,38 @@ async function agentCommandInternal(
10001044
model = normalizedStored.model;
10011045
}
10021046
}
1047+
const providerForAuthProfileValidation = provider;
1048+
if (hasExplicitRunOverride) {
1049+
const explicitRef = explicitModelOverride
1050+
? explicitProviderOverride
1051+
? normalizeModelRef(explicitProviderOverride, explicitModelOverride)
1052+
: parseModelRef(explicitModelOverride, provider)
1053+
: explicitProviderOverride
1054+
? normalizeModelRef(explicitProviderOverride, model)
1055+
: null;
1056+
if (!explicitRef) {
1057+
throw new Error("Invalid model override.");
1058+
}
1059+
const explicitKey = modelKey(explicitRef.provider, explicitRef.model);
1060+
if (
1061+
!isCliProvider(explicitRef.provider, cfg) &&
1062+
!allowAnyModel &&
1063+
!allowedModelKeys.has(explicitKey)
1064+
) {
1065+
throw new Error(
1066+
`Model override "${sanitizeForLog(explicitRef.provider)}/${sanitizeForLog(explicitRef.model)}" is not allowed for agent "${sessionAgentId}".`,
1067+
);
1068+
}
1069+
provider = explicitRef.provider;
1070+
model = explicitRef.model;
1071+
}
10031072
if (sessionEntry) {
10041073
const authProfileId = sessionEntry.authProfileOverride;
10051074
if (authProfileId) {
10061075
const entry = sessionEntry;
10071076
const store = ensureAuthProfileStore();
10081077
const profile = store.profiles[authProfileId];
1009-
if (!profile || profile.provider !== provider) {
1078+
if (!profile || profile.provider !== providerForAuthProfileValidation) {
10101079
if (sessionStore && sessionKey) {
10111080
await clearSessionAuthProfileOverride({
10121081
sessionEntry: entry,
@@ -1068,6 +1137,7 @@ async function agentCommandInternal(
10681137
const resolvedSessionFile = await resolveSessionTranscriptFile({
10691138
sessionId,
10701139
sessionKey: sessionKey ?? sessionId,
1140+
storePath,
10711141
sessionEntry,
10721142
agentId: sessionAgentId,
10731143
threadId: opts.threadId,
@@ -1132,7 +1202,7 @@ async function agentCommandInternal(
11321202
skillsSnapshot,
11331203
resolvedVerboseLevel,
11341204
agentDir,
1135-
primaryProvider: provider,
1205+
authProfileProvider: providerForAuthProfileValidation,
11361206
sessionStore,
11371207
storePath,
11381208
allowTransientCooldownProbe: runOptions?.allowTransientCooldownProbe,
@@ -1230,6 +1300,8 @@ export async function agentCommand(
12301300
// Ingress callers must opt into owner semantics explicitly via
12311301
// agentCommandFromIngress so network-facing paths cannot inherit this default by accident.
12321302
senderIsOwner: opts.senderIsOwner ?? true,
1303+
// Local/CLI callers are trusted by default for per-run model overrides.
1304+
allowModelOverride: opts.allowModelOverride ?? true,
12331305
},
12341306
runtime,
12351307
deps,
@@ -1246,10 +1318,14 @@ export async function agentCommandFromIngress(
12461318
// This keeps network-facing callers from silently picking up the local trusted default.
12471319
throw new Error("senderIsOwner must be explicitly set for ingress agent runs.");
12481320
}
1321+
if (typeof opts.allowModelOverride !== "boolean") {
1322+
throw new Error("allowModelOverride must be explicitly set for ingress agent runs.");
1323+
}
12491324
return await agentCommandInternal(
12501325
{
12511326
...opts,
12521327
senderIsOwner: opts.senderIsOwner,
1328+
allowModelOverride: opts.allowModelOverride,
12531329
},
12541330
runtime,
12551331
deps,

‎src/agents/command/types.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,10 @@ export type AgentCommandOpts = {
3939
clientTools?: ClientToolDefinition[];
4040
/** Agent id override (must exist in config). */
4141
agentId?: string;
42+
/** Per-run provider override. */
43+
provider?: string;
44+
/** Per-run model override. */
45+
model?: string;
4246
to?: string;
4347
sessionId?: string;
4448
sessionKey?: string;
@@ -65,6 +69,8 @@ export type AgentCommandOpts = {
6569
runContext?: AgentRunContext;
6670
/** Whether this caller is authorized for owner-only tools (defaults true for local CLI calls). */
6771
senderIsOwner?: boolean;
72+
/** Whether this caller is authorized to use provider/model per-run overrides. */
73+
allowModelOverride?: boolean;
6874
/** Group/spawn metadata for subagent policy inheritance and routing context. */
6975
groupId?: SpawnedRunMetadata["groupId"];
7076
groupChannel?: SpawnedRunMetadata["groupChannel"];
@@ -84,7 +90,12 @@ export type AgentCommandOpts = {
8490
workspaceDir?: SpawnedRunMetadata["workspaceDir"];
8591
};
8692

87-
export type AgentCommandIngressOpts = Omit<AgentCommandOpts, "senderIsOwner"> & {
88-
/** Ingress callsites must always pass explicit owner authorization state. */
93+
export type AgentCommandIngressOpts = Omit<
94+
AgentCommandOpts,
95+
"senderIsOwner" | "allowModelOverride"
96+
> & {
97+
/** Ingress callsites must always pass explicit owner-tool authorization state. */
8998
senderIsOwner: boolean;
99+
/** Ingress callsites must always pass explicit model-override authorization state. */
100+
allowModelOverride: boolean;
90101
};

0 commit comments

Comments
 (0)