openclaw-plugin-model-fetch 0.2.10 → 0.2.11
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.
- package/README-CN.md +1 -1
- package/README.md +1 -1
- package/dist/agent-tool.d.ts +20 -0
- package/dist/agent-tool.js +118 -0
- package/dist/index.js +2 -3
- package/dist/model-fetch.d.ts +2 -22
- package/dist/model-fetch.js +100 -319
- package/dist/model-replacement.d.ts +29 -0
- package/dist/model-replacement.js +117 -0
- package/dist/operations.d.ts +2 -14
- package/dist/operations.js +25 -364
- package/dist/session-cleanup.d.ts +23 -0
- package/dist/session-cleanup.js +187 -0
- package/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/dist/control-ui-tab.d.ts +0 -31
- package/dist/control-ui-tab.js +0 -42
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { applyModelReferenceProtection, collectCaseVariantRelations, getProvider, migrateModelRefEntries, rewriteModelReferences, syncAgentModelEntries, syncConfiguredModelPolicyAllow, } from "./model-fetch.js";
|
|
2
|
+
const CONFIG_MUTATION_MAX_ATTEMPTS = 5;
|
|
3
|
+
function isRetryableConfigConflict(error) {
|
|
4
|
+
if (!(error instanceof Error))
|
|
5
|
+
return false;
|
|
6
|
+
if (error.name !== "ConfigMutationConflictError")
|
|
7
|
+
return false;
|
|
8
|
+
return error.retryable !== false;
|
|
9
|
+
}
|
|
10
|
+
export async function mutateConfigFileWithRetry(runtime, params) {
|
|
11
|
+
let lastError;
|
|
12
|
+
for (let attempt = 0; attempt < CONFIG_MUTATION_MAX_ATTEMPTS; attempt += 1) {
|
|
13
|
+
try {
|
|
14
|
+
return await runtime.config.mutateConfigFile(params);
|
|
15
|
+
}
|
|
16
|
+
catch (error) {
|
|
17
|
+
lastError = error;
|
|
18
|
+
if (!isRetryableConfigConflict(error))
|
|
19
|
+
throw error;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
throw lastError;
|
|
23
|
+
}
|
|
24
|
+
function isRecord(value) {
|
|
25
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
26
|
+
}
|
|
27
|
+
/** Compare authored source fields without mistaking runtime defaults for drift. */
|
|
28
|
+
export function sameProviderModels(sourceProvider, sourceModels, runtimeProvider, runtimeModels) {
|
|
29
|
+
if (sourceModels.length !== runtimeModels.length)
|
|
30
|
+
return false;
|
|
31
|
+
const sourceValueMatches = (source, runtime) => {
|
|
32
|
+
if (source === undefined)
|
|
33
|
+
return true;
|
|
34
|
+
if (Array.isArray(source)) {
|
|
35
|
+
return (Array.isArray(runtime) &&
|
|
36
|
+
source.length === runtime.length &&
|
|
37
|
+
source.every((entry, index) => sourceValueMatches(entry, runtime[index])));
|
|
38
|
+
}
|
|
39
|
+
if (isRecord(source)) {
|
|
40
|
+
if (!isRecord(runtime))
|
|
41
|
+
return false;
|
|
42
|
+
return Object.entries(source).every(([key, entry]) => entry === undefined ||
|
|
43
|
+
(Object.prototype.hasOwnProperty.call(runtime, key) &&
|
|
44
|
+
sourceValueMatches(entry, runtime[key])));
|
|
45
|
+
}
|
|
46
|
+
return Object.is(source, runtime);
|
|
47
|
+
};
|
|
48
|
+
const sourceShape = (provider, model) => {
|
|
49
|
+
const sourceModel = { ...model };
|
|
50
|
+
if (sourceModel.api !== undefined && sourceModel.api === provider.api) {
|
|
51
|
+
delete sourceModel.api;
|
|
52
|
+
}
|
|
53
|
+
if (sourceModel.baseUrl !== undefined && sourceModel.baseUrl === provider.baseUrl) {
|
|
54
|
+
delete sourceModel.baseUrl;
|
|
55
|
+
}
|
|
56
|
+
return sourceModel;
|
|
57
|
+
};
|
|
58
|
+
return sourceModels.every((sourceModel, index) => {
|
|
59
|
+
const runtimeModel = runtimeModels[index];
|
|
60
|
+
if (!runtimeModel || sourceModel.id !== runtimeModel.id)
|
|
61
|
+
return false;
|
|
62
|
+
return sourceValueMatches(sourceShape(sourceProvider, sourceModel), sourceShape(runtimeProvider, runtimeModel));
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
/** Apply one replacement against the final source draft shared by tool and UI. */
|
|
66
|
+
export function replaceProviderModels(draft, replacement) {
|
|
67
|
+
const { providerId, existingModels, mergedModels, rewrites = [], caseVariants = collectCaseVariantRelations(existingModels
|
|
68
|
+
.map((model) => model.id)
|
|
69
|
+
.filter((id) => !mergedModels.some((model) => model.id === id)), mergedModels.map((model) => model.id)), targetAgents, } = replacement;
|
|
70
|
+
const target = getProvider(draft, providerId);
|
|
71
|
+
const draftExistingModels = target.models ?? [];
|
|
72
|
+
const externalModels = draftExistingModels.filter((model) => !existingModels.some((existing) => existing.id === model.id) &&
|
|
73
|
+
!mergedModels.some((merged) => merged.id === model.id));
|
|
74
|
+
const draftMergedModels = [...mergedModels, ...externalModels];
|
|
75
|
+
const rewrittenReferences = [];
|
|
76
|
+
for (const rewrite of rewrites) {
|
|
77
|
+
const result = rewriteModelReferences(draft, rewrite.fromRef, rewrite.toRef);
|
|
78
|
+
if (result.changed)
|
|
79
|
+
rewrittenReferences.push(...result.paths);
|
|
80
|
+
}
|
|
81
|
+
const rewriteEntryMigration = migrateModelRefEntries(draft, rewrites.map((rewrite) => ({ fromRef: rewrite.fromRef, toRef: rewrite.toRef })), { onAliasConflict: "error" });
|
|
82
|
+
if (rewriteEntryMigration.changed)
|
|
83
|
+
rewrittenReferences.push(...rewriteEntryMigration.paths);
|
|
84
|
+
const caseEntryMigration = migrateModelRefEntries(draft, caseVariants.map((variant) => ({
|
|
85
|
+
fromRef: `${providerId}/${variant.removedId}`,
|
|
86
|
+
toRef: `${providerId}/${variant.survivingModelId}`,
|
|
87
|
+
})), { targetAgents });
|
|
88
|
+
if (caseEntryMigration.changed)
|
|
89
|
+
rewrittenReferences.push(...caseEntryMigration.paths);
|
|
90
|
+
const protection = applyModelReferenceProtection({
|
|
91
|
+
existing: draftExistingModels,
|
|
92
|
+
merged: draftMergedModels,
|
|
93
|
+
providerId,
|
|
94
|
+
config: draft,
|
|
95
|
+
});
|
|
96
|
+
const finalModels = protection.models;
|
|
97
|
+
const finalIds = new Set(finalModels.map((model) => model.id));
|
|
98
|
+
const removedIds = draftExistingModels
|
|
99
|
+
.map((model) => model.id)
|
|
100
|
+
.filter((id) => !finalIds.has(id));
|
|
101
|
+
const protectedModels = protection.protectedModels;
|
|
102
|
+
target.models = finalModels;
|
|
103
|
+
// Applying models must not rewrite the strategy and trigger a plugin reload.
|
|
104
|
+
const syncResult = syncConfiguredModelPolicyAllow(draft, providerId, finalModels, {
|
|
105
|
+
targetAgents,
|
|
106
|
+
});
|
|
107
|
+
syncAgentModelEntries(draft, providerId, finalModels, {
|
|
108
|
+
targetAgents: syncResult.syncedAgents,
|
|
109
|
+
});
|
|
110
|
+
return {
|
|
111
|
+
finalModels,
|
|
112
|
+
removedIds,
|
|
113
|
+
protectedModels,
|
|
114
|
+
rewrittenReferences: [...new Set(rewrittenReferences)].sort((left, right) => left.localeCompare(right)),
|
|
115
|
+
syncedAgents: syncResult.syncedAgents,
|
|
116
|
+
};
|
|
117
|
+
}
|
package/dist/operations.d.ts
CHANGED
|
@@ -1,25 +1,14 @@
|
|
|
1
1
|
import type { OpenClawPluginApi } from "openclaw/plugin-sdk/core";
|
|
2
|
-
import * as sessionStoreRuntime from "openclaw/plugin-sdk/session-store-runtime";
|
|
3
2
|
import { fetchProviderModels, type ModelFetchConfig } from "./model-fetch.js";
|
|
3
|
+
import { type SessionSelectionScope, type SessionStoreRuntime } from "./session-cleanup.js";
|
|
4
4
|
import type { ApplyStrategyInput, ApplyStrategyOutput, FetchModelsOutput, ListProvidersOutput, ModelFetchParams, PreviewApplyOutput, SaveStrategyInput, SaveStrategyOutput } from "./schemas.js";
|
|
5
|
-
type SessionSelectionScope = {
|
|
6
|
-
sessionKey?: string;
|
|
7
|
-
agentId?: string;
|
|
8
|
-
};
|
|
9
|
-
type SessionStoreRuntime = {
|
|
10
|
-
getSessionEntryAsync: typeof getSessionEntryAsync;
|
|
11
|
-
patchSessionEntry: typeof patchSessionEntry;
|
|
12
|
-
listSessionEntries: (params: Parameters<typeof sessionStoreRuntime.listSessionEntries>[0]) => ReturnType<typeof sessionStoreRuntime.listSessionEntries> | ReturnType<typeof sessionStoreRuntime.listSessionEntriesAsync>;
|
|
13
|
-
};
|
|
14
|
-
declare const getSessionEntryAsync: typeof sessionStoreRuntime.getSessionEntryAsync;
|
|
15
|
-
declare const patchSessionEntry: typeof sessionStoreRuntime.patchSessionEntry;
|
|
16
5
|
export type ModelFetchOperations = ReturnType<typeof createModelFetchOperations>;
|
|
17
6
|
export declare function createModelFetchOperations({ api, factoryConfig, fetchModels, now, sessionStore, }: {
|
|
18
7
|
api: OpenClawPluginApi;
|
|
19
8
|
factoryConfig?: ModelFetchConfig;
|
|
20
9
|
fetchModels?: typeof fetchProviderModels;
|
|
21
10
|
now?: () => Date;
|
|
22
|
-
sessionStore?: SessionStoreRuntime
|
|
11
|
+
sessionStore?: Partial<SessionStoreRuntime>;
|
|
23
12
|
}): {
|
|
24
13
|
listProviders: () => Promise<ListProvidersOutput>;
|
|
25
14
|
fetchModels: (providerId: string) => Promise<FetchModelsOutput>;
|
|
@@ -49,4 +38,3 @@ export declare function registerModelFetchOperations(api: OpenClawPluginApi, opt
|
|
|
49
38
|
fetchModels?: typeof fetchProviderModels;
|
|
50
39
|
now?: () => Date;
|
|
51
40
|
}): ModelFetchOperations;
|
|
52
|
-
export {};
|
package/dist/operations.js
CHANGED
|
@@ -1,48 +1,10 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { Value } from "typebox/value";
|
|
3
|
-
import * as sessionStoreRuntime from "openclaw/plugin-sdk/session-store-runtime";
|
|
4
3
|
import { modelFetchContract } from "./contract.js";
|
|
5
|
-
import { applyModelReferenceProtection, collectCaseVariantRelations, collectModelReferenceUsages, fetchProviderModels, getProvider, listConfiguredAgentEntries, mergeModels,
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
* rewriting the config file) fails outright. The host's own config writer
|
|
10
|
-
* retries these conflicts, so mirror that behaviour here.
|
|
11
|
-
*/
|
|
12
|
-
const CONFIG_MUTATION_MAX_ATTEMPTS = 5;
|
|
13
|
-
function isRetryableConfigConflict(error) {
|
|
14
|
-
if (!(error instanceof Error))
|
|
15
|
-
return false;
|
|
16
|
-
if (error.name !== "ConfigMutationConflictError")
|
|
17
|
-
return false;
|
|
18
|
-
return error.retryable !== false;
|
|
19
|
-
}
|
|
20
|
-
async function mutateConfigFileWithRetry(runtime, params) {
|
|
21
|
-
let lastError;
|
|
22
|
-
for (let attempt = 0; attempt < CONFIG_MUTATION_MAX_ATTEMPTS; attempt += 1) {
|
|
23
|
-
try {
|
|
24
|
-
return await runtime.config.mutateConfigFile(params);
|
|
25
|
-
}
|
|
26
|
-
catch (error) {
|
|
27
|
-
lastError = error;
|
|
28
|
-
if (!isRetryableConfigConflict(error))
|
|
29
|
-
throw error;
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
throw lastError;
|
|
33
|
-
}
|
|
34
|
-
const AFFECTED_SESSION_LIMIT = 2_000;
|
|
35
|
-
const DEFAULT_AGENT_ID = "main";
|
|
36
|
-
const getSessionEntryAsync = sessionStoreRuntime.getSessionEntryAsync;
|
|
37
|
-
const patchSessionEntry = sessionStoreRuntime.patchSessionEntry;
|
|
38
|
-
async function listSessionEntriesCompat(params) {
|
|
39
|
-
if (typeof sessionStoreRuntime.listSessionEntriesAsync === "function") {
|
|
40
|
-
return sessionStoreRuntime.listSessionEntriesAsync({
|
|
41
|
-
agentId: params?.agentId ?? DEFAULT_AGENT_ID,
|
|
42
|
-
});
|
|
43
|
-
}
|
|
44
|
-
return sessionStoreRuntime.listSessionEntries(params);
|
|
45
|
-
}
|
|
4
|
+
import { applyModelReferenceProtection, collectCaseVariantRelations, collectModelReferenceUsages, fetchProviderModels, getProvider, listConfiguredAgentEntries, mergeModels, resolveDefaultModelRef, resolveApiKey, resolveProviderFilter, resolveProviderTargetAgents, selectFetchedModels, } from "./model-fetch.js";
|
|
5
|
+
import { runModelFetch } from "./agent-tool.js";
|
|
6
|
+
import { mutateConfigFileWithRetry, replaceProviderModels, sameProviderModels, } from "./model-replacement.js";
|
|
7
|
+
import { createModelFetchSessionCleanup, } from "./session-cleanup.js";
|
|
46
8
|
function isRecord(value) {
|
|
47
9
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
48
10
|
}
|
|
@@ -158,135 +120,6 @@ function sameStringSets(left, right) {
|
|
|
158
120
|
return (leftSorted.length === rightSorted.length &&
|
|
159
121
|
leftSorted.every((value, index) => value === rightSorted[index]));
|
|
160
122
|
}
|
|
161
|
-
/**
|
|
162
|
-
* Runtime config resolution fills Provider-level model defaults (notably
|
|
163
|
-
* `api`, reasoning metadata, token limits, and zero costs) into each model,
|
|
164
|
-
* while the source config used by a write keeps those fields implicit.
|
|
165
|
-
* Compare each authored source field against the runtime materialization so
|
|
166
|
-
* externally changed fields still fail without treating generated defaults as
|
|
167
|
-
* configuration drift.
|
|
168
|
-
*/
|
|
169
|
-
function sameProviderModels(sourceProvider, sourceModels, runtimeProvider, runtimeModels) {
|
|
170
|
-
if (sourceModels.length !== runtimeModels.length)
|
|
171
|
-
return false;
|
|
172
|
-
const sourceValueMatches = (source, runtime) => {
|
|
173
|
-
if (source === undefined)
|
|
174
|
-
return true;
|
|
175
|
-
if (Array.isArray(source)) {
|
|
176
|
-
return (Array.isArray(runtime) &&
|
|
177
|
-
source.length === runtime.length &&
|
|
178
|
-
source.every((entry, index) => sourceValueMatches(entry, runtime[index])));
|
|
179
|
-
}
|
|
180
|
-
if (isRecord(source)) {
|
|
181
|
-
if (!isRecord(runtime))
|
|
182
|
-
return false;
|
|
183
|
-
return Object.entries(source).every(([key, entry]) => entry === undefined ||
|
|
184
|
-
(Object.prototype.hasOwnProperty.call(runtime, key) &&
|
|
185
|
-
sourceValueMatches(entry, runtime[key])));
|
|
186
|
-
}
|
|
187
|
-
return Object.is(source, runtime);
|
|
188
|
-
};
|
|
189
|
-
const sourceShape = (provider, model) => {
|
|
190
|
-
const sourceModel = { ...model };
|
|
191
|
-
if (sourceModel.api !== undefined && sourceModel.api === provider.api) {
|
|
192
|
-
delete sourceModel.api;
|
|
193
|
-
}
|
|
194
|
-
if (sourceModel.baseUrl !== undefined && sourceModel.baseUrl === provider.baseUrl) {
|
|
195
|
-
delete sourceModel.baseUrl;
|
|
196
|
-
}
|
|
197
|
-
return sourceModel;
|
|
198
|
-
};
|
|
199
|
-
return sourceModels.every((sourceModel, index) => {
|
|
200
|
-
const runtimeModel = runtimeModels[index];
|
|
201
|
-
if (!runtimeModel || sourceModel.id !== runtimeModel.id)
|
|
202
|
-
return false;
|
|
203
|
-
return sourceValueMatches(sourceShape(sourceProvider, sourceModel), sourceShape(runtimeProvider, runtimeModel));
|
|
204
|
-
});
|
|
205
|
-
}
|
|
206
|
-
function staleOverrideMatches(entry, providerId, removedIds) {
|
|
207
|
-
if (entry.providerOverride) {
|
|
208
|
-
return entry.providerOverride === providerId && removedIds.includes(entry.modelOverride ?? "");
|
|
209
|
-
}
|
|
210
|
-
if (entry.modelOverride) {
|
|
211
|
-
return removedIds.some((modelId) => entry.modelOverride === `${providerId}/${modelId}`);
|
|
212
|
-
}
|
|
213
|
-
return entry.modelProvider === providerId && removedIds.includes(entry.model ?? "");
|
|
214
|
-
}
|
|
215
|
-
/**
|
|
216
|
-
* Session keys are stored as `agent:<agentId>:<rest>`. The agent id prefix is
|
|
217
|
-
* case insensitive, and only the leading ownership segment is parsed.
|
|
218
|
-
*/
|
|
219
|
-
function parseAgentIdFromSessionKey(sessionKey) {
|
|
220
|
-
const raw = sessionKey?.trim() ?? "";
|
|
221
|
-
if (raw.length < 7 || raw.slice(0, 6).toLowerCase() !== "agent:")
|
|
222
|
-
return undefined;
|
|
223
|
-
const separator = raw.indexOf(":", 6);
|
|
224
|
-
if (separator === -1)
|
|
225
|
-
return undefined;
|
|
226
|
-
const agentId = raw.slice(6, separator).trim();
|
|
227
|
-
const rest = raw.slice(separator + 1);
|
|
228
|
-
if (!agentId || !rest || rest.startsWith(":"))
|
|
229
|
-
return undefined;
|
|
230
|
-
return agentId;
|
|
231
|
-
}
|
|
232
|
-
/**
|
|
233
|
-
* The cleared fields of one stale session selection. A session that only kept
|
|
234
|
-
* the runtime model also loses its runtime context bookkeeping.
|
|
235
|
-
*/
|
|
236
|
-
function staleSelectionResetUpdate(entry, providerId, removedIds) {
|
|
237
|
-
const runtimeModelMatches = entry.modelProvider === providerId && removedIds.includes(entry.model ?? "");
|
|
238
|
-
return {
|
|
239
|
-
providerOverride: undefined,
|
|
240
|
-
modelOverride: undefined,
|
|
241
|
-
modelOverrideSource: undefined,
|
|
242
|
-
modelOverrideRouteResolution: undefined,
|
|
243
|
-
modelOverrideFallbackOriginProvider: undefined,
|
|
244
|
-
modelOverrideFallbackOriginModel: undefined,
|
|
245
|
-
...(runtimeModelMatches
|
|
246
|
-
? {
|
|
247
|
-
model: undefined,
|
|
248
|
-
modelProvider: undefined,
|
|
249
|
-
contextTokens: undefined,
|
|
250
|
-
contextTokensSource: undefined,
|
|
251
|
-
contextBudgetStatus: undefined,
|
|
252
|
-
}
|
|
253
|
-
: {}),
|
|
254
|
-
};
|
|
255
|
-
}
|
|
256
|
-
/**
|
|
257
|
-
* Clears the stale selection of every listed session. Each session is read
|
|
258
|
-
* again right before it is patched so a lock taken after the preview is
|
|
259
|
-
* honoured, and one failing session never stops the remaining ones.
|
|
260
|
-
*/
|
|
261
|
-
async function resetStaleSessionSelections({ candidates, providerId, removedIds, sessionStore, }) {
|
|
262
|
-
const resetSessionKeys = [];
|
|
263
|
-
if (removedIds.length === 0)
|
|
264
|
-
return resetSessionKeys;
|
|
265
|
-
for (const candidate of candidates) {
|
|
266
|
-
try {
|
|
267
|
-
const latest = await sessionStore.getSessionEntryAsync({
|
|
268
|
-
sessionKey: candidate.sessionKey,
|
|
269
|
-
agentId: candidate.agentId,
|
|
270
|
-
});
|
|
271
|
-
if (!latest || latest.modelSelectionLocked === true)
|
|
272
|
-
continue;
|
|
273
|
-
if (!staleOverrideMatches(latest, providerId, removedIds))
|
|
274
|
-
continue;
|
|
275
|
-
const updated = await sessionStore.patchSessionEntry({
|
|
276
|
-
sessionKey: candidate.sessionKey,
|
|
277
|
-
agentId: candidate.agentId,
|
|
278
|
-
preserveActivity: true,
|
|
279
|
-
update: () => staleSelectionResetUpdate(latest, providerId, removedIds),
|
|
280
|
-
});
|
|
281
|
-
if (updated)
|
|
282
|
-
resetSessionKeys.push(candidate.sessionKey);
|
|
283
|
-
}
|
|
284
|
-
catch {
|
|
285
|
-
// A single failing session must not abort the remaining cleanups.
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
return resetSessionKeys;
|
|
289
|
-
}
|
|
290
123
|
function ensurePluginEntry(draft, providerId, filter, targetAgents = []) {
|
|
291
124
|
draft.plugins ??= {};
|
|
292
125
|
draft.plugins.entries ??= {};
|
|
@@ -304,12 +137,12 @@ function ensurePluginEntry(draft, providerId, filter, targetAgents = []) {
|
|
|
304
137
|
entry.config = pluginConfig;
|
|
305
138
|
draft.plugins.entries["model-fetch"] = entry;
|
|
306
139
|
}
|
|
307
|
-
export function createModelFetchOperations({ api, factoryConfig, fetchModels = fetchProviderModels, now = () => new Date(), sessionStore
|
|
308
|
-
getSessionEntryAsync,
|
|
309
|
-
patchSessionEntry,
|
|
310
|
-
listSessionEntries: listSessionEntriesCompat,
|
|
311
|
-
}, }) {
|
|
140
|
+
export function createModelFetchOperations({ api, factoryConfig, fetchModels = fetchProviderModels, now = () => new Date(), sessionStore, }) {
|
|
312
141
|
const runtime = api.runtime;
|
|
142
|
+
const sessionCleanup = createModelFetchSessionCleanup({
|
|
143
|
+
currentConfig: () => runtime.config.current(),
|
|
144
|
+
sessionStore,
|
|
145
|
+
});
|
|
313
146
|
function currentConfig() {
|
|
314
147
|
return runtime.config.current();
|
|
315
148
|
}
|
|
@@ -319,128 +152,6 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
|
|
|
319
152
|
function savedTargetAgents(providerId, config = currentConfig()) {
|
|
320
153
|
return normalizeTargetAgents(resolveProviderTargetAgents(providerId, config, factoryConfig));
|
|
321
154
|
}
|
|
322
|
-
function configuredAgentIds(config = currentConfig()) {
|
|
323
|
-
return listConfiguredAgentEntries(config).map(({ id }) => id);
|
|
324
|
-
}
|
|
325
|
-
/**
|
|
326
|
-
* Lists the sessions of every candidate agent. `listSessionEntries` is
|
|
327
|
-
* agent scoped, so agents discovered inside the returned session keys are
|
|
328
|
-
* scanned as well.
|
|
329
|
-
*/
|
|
330
|
-
async function collectSessionEntries(agentIds) {
|
|
331
|
-
const candidates = [];
|
|
332
|
-
const visited = new Set();
|
|
333
|
-
const queue = [...agentIds];
|
|
334
|
-
while (queue.length > 0) {
|
|
335
|
-
const agentId = (queue.shift() ?? "").trim();
|
|
336
|
-
if (!agentId)
|
|
337
|
-
continue;
|
|
338
|
-
const normalized = agentId.toLowerCase();
|
|
339
|
-
if (visited.has(normalized))
|
|
340
|
-
continue;
|
|
341
|
-
visited.add(normalized);
|
|
342
|
-
let summaries = [];
|
|
343
|
-
try {
|
|
344
|
-
summaries = await sessionStore.listSessionEntries({
|
|
345
|
-
agentId,
|
|
346
|
-
readOnly: true,
|
|
347
|
-
});
|
|
348
|
-
}
|
|
349
|
-
catch {
|
|
350
|
-
// One unreadable agent store must not stop the remaining ones.
|
|
351
|
-
continue;
|
|
352
|
-
}
|
|
353
|
-
for (const summary of summaries ?? []) {
|
|
354
|
-
const sessionKey = summary?.sessionKey;
|
|
355
|
-
if (!sessionKey)
|
|
356
|
-
continue;
|
|
357
|
-
const parsedAgentId = parseAgentIdFromSessionKey(sessionKey);
|
|
358
|
-
candidates.push({
|
|
359
|
-
sessionKey,
|
|
360
|
-
agentId: parsedAgentId ?? agentId,
|
|
361
|
-
entry: summary.entry,
|
|
362
|
-
});
|
|
363
|
-
if (parsedAgentId && !visited.has(parsedAgentId.toLowerCase())) {
|
|
364
|
-
queue.push(parsedAgentId);
|
|
365
|
-
}
|
|
366
|
-
}
|
|
367
|
-
}
|
|
368
|
-
return candidates;
|
|
369
|
-
}
|
|
370
|
-
/**
|
|
371
|
-
* Sessions whose persisted model selection points at a model that the plan
|
|
372
|
-
* removes. Locked sessions are never reported as affected.
|
|
373
|
-
*/
|
|
374
|
-
function collectAffectedSessions(candidates, providerId, removedIds) {
|
|
375
|
-
const affected = [];
|
|
376
|
-
const seen = new Set();
|
|
377
|
-
for (const candidate of candidates) {
|
|
378
|
-
if (affected.length >= AFFECTED_SESSION_LIMIT)
|
|
379
|
-
break;
|
|
380
|
-
const entry = candidate.entry;
|
|
381
|
-
if (!entry)
|
|
382
|
-
continue;
|
|
383
|
-
if (entry.modelSelectionLocked === true)
|
|
384
|
-
continue;
|
|
385
|
-
if (!staleOverrideMatches(entry, providerId, removedIds))
|
|
386
|
-
continue;
|
|
387
|
-
const dedupeKey = `${candidate.agentId.toLowerCase()}::${candidate.sessionKey}`;
|
|
388
|
-
if (seen.has(dedupeKey))
|
|
389
|
-
continue;
|
|
390
|
-
seen.add(dedupeKey);
|
|
391
|
-
affected.push({
|
|
392
|
-
sessionKey: candidate.sessionKey,
|
|
393
|
-
agentId: candidate.agentId,
|
|
394
|
-
label: entry.label || entry.displayName || candidate.sessionKey,
|
|
395
|
-
});
|
|
396
|
-
}
|
|
397
|
-
return affected;
|
|
398
|
-
}
|
|
399
|
-
/**
|
|
400
|
-
* Every session across the known agents whose selection becomes stale.
|
|
401
|
-
* `main` is always scanned, the calling agent is added when known, and
|
|
402
|
-
* agents are additionally derived from the session keys themselves.
|
|
403
|
-
*/
|
|
404
|
-
async function affectedSessionsFor({ providerId, removedIds, scope, }) {
|
|
405
|
-
if (removedIds.length === 0)
|
|
406
|
-
return [];
|
|
407
|
-
const agentIds = new Set([DEFAULT_AGENT_ID]);
|
|
408
|
-
const scopeAgentId = scope.agentId?.trim();
|
|
409
|
-
if (scopeAgentId)
|
|
410
|
-
agentIds.add(scopeAgentId);
|
|
411
|
-
const scopedKeyAgentId = scope.sessionKey
|
|
412
|
-
? parseAgentIdFromSessionKey(scope.sessionKey)
|
|
413
|
-
: undefined;
|
|
414
|
-
if (scopedKeyAgentId)
|
|
415
|
-
agentIds.add(scopedKeyAgentId);
|
|
416
|
-
for (const agentId of configuredAgentIds())
|
|
417
|
-
agentIds.add(agentId);
|
|
418
|
-
const candidates = await collectSessionEntries([...agentIds]);
|
|
419
|
-
const scopedSessionKey = scope.sessionKey?.trim();
|
|
420
|
-
const scopedOwnerId = scopeAgentId ?? scopedKeyAgentId;
|
|
421
|
-
if (scopedSessionKey && scopedOwnerId) {
|
|
422
|
-
const known = candidates.some((candidate) => candidate.sessionKey === scopedSessionKey);
|
|
423
|
-
if (!known) {
|
|
424
|
-
try {
|
|
425
|
-
const entry = await sessionStore.getSessionEntryAsync({
|
|
426
|
-
sessionKey: scopedSessionKey,
|
|
427
|
-
agentId: scopedOwnerId,
|
|
428
|
-
});
|
|
429
|
-
if (entry) {
|
|
430
|
-
candidates.push({
|
|
431
|
-
sessionKey: scopedSessionKey,
|
|
432
|
-
agentId: scopedOwnerId,
|
|
433
|
-
entry,
|
|
434
|
-
});
|
|
435
|
-
}
|
|
436
|
-
}
|
|
437
|
-
catch {
|
|
438
|
-
// The scoped session is optional; ignore unreadable entries.
|
|
439
|
-
}
|
|
440
|
-
}
|
|
441
|
-
}
|
|
442
|
-
return collectAffectedSessions(candidates, providerId, removedIds);
|
|
443
|
-
}
|
|
444
155
|
/**
|
|
445
156
|
* Models kept only because of a reference are absent from `removedIds`, so the
|
|
446
157
|
* protection set has to be recomputed over removals plus protected models.
|
|
@@ -599,11 +310,7 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
|
|
|
599
310
|
}
|
|
600
311
|
async function previewApply(provider, scope = {}) {
|
|
601
312
|
const computed = await computePlan(provider);
|
|
602
|
-
const affectedSessions = await
|
|
603
|
-
providerId: provider,
|
|
604
|
-
removedIds: computed.removedIds,
|
|
605
|
-
scope,
|
|
606
|
-
});
|
|
313
|
+
const affectedSessions = await sessionCleanup.affectedSessions(provider, computed.removedIds, scope);
|
|
607
314
|
const plan = {
|
|
608
315
|
fingerprint: computed.fingerprint,
|
|
609
316
|
fetchedAt: computed.fetchedAt,
|
|
@@ -636,7 +343,7 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
|
|
|
636
343
|
const rewrites = normalizeReferenceRewrites(referenceRewrites, computed);
|
|
637
344
|
const nextTargetAgents = normalizeTargetAgents(targetAgents ?? savedTargetAgents(provider));
|
|
638
345
|
let syncedAgents = [];
|
|
639
|
-
|
|
346
|
+
let rewrittenReferences = [];
|
|
640
347
|
let removedIds = computed.removedIds;
|
|
641
348
|
let finalProtectedModels = computed.protectedModels;
|
|
642
349
|
const result = await mutateConfigFileWithRetry(runtime, {
|
|
@@ -659,75 +366,28 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
|
|
|
659
366
|
if (referenceProtectionDrift(config, provider, computed)) {
|
|
660
367
|
throw new Error("模型引用在确认后发生变化,已取消写入。请重新预览。");
|
|
661
368
|
}
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
// walker above leaves them alone. A case-only rename has to move them
|
|
670
|
-
// to the surviving spelling; otherwise the alias and the allowlist
|
|
671
|
-
// entry are dropped along with the stale id.
|
|
672
|
-
// Explicit reference rewrites can change an alias definition used by
|
|
673
|
-
// any agent, so those entries are migrated across the full roster.
|
|
674
|
-
const rewriteEntryMigration = migrateModelRefEntries(config, rewrites.map((rewrite) => ({
|
|
675
|
-
fromRef: rewrite.fromRef,
|
|
676
|
-
toRef: rewrite.toRef,
|
|
677
|
-
})), { onAliasConflict: "error" });
|
|
678
|
-
if (rewriteEntryMigration.changed) {
|
|
679
|
-
rewrittenReferences.push(...rewriteEntryMigration.paths);
|
|
680
|
-
}
|
|
681
|
-
const caseEntryMigration = migrateModelRefEntries(config, computed.caseVariants.map((variant) => ({
|
|
682
|
-
fromRef: `${provider}/${variant.removedId}`,
|
|
683
|
-
toRef: `${provider}/${variant.survivingModelId}`,
|
|
684
|
-
})), { targetAgents: nextTargetAgents });
|
|
685
|
-
if (caseEntryMigration.changed) {
|
|
686
|
-
rewrittenReferences.push(...caseEntryMigration.paths);
|
|
687
|
-
}
|
|
688
|
-
// The rewrites may have released the references that kept a model in
|
|
689
|
-
// the list, so the final list is recomputed against the rewritten
|
|
690
|
-
// draft instead of reusing the previewed one.
|
|
691
|
-
const finalModels = rewrites.length > 0
|
|
692
|
-
? applyModelReferenceProtection({
|
|
693
|
-
existing: computed.existingModels,
|
|
694
|
-
merged: computed.mergedModels,
|
|
695
|
-
providerId: provider,
|
|
696
|
-
config,
|
|
697
|
-
}).models
|
|
698
|
-
: computed.finalModels;
|
|
699
|
-
const finalIds = new Set(finalModels.map((model) => model.id));
|
|
700
|
-
removedIds = computed.existingIds.filter((id) => !finalIds.has(id));
|
|
701
|
-
finalProtectedModels = collectModelReferenceUsages(config, provider, computed.protectedModels.map((entry) => entry.modelId));
|
|
702
|
-
target.models = finalModels;
|
|
703
|
-
// Applying replaces the Provider model list; it must not rewrite this
|
|
704
|
-
// plugin's saved strategy. A plugin-config write triggers a runtime
|
|
705
|
-
// reload and invalidates the session action that is still returning.
|
|
706
|
-
const syncResult = syncConfiguredModelPolicyAllow(config, provider, finalModels, {
|
|
369
|
+
const replacement = replaceProviderModels(config, {
|
|
370
|
+
providerId: provider,
|
|
371
|
+
provider: computed.provider,
|
|
372
|
+
existingModels: computed.existingModels,
|
|
373
|
+
mergedModels: computed.mergedModels,
|
|
374
|
+
rewrites,
|
|
375
|
+
caseVariants: computed.caseVariants,
|
|
707
376
|
targetAgents: nextTargetAgents,
|
|
708
377
|
});
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
378
|
+
removedIds = replacement.removedIds;
|
|
379
|
+
finalProtectedModels = replacement.protectedModels;
|
|
380
|
+
rewrittenReferences = replacement.rewrittenReferences;
|
|
381
|
+
syncedAgents = replacement.syncedAgents;
|
|
713
382
|
},
|
|
714
383
|
});
|
|
715
384
|
// The session list is re-read after the write so the cleanup sees the
|
|
716
385
|
// latest state and honours locks taken since the preview.
|
|
717
|
-
const
|
|
386
|
+
const resetSessionKeys = await sessionCleanup.reset({
|
|
718
387
|
providerId: provider,
|
|
719
388
|
removedIds,
|
|
720
389
|
scope,
|
|
721
390
|
});
|
|
722
|
-
const resetSessionKeys = await resetStaleSessionSelections({
|
|
723
|
-
candidates: affectedSessions.map((session) => ({
|
|
724
|
-
sessionKey: session.sessionKey,
|
|
725
|
-
agentId: session.agentId,
|
|
726
|
-
})),
|
|
727
|
-
providerId: provider,
|
|
728
|
-
removedIds,
|
|
729
|
-
sessionStore,
|
|
730
|
-
});
|
|
731
391
|
return {
|
|
732
392
|
provider,
|
|
733
393
|
persisted: true,
|
|
@@ -739,7 +399,7 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
|
|
|
739
399
|
removed: removedIds.length,
|
|
740
400
|
selectedIds: computed.selectedIds,
|
|
741
401
|
protectedModels: finalProtectedModels,
|
|
742
|
-
rewrittenReferences
|
|
402
|
+
rewrittenReferences,
|
|
743
403
|
targetAgents: nextTargetAgents,
|
|
744
404
|
syncedAgents,
|
|
745
405
|
sessionSelectionResets: resetSessionKeys.length,
|
|
@@ -753,6 +413,7 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
|
|
|
753
413
|
factoryConfig,
|
|
754
414
|
fetchModels,
|
|
755
415
|
params,
|
|
416
|
+
sessionCleanup,
|
|
756
417
|
});
|
|
757
418
|
}
|
|
758
419
|
return {
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import * as sessionStoreRuntime from "openclaw/plugin-sdk/session-store-runtime";
|
|
2
|
+
import type { AffectedSession } from "./schemas.js";
|
|
3
|
+
export type SessionSelectionScope = {
|
|
4
|
+
sessionKey?: string;
|
|
5
|
+
agentId?: string;
|
|
6
|
+
};
|
|
7
|
+
export type SessionStoreRuntime = {
|
|
8
|
+
getSessionEntryAsync: typeof sessionStoreRuntime.getSessionEntryAsync;
|
|
9
|
+
patchSessionEntry: typeof sessionStoreRuntime.patchSessionEntry;
|
|
10
|
+
listSessionEntries: typeof sessionStoreRuntime.listSessionEntriesAsync;
|
|
11
|
+
};
|
|
12
|
+
export type ModelFetchSessionCleanup = {
|
|
13
|
+
affectedSessions: (providerId: string, removedIds: readonly string[], scope?: SessionSelectionScope) => Promise<AffectedSession[]>;
|
|
14
|
+
reset: (params: {
|
|
15
|
+
providerId: string;
|
|
16
|
+
removedIds: readonly string[];
|
|
17
|
+
scope?: SessionSelectionScope;
|
|
18
|
+
}) => Promise<string[]>;
|
|
19
|
+
};
|
|
20
|
+
export declare function createModelFetchSessionCleanup({ currentConfig, sessionStore: sessionStoreOverrides, }?: {
|
|
21
|
+
currentConfig?: () => unknown;
|
|
22
|
+
sessionStore?: Partial<SessionStoreRuntime>;
|
|
23
|
+
}): ModelFetchSessionCleanup;
|