Skip to content

Commit f0e81b9

Browse files
authored
refactor(model-picker): centralize session apply contracts (#114739)
* refactor(model-picker): centralize session apply contracts * fix(ci): keep model apply helper result internal * fix(model-picker): require channel codec opt-in
1 parent 62baf45 commit f0e81b9

19 files changed

Lines changed: 1252 additions & 51 deletions

‎docs/.generated/plugin-sdk-api-baseline.sha256‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ f6e3c44e7d1090a97aca554a3c247219b8de78b3cb4399cac5efde8a0a6c1156 module/inbound
7474
36721c58f479fe9ca32737f67850f4607bf8753ef6b193ff129e7a9e5fdbc6bd module/inbound-reply-dispatch
7575
5aeb593609dbf7e104294d61c6f8081f94353126ed521c7413e62cd1143e18cf module/infra-runtime
7676
2e717cccb3db127aed0287d4ea14c41a8e64e46d60c728638153e31e2fb0d296 module/ingress-effect-once
77-
7c0bc9455678102a68cc80796ca04ba16f1fe9980335de9d58f82b830aef6876 module/interactive-runtime
77+
9389d91a090259f06e5ec2aae14c9857e45988d4edc4f91170cb8bc573b966a2 module/interactive-runtime
7878
9dd66baf2def46386ad4706380e57f9068fa9bb3878be2d9ba961ec2f46d3d87 module/json-store
7979
d8ca27a737f235e09f1a9f8cd4b82ac0cde96f10c662347b6ac82e27b70b4a40 module/lazy-runtime
8080
fd00374a91ab5b393152bbbaf90010f9140cf15827bde360d0c6c8724ed34e2e module/logging-core
@@ -89,7 +89,7 @@ bebd2931dc51d67c063ff19fa1c278f8dcfe00ab23cfbd480d47329ea8e5088e module/meeting
8989
6b396a29c4efcd562accbd22dfa474f7815ce039cb8314a4771c2e37b5431ab4 module/memory-core-host-engine-foundation
9090
5d4d709d5ae573186459462fe5119bd253c13104554eb94aefbdab5f5c7ad46f module/memory-host-core
9191
87b7a3206346c0d4b294fb3a2395cbaabc3e73ff8b1b9ea925bc3aade3e52687 module/messaging-targets
92-
09f842a2787b87117d88ba6545aa0441ff8afdb85e2e66ae4d1838ebecb16148 module/model-session-runtime
92+
5011823e5530df577d800e2b910c4b4f49b59084aa1df3bc03e3962ad3aee279 module/model-session-runtime
9393
44655a08ce111a036c837b8d2e796cf0036941379ab317e5764c6c01e73b39f3 module/models-provider-runtime
9494
55a7e1e57345726b2b54a4c71c66744d5559dd40a164ca552808b689306f53f8 module/native-command-config-runtime
9595
1892da4151de02907448430a4661b8578295bb91638fa6c8d940d858d902876f module/native-command-registry

‎docs/plugins/sdk-channel-plugins.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,13 @@ shared `message` tool. Your plugin owns:
3434
Core owns the shared message tool, prompt wiring, the outer session-key shape,
3535
generic `:thread:` bookkeeping, and dispatch.
3636

37+
Core also owns model-picker product actions. A channel that renders a
38+
`ModelPickerAction` declares its `ModelPickerCapabilityProfile`, then encodes
39+
the typed action in a transport-private authenticated callback envelope. Keep
40+
approval, command, URL, web-app, question, callback, and model-picker actions
41+
distinguishable until that encoding boundary; never infer picker intent from a
42+
raw callback string. Actor and source-message checks remain channel-owned.
43+
3744
## Message adapter
3845

3946
Expose a `message` adapter with `defineChannelMessageAdapter` from

‎docs/plugins/sdk-runtime.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,21 @@ Provider and channel execution paths must use the active runtime config snapshot
5454

5555
## Reusable runtime utilities
5656

57+
Model-picker integrations use two focused runtime subpaths. Import the typed
58+
`ModelPickerAction` and `ModelPickerCapabilityProfile` contracts from
59+
`openclaw/plugin-sdk/interactive-runtime`. Import
60+
`applySessionModelSelection(...)` and its result types from
61+
`openclaw/plugin-sdk/model-session-runtime`; this is the live-session mutation
62+
seam, including its authoritative conflict check and post-commit effects. The
63+
lower-level session-entry model helpers are not a picker persistence API.
64+
65+
Model-picker actions carry only bounded snapshot and catalog tokens. Channel
66+
actor identity, source-message binding, and serialized callback data stay in
67+
the channel's private authenticated envelope. Channel codecs opt into resolving
68+
these actions with `{ modelPicker: true }`; channels without a picker
69+
capability continue to fail closed instead of treating the action as an opaque
70+
callback.
71+
5772
Use inbound `botLoopProtection` facts for bot-authored inbound messages. Core applies the shared in-memory sliding-window guard before session record and dispatch, without tying the policy to one channel. The guard tracks `(scopeId, conversationId, participant pair)` keys, counts both directions of a pair together, applies a cooldown once the window budget is exceeded, and prunes inactive entries opportunistically.
5873

5974
Channel plugins that expose this behavior to operators should prefer the shared `channels.defaults.botLoopProtection` shape for baseline budgets, then layer channel/provider-specific overrides on top. The shared config uses seconds because it is user-facing:

‎scripts/plugin-sdk-surface-report.mjs‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,8 @@ export function readPluginSdkSurfaceBudgets(env = process.env) {
184184
// +1: shared multi-claim ingress lifecycle fan-in.
185185
// +3: channel prompt-context entry/compat types and channel metadata builder.
186186
// +4: focused CLI root-option constants and parsers.
187-
4731,
187+
// +6: model-picker action/capability and authoritative session-apply contracts.
188+
4737,
188189
env,
189190
),
190191
publicFunctionExports: readPluginSdkSurfaceBudgetEnv(
@@ -211,7 +212,8 @@ export function readPluginSdkSurfaceBudgets(env = process.env) {
211212
// +1: shared multi-claim ingress lifecycle fan-in.
212213
// +1: channel metadata builder.
213214
// +3: focused CLI root-option parsers.
214-
2866,
215+
// +1: authoritative model-picker session-apply operation.
216+
2867,
215217
env,
216218
),
217219
publicDeprecatedExports: readPluginSdkSurfaceBudgetEnv(

‎src/agents/runtime-plan/types.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
* observability decisions shared across embedded-agent hot paths.
55
*/
66
import type { TSchema } from "typebox";
7+
import type { ModelPickerAction } from "../../interactive/payload.js";
78
import type {
89
ModelApi,
910
ProviderModelRouteRuntimePolicy,
@@ -137,7 +138,8 @@ type AgentRuntimeMessagePresentationAction =
137138
type: "web-app";
138139
url?: string;
139140
widgetId: string;
140-
};
141+
}
142+
| ModelPickerAction;
141143

142144
/** Portable action control exposed to agent runtime reply payloads. */
143145
type AgentRuntimeMessagePresentationButton = {
@@ -166,7 +168,10 @@ type AgentRuntimeMessagePresentationOption = {
166168
/** User-visible option label. */
167169
label: string;
168170
/** Typed action sent when selected. */
169-
action?: Extract<AgentRuntimeMessagePresentationAction, { type: "command" | "callback" }>;
171+
action?: Extract<
172+
AgentRuntimeMessagePresentationAction,
173+
{ type: "command" | "callback" | "model-picker" }
174+
>;
170175
/** @deprecated Use action. */
171176
value?: string;
172177
};

‎src/auto-reply/reply/commands-diagnostics.ts‎

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -628,17 +628,15 @@ function rewritePresentationAction(action: MessagePresentationAction): MessagePr
628628
}
629629

630630
function rewriteSelectPresentationAction(
631-
action: Extract<MessagePresentationAction, { type: "command" | "callback" }>,
632-
): Extract<MessagePresentationAction, { type: "command" | "callback" }> {
633-
return action.type === "command"
634-
? {
635-
type: "command",
636-
command: rewriteCodexDiagnosticsCommandPrefix(action.command),
637-
}
638-
: {
639-
type: "callback",
640-
value: rewriteCodexDiagnosticsCommandPrefix(action.value),
641-
};
631+
action: Extract<MessagePresentationAction, { type: "command" | "callback" | "model-picker" }>,
632+
): Extract<MessagePresentationAction, { type: "command" | "callback" | "model-picker" }> {
633+
if (action.type === "command") {
634+
return { type: "command", command: rewriteCodexDiagnosticsCommandPrefix(action.command) };
635+
}
636+
if (action.type === "callback") {
637+
return { type: "callback", value: rewriteCodexDiagnosticsCommandPrefix(action.value) };
638+
}
639+
return action;
642640
}
643641

644642
function rewriteCodexDiagnosticsCommandPrefix(value: string): string {
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,4 @@
11
/** Runtime facade for persisting inline directive state after parsing. */
22
export { persistInlineDirectives } from "./directive-handling.persist.js";
3+
// This facade is the lazy boundary used by get-reply's directive-only fast path.
4+
export { applySessionModelSelection } from "../../model-picker/apply-session-model-selection.js";

‎src/auto-reply/reply/directive-handling.persist.ts‎

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@ import type { SessionEntry } from "../../config/sessions/types.js";
1818
import type { OpenClawConfig } from "../../config/types.openclaw.js";
1919
import { triggerSessionPatchHook } from "../../gateway/session-patch-hooks.js";
2020
import { enqueueSystemEvent } from "../../infra/system-events.js";
21+
import { applySessionModelSelectionToEntry } from "../../model-picker/apply-session-model-selection.js";
2122
import { applyTraceOverride, applyVerboseOverride } from "../../sessions/level-overrides.js";
22-
import { applyModelOverrideToSessionEntry } from "../../sessions/model-overrides.js";
2323
import {
2424
formatThinkingLevels,
2525
isThinkingLevelSupported,
@@ -292,17 +292,20 @@ export async function persistInlineDirectives(params: {
292292
let modelApplied = true;
293293
let modelSwitchEvent: { alias?: string; label: string } | undefined;
294294
if (modelDirective && modelResolution?.modelSelection) {
295-
const appliedModelOverride = applyModelOverrideToSessionEntry({
295+
if (modelRuntimeResolution.kind === "invalid") {
296+
throw new Error("invalid model runtime reached persistence");
297+
}
298+
const appliedSelection = applySessionModelSelectionToEntry({
296299
entry: sessionEntry,
297-
selection: modelResolution.modelSelection,
298-
profileOverride: modelResolution.profileOverride,
300+
request: {
301+
...modelResolution.modelSelection,
302+
profileOverride: modelResolution.profileOverride,
303+
runtime: modelRuntimeResolution,
304+
},
305+
runtime: modelRuntimeResolution,
299306
markLiveSwitchPending: params.markLiveSwitchPending,
300307
});
301-
const appliedRuntimeOverride = applyModelRuntimeDirective(
302-
sessionEntry,
303-
modelRuntimeResolution,
304-
);
305-
modelUpdated = appliedModelOverride.updated || appliedRuntimeOverride.updated;
308+
modelUpdated = appliedSelection.changed;
306309
provider = modelResolution.modelSelection.provider;
307310
model = modelResolution.modelSelection.model;
308311
const thinkingRuntime = resolveEffectiveAgentRuntime({

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

Lines changed: 43 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import type { ElevatedLevel } from "../thinking.js";
1212
import type { ReplyPayload } from "../types.js";
1313
import type { CommandContext } from "./commands-types.js";
1414
import { isDirectiveOnly } from "./directive-handling.directive-only.js";
15+
import { resolveModelRuntimeDirective } from "./directive-handling.model-runtime.js";
1516
import { resolveModelSelectionFromDirective } from "./directive-handling.model-selection.js";
1617
import type { ApplyInlineDirectivesFastLaneParams } from "./directive-handling.params.js";
1718
import type { InlineDirectives } from "./directive-handling.parse.js";
@@ -323,6 +324,8 @@ export async function applyInlineDirectiveOverrides(params: {
323324
typing.cleanup();
324325
return { kind: "reply", reply: undefined };
325326
}
327+
// Only the exact model-only case uses the focused service; mixed directives
328+
// fall through so their settings remain one broad atomic session transaction.
326329
if (hasOnlyModelDirective(directives) && effectiveModelDirective) {
327330
const modelResolution = resolveModelSelectionFromDirective({
328331
directives: {
@@ -345,24 +348,47 @@ export async function applyInlineDirectiveOverrides(params: {
345348
}
346349
const modelSelection = modelResolution.modelSelection;
347350
if (modelSelection) {
348-
const persisted = await (
351+
const runtime = resolveModelRuntimeDirective({
352+
rawRuntime: directives.rawModelRuntime,
353+
provider: modelSelection.provider,
354+
cfg,
355+
sessionEntry,
356+
});
357+
if (runtime.kind === "invalid") {
358+
typing.cleanup();
359+
return { kind: "reply", reply: { text: runtime.errorText } };
360+
}
361+
const applied = await (
349362
await loadDirectivePersist()
350-
).persistInlineDirectives({
351-
...directivePersistenceContext,
352-
provider,
353-
model,
363+
).applySessionModelSelection({
364+
cfg,
365+
agentId,
366+
sessionKey,
367+
storePath,
368+
sessionEntry,
369+
sessionStore,
370+
defaultProvider,
371+
defaultModel,
372+
currentProvider: provider,
373+
currentModel: model,
374+
allowedModelKeys: modelState.allowedModelKeys,
375+
modelCatalog: modelState.allowedModelCatalog,
376+
thinkingCatalog: modelState.allowedModelCatalog,
377+
request: {
378+
...modelSelection,
379+
profileOverride: modelResolution.profileOverride,
380+
runtime,
381+
},
382+
patchModel: effectiveModelDirective,
354383
markLiveSwitchPending: true,
355384
});
356-
if (persisted.errorText) {
385+
if (applied.status === "rejected") {
357386
typing.cleanup();
358-
return { kind: "reply", reply: { text: persisted.errorText } };
387+
return { kind: "reply", reply: { text: applied.message } };
359388
}
360-
if (!persisted.sessionChangesApplied) {
389+
if (applied.status === "conflict") {
361390
typing.cleanup();
362-
return {
363-
kind: "reply",
364-
reply: { text: "Model change was not applied because the session changed. Retry." },
365-
};
391+
return { kind: "reply", reply: { text: applied.message } };
366392
}
367393
const label = `${modelSelection.provider}/${modelSelection.model}`;
368394
const labelWithAlias = modelSelection.alias ? `${modelSelection.alias} (${label})` : label;
@@ -372,13 +398,13 @@ export async function applyInlineDirectiveOverrides(params: {
372398
modelSelection.isDefault
373399
? `Model reset to default (${labelWithAlias}).`
374400
: `Model set to ${labelWithAlias} for this session.`,
375-
persisted.thinkingRemap
376-
? `Thinking level set to ${persisted.thinkingRemap.to} (${persisted.thinkingRemap.from} not supported for ${persisted.thinkingRemap.provider}/${persisted.thinkingRemap.model}).`
401+
applied.thinkingRemap
402+
? `Thinking level set to ${applied.thinkingRemap.to} (${applied.thinkingRemap.from} not supported for ${applied.thinkingRemap.provider}/${applied.thinkingRemap.model}).`
377403
: undefined,
378-
persisted.runtimeChange?.kind === "clear"
404+
applied.runtimeChange?.kind === "clear"
379405
? "Runtime reset to configured policy."
380-
: persisted.runtimeChange?.kind === "set"
381-
? `Runtime set to ${persisted.runtimeChange.runtime} for this session.`
406+
: applied.runtimeChange?.kind === "set"
407+
? `Runtime set to ${applied.runtimeChange.runtime} for this session.`
382408
: undefined,
383409
modelResolution.profileOverride
384410
? `Auth profile set to ${modelResolution.profileOverride}.`

‎src/auto-reply/reply/session-entry-persistence.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ type PersistReplySessionEntryParams = {
1212
entry: SessionEntry;
1313
initialEntry: SessionEntry;
1414
reassertLiveModelSwitchPending?: boolean;
15+
requireModelSelectionUnlocked?: boolean;
1516
sessionKey: string;
1617
skipMaintenance?: boolean;
1718
storePath: string;
@@ -20,6 +21,7 @@ type PersistReplySessionEntryParams = {
2021

2122
type PersistReplySessionEntryResult =
2223
| { status: "current"; entry: SessionEntry }
24+
| { status: "model-selection-locked"; entry: SessionEntry }
2325
| { status: "lifecycle-invalidated"; error: string; entry?: SessionEntry };
2426

2527
/** Persists reply-owned state without reverting concurrent session management. */
@@ -28,6 +30,7 @@ export async function persistReplySessionEntry(
2830
): Promise<PersistReplySessionEntryResult> {
2931
let lifecycleError: string | undefined;
3032
let lifecycleEntry: SessionEntry | undefined;
33+
let lockedEntry: SessionEntry | undefined;
3134
const persisted = await patchSessionEntry(
3235
{ sessionKey: params.sessionKey, storePath: params.storePath },
3336
(_entry, context) => {
@@ -47,6 +50,13 @@ export async function persistReplySessionEntry(
4750
lifecycleEntry = context.existingEntry;
4851
return null;
4952
}
53+
if (
54+
params.requireModelSelectionUnlocked === true &&
55+
context.existingEntry.modelSelectionLocked === true
56+
) {
57+
lockedEntry = context.existingEntry;
58+
return null;
59+
}
5060
if (
5161
sessionSnapshotTouchedFieldsConflict({
5262
initial: params.initialEntry,
@@ -79,6 +89,9 @@ export async function persistReplySessionEntry(
7989
...(lifecycleEntry ? { entry: lifecycleEntry } : {}),
8090
};
8191
}
92+
if (lockedEntry) {
93+
return { status: "model-selection-locked", entry: lockedEntry };
94+
}
8295
if (!persisted) {
8396
return {
8497
status: "lifecycle-invalidated",

0 commit comments

Comments
 (0)