openclaw-plugin-model-fetch 0.2.3 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  import type { OpenClawPluginApi } from "openclaw/plugin-sdk/core";
2
- import { getSessionEntryAsync, patchSessionEntry } from "openclaw/plugin-sdk/session-store-runtime";
2
+ import { getSessionEntryAsync, listSessionEntries, patchSessionEntry } from "openclaw/plugin-sdk/session-store-runtime";
3
3
  import { fetchProviderModels, type ModelFetchConfig } from "./model-fetch.js";
4
4
  import type { ApplyStrategyInput, ApplyStrategyOutput, FetchModelsOutput, ListProvidersOutput, ModelFetchParams, PreviewApplyOutput, SaveStrategyInput, SaveStrategyOutput } from "./schemas.js";
5
5
  type SessionSelectionScope = {
@@ -9,6 +9,7 @@ type SessionSelectionScope = {
9
9
  type SessionStoreRuntime = {
10
10
  getSessionEntryAsync: typeof getSessionEntryAsync;
11
11
  patchSessionEntry: typeof patchSessionEntry;
12
+ listSessionEntries: typeof listSessionEntries;
12
13
  };
13
14
  export type ModelFetchOperations = ReturnType<typeof createModelFetchOperations>;
14
15
  export declare function createModelFetchOperations({ api, factoryConfig, fetchModels, now, sessionStore, }: {
@@ -21,7 +22,7 @@ export declare function createModelFetchOperations({ api, factoryConfig, fetchMo
21
22
  listProviders: () => Promise<ListProvidersOutput>;
22
23
  fetchModels: (providerId: string) => Promise<FetchModelsOutput>;
23
24
  saveStrategy: ({ provider, filter, targetAgents, }: SaveStrategyInput) => Promise<SaveStrategyOutput>;
24
- previewApply: (provider: string) => Promise<PreviewApplyOutput>;
25
+ previewApply: (provider: string, scope?: SessionSelectionScope) => Promise<PreviewApplyOutput>;
25
26
  applyStrategy: ({ provider, fingerprint, expectedRemovals, targetAgents, }: ApplyStrategyInput, scope?: SessionSelectionScope) => Promise<ApplyStrategyOutput>;
26
27
  refreshProvider: (params: ModelFetchParams) => Promise<{
27
28
  provider: string;
@@ -1,8 +1,10 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { Value } from "typebox/value";
3
- import { getSessionEntryAsync, patchSessionEntry, } from "openclaw/plugin-sdk/session-store-runtime";
3
+ import { getSessionEntryAsync, listSessionEntries, patchSessionEntry, } from "openclaw/plugin-sdk/session-store-runtime";
4
4
  import { modelFetchContract } from "./contract.js";
5
5
  import { applyModelReferenceProtection, collectModelReferenceUsages, fetchProviderModels, getProvider, mergeModels, resolveApiKey, resolveProviderFilter, resolveProviderTargetAgents, runModelFetch, selectFetchedModels, syncAgentModelEntries, syncConfiguredModelPolicyAllow, } from "./model-fetch.js";
6
+ const AFFECTED_SESSION_LIMIT = 2_000;
7
+ const DEFAULT_AGENT_ID = "main";
6
8
  function isRecord(value) {
7
9
  return typeof value === "object" && value !== null && !Array.isArray(value);
8
10
  }
@@ -74,42 +76,80 @@ function staleOverrideMatches(entry, providerId, removedIds) {
74
76
  }
75
77
  return entry.modelProvider === providerId && removedIds.includes(entry.model ?? "");
76
78
  }
77
- async function resetStaleSessionSelection({ scope, providerId, removedIds, sessionStore, }) {
78
- const sessionKey = scope.sessionKey?.trim();
79
- if (!sessionKey || removedIds.length === 0)
80
- return false;
81
- const entry = await sessionStore.getSessionEntryAsync({
82
- sessionKey,
83
- agentId: scope.agentId,
84
- });
85
- if (!entry || entry.modelSelectionLocked === true)
86
- return false;
87
- if (!staleOverrideMatches(entry, providerId, removedIds))
88
- return false;
79
+ /**
80
+ * Session keys are stored as `agent:<agentId>:<rest>`. The agent id prefix is
81
+ * case insensitive, and only the leading ownership segment is parsed.
82
+ */
83
+ function parseAgentIdFromSessionKey(sessionKey) {
84
+ const raw = sessionKey?.trim() ?? "";
85
+ if (raw.length < 7 || raw.slice(0, 6).toLowerCase() !== "agent:")
86
+ return undefined;
87
+ const separator = raw.indexOf(":", 6);
88
+ if (separator === -1)
89
+ return undefined;
90
+ const agentId = raw.slice(6, separator).trim();
91
+ const rest = raw.slice(separator + 1);
92
+ if (!agentId || !rest || rest.startsWith(":"))
93
+ return undefined;
94
+ return agentId;
95
+ }
96
+ /**
97
+ * The cleared fields of one stale session selection. A session that only kept
98
+ * the runtime model also loses its runtime context bookkeeping.
99
+ */
100
+ function staleSelectionResetUpdate(entry, providerId, removedIds) {
89
101
  const runtimeModelMatches = entry.modelProvider === providerId && removedIds.includes(entry.model ?? "");
90
- const updated = await sessionStore.patchSessionEntry({
91
- sessionKey,
92
- agentId: scope.agentId,
93
- preserveActivity: true,
94
- update: () => ({
95
- providerOverride: undefined,
96
- modelOverride: undefined,
97
- modelOverrideSource: undefined,
98
- modelOverrideRouteResolution: undefined,
99
- modelOverrideFallbackOriginProvider: undefined,
100
- modelOverrideFallbackOriginModel: undefined,
101
- ...(runtimeModelMatches
102
- ? {
103
- model: undefined,
104
- modelProvider: undefined,
105
- contextTokens: undefined,
106
- contextTokensSource: undefined,
107
- contextBudgetStatus: undefined,
108
- }
109
- : {}),
110
- }),
111
- });
112
- return Boolean(updated);
102
+ return {
103
+ providerOverride: undefined,
104
+ modelOverride: undefined,
105
+ modelOverrideSource: undefined,
106
+ modelOverrideRouteResolution: undefined,
107
+ modelOverrideFallbackOriginProvider: undefined,
108
+ modelOverrideFallbackOriginModel: undefined,
109
+ ...(runtimeModelMatches
110
+ ? {
111
+ model: undefined,
112
+ modelProvider: undefined,
113
+ contextTokens: undefined,
114
+ contextTokensSource: undefined,
115
+ contextBudgetStatus: undefined,
116
+ }
117
+ : {}),
118
+ };
119
+ }
120
+ /**
121
+ * Clears the stale selection of every listed session. Each session is read
122
+ * again right before it is patched so a lock taken after the preview is
123
+ * honoured, and one failing session never stops the remaining ones.
124
+ */
125
+ async function resetStaleSessionSelections({ candidates, providerId, removedIds, sessionStore, }) {
126
+ const resetSessionKeys = [];
127
+ if (removedIds.length === 0)
128
+ return resetSessionKeys;
129
+ for (const candidate of candidates) {
130
+ try {
131
+ const latest = await sessionStore.getSessionEntryAsync({
132
+ sessionKey: candidate.sessionKey,
133
+ agentId: candidate.agentId,
134
+ });
135
+ if (!latest || latest.modelSelectionLocked === true)
136
+ continue;
137
+ if (!staleOverrideMatches(latest, providerId, removedIds))
138
+ continue;
139
+ const updated = await sessionStore.patchSessionEntry({
140
+ sessionKey: candidate.sessionKey,
141
+ agentId: candidate.agentId,
142
+ preserveActivity: true,
143
+ update: () => staleSelectionResetUpdate(latest, providerId, removedIds),
144
+ });
145
+ if (updated)
146
+ resetSessionKeys.push(candidate.sessionKey);
147
+ }
148
+ catch {
149
+ // A single failing session must not abort the remaining cleanups.
150
+ }
151
+ }
152
+ return resetSessionKeys;
113
153
  }
114
154
  function ensurePluginEntry(draft, providerId, filter, targetAgents = []) {
115
155
  draft.plugins ??= {};
@@ -128,7 +168,7 @@ function ensurePluginEntry(draft, providerId, filter, targetAgents = []) {
128
168
  entry.config = pluginConfig;
129
169
  draft.plugins.entries["model-fetch"] = entry;
130
170
  }
131
- export function createModelFetchOperations({ api, factoryConfig, fetchModels = fetchProviderModels, now = () => new Date(), sessionStore = { getSessionEntryAsync, patchSessionEntry }, }) {
171
+ export function createModelFetchOperations({ api, factoryConfig, fetchModels = fetchProviderModels, now = () => new Date(), sessionStore = { getSessionEntryAsync, patchSessionEntry, listSessionEntries }, }) {
132
172
  const runtime = api.runtime;
133
173
  function currentConfig() {
134
174
  return runtime.config.current();
@@ -139,6 +179,129 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
139
179
  function savedTargetAgents(providerId, config = currentConfig()) {
140
180
  return normalizeTargetAgents(resolveProviderTargetAgents(providerId, config, factoryConfig));
141
181
  }
182
+ function configuredAgentIds(config = currentConfig()) {
183
+ const entries = config?.agents?.entries ?? {};
184
+ return Object.keys(entries).filter((agentId) => agentId.trim().length > 0);
185
+ }
186
+ /**
187
+ * Lists the sessions of every candidate agent. `listSessionEntries` is
188
+ * agent scoped, so agents discovered inside the returned session keys are
189
+ * scanned as well.
190
+ */
191
+ async function collectSessionEntries(agentIds) {
192
+ const candidates = [];
193
+ const visited = new Set();
194
+ const queue = [...agentIds];
195
+ while (queue.length > 0) {
196
+ const agentId = (queue.shift() ?? "").trim();
197
+ if (!agentId)
198
+ continue;
199
+ const normalized = agentId.toLowerCase();
200
+ if (visited.has(normalized))
201
+ continue;
202
+ visited.add(normalized);
203
+ let summaries = [];
204
+ try {
205
+ summaries = await sessionStore.listSessionEntries({
206
+ agentId,
207
+ readOnly: true,
208
+ });
209
+ }
210
+ catch {
211
+ // One unreadable agent store must not stop the remaining ones.
212
+ continue;
213
+ }
214
+ for (const summary of summaries ?? []) {
215
+ const sessionKey = summary?.sessionKey;
216
+ if (!sessionKey)
217
+ continue;
218
+ const parsedAgentId = parseAgentIdFromSessionKey(sessionKey);
219
+ candidates.push({
220
+ sessionKey,
221
+ agentId: parsedAgentId ?? agentId,
222
+ entry: summary.entry,
223
+ });
224
+ if (parsedAgentId && !visited.has(parsedAgentId.toLowerCase())) {
225
+ queue.push(parsedAgentId);
226
+ }
227
+ }
228
+ }
229
+ return candidates;
230
+ }
231
+ /**
232
+ * Sessions whose persisted model selection points at a model that the plan
233
+ * removes. Locked sessions are never reported as affected.
234
+ */
235
+ function collectAffectedSessions(candidates, providerId, removedIds) {
236
+ const affected = [];
237
+ const seen = new Set();
238
+ for (const candidate of candidates) {
239
+ if (affected.length >= AFFECTED_SESSION_LIMIT)
240
+ break;
241
+ const entry = candidate.entry;
242
+ if (!entry)
243
+ continue;
244
+ if (entry.modelSelectionLocked === true)
245
+ continue;
246
+ if (!staleOverrideMatches(entry, providerId, removedIds))
247
+ continue;
248
+ const dedupeKey = `${candidate.agentId.toLowerCase()}::${candidate.sessionKey}`;
249
+ if (seen.has(dedupeKey))
250
+ continue;
251
+ seen.add(dedupeKey);
252
+ affected.push({
253
+ sessionKey: candidate.sessionKey,
254
+ agentId: candidate.agentId,
255
+ label: entry.label || entry.displayName || candidate.sessionKey,
256
+ });
257
+ }
258
+ return affected;
259
+ }
260
+ /**
261
+ * Every session across the known agents whose selection becomes stale.
262
+ * `main` is always scanned, the calling agent is added when known, and
263
+ * agents are additionally derived from the session keys themselves.
264
+ */
265
+ async function affectedSessionsFor({ providerId, removedIds, scope, }) {
266
+ if (removedIds.length === 0)
267
+ return [];
268
+ const agentIds = new Set([DEFAULT_AGENT_ID]);
269
+ const scopeAgentId = scope.agentId?.trim();
270
+ if (scopeAgentId)
271
+ agentIds.add(scopeAgentId);
272
+ const scopedKeyAgentId = scope.sessionKey
273
+ ? parseAgentIdFromSessionKey(scope.sessionKey)
274
+ : undefined;
275
+ if (scopedKeyAgentId)
276
+ agentIds.add(scopedKeyAgentId);
277
+ for (const agentId of configuredAgentIds())
278
+ agentIds.add(agentId);
279
+ const candidates = await collectSessionEntries([...agentIds]);
280
+ const scopedSessionKey = scope.sessionKey?.trim();
281
+ const scopedOwnerId = scopeAgentId ?? scopedKeyAgentId;
282
+ if (scopedSessionKey && scopedOwnerId) {
283
+ const known = candidates.some((candidate) => candidate.sessionKey === scopedSessionKey);
284
+ if (!known) {
285
+ try {
286
+ const entry = await sessionStore.getSessionEntryAsync({
287
+ sessionKey: scopedSessionKey,
288
+ agentId: scopedOwnerId,
289
+ });
290
+ if (entry) {
291
+ candidates.push({
292
+ sessionKey: scopedSessionKey,
293
+ agentId: scopedOwnerId,
294
+ entry,
295
+ });
296
+ }
297
+ }
298
+ catch {
299
+ // The scoped session is optional; ignore unreadable entries.
300
+ }
301
+ }
302
+ }
303
+ return collectAffectedSessions(candidates, providerId, removedIds);
304
+ }
142
305
  /**
143
306
  * Models kept only because of a reference are absent from `removedIds`, so the
144
307
  * protection set has to be recomputed over removals plus protected models.
@@ -290,8 +453,13 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
290
453
  targetAgents: nextTargetAgents,
291
454
  };
292
455
  }
293
- async function previewApply(provider) {
456
+ async function previewApply(provider, scope = {}) {
294
457
  const computed = await computePlan(provider);
458
+ const affectedSessions = await affectedSessionsFor({
459
+ providerId: provider,
460
+ removedIds: computed.removedIds,
461
+ scope,
462
+ });
295
463
  const plan = {
296
464
  fingerprint: computed.fingerprint,
297
465
  fetchedAt: computed.fetchedAt,
@@ -301,6 +469,7 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
301
469
  protectedModels: computed.protectedModels,
302
470
  selectedIds: computed.selectedIds,
303
471
  unchangedCount: computed.unchangedCount,
472
+ affectedSessions,
304
473
  };
305
474
  return {
306
475
  provider,
@@ -346,15 +515,22 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
346
515
  });
347
516
  },
348
517
  });
349
- let sessionSelectionReset = false;
350
- if (scope.sessionKey) {
351
- sessionSelectionReset = await resetStaleSessionSelection({
352
- scope,
353
- providerId: provider,
354
- removedIds: computed.removedIds,
355
- sessionStore,
356
- });
357
- }
518
+ // The session list is re-read after the write so the cleanup sees the
519
+ // latest state and honours locks taken since the preview.
520
+ const affectedSessions = await affectedSessionsFor({
521
+ providerId: provider,
522
+ removedIds: computed.removedIds,
523
+ scope,
524
+ });
525
+ const resetSessionKeys = await resetStaleSessionSelections({
526
+ candidates: affectedSessions.map((session) => ({
527
+ sessionKey: session.sessionKey,
528
+ agentId: session.agentId,
529
+ })),
530
+ providerId: provider,
531
+ removedIds: computed.removedIds,
532
+ sessionStore,
533
+ });
358
534
  return {
359
535
  provider,
360
536
  persisted: true,
@@ -368,7 +544,8 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
368
544
  protectedModels: computed.protectedModels,
369
545
  targetAgents: nextTargetAgents,
370
546
  syncedAgents,
371
- sessionSelectionReset,
547
+ sessionSelectionResets: resetSessionKeys.length,
548
+ resetSessionKeys,
372
549
  models: computed.models,
373
550
  };
374
551
  }
@@ -395,7 +572,10 @@ export function registerModelFetchOperations(api, options = {}) {
395
572
  "providers.list": () => operations.listProviders(),
396
573
  "models.fetch": (input) => operations.fetchModels(input.provider),
397
574
  "strategy.save": (input) => operations.saveStrategy(input),
398
- "strategy.preview": (input) => operations.previewApply(input.provider),
575
+ "strategy.preview": (input, context) => operations.previewApply(input.provider, {
576
+ sessionKey: context.sessionKey,
577
+ agentId: context.agentId,
578
+ }),
399
579
  "strategy.apply": (input, context) => operations.applyStrategy(input, {
400
580
  sessionKey: context.sessionKey,
401
581
  agentId: context.agentId,
package/dist/schemas.d.ts CHANGED
@@ -150,6 +150,16 @@ export declare const saveStrategyInputSchema: Type.TObject<{
150
150
  targetAgents: Type.TOptional<Type.TArray<Type.TString>>;
151
151
  }>;
152
152
  export type SaveStrategyInput = Static<typeof saveStrategyInputSchema>;
153
+ /**
154
+ * One session whose stale model selection will be cleared when the plan is
155
+ * applied. `label` is a human readable fallback for the session key.
156
+ */
157
+ export declare const affectedSessionSchema: Type.TObject<{
158
+ sessionKey: Type.TString;
159
+ agentId: Type.TString;
160
+ label: Type.TString;
161
+ }>;
162
+ export type AffectedSession = Static<typeof affectedSessionSchema>;
153
163
  export declare const applyPlanSchema: Type.TObject<{
154
164
  fingerprint: Type.TString;
155
165
  fetchedAt: Type.TString;
@@ -163,6 +173,11 @@ export declare const applyPlanSchema: Type.TObject<{
163
173
  }>>;
164
174
  selectedIds: Type.TArray<Type.TString>;
165
175
  unchangedCount: Type.TInteger;
176
+ affectedSessions: Type.TArray<Type.TObject<{
177
+ sessionKey: Type.TString;
178
+ agentId: Type.TString;
179
+ label: Type.TString;
180
+ }>>;
166
181
  }>;
167
182
  export type ApplyPlan = Static<typeof applyPlanSchema>;
168
183
  export declare const previewApplyOutputSchema: Type.TObject<{
@@ -180,6 +195,11 @@ export declare const previewApplyOutputSchema: Type.TObject<{
180
195
  }>>;
181
196
  selectedIds: Type.TArray<Type.TString>;
182
197
  unchangedCount: Type.TInteger;
198
+ affectedSessions: Type.TArray<Type.TObject<{
199
+ sessionKey: Type.TString;
200
+ agentId: Type.TString;
201
+ label: Type.TString;
202
+ }>>;
183
203
  }>;
184
204
  models: Type.TArray<Type.TObject<{
185
205
  id: Type.TString;
@@ -212,7 +232,8 @@ export declare const applyStrategyOutputSchema: Type.TObject<{
212
232
  }>>;
213
233
  targetAgents: Type.TArray<Type.TString>;
214
234
  syncedAgents: Type.TArray<Type.TString>;
215
- sessionSelectionReset: Type.TBoolean;
235
+ sessionSelectionResets: Type.TInteger;
236
+ resetSessionKeys: Type.TArray<Type.TString>;
216
237
  models: Type.TArray<Type.TObject<{
217
238
  id: Type.TString;
218
239
  name: Type.TString;
package/dist/schemas.js CHANGED
@@ -121,6 +121,15 @@ export const saveStrategyInputSchema = Type.Object({
121
121
  uniqueItems: true,
122
122
  })),
123
123
  }, { additionalProperties: false });
124
+ /**
125
+ * One session whose stale model selection will be cleared when the plan is
126
+ * applied. `label` is a human readable fallback for the session key.
127
+ */
128
+ export const affectedSessionSchema = Type.Object({
129
+ sessionKey: Type.String({ minLength: 1, maxLength: 512 }),
130
+ agentId: Type.String({ minLength: 1, maxLength: 128 }),
131
+ label: Type.String({ minLength: 1, maxLength: 512 }),
132
+ }, { additionalProperties: false });
124
133
  export const applyPlanSchema = Type.Object({
125
134
  fingerprint: Type.String({ minLength: 64, maxLength: 64 }),
126
135
  fetchedAt: Type.String({ maxLength: 64 }),
@@ -130,6 +139,7 @@ export const applyPlanSchema = Type.Object({
130
139
  protectedModels: Type.Array(protectedModelSchema, { maxItems: 2_000 }),
131
140
  selectedIds: Type.Array(Type.String({ maxLength: 512 }), { maxItems: 2_000 }),
132
141
  unchangedCount: Type.Integer({ minimum: 0 }),
142
+ affectedSessions: Type.Array(affectedSessionSchema, { maxItems: 2_000 }),
133
143
  }, { additionalProperties: false });
134
144
  export const previewApplyOutputSchema = Type.Object({
135
145
  provider: providerIdSchema,
@@ -164,7 +174,11 @@ export const applyStrategyOutputSchema = Type.Object({
164
174
  maxItems: 256,
165
175
  uniqueItems: true,
166
176
  }),
167
- sessionSelectionReset: Type.Boolean(),
177
+ sessionSelectionResets: Type.Integer({ minimum: 0 }),
178
+ resetSessionKeys: Type.Array(Type.String({ minLength: 1, maxLength: 512 }), {
179
+ maxItems: 2_000,
180
+ uniqueItems: true,
181
+ }),
168
182
  models: Type.Array(modelViewSchema, { maxItems: 2_000 }),
169
183
  }, { additionalProperties: false });
170
184
  export { emptyInputSchema, providerInputSchema };
@@ -2,7 +2,7 @@
2
2
  "id": "model-fetch",
3
3
  "name": "Model Fetch",
4
4
  "description": "Fetch and refresh configured provider model lists into OpenClaw config with independent per-provider filters.",
5
- "version": "0.2.3",
5
+ "version": "0.2.5",
6
6
  "configSchema": {
7
7
  "type": "object",
8
8
  "properties": {
@@ -61,9 +61,9 @@
61
61
  "onStartup": true
62
62
  },
63
63
  "controlUi": {
64
- "entry": "dist/control-ui/c069f02e4e1108c5f0eac0fd3c5b2810353e159ada13c0e01bfa0cbda80dad7b/index.js",
64
+ "entry": "dist/control-ui/bfc77779ea04b85bc02fc16f096d90b1c281194d30a76ce570e7fd2afa6e95d2/index.js",
65
65
  "styles": [
66
- "dist/control-ui/c069f02e4e1108c5f0eac0fd3c5b2810353e159ada13c0e01bfa0cbda80dad7b/index.css"
66
+ "dist/control-ui/bfc77779ea04b85bc02fc16f096d90b1c281194d30a76ce570e7fd2afa6e95d2/index.css"
67
67
  ]
68
68
  },
69
69
  "contracts": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openclaw-plugin-model-fetch",
3
- "version": "0.2.3",
3
+ "version": "0.2.5",
4
4
  "description": "OpenClaw plugin tool that refreshes configured provider model lists into OpenClaw config with independent per-provider filters.",
5
5
  "license": "MIT",
6
6
  "repository": {