openclaw-plugin-model-fetch 0.2.2 → 0.2.4

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,7 +1,10 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { Value } from "typebox/value";
3
+ import { getSessionEntryAsync, listSessionEntries, patchSessionEntry, } from "openclaw/plugin-sdk/session-store-runtime";
3
4
  import { modelFetchContract } from "./contract.js";
4
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";
5
8
  function isRecord(value) {
6
9
  return typeof value === "object" && value !== null && !Array.isArray(value);
7
10
  }
@@ -64,6 +67,90 @@ function sameStringSets(left, right) {
64
67
  return (leftSorted.length === rightSorted.length &&
65
68
  leftSorted.every((value, index) => value === rightSorted[index]));
66
69
  }
70
+ function staleOverrideMatches(entry, providerId, removedIds) {
71
+ if (entry.providerOverride) {
72
+ return entry.providerOverride === providerId && removedIds.includes(entry.modelOverride ?? "");
73
+ }
74
+ if (entry.modelOverride) {
75
+ return removedIds.some((modelId) => entry.modelOverride === `${providerId}/${modelId}`);
76
+ }
77
+ return entry.modelProvider === providerId && removedIds.includes(entry.model ?? "");
78
+ }
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) {
101
+ const runtimeModelMatches = entry.modelProvider === providerId && removedIds.includes(entry.model ?? "");
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;
153
+ }
67
154
  function ensurePluginEntry(draft, providerId, filter, targetAgents = []) {
68
155
  draft.plugins ??= {};
69
156
  draft.plugins.entries ??= {};
@@ -81,7 +168,7 @@ function ensurePluginEntry(draft, providerId, filter, targetAgents = []) {
81
168
  entry.config = pluginConfig;
82
169
  draft.plugins.entries["model-fetch"] = entry;
83
170
  }
84
- export function createModelFetchOperations({ api, factoryConfig, fetchModels = fetchProviderModels, now = () => new Date(), }) {
171
+ export function createModelFetchOperations({ api, factoryConfig, fetchModels = fetchProviderModels, now = () => new Date(), sessionStore = { getSessionEntryAsync, patchSessionEntry, listSessionEntries }, }) {
85
172
  const runtime = api.runtime;
86
173
  function currentConfig() {
87
174
  return runtime.config.current();
@@ -92,6 +179,129 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
92
179
  function savedTargetAgents(providerId, config = currentConfig()) {
93
180
  return normalizeTargetAgents(resolveProviderTargetAgents(providerId, config, factoryConfig));
94
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
+ }
95
305
  /**
96
306
  * Models kept only because of a reference are absent from `removedIds`, so the
97
307
  * protection set has to be recomputed over removals plus protected models.
@@ -243,8 +453,13 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
243
453
  targetAgents: nextTargetAgents,
244
454
  };
245
455
  }
246
- async function previewApply(provider) {
456
+ async function previewApply(provider, scope = {}) {
247
457
  const computed = await computePlan(provider);
458
+ const affectedSessions = await affectedSessionsFor({
459
+ providerId: provider,
460
+ removedIds: computed.removedIds,
461
+ scope,
462
+ });
248
463
  const plan = {
249
464
  fingerprint: computed.fingerprint,
250
465
  fetchedAt: computed.fetchedAt,
@@ -254,6 +469,7 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
254
469
  protectedModels: computed.protectedModels,
255
470
  selectedIds: computed.selectedIds,
256
471
  unchangedCount: computed.unchangedCount,
472
+ affectedSessions,
257
473
  };
258
474
  return {
259
475
  provider,
@@ -261,7 +477,7 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
261
477
  models: computed.models,
262
478
  };
263
479
  }
264
- async function applyStrategy({ provider, fingerprint, expectedRemovals, targetAgents, }) {
480
+ async function applyStrategy({ provider, fingerprint, expectedRemovals, targetAgents, }, scope = {}) {
265
481
  const computed = await computePlan(provider);
266
482
  if (computed.fingerprint !== fingerprint) {
267
483
  throw new Error("模型列表或筛选策略已变化,请重新预览后再确认应用。");
@@ -299,6 +515,22 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
299
515
  });
300
516
  },
301
517
  });
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
+ });
302
534
  return {
303
535
  provider,
304
536
  persisted: true,
@@ -312,6 +544,8 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
312
544
  protectedModels: computed.protectedModels,
313
545
  targetAgents: nextTargetAgents,
314
546
  syncedAgents,
547
+ sessionSelectionResets: resetSessionKeys.length,
548
+ resetSessionKeys,
315
549
  models: computed.models,
316
550
  };
317
551
  }
@@ -338,8 +572,14 @@ export function registerModelFetchOperations(api, options = {}) {
338
572
  "providers.list": () => operations.listProviders(),
339
573
  "models.fetch": (input) => operations.fetchModels(input.provider),
340
574
  "strategy.save": (input) => operations.saveStrategy(input),
341
- "strategy.preview": (input) => operations.previewApply(input.provider),
342
- "strategy.apply": (input) => operations.applyStrategy(input),
575
+ "strategy.preview": (input, context) => operations.previewApply(input.provider, {
576
+ sessionKey: context.sessionKey,
577
+ agentId: context.agentId,
578
+ }),
579
+ "strategy.apply": (input, context) => operations.applyStrategy(input, {
580
+ sessionKey: context.sessionKey,
581
+ agentId: context.agentId,
582
+ }),
343
583
  "provider.refresh": (input) => operations.refreshProvider(input),
344
584
  };
345
585
  for (const [id, operation] of Object.entries(modelFetchContract.operations)) {
@@ -368,7 +608,7 @@ export function registerModelFetchOperations(api, options = {}) {
368
608
  }
369
609
  return {
370
610
  ok: true,
371
- result: (await handler(payload)),
611
+ result: (await handler(payload, context)),
372
612
  };
373
613
  }
374
614
  catch (error) {
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,6 +232,8 @@ export declare const applyStrategyOutputSchema: Type.TObject<{
212
232
  }>>;
213
233
  targetAgents: Type.TArray<Type.TString>;
214
234
  syncedAgents: Type.TArray<Type.TString>;
235
+ sessionSelectionResets: Type.TInteger;
236
+ resetSessionKeys: Type.TArray<Type.TString>;
215
237
  models: Type.TArray<Type.TObject<{
216
238
  id: Type.TString;
217
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,6 +174,11 @@ export const applyStrategyOutputSchema = Type.Object({
164
174
  maxItems: 256,
165
175
  uniqueItems: true,
166
176
  }),
177
+ sessionSelectionResets: Type.Integer({ minimum: 0 }),
178
+ resetSessionKeys: Type.Array(Type.String({ minLength: 1, maxLength: 512 }), {
179
+ maxItems: 2_000,
180
+ uniqueItems: true,
181
+ }),
167
182
  models: Type.Array(modelViewSchema, { maxItems: 2_000 }),
168
183
  }, { additionalProperties: false });
169
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.2",
5
+ "version": "0.2.4",
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/564d9a090ebaa5338954b64f9d9da0d1a37954ca0d8c72f5a4c92fc016ccb38e/index.js",
64
+ "entry": "dist/control-ui/19f1eb3db914391c2d26d2ce107c2db20a661d83717d99fa2e32c280a7de9204/index.js",
65
65
  "styles": [
66
- "dist/control-ui/564d9a090ebaa5338954b64f9d9da0d1a37954ca0d8c72f5a4c92fc016ccb38e/index.css"
66
+ "dist/control-ui/19f1eb3db914391c2d26d2ce107c2db20a661d83717d99fa2e32c280a7de9204/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.2",
3
+ "version": "0.2.4",
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": {